repo_name
stringlengths
6
69
path
stringlengths
6
178
copies
stringclasses
278 values
size
stringlengths
4
7
content
stringlengths
671
917k
license
stringclasses
15 values
hamsterready/love-console
console.lua
1
17101
local console = { _VERSION = 'love-console v0.1.0', _DESCRIPTION = 'Simple love2d console overlay', _URL = 'https://github.com/hamsterready/love-console', _LICENSE = [[ The MIT License (MIT) Copyright (c) 2014 Maciej Lopacinski 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. ]], -- hm, should it be stored in console or as module locals? -- need to read more http://kiki.to/blog/2014/03/31/rule-2-return-a-local-table/ _KEY_TOGGLE = "`",--"f2",-- _KEY_SUBMIT = "return", _KEY_CLEAR = "escape", _KEY_DELETE = "backspace", _KEY_UP = "up", _KEY_DOWN = "down", _KEY_LEFT = "left", _KEY_RIGHT = "right", _KEY_PAGEDOWN = "pagedown", _KEY_PAGEUP = "pageup", cursor = 0, cursorlife = 1, visible = false, delta = 0, logs = {}, history = {}, historyPosition = 0, linesPerConsole = 0, fontSize = 20, font = nil, firstLine = 0, lastLine = 0, input = "", ps = "> ", mode = "none", --Options are "none", "wrap", "scissors" or "bind" motd = 'Welcome user!\nType "help" for an index of available commands.', -- This table has as its keys the names of commands as -- strings, which the user must type to run the command. The -- values are themselves tables with two properties: -- -- 1. 'description' A string of information to show via the -- help command. -- -- 2. 'implementation' A function implementing the command. -- -- See the function defineCommand() for examples of adding -- entries to this table. commands = {} } -- Dynamic polygons used to draw the arrows local up = function (x, y, w) w = w * .7 local h = w * .7 return { x, y + h; x + w, y + h; x + w/2, y } end local down = function (x, y, w) w = w * .7 local h = w * .7 return { x, y; x + w, y; x + w/2, y + h } end --When you use wrap or bind, the total number of lines depends --on the number of lines used by each entry. local totalLines = function () if console.mode == "wrap" or console.mode == "bind" then local a, b = 1, 1 local width = console.w - console.margin * 2 for i,t in ipairs(console.logs) do b = a local _,u = console.font:getWrap(t.msg, width) a = a + u end return a else return #console.logs end end local function toboolean(v) return (type(v) == "string" and v == "true") or (type(v) == "string" and v == "1") or (type(v) == "number" and v ~= 0) or (type(v) == "boolean" and v) end -- http://lua-users.org/wiki/StringTrim trim2 local function trim(s) s = s or "" return s:match "^%s*(.-)%s*$" end -- http://wiki.interfaceware.com/534.html local function string_split(s, d) local t = {} local i = 0 local f local match = '(.-)' .. d .. '()' if string.find(s, d) == nil then return {s} end for sub, j in string.gmatch(s, match) do i = i + 1 t[i] = sub f = j end if i ~= 0 then t[i+1] = string.sub(s, f) end return t end local function merge_quoted(t) local ret = {} local merging = false local buf = "" for k, v in ipairs(t) do local f, l = v:sub(1,1), v:sub(v:len()) if f == '"' and l ~= '"' then merging = true buf = v else if merging then buf = buf .. " " .. v if l == '"' then merging = false table.insert(ret, buf:sub(2,-2)) end else if f == "\"" and l == f then table.insert(ret, v:sub(2, -2)) else table.insert(ret, v) end end end end return ret end function console.load(font, keyRepeat, inputCallback, mode, levels) if mode == "none" or mode == "wrap" or mode == "scissors" or mode == "bind" then console.mode = mode end love.keyboard.setKeyRepeat(keyRepeat or false) console.font = font or love.graphics.newFont(console.fontSize) console.fontSize = font and font:getHeight() or console.fontSize console.margin = console.fontSize console.lineSpacing = 1.25 console.lineHeight = console.fontSize * console.lineSpacing console.x, console.y = 0, 0 console.colors = {} console.colors["I"] = {r = 251/255, g = 241/255, b = 213/255, a = 255/255} console.colors["D"] = {r = 235/255, g = 197/255, b = 50/255, a = 255/255} console.colors["E"] = {r = 222/255, g = 69/255, b = 61/255, a = 255/255} console.colors["background"] = {r = 23/255, g = 55/255, b = 86/255, a = 190/255} console.colors["input"] = {r = 23/255, g = 55/255, b = 86/255, a = 255/255} console.colors["default"] = {r = 215/255, g = 213/255, b = 174/255, a = 255/255} console.levels = levels or {info = true, debug=true, error=true} console.inputCallback = inputCallback or console.defaultInputCallback console.resize(love.graphics.getWidth(), love.graphics.getHeight()) end function console.newHotkeys(toggle, submit, clear, delete) console._KEY_TOGGLE = toggle or console._KEY_TOGGLE console._KEY_SUBMIT = submit or console._KEY_SUBMIT console._KEY_CLEAR = clear or console._KEY_CLEAR console._KEY_DELETE = delete or console._KEY_DELETE end function console.setMotd(message) console.motd = message end function console.resize( w, h ) console.w, console.h = w, h / 3 console.y = console.lineHeight - console.lineHeight * console.lineSpacing console.linesPerConsole = math.floor((console.h - console.margin * 2) / console.lineHeight) console.h = math.floor(console.linesPerConsole * console.lineHeight + console.margin * 2) console.firstLine = console.lastLine - console.linesPerConsole console.lastLine = console.firstLine + console.linesPerConsole end function console.textinput(t) if t ~= console._KEY_TOGGLE and console.visible then console.cursor = console.cursor + 1 local x = string.sub(console.input, 0, console.cursor) .. t if console.cursor < #console.input then x = x .. string.sub(console.input, console.cursor+1) end console.input = x --console.input = console.input .. t return true end end function console.keypressed(key) local function push_history(input) local trimmed = trim(console.input) local valid = trimmed ~= "" if valid then table.insert(console.history, trimmed) console.historyPosition = #console.history + 1 end console.input = "" console.cursor = 0 return valid end if key ~= console._KEY_TOGGLE and console.visible then if key == console._KEY_SUBMIT then local msg = console.input if push_history() then console.inputCallback(msg) end elseif key == console._KEY_CLEAR then console.input = "" elseif key == console._KEY_DELETE then if console.cursor >= 0 then local t = string.sub(console.input, 0, console.cursor) if console.cursor < #console.input then t = t .. string.sub(console.input, console.cursor+2) end console.input = t console.cursor = console.cursor - 1 end elseif key == console._KEY_LEFT and console.cursor > 0 then console.cursor = console.cursor - 1 elseif key == console._KEY_RIGHT and console.cursor < #console.input then console.cursor = console.cursor + 1 end -- history traversal if #console.history > 0 then if key == console._KEY_UP then console.historyPosition = math.min(math.max(console.historyPosition - 1, 1), #console.history) console.input = console.history[console.historyPosition] elseif key == console._KEY_DOWN then local pushing = console.historyPosition + 1 > #console.history + 1 console.historyPosition = math.min(console.historyPosition + 1, #console.history + 1) console.input = console.history[console.historyPosition] or "" if pushing then console.input = "" end end end if key == console._KEY_PAGEUP then console.firstLine = math.max(0, console.firstLine - console.linesPerConsole) console.lastLine = console.firstLine + console.linesPerConsole elseif key == console._KEY_PAGEDOWN then console.firstLine = math.min(console.firstLine + console.linesPerConsole, #console.logs - console.linesPerConsole) console.lastLine = console.firstLine + console.linesPerConsole end return true elseif key == console._KEY_TOGGLE then console.visible = not console.visible return true else end return false end function console.update( dt ) console.delta = console.delta + dt console.cursorlife = console.cursorlife - 1*dt if console.cursorlife < 0 then console.cursorlife = 1 end end function console.draw() if not console.visible then return end -- backup love.graphics.push() local r, g, b, a = love.graphics.getColor() local font = love.graphics.getFont() local blend = love.graphics.getBlendMode() local cr, cg, cb, ca = love.graphics.getColorMask() local sx, sy, sw, sh = love.graphics.getScissor() local canvas = love.graphics.getCanvas() --set everything to default love.graphics.origin() love.graphics.setBlendMode("alpha") love.graphics.setColorMask(true,true,true,true) love.graphics.setCanvas() if console.mode == "scissors" or console.mode == "bind" then love.graphics.setScissor(console.x, console.y, console.w, console.h + console.lineHeight) else love.graphics.setScissor() end -- draw console local color = console.colors.background love.graphics.setColor(color.r, color.g, color.b, color.a) love.graphics.rectangle("fill", console.x, console.y, console.w, console.h) color = console.colors.input love.graphics.setColor(color.r, color.g, color.b, color.a) love.graphics.rectangle("fill", console.x, console.y + console.h, console.w, console.lineHeight) color = console.colors.default love.graphics.setColor(color.r, color.g, color.b, color.a) love.graphics.setFont(console.font) love.graphics.print(console.ps .. " " .. console.input, console.x + console.margin, console.y + console.h + (console.lineHeight - console.fontSize) / 2 -1 ) if console.firstLine > 0 then love.graphics.polygon("fill", up(console.x + console.w - console.margin, console.y + console.margin, console.margin)) end if console.lastLine < #console.logs then love.graphics.polygon("fill", down(console.x + console.w - console.margin, console.y + console.h - console.margin * 2, console.margin)) end --Wrap and Bind are more complex than the normal mode so they are separated if console.mode == "wrap" or console.mode == "bind" then local x, width = console.x + console.margin, console.w - console.margin * 2 local k, j = 1,1 local lines = totalLines() love.graphics.setScissor(x, console.y, width, (console.linesPerConsole + 1) * console.lineHeight) for i, t in ipairs(console.logs) do local _,u = console.font:getWrap(t.msg, width) j = k + u if j > console.firstLine and k <= console.lastLine then local color = console.colors[t.level] love.graphics.setColor(color.r, color.g, color.b, color.a) local y = console.y + (k - console.firstLine)*console.lineHeight love.graphics.printf(t.msg, x, y, width) end k = j end else --This is the normal section for i, t in ipairs(console.logs) do if i > console.firstLine and i <= console.lastLine then local color = console.colors[t.level] love.graphics.setColor(color.r, color.g, color.b, color.a) love.graphics.print(t.msg, console.x + console.margin, console.y + (i - console.firstLine)*console.lineHeight) end end end -- cursor if console.cursorlife < 0.5 then local str = tostring(console.input) local offset = 1 while console.font:getWidth(str) > console.w - (console.fontSize / 4) do str = str:sub(2) offset = offset + 1 end local cursorx = ((console.x + (console.margin*2) + (console.fontSize/4)) + console.font:getWidth(str:sub(1, console.cursor + offset))) love.graphics.setColor(255, 255, 255) love.graphics.line(cursorx, console.y + console.h + console.lineHeight -5, cursorx, console.y + console.h +5) end -- rollback love.graphics.setCanvas(canvas) love.graphics.pop() love.graphics.setFont(font) love.graphics.setColor(r, g, b, a) love.graphics.setBlendMode(blend) love.graphics.setColorMask(cr, cg, cb, ca) love.graphics.setScissor(sx, sy, sw, sh) end function console.mousepressed( x, y, button ) if not console.visible then return false end if not (x >= console.x and x <= (console.x + console.w)) then return false end if not (y >= console.y and y <= (console.y + console.h + console.lineHeight)) then return false end local consumed = false if button == "wu" then console.firstLine = math.max(0, console.firstLine - 1) consumed = true end if button == "wd" then console.firstLine = math.min(#console.logs - console.linesPerConsole, console.firstLine + 1) consumed = true end console.lastLine = console.firstLine + console.linesPerConsole return consumed end function console.d(str) if console.levels.debug then a(str, 'D') end end function console.i(str) if console.levels.info then a(str, 'I') end end function console.e(str) if console.levels.error then a(str, 'E') end end function console.clearCommand(name) console.commands[name] = nil end function console.defineCommand(name, description, implementation, hidden) console.commands[name] = { description = description, implementation = implementation, hidden = hidden or false } end -- private stuff console.defineCommand( "help", "Shows information on all commands.", function () console.i("Available commands are:") for name,data in pairs(console.commands) do if not data.hidden then console.i(string.format(" %s - %s", name, data.description)) end end end ) console.defineCommand( "quit", "Quits your application.", function () love.event.quit() end ) console.defineCommand( "clear", "Clears the console.", function () console.firstLine = 0 console.lastLine = 0 console.logs = {} end ) --THIS IS A REALLY DANGEROUS FUNCTION, REMOVE IT IF YOU DONT NEED IT console.defineCommand( "lua", "Lets you run lua code from the terminal", function(...) local cmd = "" for i = 1, select("#", ...) do cmd = cmd .. tostring(select(i, ...)) .. " " end if cmd == "" then console.i("This command lets you run lua code from the terminal.") console.i("It's a really dangerous command. Don't use it!") return end xpcall(loadstring(cmd), console.e) end, true ) console.defineCommand( "motd", "Shows/sets the intro message.", function(motd) if motd then console.motd = motd console.i("Motd updated.") else console.i(console.motd) end end ) console.defineCommand( "flush", "Flush console history to disk", function(file) if file then local t = love.timer.getTime() love.filesystem.write(file, "") local buffer = "" local lines = 0 for _, v in ipairs(console.logs) do buffer = buffer .. v.msg .. "\n" lines = lines + 1 if lines >= 2048 then love.filesystem.append(file, buffer) lines = 0 buffer = "" end end love.filesystem.append(file, buffer) t = love.timer.getTime() - t console.i(string.format("Successfully flushed console logs to \"%s\" in %fs.", love.filesystem.getSaveDirectory() .. "/" .. file, t)) else console.e("Usage: flush <filename>") end end ) function console.invokeCommand(name, ...) local args = {...} if console.commands[name] ~= nil then local status, error = pcall(function() console.commands[name].implementation(unpack(args)) end) if not status then console.e(error) console.e(debug.traceback()) end else console.e("Command \"" .. name .. "\" not supported, type help for help.") end end function console.defaultInputCallback(input) local commands = string_split(input, ";") for _, line in ipairs(commands) do local args = merge_quoted(string_split(trim(line), " ")) local name = args[1] table.remove(args, 1) console.invokeCommand(name, unpack(merge_quoted(args))) end end function a(str, level) str = tostring(str) for _, str in ipairs(string_split(str, "\n")) do table.insert(console.logs, #console.logs + 1, {level = level, msg = string.format("%07.02f [".. level .. "] %s", console.delta, str)}) console.lastLine = totalLines() console.firstLine = console.lastLine - console.linesPerConsole -- print(console.logs[console.lastLine].msg) end end -- auto-initialize so that console.load() is optional console.load() console.i(console.motd) return console
mit
gedads/Neodynamis
scripts/zones/Mhaura/npcs/Graine.lua
17
1634
----------------------------------- -- Area: Mhaura -- NPC: Graine -- Standard Merchant NPC ----------------------------------- package.loaded["scripts/zones/Mhaura/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Mhaura/TextIDs"); require("scripts/globals/shop"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,GRAINE_SHOP_DIALOG); stock = {0x3098,457, --Leather Bandana 0x30a0,174, --Bronze Cap 0x30a1,1700, --Brass Cap 0x3118,698, --Leather Vest 0x3120,235, --Bronze Harness 0x3121,2286, --Brass Harness 0x3198,374, --Leather Gloves 0x31a0,128, --Bronze Mittens 0x31a1,1255, --Brass Mittens 0x3218,557, --Leather Trousesrs 0x3220,191, --Bronze Subligar 0x3221,1840, --Brass Subligar 0x3298,349, --Leather Highboots 0x32a0,117, --Bronze Leggings 0x32a1,1140} --Brass Leggings 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
gedads/Neodynamis
scripts/globals/mobskills/tidal_slash.lua
37
1331
--------------------------------------------- -- Tidal Slash -- -- Description: Deals Water<a href="http://images.wikia.com/ffxi/images/b/b7/Exclamation.gif" class="image" title="Verification Needed" data-image-name="Exclamation.gif" id="Exclamation-gif"><img alt="Verification Needed" src="http://images1.wikia.nocookie.net/__cb20061130211022/ffxi/images/thumb/b/b7/Exclamation.gif/14px-Exclamation.gif" width="14" height="12" /> damage in a threefold attack to targets in a fan-shaped area of effect. -- Type: Physical? -- Utsusemi/Blink absorb: 2-3 shadows -- Range: Melee? -- Notes: Used only by Merrows equipped with a spear. If they lost their spear, they'll use Hysteric Barrage instead. --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0; end; function onMobWeaponSkill(target, mob, skill) local numhits = 3; local accmod = 1; local dmgmod = 1; local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,info.hitslanded); target:delHP(dmg); return dmg; end;
gpl-3.0
Amorph/premake-stable
tests/base/test_os.lua
9
3145
-- -- tests/base/test_os.lua -- Automated test suite for the new OS functions. -- Copyright (c) 2008-2011 Jason Perkins and the Premake project -- T.os = { } local suite = T.os -- -- os.findlib() tests -- function suite.findlib_FindSystemLib() if os.is("windows") then test.istrue(os.findlib("user32")) elseif os.is("haiku") then test.istrue(os.findlib("root")) else test.istrue(os.findlib("m")) end end function suite.findlib_FailsOnBadLibName() test.isfalse(os.findlib("NoSuchLibraryAsThisOneHere")) end -- -- os.isfile() tests -- function suite.isfile_ReturnsTrue_OnExistingFile() test.istrue(os.isfile("premake4.lua")) end function suite.isfile_ReturnsFalse_OnNonexistantFile() test.isfalse(os.isfile("no_such_file.lua")) end -- -- os.matchfiles() tests -- function suite.matchfiles_OnNonRecursive() local result = os.matchfiles("*.lua") test.istrue(table.contains(result, "testfx.lua")) test.isfalse(table.contains(result, "folder/ok.lua")) end function suite.matchfiles_Recursive() local result = os.matchfiles("**.lua") test.istrue(table.contains(result, "folder/ok.lua")) end function suite.matchfiles_SkipsDotDirs_OnRecursive() local result = os.matchfiles("**.lua") test.isfalse(table.contains(result, ".svn/text-base/testfx.lua.svn-base")) end function suite.matchfiles_OnSubfolderMatch() local result = os.matchfiles("**/xcode/*") test.istrue(table.contains(result, "actions/xcode/test_xcode_project.lua")) test.isfalse(table.contains(result, "premake4.lua")) end function suite.matchfiles_OnDotSlashPrefix() local result = os.matchfiles("./**.lua") test.istrue(table.contains(result, "folder/ok.lua")) end function suite.matchfiles_OnImplicitEndOfString() local result = os.matchfiles("folder/*.lua") test.istrue(table.contains(result, "folder/ok.lua")) test.isfalse(table.contains(result, "folder/ok.lua.2")) end function suite.matchfiles_OnLeadingDotSlashWithPath() local result = os.matchfiles("./folder/*.lua") test.istrue(table.contains(result, "folder/ok.lua")) end -- -- os.pathsearch() tests -- function suite.pathsearch_ReturnsNil_OnNotFound() test.istrue( os.pathsearch("nosuchfile", "aaa;bbb;ccc") == nil ) end function suite.pathsearch_ReturnsPath_OnFound() test.isequal(os.getcwd(), os.pathsearch("premake4.lua", os.getcwd())) end function suite.pathsearch_FindsFile_OnComplexPath() test.isequal(os.getcwd(), os.pathsearch("premake4.lua", "aaa;"..os.getcwd()..";bbb")) end function suite.pathsearch_NilPathsAllowed() test.isequal(os.getcwd(), os.pathsearch("premake4.lua", nil, os.getcwd(), nil)) end -- -- os.uuid() tests -- function suite.guid_ReturnsValidUUID() local g = os.uuid() test.istrue(#g == 36) for i=1,36 do local ch = g:sub(i,i) test.istrue(ch:find("[ABCDEF0123456789-]")) end test.isequal("-", g:sub(9,9)) test.isequal("-", g:sub(14,14)) test.isequal("-", g:sub(19,19)) test.isequal("-", g:sub(24,24)) end
bsd-3-clause
hades2013/openwrt-mtk
package/ralink/ui/luci-mtk/src/applications/luci-openvpn/luasrc/model/cbi/openvpn.lua
65
3316
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local fs = require "nixio.fs" local sys = require "luci.sys" local uci = require "luci.model.uci".cursor() local m = Map("openvpn", translate("OpenVPN")) local s = m:section( TypedSection, "openvpn", translate("OpenVPN instances"), translate("Below is a list of configured OpenVPN instances and their current state") ) s.template = "cbi/tblsection" s.template_addremove = "openvpn/cbi-select-input-add" s.addremove = true s.add_select_options = { } s.extedit = luci.dispatcher.build_url( "admin", "services", "openvpn", "basic", "%s" ) uci:load("openvpn_recipes") uci:foreach( "openvpn_recipes", "openvpn_recipe", function(section) s.add_select_options[section['.name']] = section['_description'] or section['.name'] end ) function s.parse(self, section) local recipe = luci.http.formvalue( luci.cbi.CREATE_PREFIX .. self.config .. "." .. self.sectiontype .. ".select" ) if recipe and not s.add_select_options[recipe] then self.invalid_cts = true else TypedSection.parse( self, section ) end end function s.create(self, name) local recipe = luci.http.formvalue( luci.cbi.CREATE_PREFIX .. self.config .. "." .. self.sectiontype .. ".select" ) if name and not name:match("[^a-zA-Z0-9_]") then uci:section( "openvpn", "openvpn", name, uci:get_all( "openvpn_recipes", recipe ) ) uci:delete("openvpn", name, "_role") uci:delete("openvpn", name, "_description") uci:save("openvpn") luci.http.redirect( self.extedit:format(name) ) else self.invalid_cts = true end end s:option( Flag, "enabled", translate("Enabled") ) local active = s:option( DummyValue, "_active", translate("Started") ) function active.cfgvalue(self, section) local pid = fs.readfile("/var/run/openvpn-%s.pid" % section) if pid and #pid > 0 and tonumber(pid) ~= nil then return (sys.process.signal(pid, 0)) and translatef("yes (%i)", pid) or translate("no") end return translate("no") end local updown = s:option( Button, "_updown", translate("Start/Stop") ) updown._state = false function updown.cbid(self, section) local pid = fs.readfile("/var/run/openvpn-%s.pid" % section) self._state = pid and #pid > 0 and sys.process.signal(pid, 0) self.option = self._state and "stop" or "start" return AbstractValue.cbid(self, section) end function updown.cfgvalue(self, section) self.title = self._state and "stop" or "start" self.inputstyle = self._state and "reset" or "reload" end function updown.write(self, section, value) if self.option == "stop" then luci.sys.call("/etc/init.d/openvpn down %s" % section) else luci.sys.call("/etc/init.d/openvpn up %s" % section) end end local port = s:option( DummyValue, "port", translate("Port") ) function port.cfgvalue(self, section) local val = AbstractValue.cfgvalue(self, section) return val or "1194" end local proto = s:option( DummyValue, "proto", translate("Protocol") ) function proto.cfgvalue(self, section) local val = AbstractValue.cfgvalue(self, section) return val or "udp" end return m
gpl-2.0
pedro-andrade-inpe/terrame
packages/base/tests/observer/alternative/Chart.lua
3
13419
------------------------------------------------------------------------------------------- -- TerraME - a software platform for multiple scale spatially-explicit dynamic modeling. -- Copyright (C) 2001-2017 INPE and TerraLAB/UFOP -- www.terrame.org -- This code is part of the TerraME framework. -- This framework 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. -- You should have received a copy of the GNU Lesser General Public -- License along with this library. -- The authors reassure the license terms regarding the warranties. -- They specifically disclaim any warranties, including, but not limited to, -- the implied warranties of merchantability and fitness for a particular purpose. -- The framework provided hereunder is on an "as is" basis, and the authors have no -- obligation to provide maintenance, support, updates, enhancements, or modifications. -- In no event shall INPE and TerraLAB / UFOP be held liable to any party for direct, -- indirect, special, incidental, or consequential damages arising out of the use -- of this software and its documentation. -- ------------------------------------------------------------------------------------------- return{ Chart = function(unitTest) local c = Cell{value = 5} local error_func = function() Chart(2) end unitTest:assertError(error_func, namedArgumentsMsg()) error_func = function() Chart{} end unitTest:assertError(error_func, mandatoryArgumentMsg("target")) error_func = function() Chart{target = 2} end unitTest:assertError(error_func, "Invalid type. Charts only work with Cell, CellularSpace, Agent, Society, table, DataFrame, and instance of Model, got number.") error_func = function() Chart{target = c, select = 5} end unitTest:assertError(error_func, incompatibleTypeMsg("select", "table", 5)) error_func = function() Chart{target = c, select = "mvalue"} end unitTest:assertError(error_func, "Selected element 'mvalue' does not belong to the target. Do you mean 'value'?") error_func = function() Chart{target = c, select = "abcd"} end unitTest:assertError(error_func, "Selected element 'abcd' does not belong to the target.") error_func = function() Chart{target = c, xLabel = 5} end unitTest:assertError(error_func, incompatibleTypeMsg("xLabel", "string", 5)) error_func = function() Chart{target = c, yLabel = 5} end unitTest:assertError(error_func, incompatibleTypeMsg("yLabel", "string", 5)) error_func = function() Chart{target = c, title = 5} end unitTest:assertError(error_func, incompatibleTypeMsg("title", "string", 5)) error_func = function() Chart{target = c, xAxis = 5} end unitTest:assertError(error_func, incompatibleTypeMsg("xAxis", "string", 5)) error_func = function() Chart{target = c, xAxis = "value"} end unitTest:assertError(error_func, "The target does not have at least one valid numeric attribute to be used.") error_func = function() Chart{target = c, select = "value", xAxis = "value"} end unitTest:assertError(error_func, "Attribute 'value' cannot belong to argument 'select' as it was already selected as 'xAxis'.") error_func = function() Chart{target = c, select = {}} end unitTest:assertError(error_func, "Charts must select at least one attribute.") local cell = Cell{ value1 = 2, value2 = 3 } error_func = function() Chart{target = cell, select = {"value1", "value2"}, size = "a"} end unitTest:assertError(error_func, incompatibleTypeMsg("size", "table", "a")) error_func = function() Chart{target = cell, select = {"value1", "value2"}, style = 2} end unitTest:assertError(error_func, incompatibleTypeMsg("style", "table", 2)) error_func = function() Chart{target = cell, select = {"value1", "value2"}, width = -3} end unitTest:assertError(error_func, incompatibleValueMsg("width", "greater than zero", -3)) error_func = function() Chart{target = cell, select = {"value1", "value2"}, size = -3} end unitTest:assertError(error_func, positiveArgumentMsg("size", -3)) error_func = function() Chart{target = Environment{}, select = "value1"} end unitTest:assertError(error_func, "There is no Model instance within the Environment.") local symbolTable = { square = 1, diamond = 2, triangle = 3, ltriangle = 4, -- triangle = 5, dtriangle = 6, -- downwards triangle rtriangle = 7, cross = 8, vcross = 9, -- vertical cross hline = 10, vline = 11, asterisk = 12, star = 13, hexagon = 14, none = 15 } local styleTable = { lines = true, dots = true, none = true, steps = true, sticks = true } local penTable = { solid = 1, dash = 2, dot = 3, dashdot = 4, dashdotdot = 5 } error_func = function() Chart{target = cell, select = {"value1", "value2"}, pen = "abc"} end unitTest:assertError(error_func, switchInvalidArgumentMsg("abc", "pen", penTable)) error_func = function() Chart{target = cell, select = {"value1", "value2"}, pen = "solyd"} end unitTest:assertError(error_func, switchInvalidArgumentSuggestionMsg("solyd", "pen", "solid")) error_func = function() Chart{target = cell, select = {"value1", "value2"}, style = "abc"} end unitTest:assertError(error_func, switchInvalidArgumentMsg("abc", "style", styleTable)) error_func = function() Chart{target = cell, select = {"value1", "value2"}, style = "line"} end unitTest:assertError(error_func, switchInvalidArgumentSuggestionMsg("line", "style", "lines")) error_func = function() Chart{target = cell, select = {"value1", "value2"}, symbol = -3} end unitTest:assertError(error_func, incompatibleTypeMsg("symbol", "table", -3)) error_func = function() Chart{target = cell, select = {"value1", "value2"}, symbol = "abc"} end unitTest:assertError(error_func, switchInvalidArgumentMsg("abc", "symbol", symbolTable)) error_func = function() Chart{target = cell, select = {"value1", "value2"}, symbol = "dyamond"} end unitTest:assertError(error_func, switchInvalidArgumentSuggestionMsg("dyamond", "symbol", "diamond")) local world = CellularSpace{ xdim = 10, value = "aaa" } error_func = function() Chart{target = world} end unitTest:assertError(error_func, "The target does not have at least one valid numeric attribute to be used.") world.msum = 5 error_func = function() Chart{target = world, label = {"sss"}} end unitTest:assertError(error_func, "As select is nil, it is not possible to use label.") error_func = function() Chart{target = world, select = "value"} end unitTest:assertError(error_func, incompatibleTypeMsg("value", "number or function", "value")) cell = Cell{ value = 3 } c = Chart{target = cell} error_func = function() c:save("file.wrongext") end unitTest:assertError(error_func, invalidFileExtensionMsg("#1", "wrongext")) cell = Cell{} for i = 1, 15 do cell["v"..i] = 5 end error_func = function() Chart{target = cell} end unitTest:assertError(error_func, "Argument color is compulsory when using more than 10 attributes.") error_func = function() Chart{target = cell, select = {"v1", "v2", "v3"}, label = {"V1", "V2"}} end unitTest:assertError(error_func, "Arguments 'select' and 'label' should have the same size, got 3 and 2.") error_func = function() Chart{target = cell, select = {"v1", "v2", "v3"}, color = {"red", "blue"}} end unitTest:assertError(error_func, "Arguments 'select' and 'color' should have the same size, got 3 and 2.") error_func = function() Chart{target = cell, select = {"v1", "v2", "v3"}, color = {"red", "blu", "green"}} end unitTest:assertError(error_func, switchInvalidArgumentSuggestionMsg("blu", "color", "blue")) error_func = function() Chart{target = cell, select = {"v1", "v2", "v3"}, color = {"red", "xxx", "green"}} end unitTest:assertError(error_func, "Color 'xxx' was not found. Check the name or use a table with an RGB description.") error_func = function() Chart{target = cell, select = {"v1", "v2", "v3"}, color = {"red", {0, 0}, "green"}} end unitTest:assertError(error_func, "RGB composition should have 3 values, got 2 values in position 2.") error_func = function() Chart{target = cell, select = {"v1", "v2", "v3"}, color = {"red", {0, 0, "red"}, "green"}} end unitTest:assertError(error_func, "All the elements of an RGB composition should be numbers, got 'string' in position 2.") error_func = function() Chart{target = cell, select = {"v1", "v2", "v3"}, value = {"abc"}} end unitTest:assertError(error_func, "Argument 'value' can only be used with CellularSpace or Society, got Cell.") cell = Cell{ value = function() return {a = 2, b = 3, c = 4} end } error_func = function() Chart{target = cell, select = "value"} end unitTest:assertError(error_func, "It is only possible to observe functions that return tables using CellularSpace or Society, got Cell.") cell = Cell{ state = "alive" } local cs = CellularSpace{ xdim = 10, instance = cell } local map = Map{ target = cs, select = "x", min = 0, max = 10, color = {"black", "blue"}, slices = 5 } error_func = function() Chart{ target = map } end unitTest:assertError(error_func, "Charts can only be created from Maps that use grouping 'uniquevalue'.") error_func = function() Chart{ target = cs, select = "state", value = {"dead", "alive"}, color = {"black"} } end unitTest:assertError(error_func, "Arguments 'value' and 'color' should have the same size, got 2 and 1.") error_func = function() Chart{ target = cs, select = "state", color = {"black"} } end unitTest:assertError(error_func, "Argument 'value' is mandatory when observing a function that returns a table.") error_func = function() Chart{ target = cs, select = "state", value = 1, color = {"black"} } end unitTest:assertError(error_func, incompatibleTypeMsg("value", "table", 1)) error_func = function() Chart{ target = cs, select = "state", value = {"dead", 1}, color = {"black"} } end unitTest:assertError(error_func, "Argument 'value' should contain only strings, got number.") -- chart using data local tab = DataFrame{ first = 2000, step = 10, demand = {7, 8, 9, 10}, limit = {0.1, 0.04, 0.3, 0.07} } error_func = function() Chart{ target = tab, select = "limit", xAxis = "demand2", color = "blue" } end unitTest:assertError(error_func, "Selected column 'demand2' for argument 'xAxis' does not exist in the DataFrame.") error_func = function() Chart{ target = tab, select = "limit2", xAxis = "demand", color = "blue" } end unitTest:assertError(error_func, "Selected column 'limit2' does not exist in the DataFrame.") local init = function(model) local contacts = 6 model.timer = Timer{ Event{action = function() local proportion = model.susceptible / (model.susceptible + model.infected + model.recovered) local newInfected = model.infected * contacts * model.probability * proportion local newRecovered = model.infected / model.duration model.susceptible = model.susceptible - newInfected model.recovered = model.recovered + newRecovered model.infected = model.infected + newInfected - newRecovered end}, Event{action = function() if model.infected >= model.maximum then contacts = contacts / 2 return false end end} } end local SIR = Model{ susceptible = 9998, infected = 2, recovered = 0, duration = 2, finalTime = 30, maximum = 1000, probability = 0.25, policy = false, init = init } local e = Environment{ max1000 = SIR{maximum = 1000}, max2000 = SIR{maximum = 2000} } error_func = function() c = Chart{ target = Environment{}, select = "infected" } end unitTest:assertError(error_func, "There is no Model instance within the Environment.") error_func = function() c = Chart{ target = e } end unitTest:assertError(error_func, mandatoryArgumentMsg("select")) error_func = function() c = Chart{ target = e, select = "infected2" } end unitTest:assertError(error_func, "Selected value 'infected2' does not exist.") error_func = function() c = Chart{ target = e, select = "policy" } end unitTest:assertError(error_func, "Selected value 'policy' should be a number or a function, got boolean.") error_func = function() c = Chart{ target = e, select = "infected", color = {"blue", "red", "green"} } end unitTest:assertError(error_func, "Arguments 'select' and 'color' should have the same size, got 2 and 3.") end, save = function(unitTest) local c = Cell{value = 5} local chart = Chart{target = c} clean() local error_func = function() chart:save("file.bmp") end unitTest:assertError(error_func, "Trying to call a function of an observer that was destroyed.") end }
lgpl-3.0
gedads/Neodynamis
scripts/globals/spells/bluemagic/queasyshroom.lua
31
1990
----------------------------------------- -- Spell: Queasyshroom -- Additional effect: Poison. Duration of effect varies with TP -- Spell cost: 20 MP -- Monster Type: Plantoids -- Spell Type: Physical (Piercing) -- Blue Magic Points: 2 -- Stat Bonus: HP-5, MP+5 -- Level: 8 -- Casting Time: 2 seconds -- Recast Time: 15 seconds -- Skillchain Element(s): Dark (can open Transfixion or Detonation; can close Compression or Gravitation) -- Combos: None ----------------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/bluemagic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local params = {}; -- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage params.tpmod = TPMOD_CRITICAL; params.dmgtype = DMGTYPE_PIERCE; params.scattr = SC_DARK; params.numhits = 1; params.multiplier = 1.25; params.tp150 = 1.25; params.tp300 = 1.25; params.azuretp = 1.25; params.duppercap = 8; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.20; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; damage = BluePhysicalSpell(caster, target, spell, params); damage = BlueFinalAdjustments(caster, target, spell, damage, params); local chance = math.random(); if (damage > 0 and chance > 10) then local typeEffect = EFFECT_POISON; target:delStatusEffect(typeEffect); target:addStatusEffect(typeEffect,3,0,getBlueEffectDuration(caster,resist,typeEffect)); end return damage; end;
gpl-3.0
starlightknight/darkstar
scripts/globals/spells/kaustra.lua
12
1382
-------------------------------------- -- Spell: Kaustra -- Consumes 20% of your maximum MP. Relentless -- dark damage slowly devours an enemy. -------------------------------------- require("scripts/globals/settings") require("scripts/globals/status") require("scripts/globals/magic") -------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0 end function onSpellCast(caster,target,spell) local skill = caster:getSkillLevel(dsp.skill.DARK_MAGIC) local dINT = caster:getStat(dsp.mod.INT) - target:getStat(dsp.mod.INT) if (skill > 500) then skill = 500 end if (dINT > 300) then dINT = 300 end local duration = 3 * (1 + (skill / 11)) local base = math.floor((math.floor(0.67 * caster:getMainLvl())/10)*(37 + math.floor(0.67*dINT))) local params = {} params.diff = nil params.attribute = dsp.mod.INT params.skillType = dsp.skill.DARK_MAGIC params.bonus = 0 params.effect = nil local resist = applyResistance(caster, target, spell, params) local dmg = base * resist duration = duration * resist dmg = addBonuses(caster, spell, target, dmg) dmg = adjustForTarget(target,dmg,spell:getElement()) dmg = finalMagicAdjustments(caster,target,spell,dmg) target:addStatusEffect(dsp.effect.KAUSTRA,math.floor(dmg/3),3,duration) return dmg end
gpl-3.0
starlightknight/darkstar
scripts/zones/Southern_San_dOria_[S]/npcs/Louxiard.lua
9
1999
----------------------------------- -- Area: Southern SandOria [S] -- NPC: Louxiard -- !pos -93 -4 49 80 ----------------------------------- require("scripts/globals/quests"); ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(CRYSTAL_WAR,dsp.quest.id.crystalWar.GIFTS_OF_THE_GRIFFON) == QUEST_ACCEPTED and player:getCharVar("GiftsOfGriffonProg") == 2) then local mask = player:getCharVar("GiftsOfGriffonPlumes"); if (trade:hasItemQty(2528,1) and trade:getItemCount() == 1 and not player:getMaskBit(mask,1)) then player:startEvent(26) -- Gifts of Griffon Trade end end end; function onTrigger(player,npc) if (player:getCampaignAllegiance() > 0 and player:getQuestStatus(CRYSTAL_WAR,dsp.quest.id.crystalWar.GIFTS_OF_THE_GRIFFON) == QUEST_AVAILABLE) then player:startEvent(21); -- Gifts of Griffon Quest Start elseif (player:getQuestStatus(CRYSTAL_WAR,dsp.quest.id.crystalWar.GIFTS_OF_THE_GRIFFON) == QUEST_ACCEPTED and player:getCharVar("GiftsOfGriffonProg") == 0) then player:startEvent(22); -- Gifts of Griffon Stage 2 Cutscene elseif (player:getQuestStatus(CRYSTAL_WAR,dsp.quest.id.crystalWar.GIFTS_OF_THE_GRIFFON) == QUEST_ACCEPTED and player:getCharVar("GiftsOfGriffonProg") == 1) then player:startEvent(39); -- Gifts of Griffon Stage 2 Dialogue else player:startEvent(37); -- Default Dialogue end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) if (csid == 21) then player:addQuest(CRYSTAL_WAR,dsp.quest.id.crystalWar.GIFTS_OF_THE_GRIFFON); -- Gifts of Griffon Quest Start elseif (csid == 22) then player:setCharVar("GiftsOfGriffonProg",1); -- Gifts of Griffon Stage 2 elseif (csid == 26) then player:tradeComplete(); local mask = player:getCharVar("GiftsOfGriffonPlumes"); player:setMaskBit(mask,"GiftsOfGriffonPlumes",1,true); end end;
gpl-3.0
mmaxs/pull_requests--ettercap
src/lua/share/scripts/inject_http.lua
12
3282
--- -- Copyright (C) Ryan Linn and Mike Ryan -- -- 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. description = "This is a test script that will inject HTTP stuff"; local eclib = require('eclib') local hook_points = require("hook_points") local shortpacket = require("shortpacket") local shortsession = require("shortsession") local packet = require("packet") -- We have to hook at the filtering point so that we are certain that all the -- dissectors hae run. hook_point = hook_points.filter function split_http(str) local start,finish,header,body = string.find(str, '(.-\r?\n\r?\n)(.*)') return start,finish,header, body end function shrink_http_body(body) local modified_body = string.gsub(body, '>%s*<','><') return modified_body end -- Cache our starts-with function... local sw = shortpacket.data_starts_with("HTTP/1.") -- We only want to match packets that look like HTTP responses. packetrule = function(packet_object) if packet.is_tcp(packet_object) == false then return false end -- Check to see if it starts with the right stuff. return sw(packet_object) end local session_key_func = shortsession.ip_session("inject_http") -- Here's your action. action = function(po) local session_id = session_key_func(po) if not session_id then -- If we don't have session_id, then bail. return nil end --local src_ip = "" --local dst_ip = "" local src_ip = packet.src_ip(po) local dst_ip = packet.dst_ip(po) ettercap.log("inject_http: " .. src_ip .. " -> " .. dst_ip .. "\n") -- Get the full buffer.... reg = ettercap.reg.create_namespace(session_id) local buf = packet.read_data(po) -- Split the header/body up so we can manipulate things. local start,finish,header, body = split_http(buf) -- local start,finish,header,body = string.find(buf, '(.-\r?\n\r?\n)(.*)') if not reg['a'] then ettercap.log("Initial hit\n") reg['a'] = 1 else ettercap.log(tostring(reg['a']) .. " hit\n") reg['a'] = reg['a'] + 1 end if (not (start == nil)) then -- We've got a proper split. local orig_body_len = string.len(body) local modified_body = string.gsub(body, '<body>','<body><script>alert(document.cookie)</script>') -- We've tweaked things, so let's update the data. if (not(modified_body == body)) then ettercap.log("inject_http action : We modified the HTTP response!\n") local modified_data = header .. modified_body -- This takes care of setting the packet data, as well as flagging it -- as modified. packet.set_data(po, modified_data) end end end
gpl-2.0
starlightknight/darkstar
scripts/zones/Upper_Jeuno/npcs/Monberaux.lua
9
5690
----------------------------------- -- Area: Upper Jeuno -- NPC: Monberaux -- Starts and Finishes Quest: The Lost Cardian (finish), The kind cardian (start) -- Involved in Quests: Save the Clock Tower -- !pos -43 0 -1 244 ----------------------------------- local ID = require("scripts/zones/Upper_Jeuno/IDs"); require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/shop"); require("scripts/globals/missions"); require("scripts/globals/quests"); ----------------------------------- function onTrade(player,npc,trade) if (trade:hasItemQty(555,1) == true and trade:getItemCount() == 1) then local a = player:getCharVar("saveTheClockTowerNPCz1"); -- NPC Part1 if (a == 0 or (a ~= 4 and a ~= 5 and a ~= 6 and a ~= 12 and a ~= 20 and a ~= 7 and a ~= 28 and a ~= 13 and a ~= 22 and a ~= 14 and a ~= 21 and a ~= 15 and a ~= 23 and a ~= 29 and a ~= 30 and a ~= 31)) then player:startEvent(91,10 - player:getCharVar("saveTheClockTowerVar")); -- "Save the Clock Tower" Quest end end end; function onTrigger(player,npc) local TheLostCardien = player:getQuestStatus(JEUNO,dsp.quest.id.jeuno.THE_LOST_CARDIAN); local CooksPride = player:getQuestStatus(JEUNO,dsp.quest.id.jeuno.COOK_S_PRIDE); -- COP mission 1-1 if (player:getCurrentMission(COP) == dsp.mission.id.cop.THE_RITES_OF_LIFE and player:getCharVar("PromathiaStatus") == 1) then player:startEvent(10);--10 -- COP mission 1-2 elseif (player:getCurrentMission(COP) == dsp.mission.id.cop.BELOW_THE_ARKS and player:getCharVar("PromathiaStatus") == 0) then player:startEvent(9);--9 -- COP mission 3-5 elseif (player:getCurrentMission(COP) == dsp.mission.id.cop.DARKNESS_NAMED and player:getCharVar("PromathiaStatus") == 0) then player:startEvent(82);-- 82 elseif (player:getCurrentMission(COP) == dsp.mission.id.cop.DARKNESS_NAMED and player:getCharVar("PromathiaStatus") == 3) then player:startEvent(75); --75 elseif (player:getCurrentMission(COP) == dsp.mission.id.cop.THREE_PATHS and player:getCharVar("COP_Tenzen_s_Path") == 2) then player:startEvent(74); --74 elseif (player:getCurrentMission(COP) == dsp.mission.id.cop.THREE_PATHS and player:getCharVar("COP_Tenzen_s_Path") == 4) then player:startEvent(6); elseif (CooksPride == QUEST_COMPLETED and TheLostCardien == QUEST_AVAILABLE and player:getCharVar("theLostCardianVar") == 2) then player:startEvent(33); -- Long CS & Finish Quest "The Lost Cardian" 33 elseif (CooksPride == QUEST_COMPLETED and TheLostCardien == QUEST_AVAILABLE and player:getCharVar("theLostCardianVar") == 3) then player:startEvent(34); -- Shot CS & Finish Quest "The Lost Cardian" 34 elseif (TheLostCardien == QUEST_COMPLETED and player:getQuestStatus(JEUNO,dsp.quest.id.jeuno.THE_KIND_CARDIAN) == QUEST_ACCEPTED) then player:startEvent(32); -- 32 else player:startEvent(28); -- Standard dialog 28 end end; --Door:Infirmary 2 ++ --Door:Infirmary 10 ++ --Door:Infirmary 207 ++ --Door:Infirmary 82 ++ --Door:Infirmary 10059 nonCOP --Door:Infirmary 10060 nonCOP --Door:Infirmary 10205 nonCOP --Door:Infirmary 10061 nonCOP --Door:Infirmary 10062 nonCOP --Door:Infirmary 10207 nonCOP --Door:Infirmary 33 ++ --Door:Infirmary 34 ++ --Door:Infirmary 2 ++ --Door:Infirmary 82 ++ --Door:Infirmary 75 ++ --Door:Infirmary 10060 nonCOP --Door:Infirmary 10205 nonCOP --Tenzen 10011 --Tenzen 10012 function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) if (csid == 6) then player:setCharVar("COP_Tenzen_s_Path",5); elseif (csid == 74) then player:setCharVar("COP_Tenzen_s_Path",3); player:addKeyItem(dsp.ki.ENVELOPE_FROM_MONBERAUX); player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.ENVELOPE_FROM_MONBERAUX); elseif (csid == 10) then player:setCharVar("PromathiaStatus",0); player:addKeyItem(dsp.ki.MYSTERIOUS_AMULET); player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.MYSTERIOUS_AMULET); player:completeMission(COP,dsp.mission.id.cop.THE_RITES_OF_LIFE); player:addMission(COP,dsp.mission.id.cop.BELOW_THE_ARKS); -- start the mission 1-2 player:startEvent(206); -- 206 elseif (csid == 206) then player:startEvent(207); --207 elseif (csid == 82) then player:setCharVar("PromathiaStatus",1); elseif (csid == 75) then player:setCharVar("PromathiaStatus",0); player:completeMission(COP,dsp.mission.id.cop.DARKNESS_NAMED); player:addMission(COP,dsp.mission.id.cop.SHELTERING_DOUBT); elseif (csid == 91) then player:addCharVar("saveTheClockTowerVar", 1); player:addCharVar("saveTheClockTowerNPCz1", 4); elseif (csid == 33 and option == 0 or csid == 34 and option == 0) then player:addTitle(dsp.title.TWOS_COMPANY); player:setCharVar("theLostCardianVar",0); player:addGil(GIL_RATE*2100); player:messageSpecial(ID.text.GIL_OBTAINED,GIL_RATE*2100); player:addKeyItem(dsp.ki.TWO_OF_SWORDS); player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.TWO_OF_SWORDS); -- Two of Swords (Key Item) player:addFame(JEUNO,30); player:completeQuest(JEUNO,dsp.quest.id.jeuno.THE_LOST_CARDIAN); player:addQuest(JEUNO,dsp.quest.id.jeuno.THE_KIND_CARDIAN); -- Start next quest "THE_KING_CARDIAN" elseif (csid == 33 and option == 1) then player:setCharVar("theLostCardianVar",3); end end;
gpl-3.0
ABrandau/OpenRA
mods/d2k/maps/atreides-03b/atreides03b-AI.lua
4
1514
--[[ Copyright 2007-2019 The OpenRA Developers (see AUTHORS) This file is part of OpenRA, which is free software. It is made available to you under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. For more information, see COPYING. ]] AttackGroupSize = { easy = 6, normal = 8, hard = 10 } AttackDelays = { easy = { DateTime.Seconds(4), DateTime.Seconds(7) }, normal = { DateTime.Seconds(2), DateTime.Seconds(5) }, hard = { DateTime.Seconds(1), DateTime.Seconds(3) } } OrdosInfantryTypes = { "light_inf", "light_inf", "light_inf", "trooper", "trooper" } InitAIUnits = function() IdlingUnits[ordos] = Reinforcements.Reinforce(ordos, InitialOrdosReinforcements, OrdosPaths[2]) DefendAndRepairBase(ordos, OrdosBase, 0.75, AttackGroupSize[Difficulty]) end ActivateAI = function() LastHarvesterEaten[ordos] = true Trigger.AfterDelay(0, InitAIUnits) OConyard.Produce(AtreidesUpgrades[1]) local delay = function() return Utils.RandomInteger(AttackDelays[Difficulty][1], AttackDelays[Difficulty][2] + 1) end local toBuild = function() return { Utils.Random(OrdosInfantryTypes) } end local attackThresholdSize = AttackGroupSize[Difficulty] * 2.5 -- Finish the upgrades first before trying to build something Trigger.AfterDelay(DateTime.Seconds(14), function() ProduceUnits(ordos, OBarracks, delay, toBuild, AttackGroupSize[Difficulty], attackThresholdSize) end) end
gpl-3.0
starlightknight/darkstar
scripts/globals/mobskills/promyvion_brume.lua
11
1031
--------------------------------------------- -- Promyvion Brume -- -- Description: AoE Additional effect: poison -- Type: Magical Water -- Utsusemi/Blink absorb: Wipes shadows -- Range: 10' cone -- Notes: Additional effect can be removed with Poisona. --------------------------------------------- require("scripts/globals/settings") require("scripts/globals/status") require("scripts/globals/monstertpmoves") --------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0 end function onMobWeaponSkill(target, mob, skill) local typeEffect = dsp.effect.POISON MobStatusEffectMove(mob, target, typeEffect, 5, 3, 180) local dmgmod = 1 local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*3,dsp.magic.ele.WATER,dmgmod,TP_NO_EFFECT) local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,dsp.attackType.MAGICAL,dsp.damageType.WATER,MOBPARAM_WIPE_SHADOWS) target:takeDamage(dmg, mob, dsp.attackType.MAGICAL, dsp.damageType.WATER) return dmg end
gpl-3.0
gedads/Neodynamis
scripts/globals/items/pipin_hot_popoto.lua
12
1281
----------------------------------------- -- ID: 4282 -- Item: pipin_hot_popoto -- Food Effect: 60Min, All Races ----------------------------------------- -- HP 25 -- Vitality 3 -- HP recovered while healing 1 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,3600,4282); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 25); target:addMod(MOD_VIT, 3); target:addMod(MOD_HPHEAL, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 25); target:delMod(MOD_VIT, 3); target:delMod(MOD_HPHEAL, 1); end;
gpl-3.0
starlightknight/darkstar
scripts/globals/mobskills/final_retribution.lua
11
1112
--------------------------------------------- -- Final Retribution -- Family: Corse -- Description: Damages enemies in an area of effect. Additional effect: Stun -- Type: Physical -- Utsusemi/Blink absorb: 1-3 shadows -- Range: Radial -- Notes: Only used by some notorious monsters like Xolotl. --------------------------------------------- require("scripts/globals/settings") require("scripts/globals/status") require("scripts/globals/monstertpmoves") --------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0 end function onMobWeaponSkill(target, mob, skill) local numhits = 1 local accmod = 1 local dmgmod = 3.2 local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT) local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,dsp.attackType.PHYSICAL,dsp.damageType.SLASHING,MOBPARAM_3_SHADOW) local typeEffect = dsp.effect.STUN MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, 1, 0, 4) target:takeDamage(dmg, mob, dsp.attackType.PHYSICAL, dsp.damageType.SLASHING) return dmg end
gpl-3.0
mmaxs/pull_requests--ettercap
src/lua/share/third-party/stdlib/src/xml.lua
17
2787
-- XML extensions to string module. -- @class module -- @name xml require "base" require "string_ext" --- Write a table as XML. -- The input format is assumed to be that output by luaexpat. -- @param t table to print. -- In each element, tag is its name, attr is the table of attributes, -- and the sub-elements are held in the integer keys -- @param indent indent between levels (default: <code>"\t"</code>) -- @param spacing space before every line -- @returns XML string function string.writeXML (t, indent, spacing) indent = indent or "\t" spacing = spacing or "" return render (t, function (x) spacing = spacing .. indent if x.tag then local s = "<" .. x.tag if type (x.attr) == "table" then for i, v in pairs (x.attr) do if type (i) ~= "number" then -- luaexpat gives names of attributes in list elements s = s .. " " .. tostring (i) .. "=" .. string.format ("%q", tostring (v)) end end end if #x == 0 then s = s .. " /" end s = s .. ">" return s end return "" end, function (x) spacing = string.gsub (spacing, indent .. "$", "") if x.tag and #x > 0 then return spacing .. "</" .. x.tag .. ">" end return "" end, function (s) s = tostring (s) s = string.gsub (s, "&([%S]+)", function (s) if not string.match (s, "^#?%w+;") then return "&amp;" .. s else return "&" .. s end end) s = string.gsub (s, "<", "&lt;") s = string.gsub (s, ">", "&gt;") return s end, function (x, i, v, is, vs) local s = "" if type (i) == "number" then s = spacing .. vs end return s end, function (_, i, _, j) if type (i) == "number" or type (j) == "number" then return "\n" end return "" end) end
gpl-2.0
mynameiscraziu/sickout21
plugins/ingroup.lua
14
27651
do local function check_member(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)] = { 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 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,{receiver=receiver, data=data, msg = msg}) end end 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 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.."\nflood sensitivity : "..NUM_MSG_MAX 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_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 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) 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 'Group has been added.' 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 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 username_id(cb_extra, success, result) local mod_cmd = cb_extra.mod_cmd local receiver = cb_extra.receiver local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if mod_cmd == 'promote' then return promote(receiver, member_username, member_id) elseif mod_cmd == 'demote' then return demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function modlist(msg) local data = load_data(_config.moderation.data) if not data[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 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 .. '- @'..v..' [' ..k.. '] \n' end return message end local function callbackres(extra, success, result) local user = result.id local name = 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 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' then -- print("group "..msg.to.print_name.."("..msg.to.id..") added") --return modadd(msg) -- end if matches[1] == 'chat_created' and msg.from.id == 0 then return automodadd(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_add_user' then if not msg.service then return "Are you trying to troll me?" end local receiver = 'user#id'..msg.action.user.id local data_cat = 'rules' if not data[tostring(msg.to.id)][data_cat] then return false end local rules = data[tostring(msg.to.id)][data_cat] local rules = 'Welcome to "' .. string.gsub(msg.to.print_name, '_', ' ') ..'" this group has rules that you should follow:\n'..rules savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..msg.action.user.id) send_large_msg(receiver, rules) 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) if msg.from.id ~= 0 and not is_owner(msg) then chat_add_user(chat, user, ok_cb, true) end 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 matches[2] then if not is_owner(msg) then return "Only owner can promote" end local member = string.gsub(matches[2], "@", "") local mod_cmd = 'promote' savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member) chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'demote' and matches[2] then if not is_owner(msg) then return "Only owner can demote" end if string.gsub(matches[2], "@", "") == msg.from.username then return "You can't demote yourself" end local member = string.gsub(matches[2], "@", "") local mod_cmd = 'demote' savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member) chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) 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 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 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] == 'newlink' then if not is_momod(msg) then return "For moderators only!" end local function callback (extra , success, result) local receiver = 'chat#'..msg.to.id send_large_msg(receiver, "Created a new 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' 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] == '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] == 'help' then if not is_momod(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 end end return { patterns = { -- "^[!/](add)$", "^[!/](rules)$", "^[!/](about)$", "^[!/](setname) (.*)$", "^[!/](setphoto)$", "^[!/](promote) (.*)$", "^[!/](help)$", "^[!/](clean) (.*)$", "^[!/](demote) (.*)$", "^[!/](set) ([^%s]+) (.*)$", "^[!/](lock) (.*)$", "^[!/](setowner) (%d+)$", "^[!/](owner)$", "^[!/](res) (.*)$", "^[!/](setgpowner) (%d+) (%d+)$",-- (group id) (owner id) "^[!/](unlock) (.*)$", "^[!/](setflood) (%d+)$", "^[!/](settings)$", "^[!/](modlist)$", "^[!/](newlink)$", "^[!/](link)$", "%[(photo)%]", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
jszakmeister/packages
utils/prometheus-node-exporter-lua/files/usr/lib/lua/prometheus-collectors/cpu.lua
74
1429
-- stat/cpu collector local function scrape() local stat = get_contents("/proc/stat") -- system boot time, seconds since epoch metric("node_boot_time_seconds", "gauge", nil, string.match(stat, "btime ([0-9]+)")) -- context switches since boot (all CPUs) metric("node_context_switches_total", "counter", nil, string.match(stat, "ctxt ([0-9]+)")) -- cpu times, per CPU, per mode local cpu_mode = {"user", "nice", "system", "idle", "iowait", "irq", "softirq", "steal", "guest", "guest_nice"} local i = 0 local cpu_metric = metric("node_cpu_seconds_total", "counter") while true do local cpu = {string.match(stat, "cpu"..i.." (%d+) (%d+) (%d+) (%d+) (%d+) (%d+) (%d+) (%d+) (%d+) (%d+)")} if #cpu ~= 10 then break end for ii, mode in ipairs(cpu_mode) do cpu_metric({cpu="cpu"..i, mode=mode}, cpu[ii] / 100) end i = i + 1 end -- interrupts served metric("node_intr_total", "counter", nil, string.match(stat, "intr ([0-9]+)")) -- processes forked metric("node_forks_total", "counter", nil, string.match(stat, "processes ([0-9]+)")) -- processes running metric("node_procs_running_total", "gauge", nil, string.match(stat, "procs_running ([0-9]+)")) -- processes blocked for I/O metric("node_procs_blocked_total", "gauge", nil, string.match(stat, "procs_blocked ([0-9]+)")) end return { scrape = scrape }
gpl-2.0
strava/thrift
lib/lua/TServer.lua
11
4181
-- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you 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. -- require 'Thrift' require 'TFramedTransport' require 'TBinaryProtocol' -- TServer TServer = __TObject:new{ __type = 'TServer' } -- 2 possible constructors -- 1. {processor, serverTransport} -- 2. {processor, serverTransport, transportFactory, protocolFactory} function TServer:new(args) if ttype(args) ~= 'table' then error('TServer must be initialized with a table') end if args.processor == nil then terror('You must provide ' .. ttype(self) .. ' with a processor') end if args.serverTransport == nil then terror('You must provide ' .. ttype(self) .. ' with a serverTransport') end -- Create the object local obj = __TObject.new(self, args) if obj.transportFactory then obj.inputTransportFactory = obj.transportFactory obj.outputTransportFactory = obj.transportFactory obj.transportFactory = nil else obj.inputTransportFactory = TFramedTransportFactory:new{} obj.outputTransportFactory = obj.inputTransportFactory end if obj.protocolFactory then obj.inputProtocolFactory = obj.protocolFactory obj.outputProtocolFactory = obj.protocolFactory obj.protocolFactory = nil else obj.inputProtocolFactory = TBinaryProtocolFactory:new{} obj.outputProtocolFactory = obj.inputProtocolFactory end -- Set the __server variable in the handler so we can stop the server obj.processor.handler.__server = self return obj end function TServer:setServerEventHandler(handler) self.serverEventHandler = handler end function TServer:_clientBegin(content, iprot, oprot) if self.serverEventHandler and type(self.serverEventHandler.clientBegin) == 'function' then self.serverEventHandler:clientBegin(iprot, oprot) end end function TServer:_preServe() if self.serverEventHandler and type(self.serverEventHandler.preServe) == 'function' then self.serverEventHandler:preServe(self.serverTransport:getSocketInfo()) end end function TServer:setExceptionHandler(exceptionHandler) self.exceptionHandler = exceptionHandler end function TServer:_handleException(err) if string.find(err, 'TTransportException') == nil then if self.exceptionHandler then self.exceptionHandler(err) else print(err) end end end function TServer:serve() end function TServer:handle(client) local itrans, otrans = self.inputTransportFactory:getTransport(client), self.outputTransportFactory:getTransport(client) local iprot, oprot = self.inputProtocolFactory:getProtocol(itrans), self.outputProtocolFactory:getProtocol(otrans) self:_clientBegin(iprot, oprot) while true do local ret, err = pcall(self.processor.process, self.processor, iprot, oprot) if ret == false and err then if not string.find(err, "TTransportException") then self:_handleException(err) end break end end itrans:close() otrans:close() end function TServer:close() self.serverTransport:close() end -- TSimpleServer -- Single threaded server that handles one transport (connection) TSimpleServer = __TObject:new(TServer, { __type = 'TSimpleServer', __stop = false }) function TSimpleServer:serve() self.serverTransport:listen() self:_preServe() while not self.__stop do client = self.serverTransport:accept() self:handle(client) end self:close() end function TSimpleServer:stop() self.__stop = true end
apache-2.0
gedads/Neodynamis
scripts/globals/mobskills/everyones_grudge.lua
36
1591
--------------------------------------------- -- Everyones Grudge -- -- Notes: Invokes collective hatred to spite a single target. -- Damage done is 5x the amount of tonberries you have killed! For NM's using this it is 50 x damage. --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) if (mob:isMobType(MOBTYPE_NOTORIOUS)) then return 1; end return 0; end; function onMobWeaponSkill(target, mob, skill) local realDmg = 0; local mobID = mob:getID(); local power = 5; if (target:getID() > 100000) then realDmg = power * math.random(30,100); else realDmg = power * target:getVar("EVERYONES_GRUDGE_KILLS"); -- Damage is 5 times the amount you have killed if (mobID == 17428677 or mobID == 17433008 or mobID == 17433006 or mobID == 17433009 or mobID == 17432994 or mobID == 17433007 or mobID == 17428813 or mobID == 17432659 or mobID == 17432846 or mobID == 17428809) then realDmg = realDmg * 10; -- Sets the Multiplyer to 50 for NM's elseif (mobID == 17432799 or mobID == 17428611 or MobID == 17428554 or mobID == 17428751 or mobID == 17432609 or mobID == 16814432 or mobID == 17432624 or mobID == 17285526 or mobID == 17285460) then realDmg = realDmg * 10; -- Sets the Multiplyer to 50 for NM's , staggered list end end target:delHP(realDmg); return realDmg; end;
gpl-3.0
starlightknight/darkstar
scripts/globals/spells/foe_requiem.lua
12
1829
----------------------------------------- -- Spell: Foe Requiem ----------------------------------------- require("scripts/globals/status") require("scripts/globals/magic") require("scripts/globals/msg") ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0 end function onSpellCast(caster,target,spell) local effect = dsp.effect.REQUIEM local duration = 63 local power = 1 local pCHR = caster:getStat(dsp.mod.CHR) local mCHR = target:getStat(dsp.mod.CHR) local dCHR = (pCHR - mCHR) local params = {} params.diff = nil params.attribute = dsp.mod.CHR params.skillType = dsp.skill.SINGING params.bonus = 0 params.effect = nil resm = applyResistance(caster, target, spell, params) if (resm < 0.5) then spell:setMsg(dsp.msg.basic.MAGIC_RESIST) -- resist message return 1 end local iBoost = caster:getMod(dsp.mod.REQUIEM_EFFECT) + caster:getMod(dsp.mod.ALL_SONGS_EFFECT) power = power + iBoost if (caster:hasStatusEffect(dsp.effect.SOUL_VOICE)) then power = power * 2 elseif (caster:hasStatusEffect(dsp.effect.MARCATO)) then power = power * 1.5 end caster:delStatusEffect(dsp.effect.MARCATO) duration = duration * ((iBoost * 0.1) + (caster:getMod(dsp.mod.SONG_DURATION_BONUS)/100) + 1) if (caster:hasStatusEffect(dsp.effect.TROUBADOUR)) then duration = duration * 2 end -- Try to overwrite weaker slow / haste if (canOverwrite(target, effect, power)) then -- overwrite them target:delStatusEffect(effect) target:addStatusEffect(effect,power,3,duration) spell:setMsg(dsp.msg.basic.MAGIC_ENFEEB) else spell:setMsg(dsp.msg.basic.MAGIC_NO_EFFECT) -- no effect end return effect end
gpl-3.0
ld-test/turbo
examples/websocketclient.lua
8
2146
--- Turbo.lua WebSocketClient example. -- -- Copyright 2013 John Abrahamsen -- -- 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. _G.TURBO_SSL = true -- SSL must be enabled for WebSocket support! local turbo = require "turbo" turbo.ioloop.instance():add_callback(function() turbo.websocket.WebSocketClient("ws://127.0.0.1:8888/ws", { on_headers = function(self, headers) -- Review headers recieved from the WebSocket server. -- You can e.g drop the request if the response headers -- are not satisfactory with self:close(). end, modify_headers = function(self, headers) -- Modify outgoing headers before they are sent. -- headers parameter are a instance of httputil.HTTPHeader. end, on_connect = function(self) -- Called when the client has successfully opened a WebSocket -- connection to the server. -- When the connection is established you can write a message: self:write_message("Hello World!") end, on_message = function(self, msg) -- Print the incoming message. print(msg) self:close() end, on_close = function(self) -- I am called when connection is closed. Both gracefully and -- not gracefully. end, on_error = function(self, code, reason) -- I am called whenever there is a error with the WebSocket. -- code are defined in turbo.websocket.errors. reason are -- a string representation of the same error. end }) end):start()
apache-2.0
starlightknight/darkstar
scripts/globals/abilities/box_step.lua
12
7949
----------------------------------- -- Ability: Box Step -- Lowers target's defense. If successful, you will earn two Finishing Moves. -- Obtained: Dancer Level 30 -- TP Required: 10% -- Recast Time: 00:05 -- Duration: First Step lasts 1 minute, each following Step extends its current duration by 30 seconds. ----------------------------------- require("scripts/globals/weaponskills") require("scripts/globals/settings") require("scripts/globals/status") require("scripts/globals/msg") ----------------------------------- function onAbilityCheck(player,target,ability) if (player:getAnimation() ~= 1) then return dsp.msg.basic.REQUIRES_COMBAT,0 else if (player:hasStatusEffect(dsp.effect.TRANCE)) then return 0,0 elseif (player:getTP() < 100) then return dsp.msg.basic.NOT_ENOUGH_TP,0 else return 0,0 end end end function onUseAbility(player,target,ability,action) -- Only remove TP if the player doesn't have Trance. if not player:hasStatusEffect(dsp.effect.TRANCE) then player:delTP(100) end local hit = 2 local effect = 1 if math.random() <= getHitRate(player,target,true,player:getMod(dsp.mod.STEP_ACCURACY)) then hit = 6 local mjob = player:getMainJob() local daze = 1 if (mjob == 19) then if (target:hasStatusEffect(dsp.effect.SLUGGISH_DAZE_1)) then local duration = target:getStatusEffect(dsp.effect.SLUGGISH_DAZE_1):getDuration() target:delStatusEffectSilent(dsp.effect.SLUGGISH_DAZE_1) if (player:hasStatusEffect(dsp.effect.PRESTO)) then target:addStatusEffect(dsp.effect.SLUGGISH_DAZE_3,1,0,duration+30) daze = 3 effect = 3 else target:addStatusEffect(dsp.effect.SLUGGISH_DAZE_2,1,0,duration+30) daze = 2 effect = 2 end elseif (target:hasStatusEffect(dsp.effect.SLUGGISH_DAZE_2)) then local duration = target:getStatusEffect(dsp.effect.SLUGGISH_DAZE_2):getDuration() target:delStatusEffectSilent(dsp.effect.SLUGGISH_DAZE_2) if (player:hasStatusEffect(dsp.effect.PRESTO)) then target:addStatusEffect(dsp.effect.SLUGGISH_DAZE_4,1,0,duration+30) daze = 3 effect = 4 else target:addStatusEffect(dsp.effect.SLUGGISH_DAZE_3,1,0,duration+30) daze = 2 effect = 3 end elseif (target:hasStatusEffect(dsp.effect.SLUGGISH_DAZE_3)) then local duration = target:getStatusEffect(dsp.effect.SLUGGISH_DAZE_3):getDuration() target:delStatusEffectSilent(dsp.effect.SLUGGISH_DAZE_3) if (player:hasStatusEffect(dsp.effect.PRESTO)) then target:addStatusEffect(dsp.effect.SLUGGISH_DAZE_5,1,0,duration+30) daze = 3 effect = 5 else target:addStatusEffect(dsp.effect.SLUGGISH_DAZE_4,1,0,duration+30) daze = 2 effect = 4 end elseif (target:hasStatusEffect(dsp.effect.SLUGGISH_DAZE_4)) then local duration = target:getStatusEffect(dsp.effect.SLUGGISH_DAZE_4):getDuration() target:delStatusEffectSilent(dsp.effect.SLUGGISH_DAZE_4) if (player:hasStatusEffect(dsp.effect.PRESTO)) then daze = 3 else daze = 2 end target:addStatusEffect(dsp.effect.SLUGGISH_DAZE_5,1,0,duration+30) effect = 5 elseif (target:hasStatusEffect(dsp.effect.SLUGGISH_DAZE_5)) then local duration = target:getStatusEffect(dsp.effect.SLUGGISH_DAZE_5):getDuration() target:delStatusEffectSilent(dsp.effect.SLUGGISH_DAZE_5) target:addStatusEffect(dsp.effect.SLUGGISH_DAZE_5,1,0,duration+30) daze = 1 effect = 5 else if (player:hasStatusEffect(dsp.effect.PRESTO)) then target:addStatusEffect(dsp.effect.SLUGGISH_DAZE_2,1,0,60) daze = 3 effect = 2 else target:addStatusEffect(dsp.effect.SLUGGISH_DAZE_1,1,0,60) daze = 2 effect = 1 end end else if (target:hasStatusEffect(dsp.effect.SLUGGISH_DAZE_1)) then local duration = target:getStatusEffect(dsp.effect.SLUGGISH_DAZE_1):getDuration() target:delStatusEffectSilent(dsp.effect.SLUGGISH_DAZE_1) target:addStatusEffect(dsp.effect.SLUGGISH_DAZE_2,1,0,duration+30) effect = 2 elseif (target:hasStatusEffect(dsp.effect.SLUGGISH_DAZE_2)) then local duration = target:getStatusEffect(dsp.effect.SLUGGISH_DAZE_2):getDuration() target:delStatusEffectSilent(dsp.effect.SLUGGISH_DAZE_2) target:addStatusEffect(dsp.effect.SLUGGISH_DAZE_3,1,0,duration+30) effect = 3 elseif (target:hasStatusEffect(dsp.effect.SLUGGISH_DAZE_3)) then local duration = target:getStatusEffect(dsp.effect.SLUGGISH_DAZE_3):getDuration() target:delStatusEffectSilent(dsp.effect.SLUGGISH_DAZE_3) target:addStatusEffect(dsp.effect.SLUGGISH_DAZE_4,1,0,duration+30) effect = 4 elseif (target:hasStatusEffect(dsp.effect.SLUGGISH_DAZE_4)) then local duration = target:getStatusEffect(dsp.effect.SLUGGISH_DAZE_4):getDuration() target:delStatusEffectSilent(dsp.effect.SLUGGISH_DAZE_4) target:addStatusEffect(dsp.effect.SLUGGISH_DAZE_5,1,0,duration+30) effect = 5 elseif (target:hasStatusEffect(dsp.effect.SLUGGISH_DAZE_5)) then local duration = target:getStatusEffect(dsp.effect.SLUGGISH_DAZE_5):getDuration() target:delStatusEffectSilent(dsp.effect.SLUGGISH_DAZE_5) target:addStatusEffect(dsp.effect.SLUGGISH_DAZE_5,1,0,duration+30) effect = 5 else target:addStatusEffect(dsp.effect.SLUGGISH_DAZE_1,1,0,60) effect = 1 end end if (player:hasStatusEffect(dsp.effect.FINISHING_MOVE_1)) then player:delStatusEffectSilent(dsp.effect.FINISHING_MOVE_1) player:addStatusEffect(dsp.effect.FINISHING_MOVE_1+daze,1,0,7200) elseif (player:hasStatusEffect(dsp.effect.FINISHING_MOVE_2)) then player:delStatusEffectSilent(dsp.effect.FINISHING_MOVE_2) player:addStatusEffect(dsp.effect.FINISHING_MOVE_2+daze,1,0,7200) elseif (player:hasStatusEffect(dsp.effect.FINISHING_MOVE_3)) then player:delStatusEffectSilent(dsp.effect.FINISHING_MOVE_3) if (daze > 2) then daze = 2 end player:addStatusEffect(dsp.effect.FINISHING_MOVE_3+daze,1,0,7200) elseif (player:hasStatusEffect(dsp.effect.FINISHING_MOVE_4)) then player:delStatusEffectSilent(dsp.effect.FINISHING_MOVE_4) player:addStatusEffect(dsp.effect.FINISHING_MOVE_5,1,0,7200) elseif (player:hasStatusEffect(dsp.effect.FINISHING_MOVE_5)) then else player:addStatusEffect(dsp.effect.FINISHING_MOVE_1 - 1 + daze,1,0,7200) end else ability:setMsg(dsp.msg.basic.JA_MISS) end action:animation(target:getID(), getStepAnimation(player:getWeaponSkillType(dsp.slot.MAIN))) action:speceffect(target:getID(), hit) return effect end
gpl-3.0
thel3l/kali-nethunter
nethunter-installer/update/system/bin/scripts/test_t55x7_fsk.lua
5
2638
local cmds = require('commands') local getopt = require('getopt') local bin = require('bin') local utils = require('utils') example =[[ 1. script run test_t55x7_fsk ]] author = "Iceman" usage = "script run test_t55x7_fsk" desc =[[ This script will program a T55x7 TAG with the configuration: block 0x00 data 0x000100 The outlined procedure is as following: --ASK 00 00 80 40 -- max 2 blocks -- FSK1 -- bit rate "lf t55xx write 0 00007040" "lf t55xx detect" "lf t55xx info" Loop: change the configuretion block 0 with: -xx 00 xxxx = RF/8 -xx 04 xxxx = RF/16 -xx 08 xxxx = RF/32 -xx 0C xxxx = RF/40 -xx 10 xxxx = RF/50 -xx 14 xxxx = RF/64 -xx 18 xxxx = RF/100 -xx 1C xxxx = RF/128 testsuit for the ASK/MANCHESTER demod Arguments: -h : this help ]] local TIMEOUT = 2000 -- Shouldn't take longer than 2 seconds local DEBUG = true -- the debug flag --BLOCK 0 = 00008040 FSK local config1 = '00' local config2 = '040' local procedurecmds = { [1] = '%s%02X%X%s', [2] = 'lf t55xx detect', [3] = 'lf t55xx info', } --- -- A debug printout-function function dbg(args) if not DEBUG then return end if type(args) == "table" then local i = 1 while args[i] do dbg(args[i]) i = i+1 end else print("###", args) end end --- -- This is only meant to be used when errors occur function oops(err) print("ERROR: ",err) end --- -- Usage help function help() print(desc) print("Example usage") print(example) end -- -- Exit message function ExitMsg(msg) print( string.rep('--',20) ) print( string.rep('--',20) ) print(msg) print() end function test(modulation) local y for y = 0x0, 0x1d, 0x4 do for _ = 1, #procedurecmds do local pcmd = procedurecmds[_] if #pcmd == 0 then elseif _ == 1 then local config = pcmd:format(config1, y, modulation, config2) dbg(('lf t55xx write 0 %s'):format(config)) config = tonumber(config,16) local writecmd = Command:new{cmd = cmds.CMD_T55XX_WRITE_BLOCK, arg1 = config} local err = core.SendCommand(writecmd:getBytes()) if err then return oops(err) end local response = core.WaitForResponseTimeout(cmds.CMD_ACK,TIMEOUT) else dbg(pcmd) core.console( pcmd ) end end core.clearCommandBuffer() end print( string.rep('--',20) ) end local function main(args) print( string.rep('--',20) ) print( string.rep('--',20) ) -- Arguments for the script for o, arg in getopt.getopt(args, 'h') do if o == "h" then return help() end end core.clearCommandBuffer() test(4) test(5) test(6) test(7) print( string.rep('--',20) ) end main(args)
gpl-2.0
starlightknight/darkstar
scripts/globals/items/behemoth_steak.lua
11
1728
----------------------------------------- -- ID: 6464 -- Item: behemoth_steak -- Food Effect: 180Min, All Races ----------------------------------------- -- HP +40 -- STR +7 -- DEX +7 -- INT -3 -- Attack +23% (cap 160) -- Ranged Attack +23% (cap 160) -- Triple Attack +1% -- Lizard Killer +4 -- hHP +4 ----------------------------------------- require("scripts/globals/status") require("scripts/globals/msg") ----------------------------------------- function onItemCheck(target) local result = 0 if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then result = dsp.msg.basic.IS_FULL end return result end function onItemUse(target) target:addStatusEffect(dsp.effect.FOOD,0,0,10800,6464) end function onEffectGain(target,effect) target:addMod(dsp.mod.HP, 40) target:addMod(dsp.mod.STR, 7) target:addMod(dsp.mod.DEX, 7) target:addMod(dsp.mod.INT, -3) target:addMod(dsp.mod.FOOD_ATTP, 23) target:addMod(dsp.mod.FOOD_ATT_CAP, 160) target:addMod(dsp.mod.FOOD_RATTP, 23) target:addMod(dsp.mod.FOOD_RATT_CAP, 160) target:addMod(dsp.mod.TRIPLE_ATTACK, 1) target:addMod(dsp.mod.LIZARD_KILLER, 4) target:addMod(dsp.mod.HPHEAL, 4) end function onEffectLose(target, effect) target:delMod(dsp.mod.HP, 40) target:delMod(dsp.mod.STR, 7) target:delMod(dsp.mod.DEX, 7) target:delMod(dsp.mod.INT, -3) target:delMod(dsp.mod.FOOD_ATTP, 23) target:delMod(dsp.mod.FOOD_ATT_CAP, 160) target:delMod(dsp.mod.FOOD_RATTP, 23) target:delMod(dsp.mod.FOOD_RATT_CAP, 160) target:delMod(dsp.mod.TRIPLE_ATTACK, 1) target:delMod(dsp.mod.LIZARD_KILLER, 4) target:delMod(dsp.mod.HPHEAL, 4) end
gpl-3.0
Craige/prosody-modules
mod_carbons/mod_carbons.lua
32
5142
-- XEP-0280: Message Carbons implementation for Prosody -- Copyright (C) 2011 Kim Alvefur -- -- This file is MIT/X11 licensed. local st = require "util.stanza"; local jid_bare = require "util.jid".bare; local xmlns_carbons = "urn:xmpp:carbons:2"; local xmlns_carbons_old = "urn:xmpp:carbons:1"; local xmlns_carbons_really_old = "urn:xmpp:carbons:0"; local xmlns_forward = "urn:xmpp:forward:0"; local full_sessions, bare_sessions = full_sessions, bare_sessions; local function toggle_carbons(event) local origin, stanza = event.origin, event.stanza; local state = stanza.tags[1].attr.mode or stanza.tags[1].name; module:log("debug", "%s %sd carbons", origin.full_jid, state); origin.want_carbons = state == "enable" and stanza.tags[1].attr.xmlns; return origin.send(st.reply(stanza)); end module:hook("iq-set/self/"..xmlns_carbons..":disable", toggle_carbons); module:hook("iq-set/self/"..xmlns_carbons..":enable", toggle_carbons); -- COMPAT module:hook("iq-set/self/"..xmlns_carbons_old..":disable", toggle_carbons); module:hook("iq-set/self/"..xmlns_carbons_old..":enable", toggle_carbons); module:hook("iq-set/self/"..xmlns_carbons_really_old..":carbons", toggle_carbons); local function message_handler(event, c2s) local origin, stanza = event.origin, event.stanza; local orig_type = stanza.attr.type; local orig_from = stanza.attr.from; local orig_to = stanza.attr.to; if not (orig_type == nil or orig_type == "normal" or orig_type == "chat") then return -- No carbons for messages of type error or headline end -- Stanza sent by a local client local bare_jid = jid_bare(orig_from); local target_session = origin; local top_priority = false; local user_sessions = bare_sessions[bare_jid]; -- Stanza about to be delivered to a local client if not c2s then bare_jid = jid_bare(orig_to); target_session = full_sessions[orig_to]; user_sessions = bare_sessions[bare_jid]; if not target_session and user_sessions then -- The top resources will already receive this message per normal routing rules, -- so we are going to skip them in order to avoid sending duplicated messages. local top_resources = user_sessions.top_resources; top_priority = top_resources and top_resources[1].priority end end if not user_sessions then module:log("debug", "Skip carbons for offline user"); return -- No use in sending carbons to an offline user end if stanza:get_child("private", xmlns_carbons) then if not c2s then stanza:maptags(function(tag) if not ( tag.attr.xmlns == xmlns_carbons and tag.name == "private" ) then return tag; end end); end module:log("debug", "Message tagged private, ignoring"); return elseif stanza:get_child("no-copy", "urn:xmpp:hints") then module:log("debug", "Message has no-copy hint, ignoring"); return elseif stanza:get_child("x", "http://jabber.org/protocol/muc#user") then module:log("debug", "MUC PM, ignoring"); return end -- Create the carbon copy and wrap it as per the Stanza Forwarding XEP local copy = st.clone(stanza); copy.attr.xmlns = "jabber:client"; local carbon = st.message{ from = bare_jid, type = orig_type, } :tag(c2s and "sent" or "received", { xmlns = xmlns_carbons }) :tag("forwarded", { xmlns = xmlns_forward }) :add_child(copy):reset(); -- COMPAT local carbon_old = st.message{ from = bare_jid, type = orig_type, } :tag(c2s and "sent" or "received", { xmlns = xmlns_carbons_old }):up() :tag("forwarded", { xmlns = xmlns_forward }) :add_child(copy):reset(); -- COMPAT local carbon_really_old = st.clone(stanza) :tag(c2s and "sent" or "received", { xmlns = xmlns_carbons_really_old }):up() user_sessions = user_sessions and user_sessions.sessions; for _, session in pairs(user_sessions) do -- Carbons are sent to resources that have enabled it if session.want_carbons -- but not the resource that sent the message, or the one that it's directed to and session ~= target_session -- and isn't among the top resources that would receive the message per standard routing rules and (c2s or session.priority ~= top_priority) -- don't send v0 carbons (or copies) for c2s and (not c2s or session.want_carbons ~= xmlns_carbons_really_old) then carbon.attr.to = session.full_jid; module:log("debug", "Sending carbon to %s", session.full_jid); local carbon = session.want_carbons == xmlns_carbons_old and carbon_old -- COMPAT or session.want_carbons == xmlns_carbons_really_old and carbon_really_old -- COMPAT or carbon; session.send(carbon); end end end local function c2s_message_handler(event) return message_handler(event, true) end -- Stanzas sent by local clients module:hook("pre-message/host", c2s_message_handler, 1); module:hook("pre-message/bare", c2s_message_handler, 1); module:hook("pre-message/full", c2s_message_handler, 1); -- Stanzas to local clients module:hook("message/bare", message_handler, 1); module:hook("message/full", message_handler, 1); module:add_feature(xmlns_carbons); module:add_feature(xmlns_carbons_old); if module:get_option_boolean("carbons_v0") then module:add_feature(xmlns_carbons_really_old); end
mit
gedads/Neodynamis
scripts/zones/Abyssea-Konschtat/mobs/Turul.lua
17
2144
----------------------------------- -- Area: Abyssea - Konschtat (15) -- Mob: Turul ----------------------------------- require("scripts/globals/status"); mixins = { require("scripts/mixins/families/amphiptere") } ----------------------------------- -- onMobInitialize ----------------------------------- function onMobInitialize(mob) end; ----------------------------------- -- onMobSpawn ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob, target) end; ----------------------------------- -- onMobDisengage ----------------------------------- function onMobDisengage(mob) end; ----------------------------------- -- onMobFight ----------------------------------- function onMobFight(mob,target) -- Uncertain of threshold. Going with 50% for now. -- (possibly varies, perhaps is simply lower HP = greater cast chance?) if (mob:getHPP() <=50) then mob:setMobMod(MOBMOD_SPELL_LIST, 175); else -- I'm assuming that if it heals up, it goes back to the other spell list. mob:setMobMod(MOBMOD_SPELL_LIST, 174); -- This 'else' can be removed if that isn't the case, and a localVar added so it only execs once. end end; ------------------------------------ -- onSpellPrecast ------------------------------------ function onSpellPrecast(mob, spell) --[[ Todo: "Turul will often cast Thunder based spells on itself to recover HP." One way of handling this would be treating ele nuke heals like we do melee special (use its own list) and setting absorb element 100% chance. This would let us use the AI's already existing "heal chance" https://github.com/DarkstarProject/darkstar/blob/638b9018e563f98ceddf05d642b6e3db055ccc36/src/map/mob_spell_container.cpp#L124 ]] end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) end; ----------------------------------- -- onMobDespawn ----------------------------------- function onMobDespawn(mob) end;
gpl-3.0
starlightknight/darkstar
scripts/zones/Temenos/bcnms/central_temenos_1st_floor.lua
9
1338
----------------------------------- -- Area: Temenos -- Name: Central Temenos 1st Floor ----------------------------------- require("scripts/globals/limbus"); require("scripts/globals/battlefield") require("scripts/globals/keyitems"); -- After registering the BCNM via bcnmRegister(bcnmid) function onBattlefieldTick(battlefield, tick) dsp.battlefield.onBattlefieldTick(battlefield, tick) end function onBattlefieldRegister(player,battlefield) SetServerVariable("[C_Temenos_1st]UniqueID",os.time()); HideArmouryCrates(Central_Temenos_1st_Floor,TEMENOS); HideTemenosDoor(Central_Temenos_1st_Floor); end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBattlefieldEnter(player,battlefield) player:setCharVar("characterLimbusKey",GetServerVariable("[C_Temenos_1st]UniqueID")); player:delKeyItem(dsp.ki.COSMOCLEANSE); player:delKeyItem(dsp.ki.WHITE_CARD); end; -- Leaving 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 onBattlefieldLeave(player,battlefield,leavecode) --print("leave code "..leavecode); if leavecode == dsp.battlefield.leaveCode.LOST then SetServerVariable("[C_Temenos_1st]UniqueID",0); player:setPos(580,-1.5,4.452,192); end end;
gpl-3.0
gedads/Neodynamis
scripts/zones/Inner_Horutoto_Ruins/npcs/_5ca.lua
3
2300
----------------------------------- -- Area: Inner Horutoto Ruins -- NPC: Mahogany Door -- Involved In Quest: Making Headlines -- Involved in Mission 2-1 -- !pos -11 0 20 192 ----------------------------------- package.loaded["scripts/zones/Inner_Horutoto_Ruins/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/globals/missions"); require("scripts/zones/Inner_Horutoto_Ruins/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local MakingHeadlines = player:getQuestStatus(WINDURST,MAKING_HEADLINES); local CurrentMission = player:getCurrentMission(WINDURST) local MissionStatus = player:getVar("MissionStatus"); -- Check for Missions first (priority?) -- We should allow both missions and quests to activate if (CurrentMission == LOST_FOR_WORDS and MissionStatus == 4) then player:startEvent(0x002e); elseif (MakingHeadlines == 1) then function testflag(set,flag) return (set % (2*flag) >= flag) end local prog = player:getVar("QuestMakingHeadlines_var"); if (testflag(tonumber(prog),16) == false and testflag(tonumber(prog),8) == true) then player:messageSpecial(7208,1,WINDURST_WOODS_SCOOP); -- Confirm Story player:setVar("QuestMakingHeadlines_var",prog+16); else player:startEvent(0x002c); -- "The door is firmly shut" end else player:startEvent(0x002c); -- "The door is firmly shut" end; return 1; 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 == 0x002e) then -- Mark the progress player:setVar("MissionStatus",5); end end;
gpl-3.0
gedads/Neodynamis
scripts/zones/Windurst_Woods/npcs/Aja-Panja.lua
3
1051
----------------------------------- -- Area: Windurst Woods -- NPC: Aja-Panja -- Type: Standard NPC -- @zone 241 -- !pos -7.251 -6.55 -134.127 -- -- Auto-Script: Requires Verification (Verfied by Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x00f7); 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
Eric-Dang/pbc_test
bin/lua/test.lua
1
1661
------------------------------------------------------------------------------------------------------------------------------------------ local io = io local print = print local ipairs = ipairs local require = require ------------------------------------------------------------------------------------------------------------------------------------------ module "test" ------------------------------------------------------------------------------------------------------------------------------------------ local protobuf = require "protobuf" ------------------------------------------------------------------------------------------------------------------------------------------ addr = io.open("./addressbook.pb","rb") buffer = addr:read "*a" addr:close() protobuf.register(buffer) t = protobuf.decode("google.protobuf.FileDescriptorSet", buffer) proto = t.file[1] print(proto.name) print(proto.package) message = proto.message_type for _,v in ipairs(message) do print(v.name) for _,v in ipairs(v.field) do print("\t".. v.name .. " ["..v.number.."] " .. v.label) end end addressbook = { name = "Alice", id = 12345, phone = { { number = "1301234567" }, { number = "87654321", type = "WORK" }, } } code = protobuf.encode("tutorial.Person", addressbook) decode = protobuf.decode("tutorial.Person" , code) print(decode.name) print(decode.id) for _,v in ipairs(decode.phone) do print("\t"..v.number, v.type) end phonebuf = protobuf.pack("tutorial.Person.PhoneNumber number","87654321") buffer = protobuf.pack("tutorial.Person name id phone", "Alice", 123, { phonebuf }) print(protobuf.unpack("tutorial.Person name id phone", buffer))
mit
starlightknight/darkstar
scripts/globals/items/shall_shell.lua
11
1072
----------------------------------------- -- ID: 4484 -- Item: shall_shell -- Food Effect: 5Min, Mithra only ----------------------------------------- -- Dexterity -5 -- Vitality 4 -- Defense % 16.4 ----------------------------------------- require("scripts/globals/status") require("scripts/globals/msg") ----------------------------------------- function onItemCheck(target) local result = 0 if (target:getRace() ~= dsp.race.MITHRA) then result = dsp.msg.basic.CANNOT_EAT elseif target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then result = dsp.msg.basic.IS_FULL end return result end function onItemUse(target) target:addStatusEffect(dsp.effect.FOOD,0,0,300,4484) end function onEffectGain(target, effect) target:addMod(dsp.mod.DEX, -5) target:addMod(dsp.mod.VIT, 4) target:addMod(dsp.mod.FOOD_DEFP, 16.4) end function onEffectLose(target, effect) target:delMod(dsp.mod.DEX, -5) target:delMod(dsp.mod.VIT, 4) target:delMod(dsp.mod.FOOD_DEFP, 16.4) end
gpl-3.0
starlightknight/darkstar
scripts/globals/items/serving_of_red_curry.lua
11
1910
----------------------------------------- -- ID: 4298 -- Item: serving_of_red_curry -- Food Effect: 3 hours, All Races ----------------------------------------- -- HP +25 -- Strength +7 -- Agility +1 -- Intelligence -2 -- HP recovered while healing +2 -- MP recovered while healing +1 -- Attack +23% (Cap: 150@652 Base Attack) -- Ranged Attack +23% (Cap: 150@652 Base Ranged Attack) -- Demon Killer +4 -- Resist Sleep +3 ----------------------------------------- require("scripts/globals/status") require("scripts/globals/msg") ----------------------------------------- function onItemCheck(target) local result = 0 if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then result = dsp.msg.basic.IS_FULL end return result end function onItemUse(target) target:addStatusEffect(dsp.effect.FOOD,0,0,10800,4298) end function onEffectGain(target, effect) target:addMod(dsp.mod.HP, 25) target:addMod(dsp.mod.STR, 7) target:addMod(dsp.mod.AGI, 1) target:addMod(dsp.mod.INT, -2) target:addMod(dsp.mod.HPHEAL, 2) target:addMod(dsp.mod.MPHEAL, 1) target:addMod(dsp.mod.FOOD_ATTP, 23) target:addMod(dsp.mod.FOOD_ATT_CAP, 150) target:addMod(dsp.mod.FOOD_RATTP, 23) target:addMod(dsp.mod.FOOD_RATT_CAP, 150) target:addMod(dsp.mod.DEMON_KILLER, 4) target:addMod(dsp.mod.SLEEPRES, 3) end function onEffectLose(target, effect) target:delMod(dsp.mod.HP, 25) target:delMod(dsp.mod.STR, 7) target:delMod(dsp.mod.AGI, 1) target:delMod(dsp.mod.INT, -2) target:delMod(dsp.mod.HPHEAL, 2) target:delMod(dsp.mod.MPHEAL, 1) target:delMod(dsp.mod.FOOD_ATTP, 23) target:delMod(dsp.mod.FOOD_ATT_CAP, 150) target:delMod(dsp.mod.FOOD_RATTP, 23) target:delMod(dsp.mod.FOOD_RATT_CAP, 150) target:delMod(dsp.mod.DEMON_KILLER, 4) target:delMod(dsp.mod.SLEEPRES, 3) end
gpl-3.0
padrinoo1/televagir
plugins/banhammer.lua
106
11894
local function pre_process(msg) -- SERVICE MESSAGE if msg.action and msg.action.type then local action = msg.action.type -- Check if banned user joins chat by link if action == 'chat_add_user_link' then local user_id = msg.from.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs kick_user(user_id, msg.to.id) end end -- Check if banned user joins chat if action == 'chat_add_user' then local user_id = msg.action.user.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs kick_user(user_id, msg.to.id) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:incr(banhash) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id local banaddredis = redis:get(banhash) if banaddredis then if tonumber(banaddredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times end if tonumber(banaddredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:set(banhash, 0)-- Reset the Counter end end end if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings'] then if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] end end end if msg.action.user.username ~= nil then if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs kick_user(msg.action.user.id, msg.to.id) end end end -- No further checks return msg end -- banned user is talking ! if msg.to.type == 'chat' then local data = load_data(_config.moderation.data) local group = msg.to.id local texttext = 'groups' --if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not --chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false) --return --end local user_id = msg.from.id local chat_id = msg.to.id local banned = is_banned(user_id, chat_id) if banned or is_gbanned(user_id) then -- Check it with redis print('Banned user talking!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs kick_user(user_id, chat_id) msg.text = '' end end return msg end local function kick_ban_res(extra, success, result) --vardump(result) --vardump(extra) local member_id = result.id local user_id = member_id local member = result.username local chat_id = extra.chat_id local from_id = extra.from_id local get_cmd = extra.get_cmd local receiver = "chat#id"..chat_id if get_cmd == "kick" then if member_id == from_id then return send_large_msg(receiver, "You can't kick yourself") end if is_momod2(member_id, chat_id) and not is_admin2(sender) then return send_large_msg(receiver, "You can't kick mods/owner/admins") end return kick_user(member_id, chat_id) elseif get_cmd == 'ban' then if is_momod2(member_id, chat_id) and not is_admin2(sender) then return send_large_msg(receiver, "You can't ban mods/owner/admins") end send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned') return ban_user(member_id, chat_id) elseif get_cmd == 'unban' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned') local hash = 'banned:'..chat_id redis:srem(hash, member_id) return 'User '..user_id..' unbanned' elseif get_cmd == 'banall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned') return banall_user(member_id, chat_id) elseif get_cmd == 'unbanall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] un-globally banned') return unbanall_user(member_id, chat_id) end end local function run(msg, matches) if matches[1]:lower() == 'id' then if msg.to.type == "user" then return "Bot ID: "..msg.to.id.. "\n\nYour ID: "..msg.from.id end if type(msg.reply_id) ~= "nil" then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") id = get_message(msg.reply_id,get_message_callback_id, false) elseif matches[1]:lower() == 'id' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") return "Group ID for " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id end end if matches[1]:lower() == 'kickme' then-- /kickme local receiver = get_receiver(msg) if msg.to.type == 'chat' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false) end end if not is_momod(msg) then -- Ignore normal users return end if matches[1]:lower() == "banlist" then -- Ban list ! local chat_id = msg.to.id if matches[2] and is_admin(msg) then chat_id = matches[2] end return ban_list(chat_id) end if matches[1]:lower() == 'ban' then-- /ban if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,ban_by_reply_admins, false) else msgr = get_message(msg.reply_id,ban_by_reply, false) end end local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then return "you can't ban mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't ban your self !" end local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2]) ban_user(user_id, chat_id) else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'ban', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'unban' then -- /unban if type(msg.reply_id)~="nil" and is_momod(msg) then local msgr = get_message(msg.reply_id,unban_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then local user_id = targetuser local hash = 'banned:'..chat_id redis:srem(hash, user_id) local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2]) return 'User '..user_id..' unbanned' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'unban', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'kick' then if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,Kick_by_reply_admins, false) else msgr = get_message(msg.reply_id,Kick_by_reply, false) end end if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then return "you can't kick mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't kick your self !" end local user_id = matches[2] local chat_id = msg.to.id name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2]) kick_user(user_id, chat_id) else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'kick', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if not is_admin(msg) then return end if matches[1]:lower() == 'banall' then -- Global ban if type(msg.reply_id) ~="nil" and is_admin(msg) then return get_message(msg.reply_id,banall_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end banall_user(targetuser) return 'User ['..user_id..' ] globally banned' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'banall', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'unbanall' then -- Global unban local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end unbanall_user(user_id) return 'User ['..user_id..' ] removed from global ban list' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'unbanall', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == "gbanlist" then -- Global ban list return banall_list() end end return { patterns = { "^[!/]([Bb]anall) (.*)$", "^[!/]([Bb]anall)$", "^[!/]([Bb]anlist) (.*)$", "^[!/]([Bb]anlist)$", "^[!/]([Gg]banlist)$", "^[!/]([Bb]an) (.*)$", "^[!/]([Kk]ick)$", "^[!/]([Uu]nban) (.*)$", "^[!/]([Uu]nbanall) (.*)$", "^[!/]([Uu]nbanall)$", "^[!/]([Kk]ick) (.*)$", "^[!/]([Kk]ickme)$", "^[!/]([Bb]an)$", "^[!/]([Uu]nban)$", "^[!/]([Ii]d)$", "^([Bb]anall) (.*)$", "^([Bb]anall)$", "^([Bb]anlist) (.*)$", "^([Bb]anlist)$", "^([Gg]banlist)$", "^([Bb]an) (.*)$", "^([Kk]ick)$", "^([Uu]nban) (.*)$", "^([Uu]nbanall) (.*)$", "^([Uu]nbanall)$", "^([Kk]ick) (.*)$", "^([Kk]ickme)$", "^([Bb]an)$", "^([Uu]nban)$", "^([Ii]d)$", "^!!tgservice (.+)$" }, run = run, pre_process = pre_process }
gpl-2.0
soccermitchy/heroku-lapis
opt/src/luarocks/src/luarocks/pack.lua
20
7450
--- Module implementing the LuaRocks "pack" command. -- Creates a rock, packing sources or binaries. --module("luarocks.pack", package.seeall) local pack = {} package.loaded["luarocks.pack"] = pack local unpack = unpack or table.unpack local path = require("luarocks.path") local repos = require("luarocks.repos") local fetch = require("luarocks.fetch") local fs = require("luarocks.fs") local cfg = require("luarocks.cfg") local util = require("luarocks.util") local dir = require("luarocks.dir") local manif = require("luarocks.manif") local search = require("luarocks.search") pack.help_summary = "Create a rock, packing sources or binaries." pack.help_arguments = "{<rockspec>|<name> [<version>]}" pack.help = [[ Argument may be a rockspec file, for creating a source rock, or the name of an installed package, for creating a binary rock. In the latter case, the app version may be given as a second argument. ]] --- Create a source rock. -- Packages a rockspec and its required source files in a rock -- file with the .src.rock extension, which can later be built and -- installed with the "build" command. -- @param rockspec_file string: An URL or pathname for a rockspec file. -- @return string or (nil, string): The filename of the resulting -- .src.rock file; or nil and an error message. function pack.pack_source_rock(rockspec_file) assert(type(rockspec_file) == "string") local rockspec, err = fetch.load_rockspec(rockspec_file) if err then return nil, "Error loading rockspec: "..err end rockspec_file = rockspec.local_filename local name_version = rockspec.name .. "-" .. rockspec.version local rock_file = fs.absolute_name(name_version .. ".src.rock") local source_file, source_dir = fetch.fetch_sources(rockspec, false) if not source_file then return nil, source_dir end local ok, err = fs.change_dir(source_dir) if not ok then return nil, err end fs.delete(rock_file) fs.copy(rockspec_file, source_dir) if not fs.zip(rock_file, dir.base_name(rockspec_file), dir.base_name(source_file)) then return nil, "Failed packing "..rock_file end fs.pop_dir() return rock_file end local function copy_back_files(name, version, file_tree, deploy_dir, pack_dir) local ok, err = fs.make_dir(pack_dir) if not ok then return nil, err end for file, sub in pairs(file_tree) do local source = dir.path(deploy_dir, file) local target = dir.path(pack_dir, file) if type(sub) == "table" then local ok, err = copy_back_files(name, version, sub, source, target) if not ok then return nil, err end else local versioned = path.versioned_name(source, deploy_dir, name, version) if fs.exists(versioned) then fs.copy(versioned, target) else fs.copy(source, target) end end end return true end -- @param name string: Name of package to pack. -- @param version string or nil: A version number may also be passed. -- @return string or (nil, string): The filename of the resulting -- .src.rock file; or nil and an error message. local function do_pack_binary_rock(name, version) assert(type(name) == "string") assert(type(version) == "string" or not version) local query = search.make_query(name, version) query.exact_name = true local results = {} search.manifest_search(results, cfg.rocks_dir, query) if not next(results) then return nil, "'"..name.."' does not seem to be an installed rock." end local versions = results[name] if not version then local first = next(versions) if next(versions, first) then return nil, "Please specify which version of '"..name.."' to pack." end version = first end if not version:match("[^-]+%-%d+") then return nil, "Expected version "..version.." in version-revision format." end local info = versions[version][1] local root = path.root_dir(info.repo) local prefix = path.install_dir(name, version, root) if not fs.exists(prefix) then return nil, "'"..name.." "..version.."' does not seem to be an installed rock." end local rock_manifest = manif.load_rock_manifest(name, version, root) if not rock_manifest then return nil, "rock_manifest file not found for "..name.." "..version.." - not a LuaRocks 2 tree?" end local name_version = name .. "-" .. version local rock_file = fs.absolute_name(name_version .. "."..cfg.arch..".rock") local temp_dir = fs.make_temp_dir("pack") fs.copy_contents(prefix, temp_dir) local is_binary = false if rock_manifest.lib then local ok, err = copy_back_files(name, version, rock_manifest.lib, path.deploy_lib_dir(root), dir.path(temp_dir, "lib")) if not ok then return nil, "Failed copying back files: " .. err end is_binary = true end if rock_manifest.lua then local ok, err = copy_back_files(name, version, rock_manifest.lua, path.deploy_lua_dir(root), dir.path(temp_dir, "lua")) if not ok then return nil, "Failed copying back files: " .. err end end local ok, err = fs.change_dir(temp_dir) if not ok then return nil, err end if not is_binary and not repos.has_binaries(name, version) then rock_file = rock_file:gsub("%."..cfg.arch:gsub("%-","%%-").."%.", ".all.") end fs.delete(rock_file) if not fs.zip(rock_file, unpack(fs.list_dir())) then return nil, "Failed packing "..rock_file end fs.pop_dir() fs.delete(temp_dir) return rock_file end function pack.pack_binary_rock(name, version, cmd, ...) -- The --pack-binary-rock option for "luarocks build" basically performs -- "luarocks build" on a temporary tree and then "luarocks pack". The -- alternative would require refactoring parts of luarocks.build and -- luarocks.pack, which would save a few file operations: the idea would be -- to shave off the final deploy steps from the build phase and the initial -- collect steps from the pack phase. local temp_dir, err = fs.make_temp_dir("luarocks-build-pack-"..dir.base_name(name)) if not temp_dir then return nil, "Failed creating temporary directory: "..err end util.schedule_function(fs.delete, temp_dir) path.use_tree(temp_dir) local ok, err = cmd(...) if not ok then return nil, err end local rname, rversion = path.parse_name(name) if not rname then rname, rversion = name, version end return do_pack_binary_rock(rname, rversion) end --- Driver function for the "pack" command. -- @param arg string: may be a rockspec file, for creating a source rock, -- or the name of an installed package, for creating a binary rock. -- @param version string or nil: if the name of a package is given, a -- version may also be passed. -- @return boolean or (nil, string): true if successful or nil followed -- by an error message. function pack.run(...) local flags, arg, version = util.parse_flags(...) assert(type(version) == "string" or not version) if type(arg) ~= "string" then return nil, "Argument missing. "..util.see_help("pack") end local file, err if arg:match(".*%.rockspec") then file, err = pack.pack_source_rock(arg) else file, err = do_pack_binary_rock(arg, version) end if err then return nil, err else util.printout("Packed: "..file) return true end end return pack
gpl-2.0
gedads/Neodynamis
scripts/globals/spells/bluemagic/cannonball.lua
33
1721
----------------------------------------- -- Spell: Cannonball -- Damage varies with TP -- Spell cost: 66 MP -- Monster Type: Vermin -- Spell Type: Physical (Blunt) -- Blue Magic Points: 3 -- Stat Bonus: STR+1, DEX+1 -- Level: 70 -- Casting Time: 0.5 seconds -- Recast Time: 28.5 seconds -- Skillchain Element(s): Fusion (can open/close Light with Fragmentation WSs and spells) -- Combos: None ----------------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/bluemagic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local params = {}; -- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage params.tpmod = TPMOD_DAMAGE; params.dmgtype = DMGTYPE_H2H; params.scattr = SC_FUSION; params.numhits = 1; params.multiplier = 1.75; params.tp150 = 2.125; params.tp300 = 2.75; params.azuretp = 2.875; params.duppercap = 75; params.str_wsc = 0.5; params.dex_wsc = 0.0; params.vit_wsc = 0.5; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.offcratiomod = caster:getStat(MOD_DEF); damage = BluePhysicalSpell(caster, target, spell, params); damage = BlueFinalAdjustments(caster, target, spell, damage, params); return damage; end;
gpl-3.0
starlightknight/darkstar
scripts/commands/getmobaction.lua
12
1078
--------------------------------------------------------------------------------------------------- -- func: getmobaction -- desc: Prints mob's current action to the command user. --------------------------------------------------------------------------------------------------- cmdprops = { permission = 1, parameters = "i" }; function error(player, msg) player:PrintToPlayer(msg); player:PrintToPlayer("!getmobaction {mobID}"); end; function onTrigger(player, mobId) -- validate mobid local targ; if (mobId == nil) then targ = player:getCursorTarget(); if (not targ:isMob()) then error(player, "You must either provide a mobID or target a mob with your cursor."); return; end else targ = GetMobByID(mobId); if (targ == nil) then error(player, "Invalid mobID."); return; end end -- report mob action player:PrintToPlayer(string.format("%s %i current action ID is %i.", targ:getName(), targ:getID(), targ:getCurrentAction())); end;
gpl-3.0
pravsingh/Algorithm-Implementations
Bresenham_Based_Supercover_Line/Lua/Yonaba/bresenham_based_supercover_test.lua
27
1151
-- Tests for bresenham.lua local supercover_line = require 'bresenham_based_supercover' local total, pass = 0, 0 local function dec(str, len) return #str < len and str .. (('.'):rep(len-#str)) or str:sub(1,len) end local function run(message, f) total = total + 1 local ok, err = pcall(f) if ok then pass = pass + 1 end local status = ok and 'PASSED' or 'FAILED' print(('%02d. %68s: %s'):format(total, dec(message,68), status)) end -- Checks if t1 and t2 arrays are the same local function same(t1, t2) for k,v in ipairs(t1) do if t2[k].x ~= v.x or t2[k].y ~= v.y then return false end end return true end run('Testing Bresenham-based supercover line marching', function() local expected = { {x = 1, y = 1}, {x = 2, y = 1}, {x = 1, y = 2}, {x = 2, y = 2}, {x = 3, y = 2}, {x = 2, y = 3}, {x = 3, y = 3}, {x = 4, y = 3}, {x = 3, y = 4}, {x = 4, y = 4}, {x = 5, y = 4}, {x = 4, y = 5}, {x = 5, y = 5} } assert(same(supercover_line(1, 1, 5, 5), expected)) end) print(('-'):rep(80)) print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%') :format(total, pass, total-pass, (pass*100/total)))
mit
Maxsteam/4568584657657
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
starlightknight/darkstar
scripts/globals/abilities/martyr.lua
11
1706
----------------------------------- -- Ability: Martyr -- Sacrifices HP to heal a party member double the amount. -- Obtained: White Mage Level 75 -- Recast Time: 0:10:00 -- Duration: Instant -- Target: Party member, cannot target self. ----------------------------------- require("scripts/globals/status") require("scripts/globals/utils") require("scripts/globals/msg") ----------------------------------- function onAbilityCheck(player,target,ability) if (player:getID() == target:getID()) then return dsp.msg.basic.CANNOT_PERFORM_TARG,0 elseif (player:getHP() < 4) then -- Fails if HP < 4 return dsp.msg.basic.UNABLE_TO_USE_JA,0 else return 0,0 end end function onUseAbility(player,target,ability) -- Plus 5 percent hp recovers per extra martyr merit local meritBonus = player:getMerit(dsp.merit.MARTYR) - 5 -- printf("Martyr Merit Bonus: %d", meritBonus) local hpPercent = (200 + meritBonus) / 100 -- printf("Martyr HP Bonus Percent: %f", hpPercent) local damageHP = math.floor(player:getHP() * 0.25) -- printf("Martyr HP Damage: %d", damageHP) --We need to capture this here because the base damage is the basis for the heal local healHP = damageHP * hpPercent healHP = utils.clamp(healHP, 0,target:getMaxHP() - target:getHP()) -- If stoneskin is present, it should absorb damage... damageHP = utils.stoneskin(player, damageHP) -- printf("Martyr Final HP Damage (After Stoneskin): %d", damageHP) -- Log HP Headed for Debug -- printf("Martyr Healed HP: %d", healHP) damageHP = utils.stoneskin(player, damageHP) player:takeDamage(damageHP) target:addHP(healHP) return healHP end
gpl-3.0
O-P-E-N/CC-ROUTER
feeds/luci/modules/luci-base/luasrc/model/network.lua
1
33984
-- Copyright 2009-2015 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local type, next, pairs, ipairs, loadfile, table = type, next, pairs, ipairs, loadfile, table local tonumber, tostring, math = tonumber, tostring, math local require = require local nxo = require "nixio" local nfs = require "nixio.fs" local ipc = require "luci.ip" local sys = require "luci.sys" local utl = require "luci.util" local dsp = require "luci.dispatcher" local uci = require "luci.model.uci" local lng = require "luci.i18n" module "luci.model.network" IFACE_PATTERNS_VIRTUAL = { } IFACE_PATTERNS_IGNORE = { "^wmaster%d", "^wifi%d", "^hwsim%d", "^imq%d", "^ifb%d", "^mon%.wlan%d", "^sit%d", "^gre%d", "^lo$" } IFACE_PATTERNS_WIRELESS = { "^wlan%d", "^wl%d", "^ath%d", "^%w+%.network%d" } protocol = utl.class() local _protocols = { } local _interfaces, _bridge, _switch, _tunnel local _ubusnetcache, _ubusdevcache, _ubuswificache local _uci_real, _uci_state function _filter(c, s, o, r) local val = _uci_real:get(c, s, o) if val then local l = { } if type(val) == "string" then for val in val:gmatch("%S+") do if val ~= r then l[#l+1] = val end end if #l > 0 then _uci_real:set(c, s, o, table.concat(l, " ")) else _uci_real:delete(c, s, o) end elseif type(val) == "table" then for _, val in ipairs(val) do if val ~= r then l[#l+1] = val end end if #l > 0 then _uci_real:set(c, s, o, l) else _uci_real:delete(c, s, o) end end end end function _append(c, s, o, a) local val = _uci_real:get(c, s, o) or "" if type(val) == "string" then local l = { } for val in val:gmatch("%S+") do if val ~= a then l[#l+1] = val end end l[#l+1] = a _uci_real:set(c, s, o, table.concat(l, " ")) elseif type(val) == "table" then local l = { } for _, val in ipairs(val) do if val ~= a then l[#l+1] = val end end l[#l+1] = a _uci_real:set(c, s, o, l) end end function _stror(s1, s2) if not s1 or #s1 == 0 then return s2 and #s2 > 0 and s2 else return s1 end end function _get(c, s, o) return _uci_real:get(c, s, o) end function _set(c, s, o, v) if v ~= nil then if type(v) == "boolean" then v = v and "1" or "0" end return _uci_real:set(c, s, o, v) else return _uci_real:delete(c, s, o) end end function _wifi_iface(x) local _, p for _, p in ipairs(IFACE_PATTERNS_WIRELESS) do if x:match(p) then return true end end return false end function _wifi_state(key, val, field) local radio, radiostate, ifc, ifcstate if not next(_ubuswificache) then _ubuswificache = utl.ubus("network.wireless", "status", {}) or {} -- workaround extended section format for radio, radiostate in pairs(_ubuswificache) do for ifc, ifcstate in pairs(radiostate.interfaces) do if ifcstate.section and ifcstate.section:sub(1, 1) == '@' then local s = _uci_real:get_all('wireless.%s' % ifcstate.section) if s then ifcstate.section = s['.name'] end end end end end for radio, radiostate in pairs(_ubuswificache) do for ifc, ifcstate in pairs(radiostate.interfaces) do if ifcstate[key] == val then return ifcstate[field] end end end end function _wifi_lookup(ifn) -- got a radio#.network# pseudo iface, locate the corresponding section local radio, ifnidx = ifn:match("^(%w+)%.network(%d+)$") if radio and ifnidx then local sid = nil local num = 0 ifnidx = tonumber(ifnidx) _uci_real:foreach("wireless", "wifi-iface", function(s) if s.device == radio then num = num + 1 if num == ifnidx then sid = s['.name'] return false end end end) return sid -- looks like wifi, try to locate the section via state vars elseif _wifi_iface(ifn) then local sid = _wifi_state("ifname", ifn, "section") if not sid then _uci_state:foreach("wireless", "wifi-iface", function(s) if s.ifname == ifn then sid = s['.name'] return false end end) end return sid end end function _iface_virtual(x) local _, p for _, p in ipairs(IFACE_PATTERNS_VIRTUAL) do if x:match(p) then return true end end return false end function _iface_ignore(x) local _, p for _, p in ipairs(IFACE_PATTERNS_IGNORE) do if x:match(p) then return true end end return _iface_virtual(x) end function init(cursor) _uci_real = cursor or _uci_real or uci.cursor() _uci_state = _uci_real:substate() _interfaces = { } _bridge = { } _switch = { } _tunnel = { } _ubusnetcache = { } _ubusdevcache = { } _ubuswificache = { } -- read interface information local n, i for n, i in ipairs(nxo.getifaddrs()) do local name = i.name:match("[^:]+") local prnt = name:match("^([^%.]+)%.") if _iface_virtual(name) then _tunnel[name] = true end if _tunnel[name] or not _iface_ignore(name) then _interfaces[name] = _interfaces[name] or { idx = i.ifindex or n, name = name, rawname = i.name, flags = { }, ipaddrs = { }, ip6addrs = { } } if prnt then _switch[name] = true _switch[prnt] = true end if i.family == "packet" then _interfaces[name].flags = i.flags _interfaces[name].stats = i.data _interfaces[name].macaddr = i.addr elseif i.family == "inet" then _interfaces[name].ipaddrs[#_interfaces[name].ipaddrs+1] = ipc.IPv4(i.addr, i.netmask) elseif i.family == "inet6" then _interfaces[name].ip6addrs[#_interfaces[name].ip6addrs+1] = ipc.IPv6(i.addr, i.netmask) end end end -- read bridge informaton local b, l for l in utl.execi("brctl show") do if not l:match("STP") then local r = utl.split(l, "%s+", nil, true) if #r == 4 then b = { name = r[1], id = r[2], stp = r[3] == "yes", ifnames = { _interfaces[r[4]] } } if b.ifnames[1] then b.ifnames[1].bridge = b end _bridge[r[1]] = b elseif b then b.ifnames[#b.ifnames+1] = _interfaces[r[2]] b.ifnames[#b.ifnames].bridge = b end end end return _M end function save(self, ...) _uci_real:save(...) _uci_real:load(...) end function commit(self, ...) _uci_real:commit(...) _uci_real:load(...) end function ifnameof(self, x) if utl.instanceof(x, interface) then return x:name() elseif utl.instanceof(x, protocol) then return x:ifname() elseif type(x) == "string" then return x:match("^[^:]+") end end function get_protocol(self, protoname, netname) local v = _protocols[protoname] if v then return v(netname or "__dummy__") end end function get_protocols(self) local p = { } local _, v for _, v in ipairs(_protocols) do p[#p+1] = v("__dummy__") end return p end function register_protocol(self, protoname) local proto = utl.class(protocol) function proto.__init__(self, name) self.sid = name end function proto.proto(self) return protoname end _protocols[#_protocols+1] = proto _protocols[protoname] = proto return proto end function register_pattern_virtual(self, pat) IFACE_PATTERNS_VIRTUAL[#IFACE_PATTERNS_VIRTUAL+1] = pat end function has_ipv6(self) return nfs.access("/proc/net/ipv6_route") end function add_network(self, n, options) local oldnet = self:get_network(n) if n and #n > 0 and n:match("^[a-zA-Z0-9_]+$") and not oldnet then if _uci_real:section("network", "interface", n, options) then return network(n) end elseif oldnet and oldnet:is_empty() then if options then local k, v for k, v in pairs(options) do oldnet:set(k, v) end end return oldnet end end function get_network(self, n) if n and _uci_real:get("network", n) == "interface" then return network(n) end end function get_networks(self) local nets = { } local nls = { } _uci_real:foreach("network", "interface", function(s) nls[s['.name']] = network(s['.name']) end) local n for n in utl.kspairs(nls) do nets[#nets+1] = nls[n] end return nets end function del_network(self, n) local r = _uci_real:delete("network", n) if r then _uci_real:delete_all("network", "alias", function(s) return (s.interface == n) end) _uci_real:delete_all("network", "route", function(s) return (s.interface == n) end) _uci_real:delete_all("network", "route6", function(s) return (s.interface == n) end) _uci_real:foreach("wireless", "wifi-iface", function(s) local net local rest = { } for net in utl.imatch(s.network) do if net ~= n then rest[#rest+1] = net end end if #rest > 0 then _uci_real:set("wireless", s['.name'], "network", table.concat(rest, " ")) else _uci_real:delete("wireless", s['.name'], "network") end end) end return r end function rename_network(self, old, new) local r if new and #new > 0 and new:match("^[a-zA-Z0-9_]+$") and not self:get_network(new) then r = _uci_real:section("network", "interface", new, _uci_real:get_all("network", old)) if r then _uci_real:foreach("network", "alias", function(s) if s.interface == old then _uci_real:set("network", s['.name'], "interface", new) end end) _uci_real:foreach("network", "route", function(s) if s.interface == old then _uci_real:set("network", s['.name'], "interface", new) end end) _uci_real:foreach("network", "route6", function(s) if s.interface == old then _uci_real:set("network", s['.name'], "interface", new) end end) _uci_real:foreach("wireless", "wifi-iface", function(s) local net local list = { } for net in utl.imatch(s.network) do if net == old then list[#list+1] = new else list[#list+1] = net end end if #list > 0 then _uci_real:set("wireless", s['.name'], "network", table.concat(list, " ")) end end) _uci_real:delete("network", old) end end return r or false end function get_interface(self, i) if _interfaces[i] or _wifi_iface(i) then return interface(i) else local ifc local num = { } _uci_real:foreach("wireless", "wifi-iface", function(s) if s.device then num[s.device] = num[s.device] and num[s.device] + 1 or 1 if s['.name'] == i then ifc = interface( "%s.network%d" %{s.device, num[s.device] }) return false end end end) return ifc end end function get_interfaces(self) local iface local ifaces = { } local seen = { } local nfs = { } local baseof = { } -- find normal interfaces _uci_real:foreach("network", "interface", function(s) for iface in utl.imatch(s.ifname) do if not _iface_ignore(iface) and not _wifi_iface(iface) then seen[iface] = true nfs[iface] = interface(iface) end end end) for iface in utl.kspairs(_interfaces) do if not (seen[iface] or _iface_ignore(iface) or _wifi_iface(iface)) then nfs[iface] = interface(iface) end end -- find vlan interfaces _uci_real:foreach("network", "switch_vlan", function(s) if not s.device then return end local base = baseof[s.device] if not base then if not s.device:match("^eth%d") then local l for l in utl.execi("swconfig dev %q help 2>/dev/null" % s.device) do if not base then base = l:match("^%w+: (%w+)") end end if not base or not base:match("^eth%d") then base = "eth0" end else base = s.device end baseof[s.device] = base end local vid = tonumber(s.vid or s.vlan) if vid ~= nil and vid >= 0 and vid <= 4095 then local iface = "%s.%d" %{ base, vid } if not seen[iface] then seen[iface] = true nfs[iface] = interface(iface) end end end) for iface in utl.kspairs(nfs) do ifaces[#ifaces+1] = nfs[iface] end -- find wifi interfaces local num = { } local wfs = { } _uci_real:foreach("wireless", "wifi-iface", function(s) if s.device then num[s.device] = num[s.device] and num[s.device] + 1 or 1 local i = "%s.network%d" %{ s.device, num[s.device] } wfs[i] = interface(i) end end) for iface in utl.kspairs(wfs) do ifaces[#ifaces+1] = wfs[iface] end return ifaces end function ignore_interface(self, x) return _iface_ignore(x) end function get_wifidev(self, dev) if _uci_real:get("wireless", dev) == "wifi-device" then return wifidev(dev) end end function get_wifidevs(self) local devs = { } local wfd = { } _uci_real:foreach("wireless", "wifi-device", function(s) wfd[#wfd+1] = s['.name'] end) local dev for _, dev in utl.vspairs(wfd) do devs[#devs+1] = wifidev(dev) end return devs end function get_wifinet(self, net) local wnet = _wifi_lookup(net) if wnet then return wifinet(wnet) end end function add_wifinet(self, net, options) if type(options) == "table" and options.device and _uci_real:get("wireless", options.device) == "wifi-device" then local wnet = _uci_real:section("wireless", "wifi-iface", nil, options) return wifinet(wnet) end end function del_wifinet(self, net) local wnet = _wifi_lookup(net) if wnet then _uci_real:delete("wireless", wnet) return true end return false end function get_status_by_route(self, addr, mask) local _, object for _, object in ipairs(utl.ubus()) do local net = object:match("^network%.interface%.(.+)") if net then local s = utl.ubus(object, "status", {}) if s and s.route then local rt for _, rt in ipairs(s.route) do if not rt.table and rt.target == addr and rt.mask == mask then return net, s end end end end end end function get_status_by_address(self, addr) local _, object for _, object in ipairs(utl.ubus()) do local net = object:match("^network%.interface%.(.+)") if net then local s = utl.ubus(object, "status", {}) if s and s['ipv4-address'] then local a for _, a in ipairs(s['ipv4-address']) do if a.address == addr then return net, s end end end if s and s['ipv6-address'] then local a for _, a in ipairs(s['ipv6-address']) do if a.address == addr then return net, s end end end end end end function get_wannet(self) local net = self:get_status_by_route("0.0.0.0", 0) return net and network(net) end function get_wandev(self) local _, stat = self:get_status_by_route("0.0.0.0", 0) return stat and interface(stat.l3_device or stat.device) end function get_wan6net(self) local net = self:get_status_by_route("::", 0) return net and network(net) end function get_wan6dev(self) local _, stat = self:get_status_by_route("::", 0) return stat and interface(stat.l3_device or stat.device) end function network(name, proto) if name then local p = proto or _uci_real:get("network", name, "proto") local c = p and _protocols[p] or protocol return c(name) end end function protocol.__init__(self, name) self.sid = name end function protocol._get(self, opt) local v = _uci_real:get("network", self.sid, opt) if type(v) == "table" then return table.concat(v, " ") end return v or "" end function protocol._ubus(self, field) if not _ubusnetcache[self.sid] then _ubusnetcache[self.sid] = utl.ubus("network.interface.%s" % self.sid, "status", { }) end if _ubusnetcache[self.sid] and field then return _ubusnetcache[self.sid][field] end return _ubusnetcache[self.sid] end function protocol.get(self, opt) return _get("network", self.sid, opt) end function protocol.set(self, opt, val) return _set("network", self.sid, opt, val) end function protocol.ifname(self) local ifname if self:is_floating() then ifname = self:_ubus("l3_device") else ifname = self:_ubus("device") end if not ifname then local num = { } _uci_real:foreach("wireless", "wifi-iface", function(s) if s.device then num[s.device] = num[s.device] and num[s.device] + 1 or 1 local net for net in utl.imatch(s.network) do if net == self.sid then ifname = "%s.network%d" %{ s.device, num[s.device] } return false end end end end) end return ifname end function protocol.proto(self) return "none" end function protocol.get_i18n(self) local p = self:proto() if p == "none" then return lng.translate("Unmanaged") elseif p == "static" then return lng.translate("Static address") elseif p == "dhcp" then return lng.translate("DHCP client") else return lng.translate("Unknown") end end function protocol.type(self) return self:_get("type") end function protocol.name(self) return self.sid end function protocol.uptime(self) return self:_ubus("uptime") or 0 end function protocol.expires(self) local a = tonumber(_uci_state:get("network", self.sid, "lease_acquired")) local l = tonumber(_uci_state:get("network", self.sid, "lease_lifetime")) if a and l then l = l - (nxo.sysinfo().uptime - a) return l > 0 and l or 0 end return -1 end function protocol.metric(self) return tonumber(_uci_state:get("network", self.sid, "metric")) or 0 end function protocol.ipaddr(self) local addrs = self:_ubus("ipv4-address") return addrs and #addrs > 0 and addrs[1].address end function protocol.netmask(self) local addrs = self:_ubus("ipv4-address") return addrs and #addrs > 0 and ipc.IPv4("0.0.0.0/%d" % addrs[1].mask):mask():string() end function protocol.gwaddr(self) local _, route for _, route in ipairs(self:_ubus("route") or { }) do if route.target == "0.0.0.0" and route.mask == 0 then return route.nexthop end end end function protocol.dnsaddrs(self) local dns = { } local _, addr for _, addr in ipairs(self:_ubus("dns-server") or { }) do if not addr:match(":") then dns[#dns+1] = addr end end return dns end function protocol.ip6addr(self) local addrs = self:_ubus("ipv6-address") if addrs and #addrs > 0 then return "%s/%d" %{ addrs[1].address, addrs[1].mask } else addrs = self:_ubus("ipv6-prefix-assignment") if addrs and #addrs > 0 then return "%s/%d" %{ addrs[1].address, addrs[1].mask } end end end function protocol.gw6addr(self) local _, route for _, route in ipairs(self:_ubus("route") or { }) do if route.target == "::" and route.mask == 0 then return ipc.IPv6(route.nexthop):string() end end end function protocol.dns6addrs(self) local dns = { } local _, addr for _, addr in ipairs(self:_ubus("dns-server") or { }) do if addr:match(":") then dns[#dns+1] = addr end end return dns end function protocol.is_bridge(self) return (not self:is_virtual() and self:type() == "bridge") end function protocol.opkg_package(self) return nil end function protocol.is_installed(self) return true end function protocol.is_virtual(self) return false end function protocol.is_floating(self) return false end function protocol.is_empty(self) if self:is_floating() then return false else local rv = true if (self:_get("ifname") or ""):match("%S+") then rv = false end _uci_real:foreach("wireless", "wifi-iface", function(s) local n for n in utl.imatch(s.network) do if n == self.sid then rv = false return false end end end) return rv end end function protocol.add_interface(self, ifname) ifname = _M:ifnameof(ifname) if ifname and not self:is_floating() then -- if its a wifi interface, change its network option local wif = _wifi_lookup(ifname) if wif then _append("wireless", wif, "network", self.sid) -- add iface to our iface list else _append("network", self.sid, "ifname", ifname) end end end function protocol.del_interface(self, ifname) ifname = _M:ifnameof(ifname) if ifname and not self:is_floating() then -- if its a wireless interface, clear its network option local wif = _wifi_lookup(ifname) if wif then _filter("wireless", wif, "network", self.sid) end -- remove the interface _filter("network", self.sid, "ifname", ifname) end end function protocol.get_interface(self) if self:is_virtual() then _tunnel[self:proto() .. "-" .. self.sid] = true return interface(self:proto() .. "-" .. self.sid, self) elseif self:is_bridge() then _bridge["br-" .. self.sid] = true return interface("br-" .. self.sid, self) else local ifn = nil local num = { } for ifn in utl.imatch(_uci_real:get("network", self.sid, "ifname")) do ifn = ifn:match("^[^:/]+") return ifn and interface(ifn, self) end ifn = nil _uci_real:foreach("wireless", "wifi-iface", function(s) if s.device then num[s.device] = num[s.device] and num[s.device] + 1 or 1 local net for net in utl.imatch(s.network) do if net == self.sid then ifn = "%s.network%d" %{ s.device, num[s.device] } return false end end end end) return ifn and interface(ifn, self) end end function protocol.get_interfaces(self) if self:is_bridge() or (self:is_virtual() and not self:is_floating()) then local ifaces = { } local ifn local nfs = { } for ifn in utl.imatch(self:get("ifname")) do ifn = ifn:match("^[^:/]+") nfs[ifn] = interface(ifn, self) end for ifn in utl.kspairs(nfs) do ifaces[#ifaces+1] = nfs[ifn] end local num = { } local wfs = { } _uci_real:foreach("wireless", "wifi-iface", function(s) if s.device then num[s.device] = num[s.device] and num[s.device] + 1 or 1 local net for net in utl.imatch(s.network) do if net == self.sid then ifn = "%s.network%d" %{ s.device, num[s.device] } wfs[ifn] = interface(ifn, self) end end end end) for ifn in utl.kspairs(wfs) do ifaces[#ifaces+1] = wfs[ifn] end return ifaces end end function protocol.contains_interface(self, ifname) ifname = _M:ifnameof(ifname) if not ifname then return false elseif self:is_virtual() and self:proto() .. "-" .. self.sid == ifname then return true elseif self:is_bridge() and "br-" .. self.sid == ifname then return true else local ifn for ifn in utl.imatch(self:get("ifname")) do ifn = ifn:match("[^:]+") if ifn == ifname then return true end end local wif = _wifi_lookup(ifname) if wif then local n for n in utl.imatch(_uci_real:get("wireless", wif, "network")) do if n == self.sid then return true end end end end return false end function protocol.adminlink(self) return dsp.build_url("admin", "network", "network", self.sid) end interface = utl.class() function interface.__init__(self, ifname, network) local wif = _wifi_lookup(ifname) if wif then self.wif = wifinet(wif) self.ifname = _wifi_state("section", wif, "ifname") end self.ifname = self.ifname or ifname self.dev = _interfaces[self.ifname] self.network = network end function interface._ubus(self, field) if not _ubusdevcache[self.ifname] then _ubusdevcache[self.ifname] = utl.ubus("network.device", "status", { name = self.ifname }) end if _ubusdevcache[self.ifname] and field then return _ubusdevcache[self.ifname][field] end return _ubusdevcache[self.ifname] end function interface.name(self) return self.wif and self.wif:ifname() or self.ifname end function interface.mac(self) return (self:_ubus("macaddr") or "00:00:00:00:00:00"):upper() end function interface.ipaddrs(self) return self.dev and self.dev.ipaddrs or { } end function interface.ip6addrs(self) return self.dev and self.dev.ip6addrs or { } end function interface.type(self) if self.wif or _wifi_iface(self.ifname) then return "wifi" elseif _bridge[self.ifname] then return "bridge" elseif _tunnel[self.ifname] then return "tunnel" elseif self.ifname:match("%.") then return "vlan" elseif _switch[self.ifname] then return "switch" else return "ethernet" end end function interface.shortname(self) if self.wif then return "%s %q" %{ self.wif:active_mode(), self.wif:active_ssid() or self.wif:active_bssid() } else return self.ifname end end function interface.get_i18n(self) if self.wif then return "%s: %s %q" %{ lng.translate("Wireless Network"), self.wif:active_mode(), self.wif:active_ssid() or self.wif:active_bssid() } else return "%s: %q" %{ self:get_type_i18n(), self:name() } end end function interface.get_type_i18n(self) local x = self:type() if x == "wifi" then return lng.translate("Wireless Adapter") elseif x == "bridge" then return lng.translate("Bridge") elseif x == "switch" then return lng.translate("Ethernet Switch") elseif x == "vlan" then return lng.translate("VLAN Interface") elseif x == "tunnel" then return lng.translate("Tunnel Interface") else return lng.translate("Ethernet Adapter") end end function interface.adminlink(self) if self.wif then return self.wif:adminlink() end end function interface.ccmonitor(self) if self.wif then return self.wif:ccmonitor() end end function interface.ports(self) local members = self:_ubus("bridge-members") if members then local _, iface local ifaces = { } for _, iface in ipairs(members) do ifaces[#ifaces+1] = interface(iface) end end end function interface.bridge_id(self) if self.br then return self.br.id else return nil end end function interface.bridge_stp(self) if self.br then return self.br.stp else return false end end function interface.is_up(self) return self:_ubus("up") or false end function interface.is_bridge(self) return (self:type() == "bridge") end function interface.is_bridgeport(self) return self.dev and self.dev.bridge and true or false end function interface.tx_bytes(self) local stat = self:_ubus("statistics") return stat and stat.tx_bytes or 0 end function interface.rx_bytes(self) local stat = self:_ubus("statistics") return stat and stat.rx_bytes or 0 end function interface.tx_packets(self) local stat = self:_ubus("statistics") return stat and stat.tx_packets or 0 end function interface.rx_packets(self) local stat = self:_ubus("statistics") return stat and stat.rx_packets or 0 end function interface.get_network(self) return self:get_networks()[1] end function interface.get_networks(self) if not self.networks then local nets = { } local _, net for _, net in ipairs(_M:get_networks()) do if net:contains_interface(self.ifname) or net:ifname() == self.ifname then nets[#nets+1] = net end end table.sort(nets, function(a, b) return a.sid < b.sid end) self.networks = nets return nets else return self.networks end end function interface.get_wifinet(self) return self.wif end wifidev = utl.class() function wifidev.__init__(self, dev) self.sid = dev self.iwinfo = dev and sys.wifi.getiwinfo(dev) or { } end function wifidev.get(self, opt) return _get("wireless", self.sid, opt) end function wifidev.set(self, opt, val) return _set("wireless", self.sid, opt, val) end function wifidev.name(self) return self.sid end function wifidev.hwmodes(self) local l = self.iwinfo.hwmodelist if l and next(l) then return l else return { b = true, g = true } end end function wifidev.get_i18n(self) local t = "Generic" if self.iwinfo.type == "wl" then t = "Broadcom" elseif self.iwinfo.type == "madwifi" then t = "Atheros" end local m = "" local l = self:hwmodes() if l.a then m = m .. "a" end if l.b then m = m .. "b" end if l.g then m = m .. "g" end if l.n then m = m .. "n" end if l.ac then m = "ac" end return "%s 802.11%s Wireless Controller (%s)" %{ t, m, self:name() } end function wifidev.is_up(self) if _ubuswificache[self.sid] then return (_ubuswificache[self.sid].up == true) end local up = false _uci_state:foreach("wireless", "wifi-iface", function(s) if s.device == self.sid then if s.up == "1" then up = true return false end end end) return up end function wifidev.get_wifinet(self, net) if _uci_real:get("wireless", net) == "wifi-iface" then return wifinet(net) else local wnet = _wifi_lookup(net) if wnet then return wifinet(wnet) end end end function wifidev.get_wifinets(self) local nets = { } _uci_real:foreach("wireless", "wifi-iface", function(s) if s.device == self.sid then nets[#nets+1] = wifinet(s['.name']) end end) return nets end function wifidev.add_wifinet(self, options) options = options or { } options.device = self.sid local wnet = _uci_real:section("wireless", "wifi-iface", nil, options) if wnet then return wifinet(wnet, options) end end function wifidev.del_wifinet(self, net) if utl.instanceof(net, wifinet) then net = net.sid elseif _uci_real:get("wireless", net) ~= "wifi-iface" then net = _wifi_lookup(net) end if net and _uci_real:get("wireless", net, "device") == self.sid then _uci_real:delete("wireless", net) return true end return false end wifinet = utl.class() function wifinet.__init__(self, net, data) self.sid = net local num = { } local netid _uci_real:foreach("wireless", "wifi-iface", function(s) if s.device then num[s.device] = num[s.device] and num[s.device] + 1 or 1 if s['.name'] == self.sid then netid = "%s.network%d" %{ s.device, num[s.device] } return false end end end) local dev = _wifi_state("section", self.sid, "ifname") or netid self.netid = netid self.wdev = dev self.iwinfo = dev and sys.wifi.getiwinfo(dev) or { } self.iwdata = data or _uci_state:get_all("wireless", self.sid) or _uci_real:get_all("wireless", self.sid) or { } end function wifinet.get(self, opt) return _get("wireless", self.sid, opt) end function wifinet.set(self, opt, val) return _set("wireless", self.sid, opt, val) end function wifinet.mode(self) return _uci_state:get("wireless", self.sid, "mode") or "ap" end function wifinet.ssid(self) return _uci_state:get("wireless", self.sid, "ssid") end function wifinet.bssid(self) return _uci_state:get("wireless", self.sid, "bssid") end function wifinet.network(self) return _uci_state:get("wifinet", self.sid, "network") end function wifinet.id(self) return self.netid end function wifinet.name(self) return self.sid end function wifinet.ifname(self) local ifname = self.iwinfo.ifname if not ifname or ifname:match("^wifi%d") or ifname:match("^radio%d") then ifname = self.wdev end return ifname end function wifinet.get_device(self) if self.iwdata.device then return wifidev(self.iwdata.device) end end function wifinet.is_up(self) local ifc = self:get_interface() return (ifc and ifc:is_up() or false) end function wifinet.active_mode(self) local m = _stror(self.iwdata.mode, self.iwinfo.mode) or "ap" if m == "ap" then m = "Master" elseif m == "sta" then m = "Client" elseif m == "adhoc" then m = "Ad-Hoc" elseif m == "mesh" then m = "Mesh" elseif m == "monitor" then m = "Monitor" end return m end function wifinet.active_mode_i18n(self) return lng.translate(self:active_mode()) end function wifinet.active_ssid(self) return _stror(self.iwdata.ssid, self.iwinfo.ssid) end function wifinet.active_bssid(self) return _stror(self.iwdata.bssid, self.iwinfo.bssid) or "00:00:00:00:00:00" end function wifinet.active_encryption(self) local enc = self.iwinfo and self.iwinfo.encryption return enc and enc.description or "-" end function wifinet.assoclist(self) return self.iwinfo.assoclist or { } end function wifinet.frequency(self) local freq = self.iwinfo.frequency if freq and freq > 0 then return "%.03f" % (freq / 1000) end end function wifinet.bitrate(self) local rate = self.iwinfo.bitrate if rate and rate > 0 then return (rate / 1000) end end function wifinet.channel(self) return self.iwinfo.channel or tonumber(_uci_state:get("wireless", self.iwdata.device, "channel")) end function wifinet.signal(self) return self.iwinfo.signal or 0 end function wifinet.noise(self) return self.iwinfo.noise or 0 end function wifinet.country(self) return self.iwinfo.country or "00" end function wifinet.txpower(self) local pwr = (self.iwinfo.txpower or 0) return pwr + self:txpower_offset() end function wifinet.txpower_offset(self) return self.iwinfo.txpower_offset or 0 end function wifinet.signal_level(self, s, n) if self:active_bssid() ~= "00:00:00:00:00:00" then local signal = s or self:signal() local noise = n or self:noise() if signal < 0 and noise < 0 then local snr = -1 * (noise - signal) return math.floor(snr / 5) else return 0 end else return -1 end end function wifinet.signal_percent(self) local qc = self.iwinfo.quality or 0 local qm = self.iwinfo.quality_max or 0 if qc > 0 and qm > 0 then return math.floor((100 / qm) * qc) else return 0 end end function wifinet.shortname(self) return "%s %q" %{ lng.translate(self:active_mode()), self:active_ssid() or self:active_bssid() } end function wifinet.get_i18n(self) return "%s: %s %q (%s)" %{ lng.translate("Wireless Network"), lng.translate(self:active_mode()), self:active_ssid() or self:active_bssid(), self:ifname() } end function wifinet.adminlink(self) return dsp.build_url("admin", "network", "wireless", self.netid) end function wifinet.ccmonitor(self) return dsp.build_url("admin", "network", "ccmonitor", self.netid) end function wifinet.get_network(self) return self:get_networks()[1] end function wifinet.get_networks(self) local nets = { } local net for net in utl.imatch(tostring(self.iwdata.network)) do if _uci_real:get("network", net) == "interface" then nets[#nets+1] = network(net) end end table.sort(nets, function(a, b) return a.sid < b.sid end) return nets end function wifinet.get_interface(self) return interface(self:ifname()) end -- setup base protocols _M:register_protocol("static") _M:register_protocol("dhcp") _M:register_protocol("none") -- load protocol extensions local exts = nfs.dir(utl.libpath() .. "/model/network") if exts then local ext for ext in exts do if ext:match("%.lua$") then require("luci.model.network." .. ext:gsub("%.lua$", "")) end end end
gpl-2.0
dantezhu/neon
examples/demo1/src/cocos/framework/extends/MenuEx.lua
57
1228
--[[ Copyright (c) 2011-2014 chukong-inc.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]] local Menu = cc.Menu local MenuItem = cc.MenuItem function MenuItem:onClicked(callback) self:registerScriptTapHandler(callback) return self end
mit
jackkkk21/botjack
plugins/stats.lua
168
4001
do -- Returns a table with `name` and `msgs` local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ['..user_id..']' return user_info end local function chat_stats(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'users in this chat \n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end local file = io.open("./groups/lists/"..chat_id.."stats.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..chat_id,"./groups/lists/"..chat_id.."stats.txt", ok_cb, false) return --text end local function chat_stats2(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'users in this chat \n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end return text end -- Save stats, ban user local function bot_stats() local redis_scan = [[ local cursor = '0' local count = 0 repeat local r = redis.call("SCAN", cursor, "MATCH", KEYS[1]) cursor = r[1] count = count + #r[2] until cursor == '0' return count]] -- Users local hash = 'msgs:*:'..our_id local r = redis:eval(redis_scan, 1, hash) local text = 'Users: '..r hash = 'chat:*:users' r = redis:eval(redis_scan, 1, hash) text = text..'\nGroups: '..r return text end local function run(msg, matches) if matches[1]:lower() == 'creedbot' then -- Put everything you like :) local about = _config.about_text local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /creedbot ") return about end if matches[1]:lower() == "statslist" then if not is_momod(msg) then return "For mods only !" end local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ") return chat_stats2(chat_id) end if matches[1]:lower() == "stats" then if not matches[2] then if not is_momod(msg) then return "For mods only !" end if msg.to.type == 'chat' then local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ") return chat_stats(chat_id) else return end end if matches[2] == "creedbot" then -- Put everything you like :) if not is_admin(msg) then return "For admins only !" else return bot_stats() end end if matches[2] == "group" then if not is_admin(msg) then return "For admins only !" else return chat_stats(matches[3]) end end end end return { patterns = { "^[!/]([Ss]tats)$", "^[!/]([Ss]tatslist)$", "^[!/]([Ss]tats) (group) (%d+)", "^[!/]([Ss]tats) (creedbot)",-- Put everything you like :) "^[!/]([Cc]reedbot)"-- Put everything you like :) }, run = run } end
gpl-2.0
starlightknight/darkstar
scripts/zones/Lower_Jeuno/npcs/Tuh_Almobankha.lua
9
3900
----------------------------------- -- Area: Lower Jeuno -- NPC: Tuh Almobankha -- Title Change NPC -- !pos -14 0 -61 245 ----------------------------------- require("scripts/globals/titles") ----------------------------------- local eventId = 10014 local titleInfo = { { cost = 200, title = { dsp.title.BROWN_MAGE_GUINEA_PIG, dsp.title.BROWN_MAGIC_BYPRODUCT, dsp.title.RESEARCHER_OF_CLASSICS, dsp.title.TORCHBEARER, dsp.title.FORTUNETELLER_IN_TRAINING, dsp.title.CHOCOBO_TRAINER, dsp.title.CLOCK_TOWER_PRESERVATIONIST, dsp.title.LIFE_SAVER, dsp.title.CARD_COLLECTOR, dsp.title.TWOS_COMPANY, dsp.title.TRADER_OF_ANTIQUITIES, dsp.title.GOBLINS_EXCLUSIVE_FASHION_MANNEQUIN, dsp.title.TENSHODO_MEMBER, }, }, { cost = 300, title = { dsp.title.ACTIVIST_FOR_KINDNESS, dsp.title.ENVOY_TO_THE_NORTH, dsp.title.EXORCIST_IN_TRAINING, dsp.title.FOOLS_ERRAND_RUNNER, dsp.title.STREET_SWEEPER, dsp.title.MERCY_ERRAND_RUNNER, dsp.title.BELIEVER_OF_ALTANA, dsp.title.TRADER_OF_MYSTERIES, dsp.title.WANDERING_MINSTREL, dsp.title.ANIMAL_TRAINER, dsp.title.HAVE_WINGS_WILL_FLY, dsp.title.ROD_RETRIEVER, dsp.title.DESTINED_FELLOW, dsp.title.TROUPE_BRILIOTH_DANCER, dsp.title.PROMISING_DANCER, dsp.title.STARDUST_DANCER, }, }, { cost = 400, title = { dsp.title.TIMEKEEPER, dsp.title.BRINGER_OF_BLISS, dsp.title.PROFESSIONAL_LOAFER, dsp.title.TRADER_OF_RENOWN, dsp.title.HORIZON_BREAKER, dsp.title.SUMMIT_BREAKER, dsp.title.BROWN_BELT, dsp.title.DUCAL_DUPE, dsp.title.CHOCOBO_LOVE_GURU, dsp.title.PICKUP_ARTIST, dsp.title.WORTHY_OF_TRUST, dsp.title.A_FRIEND_INDEED, dsp.title.CHOCOROOKIE, dsp.title.CRYSTAL_STAKES_CUPHOLDER, dsp.title.WINNING_OWNER, dsp.title.VICTORIOUS_OWNER, dsp.title.TRIUMPHANT_OWNER, dsp.title.HIGH_ROLLER, dsp.title.FORTUNES_FAVORITE, dsp.title.CHOCOCHAMPION, }, }, { cost = 500, title = { dsp.title.PARAGON_OF_BEASTMASTER_EXCELLENCE, dsp.title.PARAGON_OF_BARD_EXCELLENCE, dsp.title.SKY_BREAKER, dsp.title.BLACK_BELT, dsp.title.GREEDALOX, dsp.title.CLOUD_BREAKER, dsp.title.STAR_BREAKER, dsp.title.ULTIMATE_CHAMPION_OF_THE_WORLD, dsp.title.DYNAMIS_JEUNO_INTERLOPER, dsp.title.DYNAMIS_BEAUCEDINE_INTERLOPER, dsp.title.DYNAMIS_XARCABARD_INTERLOPER, dsp.title.DYNAMIS_QUFIM_INTERLOPER, dsp.title.CONQUEROR_OF_FATE, dsp.title.SUPERHERO, dsp.title.SUPERHEROINE, dsp.title.ELEGANT_DANCER, dsp.title.DAZZLING_DANCE_DIVA, dsp.title.GRIMOIRE_BEARER, dsp.title.FELLOW_FORTIFIER, dsp.title.BUSHIN_ASPIRANT, dsp.title.BUSHIN_RYU_INHERITOR, }, }, { cost = 600, title = { dsp.title.GRAND_GREEDALOX, dsp.title.SILENCER_OF_THE_ECHO, }, }, } function onTrade(player,npc,trade) end function onTrigger(player,npc) dsp.title.changerOnTrigger(player, eventId, titleInfo) end function onEventUpdate(player,csid,option) end function onEventFinish(player,csid,option) dsp.title.changerOnEventFinish(player, csid, option, eventId, titleInfo) end
gpl-3.0
telergybot/infernalmann
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
starlightknight/darkstar
scripts/zones/Southern_San_dOria/npcs/Rosel.lua
9
2611
----------------------------------- -- Area: Southern San d'Oria -- NPC: Rosel -- Starts and Finishes Quest: Rosel the Armorer -- !zone 230 ------------------------------------- local ID = require("scripts/zones/Southern_San_dOria/IDs"); require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/titles"); require("scripts/globals/quests"); require("scripts/globals/shop"); ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(SANDORIA,dsp.quest.id.sandoria.FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then if (trade:hasItemQty(532,1) and trade:getItemCount() == 1 and player:getCharVar("tradeRosel") == 0) then player:messageSpecial(ID.text.ROSEL_DIALOG); player:addCharVar("FFR", -1) player:setCharVar("tradeRosel",1); player:messageSpecial(ID.text.FLYER_ACCEPTED); player:tradeComplete(); elseif (player:getCharVar("tradeRosel") ==1) then player:messageSpecial(ID.text.FLYER_ALREADY); end end end; function onTrigger(player,npc) local RoselTheArmorer = player:getQuestStatus(SANDORIA,dsp.quest.id.sandoria.ROSEL_THE_ARMORER); local receiprForThePrince = player:hasKeyItem(dsp.ki.RECEIPT_FOR_THE_PRINCE); if (player:getCharVar("RefuseRoselTheArmorerQuest") == 1 and RoselTheArmorer == QUEST_AVAILABLE) then player:startEvent(524); elseif (RoselTheArmorer == QUEST_AVAILABLE) then player:startEvent(523); player:setCharVar("RefuseRoselTheArmorerQuest",1); elseif (RoselTheArmorer == QUEST_ACCEPTED and receiprForThePrince) then player:startEvent(524); elseif (RoselTheArmorer == QUEST_ACCEPTED and receiprForThePrince == false) then player:startEvent(527); end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) -- Rosel the Armorer, get quest and receipt for prince if ((csid == 523 or csid == 524) and option == 0) then player:addQuest(SANDORIA, dsp.quest.id.sandoria.ROSEL_THE_ARMORER); player:setCharVar("RefuseRoselTheArmorerQuest",0); player:addKeyItem(dsp.ki.RECEIPT_FOR_THE_PRINCE); player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.RECEIPT_FOR_THE_PRINCE); -- Rosel the Armorer, finished quest, recieve 200gil elseif (csid == 527) then npcUtil.completeQuest(player, SANDORIA, dsp.quest.id.sandoria.ROSEL_THE_ARMORER, { title= dsp.title.ENTRANCE_DENIED, gil= 200 }); end end;
gpl-3.0
starlightknight/darkstar
scripts/globals/effects/transcendency.lua
12
1636
----------------------------------- require("scripts/globals/status") ----------------------------------- function onEffectGain(target,effect) target:addMod(dsp.mod.HP, 9000) target:addMod(dsp.mod.MP, 9000) target:addMod(dsp.mod.REGEN, 300) target:addMod(dsp.mod.REFRESH, 300) target:addMod(dsp.mod.REGAIN, 500) target:addMod(dsp.mod.STR, 900) target:addMod(dsp.mod.DEX, 900) target:addMod(dsp.mod.VIT, 900) target:addMod(dsp.mod.AGI, 900) target:addMod(dsp.mod.INT, 900) target:addMod(dsp.mod.MND, 900) target:addMod(dsp.mod.CHR, 900) target:addMod(dsp.mod.ATT, 9000) target:addMod(dsp.mod.DEF, 9000) target:addMod(dsp.mod.ACC, 1000) target:addMod(dsp.mod.EVA, 1000) target:addMod(dsp.mod.MATT, 900) target:addMod(dsp.mod.RACC, 1000) target:addMod(dsp.mod.RATT, 9000) end function onEffectTick(target,effect) end function onEffectLose(target,effect) target:delMod(dsp.mod.HP, 9000) target:delMod(dsp.mod.MP, 9000) target:delMod(dsp.mod.REGEN, 300) target:delMod(dsp.mod.REFRESH, 300) target:delMod(dsp.mod.REGAIN, 500) target:delMod(dsp.mod.STR, 900) target:delMod(dsp.mod.DEX, 900) target:delMod(dsp.mod.VIT, 900) target:delMod(dsp.mod.AGI, 900) target:delMod(dsp.mod.INT, 900) target:delMod(dsp.mod.MND, 900) target:delMod(dsp.mod.CHR, 900) target:delMod(dsp.mod.ATT, 9000) target:delMod(dsp.mod.DEF, 9000) target:delMod(dsp.mod.ACC, 1000) target:delMod(dsp.mod.EVA, 1000) target:delMod(dsp.mod.MATT, 900) target:delMod(dsp.mod.RACC, 1000) target:delMod(dsp.mod.RATT, 9000) end
gpl-3.0
O-P-E-N/CC-ROUTER
feeds/luci/applications/luci-app-statistics/luasrc/statistics/i18n.lua
39
1879
-- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. module("luci.statistics.i18n", package.seeall) require("luci.util") require("luci.i18n") Instance = luci.util.class() function Instance.__init__( self, graph ) self.i18n = luci.i18n self.graph = graph end function Instance._subst( self, str, val ) str = str:gsub( "%%H", self.graph.opts.host or "" ) str = str:gsub( "%%pn", val.plugin or "" ) str = str:gsub( "%%pi", val.pinst or "" ) str = str:gsub( "%%dt", val.dtype or "" ) str = str:gsub( "%%di", val.dinst or "" ) str = str:gsub( "%%ds", val.dsrc or "" ) return str end function Instance.title( self, plugin, pinst, dtype, dinst, user_title ) local title = user_title or "p=%s/pi=%s/dt=%s/di=%s" % { plugin, (pinst and #pinst > 0) and pinst or "(nil)", (dtype and #dtype > 0) and dtype or "(nil)", (dinst and #dinst > 0) and dinst or "(nil)" } return self:_subst( title, { plugin = plugin, pinst = pinst, dtype = dtype, dinst = dinst } ) end function Instance.label( self, plugin, pinst, dtype, dinst, user_label ) local label = user_label or "dt=%s/di=%s" % { (dtype and #dtype > 0) and dtype or "(nil)", (dinst and #dinst > 0) and dinst or "(nil)" } return self:_subst( label, { plugin = plugin, pinst = pinst, dtype = dtype, dinst = dinst } ) end function Instance.ds( self, source ) local label = source.title or "dt=%s/di=%s/ds=%s" % { (source.type and #source.type > 0) and source.type or "(nil)", (source.instance and #source.instance > 0) and source.instance or "(nil)", (source.ds and #source.ds > 0) and source.ds or "(nil)" } return self:_subst( label, { dtype = source.type, dinst = source.instance, dsrc = source.ds } ):gsub(":", "\\:") end
gpl-2.0
gedads/Neodynamis
scripts/zones/Abyssea-Empyreal_Paradox/Zone.lua
33
1376
----------------------------------- -- -- Zone: Abyssea - Empyreal_Paradox -- ----------------------------------- package.loaded["scripts/zones/Abyssea-Empyreal_Paradox/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Abyssea-Empyreal_Paradox/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then --player:setPos(-495,0,483,205); -- BC Area player:setPos(540,-500,-565,64); end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
tommy3/Urho3D
Source/ThirdParty/LuaJIT/dynasm/dasm_arm64.lua
33
34807
------------------------------------------------------------------------------ -- DynASM ARM64 module. -- -- Copyright (C) 2005-2016 Mike Pall. All rights reserved. -- See dynasm.lua for full copyright notice. ------------------------------------------------------------------------------ -- Module information: local _info = { arch = "arm", description = "DynASM ARM64 module", version = "1.4.0", vernum = 10400, release = "2015-10-18", author = "Mike Pall", license = "MIT", } -- Exported glue functions for the arch-specific module. local _M = { _info = _info } -- Cache library functions. local type, tonumber, pairs, ipairs = type, tonumber, pairs, ipairs local assert, setmetatable, rawget = assert, setmetatable, rawget local _s = string local sub, format, byte, char = _s.sub, _s.format, _s.byte, _s.char local match, gmatch, gsub = _s.match, _s.gmatch, _s.gsub local concat, sort, insert = table.concat, table.sort, table.insert local bit = bit or require("bit") local band, shl, shr, sar = bit.band, bit.lshift, bit.rshift, bit.arshift local ror, tohex = bit.ror, bit.tohex -- Inherited tables and callbacks. local g_opt, g_arch local wline, werror, wfatal, wwarn -- Action name list. -- CHECK: Keep this in sync with the C code! local action_names = { "STOP", "SECTION", "ESC", "REL_EXT", "ALIGN", "REL_LG", "LABEL_LG", "REL_PC", "LABEL_PC", "IMM", "IMM6", "IMM12", "IMM13W", "IMM13X", "IMML", } -- Maximum number of section buffer positions for dasm_put(). -- CHECK: Keep this in sync with the C code! local maxsecpos = 25 -- Keep this low, to avoid excessively long C lines. -- Action name -> action number. local map_action = {} for n,name in ipairs(action_names) do map_action[name] = n-1 end -- Action list buffer. local actlist = {} -- Argument list for next dasm_put(). Start with offset 0 into action list. local actargs = { 0 } -- Current number of section buffer positions for dasm_put(). local secpos = 1 ------------------------------------------------------------------------------ -- Dump action names and numbers. local function dumpactions(out) out:write("DynASM encoding engine action codes:\n") for n,name in ipairs(action_names) do local num = map_action[name] out:write(format(" %-10s %02X %d\n", name, num, num)) end out:write("\n") end -- Write action list buffer as a huge static C array. local function writeactions(out, name) local nn = #actlist if nn == 0 then nn = 1; actlist[0] = map_action.STOP end out:write("static const unsigned int ", name, "[", nn, "] = {\n") for i = 1,nn-1 do assert(out:write("0x", tohex(actlist[i]), ",\n")) end assert(out:write("0x", tohex(actlist[nn]), "\n};\n\n")) end ------------------------------------------------------------------------------ -- Add word to action list. local function wputxw(n) assert(n >= 0 and n <= 0xffffffff and n % 1 == 0, "word out of range") actlist[#actlist+1] = n end -- Add action to list with optional arg. Advance buffer pos, too. local function waction(action, val, a, num) local w = assert(map_action[action], "bad action name `"..action.."'") wputxw(w * 0x10000 + (val or 0)) if a then actargs[#actargs+1] = a end if a or num then secpos = secpos + (num or 1) end end -- Flush action list (intervening C code or buffer pos overflow). local function wflush(term) if #actlist == actargs[1] then return end -- Nothing to flush. if not term then waction("STOP") end -- Terminate action list. wline(format("dasm_put(Dst, %s);", concat(actargs, ", ")), true) actargs = { #actlist } -- Actionlist offset is 1st arg to next dasm_put(). secpos = 1 -- The actionlist offset occupies a buffer position, too. end -- Put escaped word. local function wputw(n) if n <= 0x000fffff then waction("ESC") end wputxw(n) end -- Reserve position for word. local function wpos() local pos = #actlist+1 actlist[pos] = "" return pos end -- Store word to reserved position. local function wputpos(pos, n) assert(n >= 0 and n <= 0xffffffff and n % 1 == 0, "word out of range") if n <= 0x000fffff then insert(actlist, pos+1, n) n = map_action.ESC * 0x10000 end actlist[pos] = n end ------------------------------------------------------------------------------ -- Global label name -> global label number. With auto assignment on 1st use. local next_global = 20 local map_global = setmetatable({}, { __index = function(t, name) if not match(name, "^[%a_][%w_]*$") then werror("bad global label") end local n = next_global if n > 2047 then werror("too many global labels") end next_global = n + 1 t[name] = n return n end}) -- Dump global labels. local function dumpglobals(out, lvl) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("Global labels:\n") for i=20,next_global-1 do out:write(format(" %s\n", t[i])) end out:write("\n") end -- Write global label enum. local function writeglobals(out, prefix) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("enum {\n") for i=20,next_global-1 do out:write(" ", prefix, t[i], ",\n") end out:write(" ", prefix, "_MAX\n};\n") end -- Write global label names. local function writeglobalnames(out, name) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("static const char *const ", name, "[] = {\n") for i=20,next_global-1 do out:write(" \"", t[i], "\",\n") end out:write(" (const char *)0\n};\n") end ------------------------------------------------------------------------------ -- Extern label name -> extern label number. With auto assignment on 1st use. local next_extern = 0 local map_extern_ = {} local map_extern = setmetatable({}, { __index = function(t, name) -- No restrictions on the name for now. local n = next_extern if n > 2047 then werror("too many extern labels") end next_extern = n + 1 t[name] = n map_extern_[n] = name return n end}) -- Dump extern labels. local function dumpexterns(out, lvl) out:write("Extern labels:\n") for i=0,next_extern-1 do out:write(format(" %s\n", map_extern_[i])) end out:write("\n") end -- Write extern label names. local function writeexternnames(out, name) out:write("static const char *const ", name, "[] = {\n") for i=0,next_extern-1 do out:write(" \"", map_extern_[i], "\",\n") end out:write(" (const char *)0\n};\n") end ------------------------------------------------------------------------------ -- Arch-specific maps. -- Ext. register name -> int. name. local map_archdef = { xzr = "@x31", wzr = "@w31", lr = "x30", } -- Int. register name -> ext. name. local map_reg_rev = { ["@x31"] = "xzr", ["@w31"] = "wzr", x30 = "lr", } local map_type = {} -- Type name -> { ctype, reg } local ctypenum = 0 -- Type number (for Dt... macros). -- Reverse defines for registers. function _M.revdef(s) return map_reg_rev[s] or s end local map_shift = { lsl = 0, lsr = 1, asr = 2, } local map_extend = { uxtb = 0, uxth = 1, uxtw = 2, uxtx = 3, sxtb = 4, sxth = 5, sxtw = 6, sxtx = 7, } local map_cond = { eq = 0, ne = 1, cs = 2, cc = 3, mi = 4, pl = 5, vs = 6, vc = 7, hi = 8, ls = 9, ge = 10, lt = 11, gt = 12, le = 13, al = 14, hs = 2, lo = 3, } ------------------------------------------------------------------------------ local parse_reg_type local function parse_reg(expr) if not expr then werror("expected register name") end local tname, ovreg = match(expr, "^([%w_]+):(@?%l%d+)$") local tp = map_type[tname or expr] if tp then local reg = ovreg or tp.reg if not reg then werror("type `"..(tname or expr).."' needs a register override") end expr = reg end local ok31, rt, r = match(expr, "^(@?)([xwqdshb])([123]?[0-9])$") if r then r = tonumber(r) if r <= 30 or (r == 31 and ok31 ~= "" or (rt ~= "w" and rt ~= "x")) then if not parse_reg_type then parse_reg_type = rt elseif parse_reg_type ~= rt then werror("register size mismatch") end return r, tp end end werror("bad register name `"..expr.."'") end local function parse_reg_base(expr) if expr == "sp" then return 0x3e0 end local base, tp = parse_reg(expr) if parse_reg_type ~= "x" then werror("bad register type") end parse_reg_type = false return shl(base, 5), tp end local parse_ctx = {} local loadenv = setfenv and function(s) local code = loadstring(s, "") if code then setfenv(code, parse_ctx) end return code end or function(s) return load(s, "", nil, parse_ctx) end -- Try to parse simple arithmetic, too, since some basic ops are aliases. local function parse_number(n) local x = tonumber(n) if x then return x end local code = loadenv("return "..n) if code then local ok, y = pcall(code) if ok then return y end end return nil end local function parse_imm(imm, bits, shift, scale, signed) imm = match(imm, "^#(.*)$") if not imm then werror("expected immediate operand") end local n = parse_number(imm) if n then local m = sar(n, scale) if shl(m, scale) == n then if signed then local s = sar(m, bits-1) if s == 0 then return shl(m, shift) elseif s == -1 then return shl(m + shl(1, bits), shift) end else if sar(m, bits) == 0 then return shl(m, shift) end end end werror("out of range immediate `"..imm.."'") else waction("IMM", (signed and 32768 or 0)+scale*1024+bits*32+shift, imm) return 0 end end local function parse_imm12(imm) imm = match(imm, "^#(.*)$") if not imm then werror("expected immediate operand") end local n = parse_number(imm) if n then if shr(n, 12) == 0 then return shl(n, 10) elseif band(n, 0xff000fff) == 0 then return shr(n, 2) + 0x00400000 end werror("out of range immediate `"..imm.."'") else waction("IMM12", 0, imm) return 0 end end local function parse_imm13(imm) imm = match(imm, "^#(.*)$") if not imm then werror("expected immediate operand") end local n = parse_number(imm) local r64 = parse_reg_type == "x" if n and n % 1 == 0 and n >= 0 and n <= 0xffffffff then local inv = false if band(n, 1) == 1 then n = bit.bnot(n); inv = true end local t = {} for i=1,32 do t[i] = band(n, 1); n = shr(n, 1) end local b = table.concat(t) b = b..(r64 and (inv and "1" or "0"):rep(32) or b) local p0, p1, p0a, p1a = b:match("^(0+)(1+)(0*)(1*)") if p0 then local w = p1a == "" and (r64 and 64 or 32) or #p1+#p0a if band(w, w-1) == 0 and b == b:sub(1, w):rep(64/w) then local s = band(-2*w, 0x3f) - 1 if w == 64 then s = s + 0x1000 end if inv then return shl(w-#p1-#p0, 16) + shl(s+w-#p1, 10) else return shl(w-#p0, 16) + shl(s+#p1, 10) end end end werror("out of range immediate `"..imm.."'") elseif r64 then waction("IMM13X", 0, format("(unsigned int)(%s)", imm)) actargs[#actargs+1] = format("(unsigned int)((unsigned long long)(%s)>>32)", imm) return 0 else waction("IMM13W", 0, imm) return 0 end end local function parse_imm6(imm) imm = match(imm, "^#(.*)$") if not imm then werror("expected immediate operand") end local n = parse_number(imm) if n then if n >= 0 and n <= 63 then return shl(band(n, 0x1f), 19) + (n >= 32 and 0x80000000 or 0) end werror("out of range immediate `"..imm.."'") else waction("IMM6", 0, imm) return 0 end end local function parse_imm_load(imm, scale) local n = parse_number(imm) if n then local m = sar(n, scale) if shl(m, scale) == n and m >= 0 and m < 0x1000 then return shl(m, 10) + 0x01000000 -- Scaled, unsigned 12 bit offset. elseif n >= -256 and n < 256 then return shl(band(n, 511), 12) -- Unscaled, signed 9 bit offset. end werror("out of range immediate `"..imm.."'") else waction("IMML", 0, imm) return 0 end end local function parse_fpimm(imm) imm = match(imm, "^#(.*)$") if not imm then werror("expected immediate operand") end local n = parse_number(imm) if n then local m, e = math.frexp(n) local s, e2 = 0, band(e-2, 7) if m < 0 then m = -m; s = 0x00100000 end m = m*32-16 if m % 1 == 0 and m >= 0 and m <= 15 and sar(shl(e2, 29), 29)+2 == e then return s + shl(e2, 17) + shl(m, 13) end werror("out of range immediate `"..imm.."'") else werror("NYI fpimm action") end end local function parse_shift(expr) local s, s2 = match(expr, "^(%S+)%s*(.*)$") s = map_shift[s] if not s then werror("expected shift operand") end return parse_imm(s2, 6, 10, 0, false) + shl(s, 22) end local function parse_lslx16(expr) local n = match(expr, "^lsl%s*#(%d+)$") n = tonumber(n) if not n then werror("expected shift operand") end if band(n, parse_reg_type == "x" and 0xffffffcf or 0xffffffef) ~= 0 then werror("bad shift amount") end return shl(n, 17) end local function parse_extend(expr) local s, s2 = match(expr, "^(%S+)%s*(.*)$") if s == "lsl" then s = parse_reg_type == "x" and 3 or 2 else s = map_extend[s] end if not s then werror("expected extend operand") end return (s2 == "" and 0 or parse_imm(s2, 3, 10, 0, false)) + shl(s, 13) end local function parse_cond(expr, inv) local c = map_cond[expr] if not c then werror("expected condition operand") end return shl(bit.bxor(c, inv), 12) end local function parse_load(params, nparams, n, op) if params[n+2] then werror("too many operands") end local pn, p2 = params[n], params[n+1] local p1, wb = match(pn, "^%[%s*(.-)%s*%](!?)$") if not p1 then if not p2 then local reg, tailr = match(pn, "^([%w_:]+)%s*(.*)$") if reg and tailr ~= "" then local base, tp = parse_reg_base(reg) if tp then waction("IMML", 0, format(tp.ctypefmt, tailr)) return op + base end end end werror("expected address operand") end local scale = shr(op, 30) if p2 then if wb == "!" then werror("bad use of '!'") end op = op + parse_reg_base(p1) + parse_imm(p2, 9, 12, 0, true) + 0x400 elseif wb == "!" then local p1a, p2a = match(p1, "^([^,%s]*)%s*,%s*(.*)$") if not p1a then werror("bad use of '!'") end op = op + parse_reg_base(p1a) + parse_imm(p2a, 9, 12, 0, true) + 0xc00 else local p1a, p2a = match(p1, "^([^,%s]*)%s*(.*)$") op = op + parse_reg_base(p1a) if p2a ~= "" then local imm = match(p2a, "^,%s*#(.*)$") if imm then op = op + parse_imm_load(imm, scale) else local p2b, p3b, p3s = match(p2a, "^,%s*([^,%s]*)%s*,?%s*(%S*)%s*(.*)$") op = op + shl(parse_reg(p2b), 16) + 0x00200800 if parse_reg_type ~= "x" and parse_reg_type ~= "w" then werror("bad index register type") end if p3b == "" then if parse_reg_type ~= "x" then werror("bad index register type") end op = op + 0x6000 else if p3s == "" or p3s == "#0" then elseif p3s == "#"..scale then op = op + 0x1000 else werror("bad scale") end if parse_reg_type == "x" then if p3b == "lsl" and p3s ~= "" then op = op + 0x6000 elseif p3b == "sxtx" then op = op + 0xe000 else werror("bad extend/shift specifier") end else if p3b == "uxtw" then op = op + 0x4000 elseif p3b == "sxtw" then op = op + 0xc000 else werror("bad extend/shift specifier") end end end end else if wb == "!" then werror("bad use of '!'") end op = op + 0x01000000 end end return op end local function parse_load_pair(params, nparams, n, op) if params[n+2] then werror("too many operands") end local pn, p2 = params[n], params[n+1] local scale = shr(op, 30) == 0 and 2 or 3 local p1, wb = match(pn, "^%[%s*(.-)%s*%](!?)$") if not p1 then if not p2 then local reg, tailr = match(pn, "^([%w_:]+)%s*(.*)$") if reg and tailr ~= "" then local base, tp = parse_reg_base(reg) if tp then waction("IMM", 32768+7*32+15+scale*1024, format(tp.ctypefmt, tailr)) return op + base + 0x01000000 end end end werror("expected address operand") end if p2 then if wb == "!" then werror("bad use of '!'") end op = op + 0x00800000 else local p1a, p2a = match(p1, "^([^,%s]*)%s*,%s*(.*)$") if p1a then p1, p2 = p1a, p2a else p2 = "#0" end op = op + (wb == "!" and 0x01800000 or 0x01000000) end return op + parse_reg_base(p1) + parse_imm(p2, 7, 15, scale, true) end local function parse_label(label, def) local prefix = sub(label, 1, 2) -- =>label (pc label reference) if prefix == "=>" then return "PC", 0, sub(label, 3) end -- ->name (global label reference) if prefix == "->" then return "LG", map_global[sub(label, 3)] end if def then -- [1-9] (local label definition) if match(label, "^[1-9]$") then return "LG", 10+tonumber(label) end else -- [<>][1-9] (local label reference) local dir, lnum = match(label, "^([<>])([1-9])$") if dir then -- Fwd: 1-9, Bkwd: 11-19. return "LG", lnum + (dir == ">" and 0 or 10) end -- extern label (extern label reference) local extname = match(label, "^extern%s+(%S+)$") if extname then return "EXT", map_extern[extname] end end werror("bad label `"..label.."'") end local function branch_type(op) if band(op, 0x7c000000) == 0x14000000 then return 0 -- B, BL elseif shr(op, 24) == 0x54 or band(op, 0x7e000000) == 0x34000000 or band(op, 0x3b000000) == 0x18000000 then return 0x800 -- B.cond, CBZ, CBNZ, LDR* literal elseif band(op, 0x7e000000) == 0x36000000 then return 0x1000 -- TBZ, TBNZ elseif band(op, 0x9f000000) == 0x10000000 then return 0x2000 -- ADR elseif band(op, 0x9f000000) == band(0x90000000) then return 0x3000 -- ADRP else assert(false, "unknown branch type") end end ------------------------------------------------------------------------------ local map_op, op_template local function op_alias(opname, f) return function(params, nparams) if not params then return "-> "..opname:sub(1, -3) end f(params, nparams) op_template(params, map_op[opname], nparams) end end local function alias_bfx(p) p[4] = "#("..p[3]:sub(2)..")+("..p[4]:sub(2)..")-1" end local function alias_bfiz(p) parse_reg(p[1]) if parse_reg_type == "w" then p[3] = "#-("..p[3]:sub(2)..")%32" p[4] = "#("..p[4]:sub(2)..")-1" else p[3] = "#-("..p[3]:sub(2)..")%64" p[4] = "#("..p[4]:sub(2)..")-1" end end local alias_lslimm = op_alias("ubfm_4", function(p) parse_reg(p[1]) local sh = p[3]:sub(2) if parse_reg_type == "w" then p[3] = "#-("..sh..")%32" p[4] = "#31-("..sh..")" else p[3] = "#-("..sh..")%64" p[4] = "#63-("..sh..")" end end) -- Template strings for ARM instructions. map_op = { -- Basic data processing instructions. add_3 = "0b000000DNMg|11000000pDpNIg|8b206000pDpNMx", add_4 = "0b000000DNMSg|0b200000DNMXg|8b200000pDpNMXx|8b200000pDpNxMwX", adds_3 = "2b000000DNMg|31000000DpNIg|ab206000DpNMx", adds_4 = "2b000000DNMSg|2b200000DNMXg|ab200000DpNMXx|ab200000DpNxMwX", cmn_2 = "2b00001fNMg|3100001fpNIg|ab20601fpNMx", cmn_3 = "2b00001fNMSg|2b20001fNMXg|ab20001fpNMXx|ab20001fpNxMwX", sub_3 = "4b000000DNMg|51000000pDpNIg|cb206000pDpNMx", sub_4 = "4b000000DNMSg|4b200000DNMXg|cb200000pDpNMXx|cb200000pDpNxMwX", subs_3 = "6b000000DNMg|71000000DpNIg|eb206000DpNMx", subs_4 = "6b000000DNMSg|6b200000DNMXg|eb200000DpNMXx|eb200000DpNxMwX", cmp_2 = "6b00001fNMg|7100001fpNIg|eb20601fpNMx", cmp_3 = "6b00001fNMSg|6b20001fNMXg|eb20001fpNMXx|eb20001fpNxMwX", neg_2 = "4b0003e0DMg", neg_3 = "4b0003e0DMSg", negs_2 = "6b0003e0DMg", negs_3 = "6b0003e0DMSg", adc_3 = "1a000000DNMg", adcs_3 = "3a000000DNMg", sbc_3 = "5a000000DNMg", sbcs_3 = "7a000000DNMg", ngc_2 = "5a0003e0DMg", ngcs_2 = "7a0003e0DMg", and_3 = "0a000000DNMg|12000000pDNig", and_4 = "0a000000DNMSg", orr_3 = "2a000000DNMg|32000000pDNig", orr_4 = "2a000000DNMSg", eor_3 = "4a000000DNMg|52000000pDNig", eor_4 = "4a000000DNMSg", ands_3 = "6a000000DNMg|72000000DNig", ands_4 = "6a000000DNMSg", tst_2 = "6a00001fNMg|7200001fNig", tst_3 = "6a00001fNMSg", bic_3 = "0a200000DNMg", bic_4 = "0a200000DNMSg", orn_3 = "2a200000DNMg", orn_4 = "2a200000DNMSg", eon_3 = "4a200000DNMg", eon_4 = "4a200000DNMSg", bics_3 = "6a200000DNMg", bics_4 = "6a200000DNMSg", movn_2 = "12800000DWg", movn_3 = "12800000DWRg", movz_2 = "52800000DWg", movz_3 = "52800000DWRg", movk_2 = "72800000DWg", movk_3 = "72800000DWRg", -- TODO: this doesn't cover all valid immediates for mov reg, #imm. mov_2 = "2a0003e0DMg|52800000DW|320003e0pDig|11000000pDpNg", mov_3 = "2a0003e0DMSg", mvn_2 = "2a2003e0DMg", mvn_3 = "2a2003e0DMSg", adr_2 = "10000000DBx", adrp_2 = "90000000DBx", csel_4 = "1a800000DNMCg", csinc_4 = "1a800400DNMCg", csinv_4 = "5a800000DNMCg", csneg_4 = "5a800400DNMCg", cset_2 = "1a9f07e0Dcg", csetm_2 = "5a9f03e0Dcg", cinc_3 = "1a800400DNmcg", cinv_3 = "5a800000DNmcg", cneg_3 = "5a800400DNmcg", ccmn_4 = "3a400000NMVCg|3a400800N5VCg", ccmp_4 = "7a400000NMVCg|7a400800N5VCg", madd_4 = "1b000000DNMAg", msub_4 = "1b008000DNMAg", mul_3 = "1b007c00DNMg", mneg_3 = "1b00fc00DNMg", smaddl_4 = "9b200000DxNMwAx", smsubl_4 = "9b208000DxNMwAx", smull_3 = "9b207c00DxNMw", smnegl_3 = "9b20fc00DxNMw", smulh_3 = "9b407c00DNMx", umaddl_4 = "9ba00000DxNMwAx", umsubl_4 = "9ba08000DxNMwAx", umull_3 = "9ba07c00DxNMw", umnegl_3 = "9ba0fc00DxNMw", umulh_3 = "9bc07c00DNMx", udiv_3 = "1ac00800DNMg", sdiv_3 = "1ac00c00DNMg", -- Bit operations. sbfm_4 = "13000000DN12w|93400000DN12x", bfm_4 = "33000000DN12w|b3400000DN12x", ubfm_4 = "53000000DN12w|d3400000DN12x", extr_4 = "13800000DNM2w|93c00000DNM2x", sxtb_2 = "13001c00DNw|93401c00DNx", sxth_2 = "13003c00DNw|93403c00DNx", sxtw_2 = "93407c00DxNw", uxtb_2 = "53001c00DNw", uxth_2 = "53003c00DNw", sbfx_4 = op_alias("sbfm_4", alias_bfx), bfxil_4 = op_alias("bfm_4", alias_bfx), ubfx_4 = op_alias("ubfm_4", alias_bfx), sbfiz_4 = op_alias("sbfm_4", alias_bfiz), bfi_4 = op_alias("bfm_4", alias_bfiz), ubfiz_4 = op_alias("ubfm_4", alias_bfiz), lsl_3 = function(params, nparams) if params and params[3]:byte() == 35 then return alias_lslimm(params, nparams) else return op_template(params, "1ac02000DNMg", nparams) end end, lsr_3 = "1ac02400DNMg|53007c00DN1w|d340fc00DN1x", asr_3 = "1ac02800DNMg|13007c00DN1w|9340fc00DN1x", ror_3 = "1ac02c00DNMg|13800000DNm2w|93c00000DNm2x", clz_2 = "5ac01000DNg", cls_2 = "5ac01400DNg", rbit_2 = "5ac00000DNg", rev_2 = "5ac00800DNw|dac00c00DNx", rev16_2 = "5ac00400DNg", rev32_2 = "dac00800DNx", -- Loads and stores. ["strb_*"] = "38000000DwL", ["ldrb_*"] = "38400000DwL", ["ldrsb_*"] = "38c00000DwL|38800000DxL", ["strh_*"] = "78000000DwL", ["ldrh_*"] = "78400000DwL", ["ldrsh_*"] = "78c00000DwL|78800000DxL", ["str_*"] = "b8000000DwL|f8000000DxL|bc000000DsL|fc000000DdL", ["ldr_*"] = "18000000DwB|58000000DxB|1c000000DsB|5c000000DdB|b8400000DwL|f8400000DxL|bc400000DsL|fc400000DdL", ["ldrsw_*"] = "98000000DxB|b8800000DxL", -- NOTE: ldur etc. are handled by ldr et al. ["stp_*"] = "28000000DAwP|a8000000DAxP|2c000000DAsP|6c000000DAdP", ["ldp_*"] = "28400000DAwP|a8400000DAxP|2c400000DAsP|6c400000DAdP", ["ldpsw_*"] = "68400000DAxP", -- Branches. b_1 = "14000000B", bl_1 = "94000000B", blr_1 = "d63f0000Nx", br_1 = "d61f0000Nx", ret_0 = "d65f03c0", ret_1 = "d65f0000Nx", -- b.cond is added below. cbz_2 = "34000000DBg", cbnz_2 = "35000000DBg", tbz_3 = "36000000DTBw|36000000DTBx", tbnz_3 = "37000000DTBw|37000000DTBx", -- Miscellaneous instructions. -- TODO: hlt, hvc, smc, svc, eret, dcps[123], drps, mrs, msr -- TODO: sys, sysl, ic, dc, at, tlbi -- TODO: hint, yield, wfe, wfi, sev, sevl -- TODO: clrex, dsb, dmb, isb nop_0 = "d503201f", brk_0 = "d4200000", brk_1 = "d4200000W", -- Floating point instructions. fmov_2 = "1e204000DNf|1e260000DwNs|1e270000DsNw|9e660000DxNd|9e670000DdNx|1e201000DFf", fabs_2 = "1e20c000DNf", fneg_2 = "1e214000DNf", fsqrt_2 = "1e21c000DNf", fcvt_2 = "1e22c000DdNs|1e624000DsNd", -- TODO: half-precision and fixed-point conversions. fcvtas_2 = "1e240000DwNs|9e240000DxNs|1e640000DwNd|9e640000DxNd", fcvtau_2 = "1e250000DwNs|9e250000DxNs|1e650000DwNd|9e650000DxNd", fcvtms_2 = "1e300000DwNs|9e300000DxNs|1e700000DwNd|9e700000DxNd", fcvtmu_2 = "1e310000DwNs|9e310000DxNs|1e710000DwNd|9e710000DxNd", fcvtns_2 = "1e200000DwNs|9e200000DxNs|1e600000DwNd|9e600000DxNd", fcvtnu_2 = "1e210000DwNs|9e210000DxNs|1e610000DwNd|9e610000DxNd", fcvtps_2 = "1e280000DwNs|9e280000DxNs|1e680000DwNd|9e680000DxNd", fcvtpu_2 = "1e290000DwNs|9e290000DxNs|1e690000DwNd|9e690000DxNd", fcvtzs_2 = "1e380000DwNs|9e380000DxNs|1e780000DwNd|9e780000DxNd", fcvtzu_2 = "1e390000DwNs|9e390000DxNs|1e790000DwNd|9e790000DxNd", scvtf_2 = "1e220000DsNw|9e220000DsNx|1e620000DdNw|9e620000DdNx", ucvtf_2 = "1e230000DsNw|9e230000DsNx|1e630000DdNw|9e630000DdNx", frintn_2 = "1e244000DNf", frintp_2 = "1e24c000DNf", frintm_2 = "1e254000DNf", frintz_2 = "1e25c000DNf", frinta_2 = "1e264000DNf", frintx_2 = "1e274000DNf", frinti_2 = "1e27c000DNf", fadd_3 = "1e202800DNMf", fsub_3 = "1e203800DNMf", fmul_3 = "1e200800DNMf", fnmul_3 = "1e208800DNMf", fdiv_3 = "1e201800DNMf", fmadd_4 = "1f000000DNMAf", fmsub_4 = "1f008000DNMAf", fnmadd_4 = "1f200000DNMAf", fnmsub_4 = "1f208000DNMAf", fmax_3 = "1e204800DNMf", fmaxnm_3 = "1e206800DNMf", fmin_3 = "1e205800DNMf", fminnm_3 = "1e207800DNMf", fcmp_2 = "1e202000NMf|1e202008NZf", fcmpe_2 = "1e202010NMf|1e202018NZf", fccmp_4 = "1e200400NMVCf", fccmpe_4 = "1e200410NMVCf", fcsel_4 = "1e200c00DNMCf", -- TODO: crc32*, aes*, sha*, pmull -- TODO: SIMD instructions. } for cond,c in pairs(map_cond) do map_op["b"..cond.."_1"] = tohex(0x54000000+c).."B" end ------------------------------------------------------------------------------ -- Handle opcodes defined with template strings. local function parse_template(params, template, nparams, pos) local op = tonumber(sub(template, 1, 8), 16) local n = 1 local rtt = {} parse_reg_type = false -- Process each character. for p in gmatch(sub(template, 9), ".") do local q = params[n] if p == "D" then op = op + parse_reg(q); n = n + 1 elseif p == "N" then op = op + shl(parse_reg(q), 5); n = n + 1 elseif p == "M" then op = op + shl(parse_reg(q), 16); n = n + 1 elseif p == "A" then op = op + shl(parse_reg(q), 10); n = n + 1 elseif p == "m" then op = op + shl(parse_reg(params[n-1]), 16) elseif p == "p" then if q == "sp" then params[n] = "@x31" end elseif p == "g" then if parse_reg_type == "x" then op = op + 0x80000000 elseif parse_reg_type ~= "w" then werror("bad register type") end parse_reg_type = false elseif p == "f" then if parse_reg_type == "d" then op = op + 0x00400000 elseif parse_reg_type ~= "s" then werror("bad register type") end parse_reg_type = false elseif p == "x" or p == "w" or p == "d" or p == "s" then if parse_reg_type ~= p then werror("register size mismatch") end parse_reg_type = false elseif p == "L" then op = parse_load(params, nparams, n, op) elseif p == "P" then op = parse_load_pair(params, nparams, n, op) elseif p == "B" then local mode, v, s = parse_label(q, false); n = n + 1 local m = branch_type(op) waction("REL_"..mode, v+m, s, 1) elseif p == "I" then op = op + parse_imm12(q); n = n + 1 elseif p == "i" then op = op + parse_imm13(q); n = n + 1 elseif p == "W" then op = op + parse_imm(q, 16, 5, 0, false); n = n + 1 elseif p == "T" then op = op + parse_imm6(q); n = n + 1 elseif p == "1" then op = op + parse_imm(q, 6, 16, 0, false); n = n + 1 elseif p == "2" then op = op + parse_imm(q, 6, 10, 0, false); n = n + 1 elseif p == "5" then op = op + parse_imm(q, 5, 16, 0, false); n = n + 1 elseif p == "V" then op = op + parse_imm(q, 4, 0, 0, false); n = n + 1 elseif p == "F" then op = op + parse_fpimm(q); n = n + 1 elseif p == "Z" then if q ~= "#0" and q ~= "#0.0" then werror("expected zero immediate") end n = n + 1 elseif p == "S" then op = op + parse_shift(q); n = n + 1 elseif p == "X" then op = op + parse_extend(q); n = n + 1 elseif p == "R" then op = op + parse_lslx16(q); n = n + 1 elseif p == "C" then op = op + parse_cond(q, 0); n = n + 1 elseif p == "c" then op = op + parse_cond(q, 1); n = n + 1 else assert(false) end end wputpos(pos, op) end function op_template(params, template, nparams) if not params then return template:gsub("%x%x%x%x%x%x%x%x", "") end -- Limit number of section buffer positions used by a single dasm_put(). -- A single opcode needs a maximum of 3 positions. if secpos+3 > maxsecpos then wflush() end local pos = wpos() local lpos, apos, spos = #actlist, #actargs, secpos local ok, err for t in gmatch(template, "[^|]+") do ok, err = pcall(parse_template, params, t, nparams, pos) if ok then return end secpos = spos actlist[lpos+1] = nil actlist[lpos+2] = nil actlist[lpos+3] = nil actargs[apos+1] = nil actargs[apos+2] = nil actargs[apos+3] = nil end error(err, 0) end map_op[".template__"] = op_template ------------------------------------------------------------------------------ -- Pseudo-opcode to mark the position where the action list is to be emitted. map_op[".actionlist_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeactions(out, name) end) end -- Pseudo-opcode to mark the position where the global enum is to be emitted. map_op[".globals_1"] = function(params) if not params then return "prefix" end local prefix = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeglobals(out, prefix) end) end -- Pseudo-opcode to mark the position where the global names are to be emitted. map_op[".globalnames_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeglobalnames(out, name) end) end -- Pseudo-opcode to mark the position where the extern names are to be emitted. map_op[".externnames_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeexternnames(out, name) end) end ------------------------------------------------------------------------------ -- Label pseudo-opcode (converted from trailing colon form). map_op[".label_1"] = function(params) if not params then return "[1-9] | ->global | =>pcexpr" end if secpos+1 > maxsecpos then wflush() end local mode, n, s = parse_label(params[1], true) if mode == "EXT" then werror("bad label definition") end waction("LABEL_"..mode, n, s, 1) end ------------------------------------------------------------------------------ -- Pseudo-opcodes for data storage. map_op[".long_*"] = function(params) if not params then return "imm..." end for _,p in ipairs(params) do local n = tonumber(p) if not n then werror("bad immediate `"..p.."'") end if n < 0 then n = n + 2^32 end wputw(n) if secpos+2 > maxsecpos then wflush() end end end -- Alignment pseudo-opcode. map_op[".align_1"] = function(params) if not params then return "numpow2" end if secpos+1 > maxsecpos then wflush() end local align = tonumber(params[1]) if align then local x = align -- Must be a power of 2 in the range (2 ... 256). for i=1,8 do x = x / 2 if x == 1 then waction("ALIGN", align-1, nil, 1) -- Action byte is 2**n-1. return end end end werror("bad alignment") end ------------------------------------------------------------------------------ -- Pseudo-opcode for (primitive) type definitions (map to C types). map_op[".type_3"] = function(params, nparams) if not params then return nparams == 2 and "name, ctype" or "name, ctype, reg" end local name, ctype, reg = params[1], params[2], params[3] if not match(name, "^[%a_][%w_]*$") then werror("bad type name `"..name.."'") end local tp = map_type[name] if tp then werror("duplicate type `"..name.."'") end -- Add #type to defines. A bit unclean to put it in map_archdef. map_archdef["#"..name] = "sizeof("..ctype..")" -- Add new type and emit shortcut define. local num = ctypenum + 1 map_type[name] = { ctype = ctype, ctypefmt = format("Dt%X(%%s)", num), reg = reg, } wline(format("#define Dt%X(_V) (int)(ptrdiff_t)&(((%s *)0)_V)", num, ctype)) ctypenum = num end map_op[".type_2"] = map_op[".type_3"] -- Dump type definitions. local function dumptypes(out, lvl) local t = {} for name in pairs(map_type) do t[#t+1] = name end sort(t) out:write("Type definitions:\n") for _,name in ipairs(t) do local tp = map_type[name] local reg = tp.reg or "" out:write(format(" %-20s %-20s %s\n", name, tp.ctype, reg)) end out:write("\n") end ------------------------------------------------------------------------------ -- Set the current section. function _M.section(num) waction("SECTION", num) wflush(true) -- SECTION is a terminal action. end ------------------------------------------------------------------------------ -- Dump architecture description. function _M.dumparch(out) out:write(format("DynASM %s version %s, released %s\n\n", _info.arch, _info.version, _info.release)) dumpactions(out) end -- Dump all user defined elements. function _M.dumpdef(out, lvl) dumptypes(out, lvl) dumpglobals(out, lvl) dumpexterns(out, lvl) end ------------------------------------------------------------------------------ -- Pass callbacks from/to the DynASM core. function _M.passcb(wl, we, wf, ww) wline, werror, wfatal, wwarn = wl, we, wf, ww return wflush end -- Setup the arch-specific module. function _M.setup(arch, opt) g_arch, g_opt = arch, opt end -- Merge the core maps and the arch-specific maps. function _M.mergemaps(map_coreop, map_def) setmetatable(map_op, { __index = map_coreop }) setmetatable(map_def, { __index = map_archdef }) return map_op, map_def end return _M ------------------------------------------------------------------------------
mit
gedads/Neodynamis
scripts/zones/Rolanberry_Fields/npcs/Cavernous_Maw.lua
3
2921
----------------------------------- -- Area: Rolanberry Fields -- NPC: Cavernous Maw -- !pos -198 8 361 110 -- Teleports Players to Rolanberry Fields [S] ----------------------------------- package.loaded["scripts/zones/Rolanberry_Fields/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/teleports"); require("scripts/globals/missions"); require("scripts/globals/campaign"); require("scripts/zones/Rolanberry_Fields/TextIDs"); require("scripts/globals/titles"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (ENABLE_WOTG == 1 and player:hasKeyItem(PURE_WHITE_FEATHER) == false) then player:startEvent(500,1); elseif (ENABLE_WOTG == 1 and hasMawActivated(player,1)) then if (player:getCurrentMission(WOTG) == BACK_TO_THE_BEGINNING and (player:getQuestStatus(CRYSTAL_WAR, CLAWS_OF_THE_GRIFFON) == QUEST_COMPLETED or player:getQuestStatus(CRYSTAL_WAR, THE_TIGRESS_STRIKES) == QUEST_COMPLETED or player:getQuestStatus(CRYSTAL_WAR, FIRES_OF_DISCONTENT) == QUEST_COMPLETED)) then player:startEvent(501); else player:startEvent(904); end else player:messageSpecial(NOTHING_HAPPENS); 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:",csid); -- printf("RESULT:",option); if (csid == 500) then local r = math.random(1,3); player:addKeyItem(PURE_WHITE_FEATHER); player:messageSpecial(KEYITEM_OBTAINED,PURE_WHITE_FEATHER); player:completeMission(WOTG,CAVERNOUS_MAWS); player:addMission(WOTG,BACK_TO_THE_BEGINNING); if (r == 1) then player:addNationTeleport(MAW,1); toMaw(player,1); -- go to Batallia_Downs[S] elseif (r == 2) then player:addNationTeleport(MAW,2); toMaw(player,3); -- go to Rolanberry_Fields_[S] elseif (r == 3) then player:addNationTeleport(MAW,4); toMaw(player,5); -- go to Sauromugue_Champaign_[S] end; elseif (csid == 904 and option == 1) then toMaw(player,3); -- go to Rolanberry_Fields_[S] elseif (csid == 501) then player:completeMission(WOTG, BACK_TO_THE_BEGINNING); player:addMission(WOTG, CAIT_SITH); player:addTitle(CAIT_SITHS_ASSISTANT); toMaw(player,3); end; end;
gpl-3.0
blogic/packages
utils/prometheus-node-exporter-lua/files/usr/lib/lua/prometheus-collectors/bmx6.lua
78
1115
#!/usr/bin/lua local json = require "cjson" local function interpret_suffix(rate) local value = string.sub(rate, 1, -2) local suffix = string.sub(rate, -1) if suffix == "K" then return tonumber(value) * 10^3 end if suffix == "M" then return tonumber(value) * 10^6 end if suffix == "G" then return tonumber(value) * 10^9 end return rate end local function scrape() local status = json.decode(get_contents("/var/run/bmx6/json/status")).status local labels = { version = status.version, id = status.name, address = status.primaryIp } metric("bmx6_status", "gauge", labels, 1) local links = json.decode(get_contents("/var/run/bmx6/json/links")).links local metric_bmx6_rxRate = metric("bmx6_link_rxRate","gauge") local metric_bmx6_txRate = metric("bmx6_link_txRate","gauge") for _, link in pairs(links) do local labels = { source = status.name, target = link.name, dev = link.viaDev } metric_bmx6_rxRate(labels, interpret_suffix(link.rxRate)) metric_bmx6_txRate(labels, interpret_suffix(link.txRate)) end end return { scrape = scrape }
gpl-2.0
disslove85/NOVA1-BOT
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
starlightknight/darkstar
scripts/zones/Windurst_Woods/npcs/Mourices.lua
9
3101
----------------------------------- -- Area: Windurst Woods -- NPC: Mourices -- Involved In Mission: Journey Abroad -- !pos -50.646 -0.501 -27.642 241 ----------------------------------- require("scripts/globals/keyitems") require("scripts/globals/missions") require("scripts/globals/npc_util") ----------------------------------- function onTrade(player,npc,trade) local missionStatus = player:getCharVar("MissionStatus") if player:getCurrentMission(SANDORIA) == dsp.mission.id.sandoria.JOURNEY_TO_WINDURST and npcUtil.tradeHas(trade, {{12298,2}}) then -- Parana Shield x2 if missionStatus == 5 then player:startEvent(455) -- before deliver shield to the yagudo elseif missionStatus == 6 then player:startEvent(457) -- after deliver...Finish part of this quest end end end function onTrigger(player,npc) local missionStatus = player:getCharVar("MissionStatus") if player:getCurrentMission(SANDORIA) == dsp.mission.id.sandoria.JOURNEY_ABROAD then -- San d'Oria Mission 2-3 Part I - Windurst > Bastok if missionStatus == 2 then player:startEvent(448) elseif missionStatus == 7 then player:startEvent(458) -- San d'Oria Mission 2-3 Part II - Bastok > Windurst elseif missionStatus == 6 then player:startEvent(462) elseif missionStatus == 11 then player:startEvent(468) end -- San d'Oria Mission 2-3 Part I - Windurst > Bastok elseif player:getCurrentMission(SANDORIA) == dsp.mission.id.sandoria.JOURNEY_TO_WINDURST then if missionStatus >= 3 and missionStatus <= 5 then player:startEvent(449) elseif missionStatus == 6 then player:startEvent(456) end -- San d'Oria Mission 2-3 Part II - Bastok > Windurst elseif player:getCurrentMission(SANDORIA) == dsp.mission.id.sandoria.JOURNEY_TO_WINDURST2 then if missionStatus == 7 or missionStatus == 8 then player:startEvent(463) elseif missionStatus == 9 or missionStatus == 10 then player:startEvent(467) end else player:startEvent(441) end end function onEventUpdate(player,csid,option) end function onEventFinish(player,csid,option) if csid == 448 then player:addMission(SANDORIA,dsp.mission.id.sandoria.JOURNEY_TO_WINDURST) player:setCharVar("MissionStatus",3) player:delKeyItem(dsp.ki.LETTER_TO_THE_CONSULS_SANDORIA) elseif csid == 457 then player:setCharVar("MissionStatus",7) player:confirmTrade() player:addMission(SANDORIA,dsp.mission.id.sandoria.JOURNEY_ABROAD) elseif csid == 462 then player:addMission(SANDORIA,dsp.mission.id.sandoria.JOURNEY_TO_WINDURST2) player:setCharVar("MissionStatus",7) elseif csid == 467 then player:addMission(SANDORIA,dsp.mission.id.sandoria.JOURNEY_ABROAD) player:delKeyItem(dsp.ki.KINDRED_CREST) player:setCharVar("MissionStatus",11) npcUtil.giveKeyItem(player, dsp.ki.KINDRED_REPORT) end end
gpl-3.0
dimitarcl/premake-dev
tests/actions/vstudio/cs2005/projectelement.lua
2
1144
-- -- tests/actions/vstudio/cs2005/projectelement.lua -- Validate generation of <Project/> element in Visual Studio 2005+ .csproj -- Copyright (c) 2009-2011 Jason Perkins and the Premake project -- T.vstudio_cs2005_projectelement = { } local suite = T.vstudio_cs2005_projectelement local cs2005 = premake.vstudio.cs2005 -- -- Setup -- local sln, prj function suite.setup() sln, prj = test.createsolution() end local function prepare() cs2005.xmlDeclaration() cs2005.projectElement(prj) end -- -- Tests -- function suite.On2005() _ACTION = "vs2005" prepare() test.capture [[ <Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> ]] end function suite.On2008() _ACTION = "vs2008" prepare() test.capture [[ <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> ]] end function suite.On2010() _ACTION = "vs2010" prepare() test.capture [[ <?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> ]] end
bsd-3-clause
gedads/Neodynamis
scripts/zones/Tavnazian_Safehold/npcs/Justinius.lua
3
1989
----------------------------------- -- Area: Tavnazian Safehold -- NPC: Justinius -- Involved in mission : COP2-3 -- !pos 76 -34 68 26 ----------------------------------- package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil; ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/missions"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getCurrentMission(COP) == DISTANT_BELIEFS and player:getVar("PromathiaStatus") == 3) then player:startEvent(0x0071); elseif (player:getCurrentMission(COP) == SHELTERING_DOUBT and player:getVar("PromathiaStatus") == 2) then player:startEvent(0x006D); elseif (player:getCurrentMission(COP) == THE_SAVAGE and player:getVar("PromathiaStatus") == 2) then player:startEvent(0x006E); else player:startEvent(0x007B); 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 == 0x0071) then player:setVar("PromathiaStatus",0); player:completeMission(COP,DISTANT_BELIEFS); player:addMission(COP,AN_ETERNAL_MELODY); elseif (csid == 0x006D) then player:setVar("PromathiaStatus",3); elseif (csid == 0x006E) then player:setVar("PromathiaStatus",0); player:completeMission(COP,THE_SAVAGE); player:addMission(COP,THE_SECRETS_OF_WORSHIP); player:addTitle(NAGMOLADAS_UNDERLING); end end;
gpl-3.0
SuetyDig/IntWars
lua/config.lua
3
1066
players = { ["player1"] = { ["rank"] = "DIAMOND", ["name"] = "Test", ["champion"] = "Ezreal", ["team"] = "BLUE", -- BLUE or PURPLE ["skin"] = 0, ["summoner1"] = "HEAL", ["summoner2"] = "FLASH", ["ribbon"] = 2, -- [ 1 = Leader (Yellow) ] [ 2 = Mentor (Blue) ] [ 4 = Cooperative (Green) ] ["icon"] = 0 -- Summoner Icon ID }, --[[-- uncomment this for more players! you can also add more, up to 12! ["player2"] = { ["rank"] = "DIAMOND", ["name"] = "Test2", ["champion"] = "Ezreal", ["team"] = "PURPLE", ["skin"] = 1, ["summoner1"] = "FLASH", ["summoner2"] = "IGNITE", ["ribbon"] = 2, ["icon"] = 0 }, --]] --[[ ["player3"] = { ["rank"] = "DIAMOND", ["name"] = "Test3", ["champion"] = "Caitlyn", ["team"] = "BLUE", ["skin"] = 3, ["summoner1"] = "CLEANSE", ["summoner2"] = "TELEPORT", ["ribbon"] = 2, ["icon"] = 0 }--]] } game = { --[[ 1 - Summoner's Rift 6 - Crystal Scar 8 - Twisted Treeline 12 - Howling Abyss 11 - New Summoner's Rift (only on the PBE client) --]] ["map"] = 1 }
gpl-3.0
alomina007/asli
plugins/admin.lua
3
7404
local function set_bot_photo(msg, success, result) local receiver = get_receiver(msg) if success then local file = 'data/photos/bot.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) set_profile_photo(file, ok_cb, false) send_large_msg(receiver, 'عکس تغییر کرد!', ok_cb, false) redis:del("bot:photo") else print('Error downloading: '..msg.id) send_large_msg(receiver, 'مشکل.لطفا دوباره امتحان کنید!', ok_cb, false) end end local function parsed_url(link) local parsed_link = URL.parse(link) local parsed_path = URL.parse_path(parsed_link.path) return parsed_path[2] end local function get_contact_list_callback (cb_extra, success, result) local text = " " for k,v in pairs(result) do if v.print_name and v.id and v.phone then text = text..string.gsub(v.print_name , "_" , " ").." ["..v.id.."] = "..v.phone.."\n" end end local file = io.open("contact_list.txt", "w") file:write(text) file:flush() file:close() send_document("user#id"..cb_extra.target,"contact_list.txt", ok_cb, false)--.txt format local file = io.open("contact_list.json", "w") file:write(json:encode_pretty(result)) file:flush() file:close() send_document("user#id"..cb_extra.target,"contact_list.json", ok_cb, false)--json format end local function user_info_callback(cb_extra, success, result) result.access_hash = nil result.flags = nil result.phone = nil if result.username then result.username = '@'..result.username end result.print_name = result.print_name:gsub("_","") local text = serpent.block(result, {comment=false}) text = text:gsub("[{}]", "") text = text:gsub('"', "") text = text:gsub(",","") if cb_extra.msg.to.type == "chat" then send_large_msg("chat#id"..cb_extra.msg.to.id, text) else send_large_msg("user#id"..cb_extra.msg.to.id, text) end end local function get_dialog_list_callback(cb_extra, success, result) local text = "" for k,v in pairs(result) do if v.peer then if v.peer.type == "chat" then text = text.."group{"..v.peer.title.."}["..v.peer.id.."]("..v.peer.members_num..")" else if v.peer.print_name and v.peer.id then text = text.."user{"..v.peer.print_name.."}["..v.peer.id.."]" end if v.peer.username then text = text.."("..v.peer.username..")" end if v.peer.phone then text = text.."'"..v.peer.phone.."'" end end end if v.message then text = text..'\nlast msg >\nmsg id = '..v.message.id if v.message.text then text = text .. "\n text = "..v.message.text end if v.message.action then text = text.."\n"..serpent.block(v.message.action, {comment=false}) end if v.message.from then if v.message.from.print_name then text = text.."\n From > \n"..string.gsub(v.message.from.print_name, "_"," ").."["..v.message.from.id.."]" end if v.message.from.username then text = text.."( "..v.message.from.username.." )" end if v.message.from.phone then text = text.."' "..v.message.from.phone.." '" end end end text = text.."\n\n" end local file = io.open("dialog_list.txt", "w") file:write(text) file:flush() file:close() send_document("user#id"..cb_extra.target,"dialog_list.txt", ok_cb, false)--.txt format local file = io.open("dialog_list.json", "w") file:write(json:encode_pretty(result)) file:flush() file:close() send_document("user#id"..cb_extra.target,"dialog_list.json", ok_cb, false)--json format end local function run(msg,matches) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) local group = msg.to.id if not is_admin(msg) then return end if msg.media then if msg.media.type == 'photo' and redis:get("bot:photo") then if redis:get("bot:photo") == 'waiting' then load_photo(msg.id, set_bot_photo, msg) end end end if matches[1] == "setbotphoto" then redis:set("bot:photo", "waiting") return 'لطفا عکس جدید ربات را ارسال کنید' end if matches[1] == "markread" then if matches[2] == "on" then redis:set("bot:markread", "on") return "خواندن پیام ها روشن شد" end if matches[2] == "off" then redis:del("bot:markread") return "خواندن پیام ها خاموش شد" end return end if matches[1] == "pm" then send_large_msg("user#id"..matches[2],matches[3]) return "پیام ارسال شد" end if matches[1] == "block" then if is_admin2(matches[2]) then return "شما نمیتوانید ادمین هارا بلاک کنید" end block_user("user#id"..matches[2],ok_cb,false) return "کاربر بلاک شد" end if matches[1] == "unblock" then unblock_user("user#id"..matches[2],ok_cb,false) return "کاربر از بلاک خارج شد" end if matches[1] == "import" then--join by group link local hash = parsed_url(matches[2]) import_chat_link(hash,ok_cb,false) end if matches[1] == "contactlist" then get_contact_list(get_contact_list_callback, {target = msg.from.id}) return "من لیست تماس را به خصوصی شما در قالب متن ارسال کردم" end if matches[1] == "addcontact" and matches[2] then add_contact(matches[2],matches[3],matches[4],ok_cb,false) return "شماره "..matches[2].." در لیست شماره ها دخیره شد" end if matches[1] == "delcontact" then del_contact("user#id"..matches[2],ok_cb,false) return "کاربر "..matches[2].." از لیست شماره ها پاک شد" end if matches[1] == "dialoglist" then get_dialog_list(get_dialog_list_callback, {target = msg.from.id}) return "من لیست محاوره ای را در قالب متن به خصوصی شما ارسال کردم" end if matches[1] == "whois" then user_info("user#id"..matches[2],user_info_callback,{msg=msg}) end if matches[1] == "sync_gbans" then if not is_sudo(msg) then-- Sudo only return end local url = "http://seedteam.org/Teleseed/Global_bans.json" local SEED_gbans = http.request(url) local jdat = json:decode(SEED_gbans) for k,v in pairs(jdat) do redis:hset('user:'..v, 'print_name', k) banall_user(v) print(k, v.." Globally banned") end end return end return { patterns = { "^[!/](pm) (%d+) (.*)$", "^[!/](import) (.*)$", "^[!/](unblock) (%d+)$", "^[!/](block) (%d+)$", "^[!/](markread) (on)$", "^[!/](markread) (off)$", "^[!/](setbotphoto)$", "%[(photo)%]", "^[!/](contactlist)$", "^[!/](dialoglist)$", "^[!/](delcontact) (%d+)$", "^[!/](addcontact) (.*) (.*) (.*)$", "^[!/](whois) (%d+)$", "^/(sync_gbans)$"--sync your global bans with seed }, run = run, } --By @imandaneshi :) --https://github.com/SEEDTEAM/TeleSeed/blob/master/plugins/admin.lua
gpl-2.0
gedads/Neodynamis
scripts/zones/Desuetia_Empyreal_Paradox/Zone.lua
30
1470
----------------------------------- -- -- Zone: Desuetia Empyreal Paradox (290) -- ----------------------------------- package.loaded["scripts/zones/Desuetia_Empyreal_Paradox/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Desuetia_Empyreal_Paradox/TextIDs"); require("scripts/globals/settings"); require("scripts/globals/zone"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then -- player:setPos(x, y, z, rot); end return cs; end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
strava/thrift
lib/lua/TTransport.lua
115
2800
-- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you 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. -- require 'Thrift' TTransportException = TException:new { UNKNOWN = 0, NOT_OPEN = 1, ALREADY_OPEN = 2, TIMED_OUT = 3, END_OF_FILE = 4, INVALID_FRAME_SIZE = 5, INVALID_TRANSFORM = 6, INVALID_CLIENT_TYPE = 7, errorCode = 0, __type = 'TTransportException' } function TTransportException:__errorCodeToString() if self.errorCode == self.NOT_OPEN then return 'Transport not open' elseif self.errorCode == self.ALREADY_OPEN then return 'Transport already open' elseif self.errorCode == self.TIMED_OUT then return 'Transport timed out' elseif self.errorCode == self.END_OF_FILE then return 'End of file' elseif self.errorCode == self.INVALID_FRAME_SIZE then return 'Invalid frame size' elseif self.errorCode == self.INVALID_TRANSFORM then return 'Invalid transform' elseif self.errorCode == self.INVALID_CLIENT_TYPE then return 'Invalid client type' else return 'Default (unknown)' end end TTransportBase = __TObject:new{ __type = 'TTransportBase' } function TTransportBase:isOpen() end function TTransportBase:open() end function TTransportBase:close() end function TTransportBase:read(len) end function TTransportBase:readAll(len) local buf, have, chunk = '', 0 while have < len do chunk = self:read(len - have) have = have + string.len(chunk) buf = buf .. chunk if string.len(chunk) == 0 then terror(TTransportException:new{ errorCode = TTransportException.END_OF_FILE }) end end return buf end function TTransportBase:write(buf) end function TTransportBase:flush() end TServerTransportBase = __TObject:new{ __type = 'TServerTransportBase' } function TServerTransportBase:listen() end function TServerTransportBase:accept() end function TServerTransportBase:close() end TTransportFactoryBase = __TObject:new{ __type = 'TTransportFactoryBase' } function TTransportFactoryBase:getTransport(trans) return trans end
apache-2.0
gedads/Neodynamis
scripts/globals/items/slice_of_salted_hare.lua
12
1263
----------------------------------------- -- ID: 5737 -- Item: slice_of_salted_hare -- Food Effect: 30Min, All Races ----------------------------------------- -- HP 10 -- Strength 1 -- hHP +1 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,5737); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 10); target:addMod(MOD_STR, 1); target:addMod(MOD_HPHEAL, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 10); target:delMod(MOD_STR, 1); target:delMod(MOD_HPHEAL, 1); end;
gpl-3.0
gedads/Neodynamis
scripts/zones/Halvung/npcs/qm2.lua
3
1318
----------------------------------- -- Area: Halvung -- NPC: ??? (Spawn Dextrose(ZNM T2)) -- !pos -144 11 464 62 ----------------------------------- package.loaded["scripts/zones/Halvung/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Halvung/TextIDs"); require("scripts/globals/status"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local mobID = 17031598; if (trade:hasItemQty(2589,1) and trade:getItemCount() == 1) then -- Trade Granulated Sugar 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
mishin/Algorithm-Implementations
Newton_Raphson/Lua/Yonaba/newtonraphson.lua
52
1091
-- Newton (Raphson) root finding algorithm implementation -- See : http://en.wikipedia.org/wiki/Newton%27s_method -- Fuzzy equality test local function fuzzyEqual(a, b, eps) local eps = eps or 1e-4 return (math.abs(a - b) < eps) end -- Evaluates the derivative of function f at x0 -- Uses Newton's centered slope approximation local function drvMid(f, x0, initStep) local step = initStep or 0.1 local incr1, incr2 = (f(x0 + step) - f(x0 - step)) / (2 * step) repeat incr2 = incr1 step = step / 2 incr1 = (f(x0 + step) - f(x0 - step)) / (2 * step) until fuzzyEqual(incr1, incr2) return incr1 end -- Find a zero for a given function f -- f : the equation, to be solved (f(x) = 0) -- initStep : (optional) initial value for iterations -- eps : (optional) accuracy parameter for convergence -- returns : a zero for the function f return function(f, initStep, eps) local next_x = initStep or 0 local prev_x repeat prev_x = next_x next_x = next_x - (f(next_x) / drvMid(f, next_x)) until fuzzyEqual(next_x, prev_x, eps) return next_x end
mit
zzzaaiidd/TCHUKY
data/config.lua
1
1386
do local _ = { about_text = "▫️Welcome to TCHUKY V8 For more information Subscribe to the channel @zzzaiddd \n https://github.com/zzzaaiidd/TCHUKY\n\n▫️Dev @zzaiddd\n\n▫️ Dev Bot @zzaiddd_bot\n\n ▫️channel@ zzzaiddd ", enabled_plugins = { "badword", "admin", "ingroup", "stats", "anti_spam", "owners", "arabic_lock", "set", "get", "invite", "all", "leave_ban", "setwelcome", "msg_checks", "hello", "isup", "onservice", "supergroup", "banhammer", "broadcast", "badword", "addsudo", "insta", "info", "textphoto", "lock_bot", "lock_fwd", "me", "plugins", "image", "sticker", "map", "voice", "getlink", "getfile", "zzaiddd", "VIRSON", "zzaiddd1", "zzaiddd2", "zzaiddd3", "zzaiddd4", "zzaiddd5", "zzaiddd6", "zzaiddd7", "newgroup", "replay", "help", "stats", "lock_media", "decoration", "nedme", "writer", "@zzaiddd", "kickall", "run", "delete", "Serverinfo", "leave_bot", "kickme", "addreplay", "addtime", "tagall", "design" }, help_text = "", help_text_realm = "", help_text_super = "", moderation = { data = "data/moderation.json" }, sudo_users = { 244300626, 272806295, } } return _ end
gpl-2.0
raymondtfr/forgottenserver
data/npc/lib/npcsystem/modules.lua
3
38824
-- Advanced NPC System by Jiddo if Modules == nil then -- default words for greeting and ungreeting the npc. Should be a table containing all such words. FOCUS_GREETWORDS = {"hi", "hello"} FOCUS_FAREWELLWORDS = {"bye", "farewell"} -- The words for requesting trade window. SHOP_TRADEREQUEST = {"trade"} -- The word for accepting/declining an offer. CAN ONLY CONTAIN ONE FIELD! Should be a table with a single string value. SHOP_YESWORD = {"yes"} SHOP_NOWORD = {"no"} -- Pattern used to get the amount of an item a player wants to buy/sell. PATTERN_COUNT = "%d+" -- Constants used to separate buying from selling. SHOPMODULE_SELL_ITEM = 1 SHOPMODULE_BUY_ITEM = 2 SHOPMODULE_BUY_ITEM_CONTAINER = 3 -- Constants used for shop mode. Notice: addBuyableItemContainer is working on all modes SHOPMODULE_MODE_TALK = 1 -- Old system used before client version 8.2: sell/buy item name SHOPMODULE_MODE_TRADE = 2 -- Trade window system introduced in client version 8.2 SHOPMODULE_MODE_BOTH = 3 -- Both working at one time -- Used shop mode SHOPMODULE_MODE = SHOPMODULE_MODE_BOTH Modules = { parseableModules = {} } StdModule = {} -- These callback function must be called with parameters.npcHandler = npcHandler in the parameters table or they will not work correctly. -- Notice: The members of StdModule have not yet been tested. If you find any bugs, please report them to me. -- Usage: -- keywordHandler:addKeyword({"offer"}, StdModule.say, {npcHandler = npcHandler, text = "I sell many powerful melee weapons."}) function StdModule.say(cid, message, keywords, parameters, node) local npcHandler = parameters.npcHandler if npcHandler == nil then error("StdModule.say called without any npcHandler instance.") end local onlyFocus = (parameters.onlyFocus == nil or parameters.onlyFocus == true) if not npcHandler:isFocused(cid) and onlyFocus then return false end local parseInfo = {[TAG_PLAYERNAME] = Player(cid):getName()} npcHandler:say(npcHandler:parseMessage(parameters.text or parameters.message, parseInfo), cid, parameters.publicize and true) if parameters.reset then npcHandler:resetNpc(cid) elseif parameters.moveup then npcHandler.keywordHandler:moveUp(cid, parameters.moveup) end return true end --Usage: -- local node1 = keywordHandler:addKeyword({"promot"}, StdModule.say, {npcHandler = npcHandler, text = "I can promote you for 20000 gold coins. Do you want me to promote you?"}) -- node1:addChildKeyword({"yes"}, StdModule.promotePlayer, {npcHandler = npcHandler, cost = 20000, level = 20}, text = "Congratulations! You are now promoted.") -- node1:addChildKeyword({"no"}, StdModule.say, {npcHandler = npcHandler, text = "Allright then. Come back when you are ready."}, reset = true) function StdModule.promotePlayer(cid, message, keywords, parameters, node) local npcHandler = parameters.npcHandler if npcHandler == nil then error("StdModule.promotePlayer called without any npcHandler instance.") end if not npcHandler:isFocused(cid) then return false end local player = Player(cid) if player:isPremium() or not parameters.premium then local promotion = player:getVocation():getPromotion() if player:getStorageValue(STORAGEVALUE_PROMOTION) == 1 then npcHandler:say("You are already promoted!", cid) elseif player:getLevel() < parameters.level then npcHandler:say("I am sorry, but I can only promote you once you have reached level " .. parameters.level .. ".", cid) elseif not player:removeMoney(parameters.cost) then npcHandler:say("You do not have enough money!", cid) else npcHandler:say(parameters.text, cid) player:setVocation(promotion) player:setStorageValue(STORAGEVALUE_PROMOTION, 1) end else npcHandler:say("You need a premium account in order to get promoted.", cid) end npcHandler:resetNpc(cid) return true end function StdModule.learnSpell(cid, message, keywords, parameters, node) local npcHandler = parameters.npcHandler if npcHandler == nil then error("StdModule.learnSpell called without any npcHandler instance.") end if not npcHandler:isFocused(cid) then return false end local player = Player(cid) if player:isPremium() or not parameters.premium then if player:hasLearnedSpell(parameters.spellName) then npcHandler:say("You already know this spell.", cid) elseif not player:canLearnSpell(parameters.spellName) then npcHandler:say("You cannot learn this spell.", cid) elseif not player:removeMoney(parameters.price) then npcHandler:say("You do not have enough money, this spell costs " .. parameters.price .. " gold.", cid) else npcHandler:say("You have learned " .. parameters.spellName .. ".", cid) player:learnSpell(parameters.spellName) end else npcHandler:say("You need a premium account in order to buy " .. parameters.spellName .. ".", cid) end npcHandler:resetNpc(cid) return true end function StdModule.bless(cid, message, keywords, parameters, node) local npcHandler = parameters.npcHandler if npcHandler == nil then error("StdModule.bless called without any npcHandler instance.") end if not npcHandler:isFocused(cid) or getWorldType() == WORLD_TYPE_PVP_ENFORCED then return false end local player = Player(cid) if player:isPremium() or not parameters.premium then if player:hasBlessing(parameters.bless) then npcHandler:say("Gods have already blessed you with this blessing!", cid) elseif not player:removeMoney(parameters.cost) then npcHandler:say("You don't have enough money for blessing.", cid) else player:addBlessing(parameters.bless) npcHandler:say("You have been blessed by one of the five gods!", cid) end else npcHandler:say("You need a premium account in order to be blessed.", cid) end npcHandler:resetNpc(cid) return true end function StdModule.travel(cid, message, keywords, parameters, node) local npcHandler = parameters.npcHandler if npcHandler == nil then error("StdModule.travel called without any npcHandler instance.") end if not npcHandler:isFocused(cid) then return false end local player = Player(cid) if player:isPremium() or not parameters.premium then if player:isPzLocked() then npcHandler:say("First get rid of those blood stains! You are not going to ruin my vehicle!", cid) elseif parameters.level and player:getLevel() < parameters.level then npcHandler:say("You must reach level " .. parameters.level .. " before I can let you go there.", cid) elseif not player:removeMoney(parameters.cost) then npcHandler:say("You don't have enough money.", cid) else npcHandler:say(parameters.msg or "Set the sails!", cid) npcHandler:releaseFocus(cid) local destination = Position(parameters.destination) local position = player:getPosition() player:teleportTo(destination) position:sendMagicEffect(CONST_ME_TELEPORT) destination:sendMagicEffect(CONST_ME_TELEPORT) end else npcHandler:say("I'm sorry, but you need a premium account in order to travel onboard our ships.", cid) end npcHandler:resetNpc(cid) return true end FocusModule = { npcHandler = nil } -- Creates a new instance of FocusModule without an associated NpcHandler. function FocusModule:new() local obj = {} setmetatable(obj, self) self.__index = self return obj end -- Inits the module and associates handler to it. function FocusModule:init(handler) self.npcHandler = handler for i, word in pairs(FOCUS_GREETWORDS) do local obj = {} obj[#obj + 1] = word obj.callback = FOCUS_GREETWORDS.callback or FocusModule.messageMatcher handler.keywordHandler:addKeyword(obj, FocusModule.onGreet, {module = self}) end for i, word in pairs(FOCUS_FAREWELLWORDS) do local obj = {} obj[#obj + 1] = word obj.callback = FOCUS_FAREWELLWORDS.callback or FocusModule.messageMatcher handler.keywordHandler:addKeyword(obj, FocusModule.onFarewell, {module = self}) end return true end -- Greeting callback function. function FocusModule.onGreet(cid, message, keywords, parameters) parameters.module.npcHandler:onGreet(cid) return true end -- UnGreeting callback function. function FocusModule.onFarewell(cid, message, keywords, parameters) if parameters.module.npcHandler:isFocused(cid) then parameters.module.npcHandler:onFarewell(cid) return true else return false end end -- Custom message matching callback function for greeting messages. function FocusModule.messageMatcher(keywords, message) for i, word in pairs(keywords) do if type(word) == "string" then if string.find(message, word) and not string.find(message, "[%w+]" .. word) and not string.find(message, word .. "[%w+]") then return true end end end return false end KeywordModule = { npcHandler = nil } -- Add it to the parseable module list. Modules.parseableModules["module_keywords"] = KeywordModule function KeywordModule:new() local obj = {} setmetatable(obj, self) self.__index = self return obj end function KeywordModule:init(handler) self.npcHandler = handler return true end -- Parses all known parameters. function KeywordModule:parseParameters() local ret = NpcSystem.getParameter("keywords") if ret then self:parseKeywords(ret) end end function KeywordModule:parseKeywords(data) local n = 1 for keys in string.gmatch(data, "[^;]+") do local i = 1 local keywords = {} for temp in string.gmatch(keys, "[^,]+") do keywords[#keywords + 1] = temp i = i + 1 end if i ~= 1 then local reply = NpcSystem.getParameter("keyword_reply" .. n) if reply then self:addKeyword(keywords, reply) else print("[Warning : " .. Npc():getName() .. "] NpcSystem:", "Parameter '" .. "keyword_reply" .. n .. "' missing. Skipping...") end else print("[Warning : " .. Npc():getName() .. "] NpcSystem:", "No keywords found for keyword set #" .. n .. ". Skipping...") end n = n + 1 end end function KeywordModule:addKeyword(keywords, reply) self.npcHandler.keywordHandler:addKeyword(keywords, StdModule.say, {npcHandler = self.npcHandler, onlyFocus = true, text = reply, reset = true}) end TravelModule = { npcHandler = nil, destinations = nil, yesNode = nil, noNode = nil, } -- Add it to the parseable module list. Modules.parseableModules["module_travel"] = TravelModule function TravelModule:new() local obj = {} setmetatable(obj, self) self.__index = self return obj end function TravelModule:init(handler) self.npcHandler = handler self.yesNode = KeywordNode:new(SHOP_YESWORD, TravelModule.onConfirm, {module = self}) self.noNode = KeywordNode:new(SHOP_NOWORD, TravelModule.onDecline, {module = self}) self.destinations = {} return true end -- Parses all known parameters. function TravelModule:parseParameters() local ret = NpcSystem.getParameter("travel_destinations") if ret then self:parseDestinations(ret) self.npcHandler.keywordHandler:addKeyword({"destination"}, TravelModule.listDestinations, {module = self}) self.npcHandler.keywordHandler:addKeyword({"where"}, TravelModule.listDestinations, {module = self}) self.npcHandler.keywordHandler:addKeyword({"travel"}, TravelModule.listDestinations, {module = self}) end end function TravelModule:parseDestinations(data) for destination in string.gmatch(data, "[^;]+") do local i = 1 local name = nil local x = nil local y = nil local z = nil local cost = nil local premium = false for temp in string.gmatch(destination, "[^,]+") do if i == 1 then name = temp elseif i == 2 then x = tonumber(temp) elseif i == 3 then y = tonumber(temp) elseif i == 4 then z = tonumber(temp) elseif i == 5 then cost = tonumber(temp) elseif i == 6 then premium = temp == "true" else print("[Warning : " .. getCreatureName(getNpcCid()) .. "] NpcSystem:", "Unknown parameter found in travel destination parameter.", temp, destination) end i = i + 1 end if name and x and y and z and cost then self:addDestination(name, {x=x, y=y, z=z}, cost, premium) else print("[Warning : " .. Npc():getName() .. "] NpcSystem:", "Parameter(s) missing for travel destination:", name, x, y, z, cost, premium) end end end function TravelModule:addDestination(name, position, price, premium) self.destinations[#self.destinations + 1] = name local parameters = { cost = price, destination = position, premium = premium, module = self } local keywords = {} keywords[#keywords + 1] = name local keywords2 = {} keywords2[#keywords2 + 1] = "bring me to " .. name local node = self.npcHandler.keywordHandler:addKeyword(keywords, TravelModule.travel, parameters) self.npcHandler.keywordHandler:addKeyword(keywords2, TravelModule.bringMeTo, parameters) node:addChildKeywordNode(self.yesNode) node:addChildKeywordNode(self.noNode) if npcs_loaded_travel[getNpcCid()] == nil then npcs_loaded_travel[getNpcCid()] = getNpcCid() self.npcHandler.keywordHandler:addKeyword({'yes'}, TravelModule.onConfirm, {module = self}) self.npcHandler.keywordHandler:addKeyword({'no'}, TravelModule.onDecline, {module = self}) end end function TravelModule.travel(cid, message, keywords, parameters, node) local module = parameters.module if not module.npcHandler:isFocused(cid) then return false end local npcHandler = module.npcHandler shop_destination[cid] = parameters.destination shop_cost[cid] = parameters.cost shop_premium[cid] = parameters.premium shop_npcuid[cid] = getNpcCid() local cost = parameters.cost local destination = parameters.destination local premium = parameters.premium module.npcHandler:say("Do you want to travel to " .. keywords[1] .. " for " .. cost .. " gold coins?", cid) return true end function TravelModule.onConfirm(cid, message, keywords, parameters, node) local module = parameters.module if not module.npcHandler:isFocused(cid) then return false end if shop_npcuid[cid] ~= Npc().uid then return false end local npcHandler = module.npcHandler local cost = shop_cost[cid] local destination = Position(shop_destination[cid]) local player = Player(cid) if player:isPremium() or not shop_premium[cid] then if not player:removeMoney(cost) then npcHandler:say("You do not have enough money!", cid) elseif player:isPzLocked(cid) then npcHandler:say("Get out of there with this blood.", cid) else npcHandler:say("It was a pleasure doing business with you.", cid) npcHandler:releaseFocus(cid) local position = player:getPosition() player:teleportTo(destination) position:sendMagicEffect(CONST_ME_TELEPORT) destination:sendMagicEffect(CONST_ME_TELEPORT) end else npcHandler:say("I can only allow premium players to travel there.", cid) end npcHandler:resetNpc(cid) return true end -- onDecline keyword callback function. Generally called when the player sais "no" after wanting to buy an item. function TravelModule.onDecline(cid, message, keywords, parameters, node) local module = parameters.module if not module.npcHandler:isFocused(cid) or shop_npcuid[cid] ~= getNpcCid() then return false end local parentParameters = node:getParent():getParameters() local parseInfo = { [TAG_PLAYERNAME] = Player(cid):getName() } local msg = module.npcHandler:parseMessage(module.npcHandler:getMessage(MESSAGE_DECLINE), parseInfo) module.npcHandler:say(msg, cid) module.npcHandler:resetNpc(cid) return true end function TravelModule.bringMeTo(cid, message, keywords, parameters, node) local module = parameters.module if not module.npcHandler:isFocused(cid) then return false end local cost = parameters.cost local destination = Position(parameters.destination) local player = Player(cid) if player:isPremium() or not parameters.premium then if player:removeMoney(cost) then local position = player:getPosition() player:teleportTo(destination) position:sendMagicEffect(CONST_ME_TELEPORT) destination:sendMagicEffect(CONST_ME_TELEPORT) end end return true end function TravelModule.listDestinations(cid, message, keywords, parameters, node) local module = parameters.module if not module.npcHandler:isFocused(cid) then return false end local msg = "I can bring you to " --local i = 1 local maxn = #module.destinations for i, destination in pairs(module.destinations) do msg = msg .. destination if i == maxn - 1 then msg = msg .. " and " elseif i == maxn then msg = msg .. "." else msg = msg .. ", " end i = i + 1 end module.npcHandler:say(msg, cid) module.npcHandler:resetNpc(cid) return true end ShopModule = { npcHandler = nil, yesNode = nil, noNode = nil, noText = "", maxCount = 100, amount = 0 } -- Add it to the parseable module list. Modules.parseableModules["module_shop"] = ShopModule -- Creates a new instance of ShopModule function ShopModule:new() local obj = {} setmetatable(obj, self) self.__index = self return obj end -- Parses all known parameters. function ShopModule:parseParameters() local ret = NpcSystem.getParameter("shop_buyable") if ret then self:parseBuyable(ret) end local ret = NpcSystem.getParameter("shop_sellable") if ret then self:parseSellable(ret) end local ret = NpcSystem.getParameter("shop_buyable_containers") if ret then self:parseBuyableContainers(ret) end end -- Parse a string contaning a set of buyable items. function ShopModule:parseBuyable(data) for item in string.gmatch(data, "[^;]+") do local i = 1 local name = nil local itemid = nil local cost = nil local subType = nil local realName = nil for temp in string.gmatch(item, "[^,]+") do if i == 1 then name = temp elseif i == 2 then itemid = tonumber(temp) elseif i == 3 then cost = tonumber(temp) elseif i == 4 then subType = tonumber(temp) elseif i == 5 then realName = temp else print("[Warning : " .. Npc():getName() .. "] NpcSystem:", "Unknown parameter found in buyable items parameter.", temp, item) end i = i + 1 end local it = ItemType(itemid) if subType == nil and it:getCharges() ~= 0 then subType = it:getCharges() end if SHOPMODULE_MODE == SHOPMODULE_MODE_TRADE then if itemid and cost then if subType == nil and it:isFluidContainer() then print("[Warning : " .. Npc():getName() .. "] NpcSystem:", "SubType missing for parameter item:", item) else self:addBuyableItem(nil, itemid, cost, subType, realName) end else print("[Warning : " .. Npc():getName() .. "] NpcSystem:", "Parameter(s) missing for item:", itemid, cost) end else if name and itemid and cost then if subType == nil and it:isFluidContainer() then print("[Warning : " .. Npc():getName() .. "] NpcSystem:", "SubType missing for parameter item:", item) else local names = {} names[#names + 1] = name self:addBuyableItem(names, itemid, cost, subType, realName) end else print("[Warning : " .. Npc():getName() .. "] NpcSystem:", "Parameter(s) missing for item:", name, itemid, cost) end end end end -- Parse a string contaning a set of sellable items. function ShopModule:parseSellable(data) for item in string.gmatch(data, "[^;]+") do local i = 1 local name = nil local itemid = nil local cost = nil local realName = nil local subType = nil for temp in string.gmatch(item, "[^,]+") do if i == 1 then name = temp elseif i == 2 then itemid = tonumber(temp) elseif i == 3 then cost = tonumber(temp) elseif i == 4 then realName = temp elseif i == 5 then subType = tonumber(temp) else print("[Warning : " .. Npc():getName() .. "] NpcSystem:", "Unknown parameter found in sellable items parameter.", temp, item) end i = i + 1 end if SHOPMODULE_MODE == SHOPMODULE_MODE_TRADE then if itemid and cost then self:addSellableItem(nil, itemid, cost, realName, subType) else print("[Warning : " .. Npc():getName() .. "] NpcSystem:", "Parameter(s) missing for item:", itemid, cost) end else if name and itemid and cost then local names = {} names[#names + 1] = name self:addSellableItem(names, itemid, cost, realName, subType) else print("[Warning : " .. Npc():getName() .. "] NpcSystem:", "Parameter(s) missing for item:", name, itemid, cost) end end end end -- Parse a string contaning a set of buyable items. function ShopModule:parseBuyableContainers(data) for item in string.gmatch(data, "[^;]+") do local i = 1 local name = nil local container = nil local itemid = nil local cost = nil local subType = nil local realName = nil for temp in string.gmatch(item, "[^,]+") do if i == 1 then name = temp elseif i == 2 then itemid = tonumber(temp) elseif i == 3 then itemid = tonumber(temp) elseif i == 4 then cost = tonumber(temp) elseif i == 5 then subType = tonumber(temp) elseif i == 6 then realName = temp else print("[Warning : " .. Npc():getName() .. "] NpcSystem:", "Unknown parameter found in buyable items parameter.", temp, item) end i = i + 1 end if name and container and itemid and cost then if subType == nil and ItemType(itemid):isFluidContainer() then print("[Warning : " .. Npc():getName() .. "] NpcSystem:", "SubType missing for parameter item:", item) else local names = {} names[#names + 1] = name self:addBuyableItemContainer(names, container, itemid, cost, subType, realName) end else print("[Warning : " .. Npc():getName() .. "] NpcSystem:", "Parameter(s) missing for item:", name, container, itemid, cost) end end end -- Initializes the module and associates handler to it. function ShopModule:init(handler) self.npcHandler = handler self.yesNode = KeywordNode:new(SHOP_YESWORD, ShopModule.onConfirm, {module = self}) self.noNode = KeywordNode:new(SHOP_NOWORD, ShopModule.onDecline, {module = self}) self.noText = handler:getMessage(MESSAGE_DECLINE) if SHOPMODULE_MODE ~= SHOPMODULE_MODE_TALK then for i, word in pairs(SHOP_TRADEREQUEST) do local obj = {} obj[#obj + 1] = word obj.callback = SHOP_TRADEREQUEST.callback or ShopModule.messageMatcher handler.keywordHandler:addKeyword(obj, ShopModule.requestTrade, {module = self}) end end return true end -- Custom message matching callback function for requesting trade messages. function ShopModule.messageMatcher(keywords, message) for i, word in pairs(keywords) do if type(word) == "string" then if string.find(message, word) and not string.find(message, "[%w+]" .. word) and not string.find(message, word .. "[%w+]") then return true end end end return false end -- Resets the module-specific variables. function ShopModule:reset() self.amount = 0 end -- Function used to match a number value from a string. function ShopModule:getCount(message) local ret = 1 local b, e = string.find(message, PATTERN_COUNT) if b and e then ret = tonumber(string.sub(message, b, e)) end if ret <= 0 then ret = 1 elseif ret > self.maxCount then ret = self.maxCount end return ret end -- Adds a new buyable item. -- names = A table containing one or more strings of alternative names to this item. Used only for old buy/sell system. -- itemid = The itemid of the buyable item -- cost = The price of one single item -- subType - The subType of each rune or fluidcontainer item. Can be left out if it is not a rune/fluidcontainer. Default value is 1. -- realName - The real, full name for the item. Will be used as ITEMNAME in MESSAGE_ONBUY and MESSAGE_ONSELL if defined. Default value is nil (getItemName will be used) function ShopModule:addBuyableItem(names, itemid, cost, itemSubType, realName) if SHOPMODULE_MODE ~= SHOPMODULE_MODE_TALK then if itemSubType == nil then itemSubType = 1 end local shopItem = self:getShopItem(itemid, itemSubType) if shopItem == nil then self.npcHandler.shopItems[#self.npcHandler.shopItems + 1] = {id = itemid, buy = cost, sell = -1, subType = itemSubType, name = realName or ItemType(itemid):getName()} else shopItem.buy = cost end end if names and SHOPMODULE_MODE ~= SHOPMODULE_MODE_TRADE then for i, name in pairs(names) do local parameters = { itemid = itemid, cost = cost, eventType = SHOPMODULE_BUY_ITEM, module = self, realName = realName or ItemType(itemid):getName(), subType = itemSubType or 1 } keywords = {} keywords[#keywords + 1] = "buy" keywords[#keywords + 1] = name local node = self.npcHandler.keywordHandler:addKeyword(keywords, ShopModule.tradeItem, parameters) node:addChildKeywordNode(self.yesNode) node:addChildKeywordNode(self.noNode) end end if npcs_loaded_shop[getNpcCid()] == nil then npcs_loaded_shop[getNpcCid()] = getNpcCid() self.npcHandler.keywordHandler:addKeyword({'yes'}, ShopModule.onConfirm, {module = self}) self.npcHandler.keywordHandler:addKeyword({'no'}, ShopModule.onDecline, {module = self}) end end function ShopModule:getShopItem(itemId, itemSubType) if ItemType(itemId):isFluidContainer() then for i = 1, #self.npcHandler.shopItems do local shopItem = self.npcHandler.shopItems[i] if shopItem.id == itemId and shopItem.subType == itemSubType then return shopItem end end else for i = 1, #self.npcHandler.shopItems do local shopItem = self.npcHandler.shopItems[i] if shopItem.id == itemId then return shopItem end end end return nil end -- Adds a new buyable container of items. -- names = A table containing one or more strings of alternative names to this item. -- container = Backpack, bag or any other itemid of container where bought items will be stored -- itemid = The itemid of the buyable item -- cost = The price of one single item -- subType - The subType of each rune or fluidcontainer item. Can be left out if it is not a rune/fluidcontainer. Default value is 1. -- realName - The real, full name for the item. Will be used as ITEMNAME in MESSAGE_ONBUY and MESSAGE_ONSELL if defined. Default value is nil (getItemName will be used) function ShopModule:addBuyableItemContainer(names, container, itemid, cost, subType, realName) if names then for i, name in pairs(names) do local parameters = { container = container, itemid = itemid, cost = cost, eventType = SHOPMODULE_BUY_ITEM_CONTAINER, module = self, realName = realName or ItemType(itemid):getName(), subType = subType or 1 } keywords = {} keywords[#keywords + 1] = "buy" keywords[#keywords + 1] = name local node = self.npcHandler.keywordHandler:addKeyword(keywords, ShopModule.tradeItem, parameters) node:addChildKeywordNode(self.yesNode) node:addChildKeywordNode(self.noNode) end end end -- Adds a new sellable item. -- names = A table containing one or more strings of alternative names to this item. Used only by old buy/sell system. -- itemid = The itemid of the sellable item -- cost = The price of one single item -- realName - The real, full name for the item. Will be used as ITEMNAME in MESSAGE_ONBUY and MESSAGE_ONSELL if defined. Default value is nil (getItemName will be used) function ShopModule:addSellableItem(names, itemid, cost, realName, itemSubType) if SHOPMODULE_MODE ~= SHOPMODULE_MODE_TALK then if itemSubType == nil then itemSubType = 0 end local shopItem = self:getShopItem(itemid, itemSubType) if shopItem == nil then self.npcHandler.shopItems[#self.npcHandler.shopItems + 1] = {id = itemid, buy = -1, sell = cost, subType = itemSubType, name = realName or getItemName(itemid)} else shopItem.sell = cost end end if names and SHOPMODULE_MODE ~= SHOPMODULE_MODE_TRADE then for i, name in pairs(names) do local parameters = { itemid = itemid, cost = cost, eventType = SHOPMODULE_SELL_ITEM, module = self, realName = realName or getItemName(itemid) } keywords = {} keywords[#keywords + 1] = "sell" keywords[#keywords + 1] = name local node = self.npcHandler.keywordHandler:addKeyword(keywords, ShopModule.tradeItem, parameters) node:addChildKeywordNode(self.yesNode) node:addChildKeywordNode(self.noNode) end end end -- onModuleReset callback function. Calls ShopModule:reset() function ShopModule:callbackOnModuleReset() self:reset() return true end -- Callback onBuy() function. If you wish, you can change certain Npc to use your onBuy(). function ShopModule:callbackOnBuy(cid, itemid, subType, amount, ignoreCap, inBackpacks) local shopItem = self:getShopItem(itemid, subType) if shopItem == nil then error("[ShopModule.onBuy] shopItem == nil") return false end if shopItem.buy == -1 then error("[ShopModule.onSell] attempt to buy a non-buyable item") return false end local backpack = 1988 local totalCost = amount * shopItem.buy if inBackpacks then totalCost = isItemStackable(itemid) == TRUE and totalCost + 20 or totalCost + (math.max(1, math.floor(amount / getContainerCapById(backpack))) * 20) end local parseInfo = { [TAG_PLAYERNAME] = getPlayerName(cid), [TAG_ITEMCOUNT] = amount, [TAG_TOTALCOST] = totalCost, [TAG_ITEMNAME] = shopItem.name } if getPlayerMoney(cid) < totalCost then local msg = self.npcHandler:getMessage(MESSAGE_NEEDMONEY) msg = self.npcHandler:parseMessage(msg, parseInfo) doPlayerSendCancel(cid, msg) return false end local subType = shopItem.subType or 1 local a, b = doNpcSellItem(cid, itemid, amount, subType, ignoreCap, inBackpacks, backpack) if a < amount then local msgId = MESSAGE_NEEDMORESPACE if a == 0 then msgId = MESSAGE_NEEDSPACE end local msg = self.npcHandler:getMessage(msgId) parseInfo[TAG_ITEMCOUNT] = a msg = self.npcHandler:parseMessage(msg, parseInfo) doPlayerSendCancel(cid, msg) self.npcHandler.talkStart[cid] = os.time() if a > 0 then doPlayerRemoveMoney(cid, ((a * shopItem.buy) + (b * 20))) return true end return false else local msg = self.npcHandler:getMessage(MESSAGE_BOUGHT) msg = self.npcHandler:parseMessage(msg, parseInfo) doPlayerSendTextMessage(cid, MESSAGE_INFO_DESCR, msg) doPlayerRemoveMoney(cid, totalCost) self.npcHandler.talkStart[cid] = os.time() return true end end -- Callback onSell() function. If you wish, you can change certain Npc to use your onSell(). function ShopModule:callbackOnSell(cid, itemid, subType, amount, ignoreEquipped, _) local shopItem = self:getShopItem(itemid, subType) if shopItem == nil then error("[ShopModule.onSell] items[itemid] == nil") return false end if shopItem.sell == -1 then error("[ShopModule.onSell] attempt to sell a non-sellable item") return false end local parseInfo = { [TAG_PLAYERNAME] = getPlayerName(cid), [TAG_ITEMCOUNT] = amount, [TAG_TOTALCOST] = amount * shopItem.sell, [TAG_ITEMNAME] = shopItem.name } if not isItemFluidContainer(itemid) then subType = -1 end if doPlayerRemoveItem(cid, itemid, amount, subType, ignoreEquipped) then local msg = self.npcHandler:getMessage(MESSAGE_SOLD) msg = self.npcHandler:parseMessage(msg, parseInfo) doPlayerSendTextMessage(cid, MESSAGE_INFO_DESCR, msg) doPlayerAddMoney(cid, amount * shopItem.sell) self.npcHandler.talkStart[cid] = os.time() return true else local msg = self.npcHandler:getMessage(MESSAGE_NEEDITEM) msg = self.npcHandler:parseMessage(msg, parseInfo) doPlayerSendCancel(cid, msg) self.npcHandler.talkStart[cid] = os.time() return false end end -- Callback for requesting a trade window with the NPC. function ShopModule.requestTrade(cid, message, keywords, parameters, node) local module = parameters.module if not module.npcHandler:isFocused(cid) then return false end if not module.npcHandler:onTradeRequest(cid) then return false end local itemWindow = {} for i = 1, #module.npcHandler.shopItems do itemWindow[#itemWindow + 1] = module.npcHandler.shopItems[i] end if itemWindow[1] == nil then local parseInfo = { [TAG_PLAYERNAME] = getPlayerName(cid) } local msg = module.npcHandler:parseMessage(module.npcHandler:getMessage(MESSAGE_NOSHOP), parseInfo) module.npcHandler:say(msg, cid) return true end local parseInfo = { [TAG_PLAYERNAME] = getPlayerName(cid) } local msg = module.npcHandler:parseMessage(module.npcHandler:getMessage(MESSAGE_SENDTRADE), parseInfo) openShopWindow(cid, itemWindow, function(cid, itemid, subType, amount, ignoreCap, inBackpacks) module.npcHandler:onBuy(cid, itemid, subType, amount, ignoreCap, inBackpacks) end, function(cid, itemid, subType, amount, ignoreCap, inBackpacks) module.npcHandler:onSell(cid, itemid, subType, amount, ignoreCap, inBackpacks) end) module.npcHandler:say(msg, cid) return true end -- onConfirm keyword callback function. Sells/buys the actual item. function ShopModule.onConfirm(cid, message, keywords, parameters, node) local module = parameters.module if not module.npcHandler:isFocused(cid) or shop_npcuid[cid] ~= getNpcCid() then return false end shop_npcuid[cid] = 0 local parentParameters = node:getParent():getParameters() local parseInfo = { [TAG_PLAYERNAME] = getPlayerName(cid), [TAG_ITEMCOUNT] = shop_amount[cid], [TAG_TOTALCOST] = shop_cost[cid] * shop_amount[cid], [TAG_ITEMNAME] = shop_rlname[cid] } if shop_eventtype[cid] == SHOPMODULE_SELL_ITEM then local ret = doPlayerSellItem(cid, shop_itemid[cid], shop_amount[cid], shop_cost[cid] * shop_amount[cid]) if ret == true then local msg = module.npcHandler:getMessage(MESSAGE_ONSELL) msg = module.npcHandler:parseMessage(msg, parseInfo) module.npcHandler:say(msg, cid) else local msg = module.npcHandler:getMessage(MESSAGE_MISSINGITEM) msg = module.npcHandler:parseMessage(msg, parseInfo) module.npcHandler:say(msg, cid) end elseif shop_eventtype[cid] == SHOPMODULE_BUY_ITEM then local cost = shop_cost[cid] * shop_amount[cid] if getPlayerMoney(cid) < cost then local msg = module.npcHandler:getMessage(MESSAGE_MISSINGMONEY) msg = module.npcHandler:parseMessage(msg, parseInfo) module.npcHandler:say(msg, cid) return false end local a, b = doNpcSellItem(cid, shop_itemid[cid], shop_amount[cid], shop_subtype[cid], false, false, 1988) if a < shop_amount[cid] then local msgId = MESSAGE_NEEDMORESPACE if a == 0 then msgId = MESSAGE_NEEDSPACE end local msg = module.npcHandler:getMessage(msgId) msg = module.npcHandler:parseMessage(msg, parseInfo) module.npcHandler:say(msg, cid) if a > 0 then doPlayerRemoveMoney(cid, a * shop_cost[cid]) if shop_itemid[cid] == ITEM_PARCEL then doNpcSellItem(cid, ITEM_LABEL, shop_amount[cid], shop_subtype[cid], true, false, 1988) end return true end return false else local msg = module.npcHandler:getMessage(MESSAGE_ONBUY) msg = module.npcHandler:parseMessage(msg, parseInfo) module.npcHandler:say(msg, cid) doPlayerRemoveMoney(cid, cost) if shop_itemid[cid] == ITEM_PARCEL then doNpcSellItem(cid, ITEM_LABEL, shop_amount[cid], shop_subtype[cid], true, false, 1988) end return true end elseif shop_eventtype[cid] == SHOPMODULE_BUY_ITEM_CONTAINER then local ret = doPlayerBuyItemContainer(cid, shop_container[cid], shop_itemid[cid], shop_amount[cid], shop_cost[cid] * shop_amount[cid], shop_subtype[cid]) if ret == true then local msg = module.npcHandler:getMessage(MESSAGE_ONBUY) msg = module.npcHandler:parseMessage(msg, parseInfo) module.npcHandler:say(msg, cid) else local msg = module.npcHandler:getMessage(MESSAGE_MISSINGMONEY) msg = module.npcHandler:parseMessage(msg, parseInfo) module.npcHandler:say(msg, cid) end end module.npcHandler:resetNpc(cid) return true end -- onDecline keyword callback function. Generally called when the player sais "no" after wanting to buy an item. function ShopModule.onDecline(cid, message, keywords, parameters, node) local module = parameters.module if not module.npcHandler:isFocused(cid) or shop_npcuid[cid] ~= getNpcCid() then return false end shop_npcuid[cid] = 0 local parentParameters = node:getParent():getParameters() local parseInfo = { [TAG_PLAYERNAME] = getPlayerName(cid), [TAG_ITEMCOUNT] = shop_amount[cid], [TAG_TOTALCOST] = shop_cost[cid] * shop_amount[cid], [TAG_ITEMNAME] = shop_rlname[cid] } local msg = module.npcHandler:parseMessage(module.noText, parseInfo) module.npcHandler:say(msg, cid) module.npcHandler:resetNpc(cid) return true end -- tradeItem callback function. Makes the npc say the message defined by MESSAGE_BUY or MESSAGE_SELL function ShopModule.tradeItem(cid, message, keywords, parameters, node) local module = parameters.module if not module.npcHandler:isFocused(cid) then return false end if not module.npcHandler:onTradeRequest(cid) then return true end local count = module:getCount(message) module.amount = count shop_amount[cid] = module.amount shop_cost[cid] = parameters.cost shop_rlname[cid] = parameters.realName shop_itemid[cid] = parameters.itemid shop_container[cid] = parameters.container shop_npcuid[cid] = getNpcCid() shop_eventtype[cid] = parameters.eventType shop_subtype[cid] = parameters.subType local parseInfo = { [TAG_PLAYERNAME] = getPlayerName(cid), [TAG_ITEMCOUNT] = shop_amount[cid], [TAG_TOTALCOST] = shop_cost[cid] * shop_amount[cid], [TAG_ITEMNAME] = shop_rlname[cid] } if shop_eventtype[cid] == SHOPMODULE_SELL_ITEM then local msg = module.npcHandler:getMessage(MESSAGE_SELL) msg = module.npcHandler:parseMessage(msg, parseInfo) module.npcHandler:say(msg, cid) elseif shop_eventtype[cid] == SHOPMODULE_BUY_ITEM then local msg = module.npcHandler:getMessage(MESSAGE_BUY) msg = module.npcHandler:parseMessage(msg, parseInfo) module.npcHandler:say(msg, cid) elseif shop_eventtype[cid] == SHOPMODULE_BUY_ITEM_CONTAINER then local msg = module.npcHandler:getMessage(MESSAGE_BUY) msg = module.npcHandler:parseMessage(msg, parseInfo) module.npcHandler:say(msg, cid) end return true end end
gpl-2.0
gedads/Neodynamis
scripts/globals/items/serving_of_vermillion_jelly.lua
12
1416
----------------------------------------- -- ID: 5158 -- Item: Vermillion Jelly -- Food Effect: 4 hours, All Races ----------------------------------------- -- MP +12%(Cap: 90@750 Base MP) -- Intelligence +6 -- MP Recovered While Healing +2 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,14400,5158); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_MPP, 12); target:addMod(MOD_FOOD_MP_CAP, 90); target:addMod(MOD_INT, 6); target:addMod(MOD_MPHEAL, 2); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_FOOD_MPP,12); target:delMod(MOD_FOOD_MP_CAP, 90); target:delMod(MOD_INT, 6); target:delMod(MOD_MPHEAL, 2); end;
gpl-3.0
starlightknight/darkstar
scripts/zones/Port_Bastok/npcs/Qiji.lua
9
1592
----------------------------------- -- Area: Port Bastok -- NPC: Qiji -- Starts & Ends Quest: Forever to Hold ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/quests"); local ID = require("scripts/zones/Port_Bastok/IDs"); ----------------------------------- function onTrade(player,npc,trade) if (trade:hasItemQty(12497,1) and trade:getItemCount() == 1) then -- Trade Brass Hairpin if (player:getCharVar("ForevertoHold_Event") == 1) then player:startEvent(124); player:setCharVar("ForevertoHold_Event",2); end end end; function onTrigger(player,npc) local ForevertoHold = player:getQuestStatus(BASTOK,dsp.quest.id.bastok.FOREVER_TO_HOLD); if (player:getFameLevel(BASTOK) >= 2 and ForevertoHold == QUEST_AVAILABLE) then player:startEvent(123); elseif (ForevertoHold == QUEST_ACCEPTED and player:getCharVar("ForevertoHold_Event") == 3) then player:startEvent(126); else player:startEvent(33); end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) if (csid == 123) then player:addQuest(BASTOK,dsp.quest.id.bastok.FOREVER_TO_HOLD); player:setCharVar("ForevertoHold_Event",1); elseif (csid == 126) then player:addTitle(dsp.title.QIJIS_FRIEND); player:addGil(GIL_RATE*300); player:messageSpecial(ID.text.GIL_OBTAINED,GIL_RATE*300); player:addFame(BASTOK,80); player:completeQuest(BASTOK,dsp.quest.id.bastok.FOREVER_TO_HOLD); end end;
gpl-3.0
ABrandau/OpenRA
mods/cnc/maps/nod07b/nod07b-AI.lua
4
6205
--[[ Copyright 2007-2019 The OpenRA Developers (see AUTHORS) This file is part of OpenRA, which is free software. It is made available to you under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. For more information, see COPYING. ]] AttackPaths = { { AttackPath1 }, { AttackPath2 } } GDIBase = { GDICYard, GDIPyle, GDIWeap, GDIHQ, GDIProc, GDINuke1, GDINuke2, GDINuke3, GDIBuilding1, GDIBuilding2, GDIBuilding3, GDIBuilding4, GDIBuilding5, GDIBuilding6, GDIBuilding7, GDIBuilding8, GDIBuilding9 } InfantryAttackGroup = { } InfantryGroupSize = 4 InfantryProductionCooldown = DateTime.Minutes(3) InfantryProductionTypes = { "e1", "e1", "e2" } HarvesterProductionType = { "harv" } VehicleAttackGroup = { } VehicleGroupSize = 4 VehicleProductionCooldown = DateTime.Minutes(4) VehicleProductionTypes = { "jeep", "jeep", "mtnk", "mtnk", "mtnk" } StartingCash = 4000 BaseProc = { type = "proc", pos = CPos.New(49, 36), cost = 1500, exists = true } BaseNuke1 = { type = "nuke", pos = CPos.New(52, 36), cost = 500, exists = true } BaseNuke2 = { type = "nuke", pos = CPos.New(54, 36), cost = 500, exists = true } BaseNuke3 = { type = "nuke", pos = CPos.New(56, 36), cost = 500, exists = true } InfantryProduction = { type = "pyle", pos = CPos.New(52, 39), cost = 500, exists = true } VehicleProduction = { type = "weap", pos = CPos.New(55, 39), cost = 2000, exists = true } BaseBuildings = { BaseProc, BaseNuke1, BaseNuke2, BaseNuke3, InfantryProduction, VehicleProduction } BuildBase = function(cyard) Utils.Do(BaseBuildings, function(building) if not building.exists and not cyardIsBuilding then BuildBuilding(building, cyard) return end end) Trigger.AfterDelay(DateTime.Seconds(10), function() BuildBase(cyard) end) end BuildBuilding = function(building, cyard) cyardIsBuilding = true Trigger.AfterDelay(Actor.BuildTime(building.type), function() cyardIsBuilding = false if cyard.IsDead or cyard.Owner ~= enemy then return end local actor = Actor.Create(building.type, true, { Owner = enemy, Location = building.pos }) enemy.Cash = enemy.Cash - building.cost building.exists = true if actor.Type == 'pyle' or actor.Type == 'hand' then Trigger.AfterDelay(DateTime.Seconds(10), function() ProduceInfantry(actor) end) elseif actor.Type == 'weap' or actor.Type == 'afld' then Trigger.AfterDelay(DateTime.Seconds(10), function() ProduceVehicle(actor) end) end Trigger.OnKilled(actor, function() building.exists = false end) Trigger.OnDamaged(actor, function(building) if building.Owner == enemy and building.Health < building.MaxHealth * 3/4 then building.StartBuildingRepairs() end end) Trigger.AfterDelay(DateTime.Seconds(10), function() BuildBase(cyard) end) end) end CheckForHarvester = function() local harv = enemy.GetActorsByType("harv") return #harv > 0 end IdleHunt = function(unit) if not unit.IsDead then Trigger.OnIdle(unit, unit.Hunt) end end IdlingUnits = function(enemy) local lazyUnits = enemy.GetGroundAttackers() Utils.Do(lazyUnits, function(unit) IdleHunt(unit) end) end ProduceHarvester = function(building) if not buildingHarvester then buildingHarvester = true building.Build(HarvesterProductionType, function() buildingHarvester = false end) end end ProduceInfantry = function(building) if building.IsDead or building.Owner ~= enemy then return elseif not CheckForHarvester() then Trigger.AfterDelay(DateTime.Seconds(10), function() ProduceInfantry(building) end) end local delay = Utils.RandomInteger(DateTime.Seconds(3), DateTime.Seconds(9)) local toBuild = { Utils.Random(InfantryProductionTypes) } local Path = Utils.Random(AttackPaths) building.Build(toBuild, function(unit) InfantryAttackGroup[#InfantryAttackGroup + 1] = unit[1] if #InfantryAttackGroup >= InfantryGroupSize then SendUnits(InfantryAttackGroup, Path) InfantryAttackGroup = { } Trigger.AfterDelay(InfantryProductionCooldown, function() ProduceInfantry(building) end) else Trigger.AfterDelay(delay, function() ProduceInfantry(building) end) end end) end ProduceVehicle = function(building) if building.IsDead or building.Owner ~= enemy then return elseif not CheckForHarvester() then ProduceHarvester(building) Trigger.AfterDelay(DateTime.Seconds(10), function() ProduceVehicle(building) end) end local delay = Utils.RandomInteger(DateTime.Seconds(12), DateTime.Seconds(17)) local toBuild = { Utils.Random(VehicleProductionTypes) } local Path = Utils.Random(AttackPaths) building.Build(toBuild, function(unit) VehicleAttackGroup[#VehicleAttackGroup + 1] = unit[1] if #VehicleAttackGroup >= VehicleGroupSize then SendUnits(VehicleAttackGroup, Path) VehicleAttackGroup = { } Trigger.AfterDelay(VehicleProductionCooldown, function() ProduceVehicle(building) end) else Trigger.AfterDelay(delay, function() ProduceVehicle(building) end) end end) end SendUnits = function(units, waypoints) Utils.Do(units, function(unit) if not unit.IsDead then Utils.Do(waypoints, function(waypoint) unit.AttackMove(waypoint.Location) end) IdleHunt(unit) end end) end StartAI = function(cyard) Utils.Do(Map.NamedActors, function(actor) if actor.Owner == enemy and actor.HasProperty("StartBuildingRepairs") then Trigger.OnDamaged(actor, function(building) if building.Owner == enemy and building.Health < 3/4 * building.MaxHealth then building.StartBuildingRepairs() end end) end end) enemy.Cash = StartingCash BuildBase(cyard) end Trigger.OnAllKilledOrCaptured(GDIBase, function() IdlingUnits(enemy) end) Trigger.OnKilled(GDIProc, function(building) BaseProc.exists = false end) Trigger.OnKilled(GDINuke1, function(building) BaseNuke1.exists = false end) Trigger.OnKilled(GDINuke2, function(building) BaseNuke2.exists = false end) Trigger.OnKilled(GDINuke3, function(building) BaseNuke3.exists = false end) Trigger.OnKilled(GDIPyle, function(building) InfantryProduction.exists = false end) Trigger.OnKilled(GDIWeap, function(building) VehicleProduction.exists = false end)
gpl-3.0
dantezhu/neon
examples/demo1/src/cocos/framework/extends/UICheckBox.lua
57
1436
--[[ Copyright (c) 2011-2014 chukong-inc.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]] local CheckBox = ccui.CheckBox function CheckBox:onEvent(callback) self:addEventListener(function(sender, eventType) local event = {} if eventType == 0 then event.name = "selected" else event.name = "unselected" end event.target = sender callback(event) end) return self end
mit
starlightknight/darkstar
scripts/globals/spells/bluemagic/cocoon.lua
12
1218
----------------------------------------- -- Spell: Cocoon -- Enhances defense -- Spell cost: 10 MP -- Monster Type: Vermin -- Spell Type: Magical (Earth) -- Blue Magic Points: 1 -- Stat Bonus: VIT+3 -- Level: 8 -- Casting Time: 1.75 seconds -- Recast Time: 60 seconds -- Duration: 90 seconds -- -- Combos: None ----------------------------------------- require("scripts/globals/bluemagic") require("scripts/globals/settings") require("scripts/globals/status") require("scripts/globals/msg") ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0 end function onSpellCast(caster,target,spell) local typeEffect = dsp.effect.DEFENSE_BOOST local power = 50 -- Percentage, not amount. local duration = 90 if (caster:hasStatusEffect(dsp.effect.DIFFUSION)) then local diffMerit = caster:getMerit(dsp.merit.DIFFUSION) if (diffMerit > 0) then duration = duration + (duration/100)* diffMerit end caster:delStatusEffect(dsp.effect.DIFFUSION) end if (target:addStatusEffect(typeEffect,power,0,duration) == false) then spell:setMsg(dsp.msg.basic.MAGIC_NO_EFFECT) end return typeEffect end
gpl-3.0
starlightknight/darkstar
scripts/globals/items/coral_butterfly.lua
11
1054
----------------------------------------- -- ID: 4580 -- Item: Coral Butterfly -- Food Effect: 5Min, Mithra only ----------------------------------------- -- Dexterity 2 -- Mind -4 ----------------------------------------- require("scripts/globals/status") require("scripts/globals/msg") ----------------------------------------- function onItemCheck(target) local result = 0 if (target:getRace() ~= dsp.race.MITHRA) then result = dsp.msg.basic.CANNOT_EAT end if (target:getMod(dsp.mod.EAT_RAW_FISH) == 1) then result = 0 end if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then result = dsp.msg.basic.IS_FULL end return result end function onItemUse(target) target:addStatusEffect(dsp.effect.FOOD,0,0,300,4580) end function onEffectGain(target, effect) target:addMod(dsp.mod.DEX, 2) target:addMod(dsp.mod.MND, -4) end function onEffectLose(target, effect) target:delMod(dsp.mod.DEX, 2) target:delMod(dsp.mod.MND, -4) end
gpl-3.0
starlightknight/darkstar
scripts/zones/Apollyon/bcnms/nw_apollyon.lua
9
1251
----------------------------------- -- Area: Appolyon -- Name: NW Apollyon ----------------------------------- require("scripts/globals/limbus"); require("scripts/globals/battlefield") require("scripts/globals/keyitems"); -- After registering the BCNM via bcnmRegister(bcnmid) function onBattlefieldTick(battlefield, tick) dsp.battlefield.onBattlefieldTick(battlefield, tick) end function onBattlefieldRegister(player,battlefield) SetServerVariable("[NW_Apollyon]UniqueID",os.time()); HideArmouryCrates(NW_Apollyon,APOLLYON_NW_SW); end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBattlefieldEnter(player,battlefield) player:setCharVar("characterLimbusKey",GetServerVariable("[NW_Apollyon]UniqueID")); player:delKeyItem(dsp.ki.COSMOCLEANSE); player:delKeyItem(dsp.ki.RED_CARD); 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 function onBattlefieldLeave(player,battlefield,leavecode) --print("leave code "..leavecode); if leavecode == dsp.battlefield.leaveCode.LOST then SetServerVariable("[NW_Apollyon]UniqueID",0); player:setPos(-668,0.1,-666); end end;
gpl-3.0
mahdib9/54
plugins/stats.lua
81
4126
do -- Returns a table with `name` and `msgs` local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ['..user_id..']' return user_info end local function chat_stats(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'users in this chat \n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end local file = io.open("./groups/lists/"..chat_id.."stats.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..chat_id,"./groups/lists/"..chat_id.."stats.txt", ok_cb, false) return --text end local function chat_stats2(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'users in this chat \n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end return text end -- Save stats, ban user local function bot_stats() local redis_scan = [[ local cursor = '0' local count = 0 repeat local r = redis.call("SCAN", cursor, "MATCH", KEYS[1]) cursor = r[1] count = count + #r[2] until cursor == '0' return count]] -- Users local hash = 'msgs:*:'..our_id local r = redis:eval(redis_scan, 1, hash) local text = 'Users: '..r hash = 'chat:*:users' r = redis:eval(redis_scan, 1, hash) text = text..'\nGroups: '..r return text end local function run(msg, matches) if matches[1]:lower() == 'nod32' then -- Put everything you like :) local about = _config.about_text local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /nod32 ") return about end if matches[1]:lower() == "statslist" then if not is_momod(msg) then return "For mods only !" end local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ") return chat_stats2(chat_id) end if matches[1]:lower() == "stats" then if not matches[2] then if not is_momod(msg) then return "For mods only !" end if msg.to.type == 'chat' then local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ") return chat_stats(chat_id) else return end end if matches[2] == "nod32" then -- Put everything you like :) if not is_admin(msg) then return "For admins only !" else return bot_stats() end end if matches[2] == "group" then if not is_admin(msg) then return "For admins only !" else return chat_stats(matches[3]) end end end end return { patterns = { "^[!/]([Ss]tats)$", "^[!/]([Ss]tatslist)$", "^[!/]([Ss]tats) (group) (%d+)", "^[!/]([Ss]tats) (nod32)",-- Put everything you like :) "^[!/]([Nn]od32)"-- Put everything you like :) }, run = run } end --Copyright and edit; @behroozyaghi --Persian Translate; @behroozyaghi --ch : @nod32team --کپی بدون ذکر منبع حرام است
gpl-2.0
starlightknight/darkstar
scripts/zones/Horlais_Peak/bcnms/horns_of_war.lua
9
1059
----------------------------------- -- Horns of War -- Horlais Peak KSNM, Themis Orb -- !additem 1553 ----------------------------------- require("scripts/globals/battlefield") ----------------------------------- function onBattlefieldInitialise(battlefield) battlefield:setLocalVar("loot", 1) end function onBattlefieldTick(battlefield, tick) dsp.battlefield.onBattlefieldTick(battlefield, tick) end function onBattlefieldRegister(player, battlefield) end function onBattlefieldEnter(player, battlefield) end function onBattlefieldLeave(player, battlefield, leavecode) if leavecode == dsp.battlefield.leaveCode.WON then local name, clearTime, partySize = battlefield:getRecord() player:startEvent(32001, battlefield:getArea(), clearTime, partySize, battlefield:getTimeInside(), 1, battlefield:getLocalVar("[cs]bit"), 0) elseif leavecode == dsp.battlefield.leaveCode.LOST then player:startEvent(32002) end end function onEventUpdate(player, csid, option) end function onEventFinish(player, csid, option) end
gpl-3.0
O-P-E-N/CC-ROUTER
feeds/luci/applications/luci-app-dump1090/luasrc/model/cbi/dump1090.lua
37
4987
-- Copyright 2014 Álvaro Fernández Rojas <noltari@gmail.com> -- Licensed to the public under the Apache License 2.0. m = Map("dump1090", "dump1090", translate("dump1090 is a Mode S decoder specifically designed for RTLSDR devices, here you can configure the settings.")) s = m:section(TypedSection, "dump1090", "") s.addremove = true s.anonymous = false enable=s:option(Flag, "disabled", translate("Enabled")) enable.enabled="0" enable.disabled="1" enable.default = "1" enable.rmempty = false respawn=s:option(Flag, "respawn", translate("Respawn")) respawn.default = false device_index=s:option(Value, "device_index", translate("RTL device index")) device_index.rmempty = true device_index.datatype = "uinteger" gain=s:option(Value, "gain", translate("Gain (-10 for auto-gain)")) gain.rmempty = true gain.datatype = "integer" enable_agc=s:option(Flag, "enable_agc", translate("Enable automatic gain control")) enable_agc.default = false freq=s:option(Value, "freq", translate("Frequency")) freq.rmempty = true freq.datatype = "uinteger" ifile=s:option(Value, "ifile", translate("Data file")) ifile.rmempty = true ifile.datatype = "file" raw=s:option(Flag, "raw", translate("Show only messages hex values")) raw.default = false net=s:option(Flag, "net", translate("Enable networking")) modeac=s:option(Flag, "modeac", translate("Enable decoding of SSR Modes 3/A & 3/C")) modeac.default = false net_beast=s:option(Flag, "net_beast", translate("TCP raw output in Beast binary format")) net_beast.default = false net_only=s:option(Flag, "net_only", translate("Enable just networking, no RTL device or file used")) net_only.default = false net_bind_address=s:option(Value, "net_bind_address", translate("IP address to bind to")) net_bind_address.rmempty = true net_bind_address.datatype = "ipaddr" net_http_port=s:option(Value, "net_http_port", translate("HTTP server port")) net_http_port.rmempty = true net_http_port.datatype = "port" net_ri_port=s:option(Value, "net_ri_port", translate("TCP raw input listen port")) net_ri_port.rmempty = true net_ri_port.datatype = "port" net_ro_port=s:option(Value, "net_ro_port", translate("TCP raw output listen port")) net_ro_port.rmempty = true net_ro_port.datatype = "port" net_sbs_port=s:option(Value, "net_sbs_port", translate("TCP BaseStation output listen port")) net_sbs_port.rmempty = true net_sbs_port.datatype = "port" net_bi_port=s:option(Value, "net_bi_port", translate("TCP Beast input listen port")) net_bi_port.rmempty = true net_bi_port.datatype = "port" net_bo_port=s:option(Value, "net_bo_port", translate("TCP Beast output listen port")) net_bo_port.rmempty = true net_bo_port.datatype = "port" net_ro_size=s:option(Value, "net_ro_size", translate("TCP raw output minimum size")) net_ro_size.rmempty = true net_ro_size.datatype = "uinteger" net_ro_rate=s:option(Value, "net_ro_rate", translate("TCP raw output memory flush rate")) net_ro_rate.rmempty = true net_ro_rate.datatype = "uinteger" net_heartbeat=s:option(Value, "net_heartbeat", translate("TCP heartbeat rate in seconds")) net_heartbeat.rmempty = true net_heartbeat.datatype = "uinteger" net_buffer=s:option(Value, "net_buffer", translate("TCP buffer size 64Kb * (2^n)")) net_buffer.rmempty = true net_buffer.datatype = "uinteger" lat=s:option(Value, "lat", translate("Reference/receiver latitude for surface posn")) lat.rmempty = true lat.datatype = "integer" lon=s:option(Value, "lon", translate("Reference/receiver longitude for surface posn")) lon.rmempty = true lon.datatype = "integer" fix=s:option(Flag, "fix", translate("Enable single-bits error correction using CRC")) fix.default = false no_fix=s:option(Flag, "no_fix", translate("Disable single-bits error correction using CRC")) no_fix.default = false no_crc_check=s:option(Flag, "no_crc_check", translate("Disable messages with broken CRC")) no_crc_check.default = false phase_enhance=s:option(Flag, "phase_enhance", translate("Enable phase enhancement")) phase_enhance.default = false agressive=s:option(Flag, "agressive", translate("More CPU for more messages")) agressive.default = false mlat=s:option(Flag, "mlat", translate("Display raw messages in Beast ascii mode")) mlat.default = false stats=s:option(Flag, "stats", translate("Print stats at exit")) stats.default = false stats_every=s:option(Value, "stats_every", translate("Show and reset stats every seconds")) stats_every.rmempty = true stats_every.datatype = "uinteger" onlyaddr=s:option(Flag, "onlyaddr", translate("Show only ICAO addresses")) onlyaddr.default = false metric=s:option(Flag, "metric", translate("Use metric units")) metric.default = false snip=s:option(Flag, "snip", translate("Strip IQ file removing samples")) snip.rmempty = true snip.datatype = "uinteger" debug_mode=s:option(Flag, "debug", translate("Debug mode flags")) debug_mode.rmempty = true ppm=s:option(Flag, "ppm", translate("Set receiver error in parts per million")) ppm.rmempty = true ppm.datatype = "uinteger" return m
gpl-2.0
ABrandau/OpenRA
mods/cnc/maps/gdi04b/gdi04b.lua
4
6237
--[[ Copyright 2007-2019 The OpenRA Developers (see AUTHORS) This file is part of OpenRA, which is free software. It is made available to you under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. For more information, see COPYING. ]] BhndTrigger = { CPos.New(39, 21), CPos.New(40, 21), CPos.New(41, 21) } Atk1Trigger = { CPos.New(35, 37) } Atk2Trigger = { CPos.New(9, 44), CPos.New(10, 44), CPos.New(11, 44), CPos.New(12, 44), CPos.New(13, 44) } AutoTrigger = { CPos.New(5, 30), CPos.New(6, 30), CPos.New(7, 30), CPos.New(8, 30), CPos.New(9, 30), CPos.New(10, 30), CPos.New(11, 30), CPos.New(12, 30), CPos.New(13, 30) } GDIHeliTrigger = { CPos.New(11, 11), CPos.New(11, 12), CPos.New(11, 13), CPos.New(11, 14), CPos.New(11, 15), CPos.New(12, 15), CPos.New(13, 15), CPos.New(14, 15), CPos.New(15, 15), CPos.New(16, 15) } Hunters = { Hunter1, Hunter2, Hunter3, Hunter4, Hunter5 } NodxUnits = { "e1", "e1", "e3", "e3" } AutoUnits = { "e1", "e1", "e1", "e3", "e3" } KillsUntilReinforcements = 12 GDIReinforcements = { "e2", "e2", "e2", "e2", "e2" } GDIReinforcementsWaypoints = { GDIReinforcementsEntry.Location, GDIReinforcementsWP1.Location } NodHeli = { { HeliEntry.Location, NodHeliLZ.Location }, { "e1", "e1", "e3", "e3" } } SendHeli = function(heli) units = Reinforcements.ReinforceWithTransport(enemy, "tran", heli[2], heli[1], { heli[1][1] }) Utils.Do(units[2], function(actor) actor.Hunt() Trigger.OnIdle(actor, actor.Hunt) Trigger.OnKilled(actor, KillCounter) end) end SendGDIReinforcements = function() Media.PlaySpeechNotification(player, "Reinforce") Reinforcements.ReinforceWithTransport(player, "apc", GDIReinforcements, GDIReinforcementsWaypoints, nil, function(apc, team) table.insert(team, apc) Trigger.OnAllKilled(team, function() Trigger.AfterDelay(DateTime.Seconds(5), SendGDIReinforcements) end) Utils.Do(team, function(unit) unit.Stance = "Defend" end) end) end Build = function(unitTypes, repeats, func) if HandOfNod.IsDead then return end local innerFunc = function(units) Utils.Do(units, func) if repeats then Trigger.OnAllKilled(units, function() Build(unitTypes, repeats, func) end) end end if not HandOfNod.Build(unitTypes, innerFunc) then Trigger.AfterDelay(DateTime.Seconds(5), function() Build(unitTypes, repeats, func) end) end end BuildNod1 = function() Build(NodxUnits, false, function(actor) Trigger.OnKilled(actor, KillCounter) actor.Patrol({ NodPatrol1.Location, NodPatrol2.Location, NodPatrol3.Location, NodPatrol4.Location }, false) Trigger.OnIdle(actor, actor.Hunt) end) end BuildNod2 = function() Build(NodxUnits, false, function(actor) Trigger.OnKilled(actor, KillCounter) actor.Patrol({ NodPatrol1.Location, NodPatrol2.Location }, false) Trigger.OnIdle(actor, actor.Hunt) end) end BuildAuto = function() Build(AutoUnits, true, function(actor) Trigger.OnKilled(actor, KillCounter) Trigger.OnIdle(actor, actor.Hunt) end) end ReinforcementsSent = false kills = 0 KillCounter = function() kills = kills + 1 end Tick = function() enemy.Cash = 1000 if not ReinforcementsSent and kills >= KillsUntilReinforcements then ReinforcementsSent = true player.MarkCompletedObjective(reinforcementsObjective) SendGDIReinforcements() end if player.HasNoRequiredUnits() then Trigger.AfterDelay(DateTime.Seconds(1), function() player.MarkFailedObjective(gdiObjective) end) end end SetupWorld = function() Utils.Do(enemy.GetGroundAttackers(), function(unit) Trigger.OnKilled(unit, KillCounter) end) Utils.Do(player.GetGroundAttackers(), function(unit) unit.Stance = "Defend" end) Utils.Do(Hunters, function(actor) actor.Hunt() end) Trigger.OnRemovedFromWorld(crate, function() player.MarkCompletedObjective(gdiObjective) end) end WorldLoaded = function() player = Player.GetPlayer("GDI") enemy = Player.GetPlayer("Nod") Trigger.OnObjectiveAdded(player, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective") end) Trigger.OnObjectiveCompleted(player, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed") end) Trigger.OnObjectiveFailed(player, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed") end) Trigger.OnPlayerWon(player, function() Media.PlaySpeechNotification(player, "Win") end) Trigger.OnPlayerLost(player, function() Media.PlaySpeechNotification(player, "Lose") end) gdiObjective = player.AddPrimaryObjective("Retrieve the crate with the stolen rods.") reinforcementsObjective = player.AddSecondaryObjective("Eliminate " .. KillsUntilReinforcements .. " Nod units for reinforcements.") enemy.AddPrimaryObjective("Defend against the GDI forces.") SetupWorld() bhndTrigger = false Trigger.OnExitedFootprint(BhndTrigger, function(a, id) if not bhndTrigger and a.Owner == player then bhndTrigger = true Trigger.RemoveFootprintTrigger(id) SendHeli(NodHeli) end end) atk1Trigger = false Trigger.OnExitedFootprint(Atk1Trigger, function(a, id) if not atk1Trigger and a.Owner == player then atk1Trigger = true Trigger.RemoveFootprintTrigger(id) BuildNod1() end end) atk2Trigger = false Trigger.OnEnteredFootprint(Atk2Trigger, function(a, id) if not atk2Trigger and a.Owner == player then atk2Trigger = true Trigger.RemoveFootprintTrigger(id) BuildNod2() end end) autoTrigger = false Trigger.OnEnteredFootprint(AutoTrigger, function(a, id) if not autoTrigger and a.Owner == player then autoTrigger = true Trigger.RemoveFootprintTrigger(id) BuildAuto() Trigger.AfterDelay(DateTime.Seconds(4), function() tank.Hunt() end) end end) gdiHeliTrigger = false Trigger.OnEnteredFootprint(GDIHeliTrigger, function(a, id) if not gdiHeliTrigger and a.Owner == player then gdiHeliTrigger = true Trigger.RemoveFootprintTrigger(id) Reinforcements.ReinforceWithTransport(player, "tran", nil, { HeliEntry.Location, GDIHeliLZ.Location }) end end) Camera.Position = GDIReinforcementsWP1.CenterPosition end
gpl-3.0
gedads/Neodynamis
scripts/zones/Dynamis-Xarcabard/mobs/Animated_Tabar.lua
17
1486
----------------------------------- -- Area: Dynamis Xarcabard -- MOB: Animated Tabar ----------------------------------- require("scripts/globals/status"); require("scripts/zones/Dynamis-Xarcabard/TextIDs"); ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) if (mob:AnimationSub() == 3) then SetDropRate(116,1575,1000); else SetDropRate(116,1575,0); end target:showText(mob,ANIMATED_TABAR_DIALOG); SpawnMob(17330380):updateEnmity(target); SpawnMob(17330381):updateEnmity(target); SpawnMob(17330382):updateEnmity(target); SpawnMob(17330392):updateEnmity(target); SpawnMob(17330393):updateEnmity(target); SpawnMob(17330394):updateEnmity(target); end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob,target) -- TODO: add battle dialog end; ----------------------------------- -- onMobDisengage ----------------------------------- function onMobDisengage(mob) mob:showText(mob,ANIMATED_TABAR_DIALOG+2); end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) player:showText(mob,ANIMATED_TABAR_DIALOG+1); DespawnMob(17330380); DespawnMob(17330381); DespawnMob(17330382); DespawnMob(17330392); DespawnMob(17330393); DespawnMob(17330394); end;
gpl-3.0
gedads/Neodynamis
scripts/zones/Northern_San_dOria/npcs/Shomo_Pochachilo.lua
3
1319
----------------------------------- -- Area: Northern San d'Oria -- NPC: Shomo Pochachilo -- Type: Standard Info NPC -- @zone 231 -- !pos 28.369 -0.199 30.061 ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Northern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) quest_FatherAndSon = player:getQuestStatus(SANDORIA,FATHER_AND_SON); if (quest_FatherAndSon == QUEST_COMPLETED) then player:startEvent(0x02b8); else player:startEvent(0x02a3); 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
teleowner/TELEOWNER
supergroup.lua
2
92532
--Begin supergrpup.lua --Check members #Add supergroup local function check_member_super(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg if success == 0 then send_large_msg(receiver, "ابتدا مرا ادمین کنید!") 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 = '🔓', lock_link = "🔓", flood = '🔓', lock_spam = '🔓', lock_sticker = '🔓', member = '🔓', public = '🔓', lock_rtl = '🔓', expiretime = 'null', --lock_contacts = 'no', strict = '🔓' } } 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 = '!سوپر گروه اضافه شد' 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 = '!سوپر گروه پاک شد' 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 = "لیست سرپرستان سوپر گروه "..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 local function callback_clean_bots (extra, success, result) local receiver = 'channel#id'..msg.to.id local channel_id = msg.to.id for k,v in pairs(result) do local bot_id = v.peer_id kick_user(bot_id,channel_id) end end --Get and output info about supergroup local function callback_info(cb_extra, success, result) local title ="اطلاعات سوپر گروه <code>["..result.title.."]</code>\n\n" local user_num = "تعداد عضو: <code>"..result.participants_count.."</code>\n" local admin_num = "تعداد ادمین: <code>"..result.admins_count.."</code>\n" local kicked_num = "تعداد افراد اخراج شده: <code>"..result.kicked_count.."</code>\n\n" local channel_id = "Group ID: <code>"..result.peer_id.."</code>\n" if result.username then channel_username = "Username: @"..result.username else channel_username = "" end local text = title..admin_num..user_num..kicked_num..channel_id..channel_username send_large_msg(cb_extra.receiver, text) end --Get and output members of supergroup local function callback_who(cb_extra, success, result) local text = "Members for "..cb_extra.receiver local i = 1 for k,v in pairsByKeys(result) do if not v.print_name then name = " " else vname = v.print_name:gsub("‮", "") name = vname:gsub("_", " ") end if v.username then username = " @"..v.username else username = "" end text = text.."\n"..i.." - "..name.." "..username.." [ "..v.peer_id.." ]\n" --text = text.."\n"..username i = i + 1 end local file = io.open("./groups/lists/supergroups/"..cb_extra.receiver..".txt", "w") file:write(text) file:flush() file:close() send_document(cb_extra.receiver,"./groups/lists/supergroups/"..cb_extra.receiver..".txt", ok_cb, false) post_msg(cb_extra.receiver, text, ok_cb, false) end --Get and output list of kicked users for supergroup local function callback_kicked(cb_extra, success, result) --vardump(result) local text = "Kicked Members for SuperGroup "..cb_extra.receiver.."\n\n" --sosha 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 == '🔐' then return 'ضد تبلیغ از قبل فعال بوده است' else data[tostring(target)]['settings']['lock_link'] = '🔐' save_data(_config.moderation.data, data) return 'ضد تبلیغ فعال شد' 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 == '🔓' then return 'ضد تبلیغ از قبل غیرفعال بوده است' else data[tostring(target)]['settings']['lock_link'] = '🔓' save_data(_config.moderation.data, data) return 'ضد تبلیغ غیرفعال شد' 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 "شما صاحب گروه نیستید!" end local group_spam_lock = data[tostring(target)]['settings']['lock_spam'] if group_spam_lock == '🔐' then return 'ضد اسپم از قبل فعال بوده است' else data[tostring(target)]['settings']['lock_spam'] = '🔐' save_data(_config.moderation.data, data) return 'ضد اسپم فعال شد' 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 == '🔓' then return 'ضد اسپم از قبل غیرفعال بوده است' else data[tostring(target)]['settings']['lock_spam'] = '🔓' save_data(_config.moderation.data, data) return 'ضد اسپم غیرفعال شد' 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 == '🔐' then return 'ضد فلود از قبل فعال بوده است' else data[tostring(target)]['settings']['flood'] = '🔐' save_data(_config.moderation.data, data) return 'ضد فلود فعال شد' 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 == '🔓' then return 'ضد فلود از قبل غیرفعال بوده است' else data[tostring(target)]['settings']['flood'] = '🔓' save_data(_config.moderation.data, data) return 'ضد فلود غیرفعال شد' end end --***Lock By Sosha***-- --[[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' 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 end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'no' then return 'Arabic/Persian is already unlocked' else data[tostring(target)]['settings']['lock_arabic'] = 'no' save_data(_config.moderation.data, data) return 'Arabic/Persian has been unlocked' 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 == '🔐' then return 'کاربران گروه از قبل قفل بوده است' else data[tostring(target)]['settings']['lock_member'] = '🔐' save_data(_config.moderation.data, data) end return 'کاربران گروه قفل شدند' 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 == '🔓' then return 'کاربران گروه قفل نبوده است' else data[tostring(target)]['settings']['lock_member'] = '🔓' save_data(_config.moderation.data, data) return 'کاربران گروه از قفل خارج شدند' end end --***Lock By Sosha***-- --[[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' --sosha else data[tostring(target)]['settings']['lock_rtl'] = 'yes' save_data(_config.moderation.data, data) return 'RTL has been locked' --sosha 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 already unlocked' --sosha else data[tostring(target)]['settings']['lock_rtl'] = 'no' save_data(_config.moderation.data, data) return 'RTL has been unlocked' --sosha end end]] local function lock_group_welcome(msg, data, target) if not is_momod(msg) then return "شما مدیر گروه نیستید" end local welcoms = data[tostring(target)]['welcome'] if welcoms == '✅' then return 'پیام خوش امد گویی فعال است' else data[tostring(target)]['welcome'] = '✅' save_data(_config.moderation.data, data) return 'پیام خوش امد گویی فعال شد\nبرای تغییر این پیام از دستور زیر استفاده کنید\n/set welcome <welcomemsg>' end end local function unlock_group_welcome(msg, data, target) if not is_momod(msg) then return "شما مدیر گروه نیستید" end local welcoms = data[tostring(target)]['welcome'] if welcoms == '❌' then return 'پیام خوش امد گویی غیر فعال است' else data[tostring(target)]['welcome'] = '❌' save_data(_config.moderation.data, data) return 'پیام خوش امد گویی غیر فعال شد' 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 == '🔐' then return 'ضد استیکر از قبل فعال بوده است' else data[tostring(target)]['settings']['lock_sticker'] = '🔐' save_data(_config.moderation.data, data) return 'ضد استیکر فعال شد' 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 == '🔓' then return 'ضد استیکر از قبل غیرفعال بوده است' else data[tostring(target)]['settings']['lock_sticker'] = '🔓' save_data(_config.moderation.data, data) return 'ضد استیکر غیرفعال شد' end end local function lock_group_contacts(msg, data, target) if not is_momod(msg) then return end local group_contacts_lock = data[tostring(target)]['settings']['lock_contact'] if group_contacts_lock == '🔐' then return 'ضد اشتراک گذاشتن مخاطب از قبل فعال بوده است' else data[tostring(target)]['settings']['lock_contact'] = '🔐' save_data(_config.moderation.data, data) return 'ضد اشتراک گذاشتن مخاطب فعال شد' 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_contact'] if group_contacts_lock == '🔓' then return 'ضد اشتراک گذاشتن مخاطب از قبل غیرفعال بوده است' else data[tostring(target)]['settings']['lock_contact'] = '🔓' save_data(_config.moderation.data, data) return 'ضد اشتراک گذاشتن مخاطب غیرفعال شد' 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 == '🔐' then return 'Settings are already strictly enforced' --sosha else data[tostring(target)]['settings']['strict'] = '🔐' save_data(_config.moderation.data, data) return 'Settings will be strictly enforced' --sosha 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 == '🔓' then return 'Settings are not strictly enforced' --sosha else data[tostring(target)]['settings']['strict'] = '🔓' save_data(_config.moderation.data, data) return 'Settings will not be strictly enforced' --sosha 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 'قوانین گروه ثبت شد' 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 'قوانین گروه در دسترس نیست' 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..' \nقوانین گروه:\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 "شما مدیر گروه نیستید!" 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 == '🔐' then return 'گروه از قبل عمومی بوده است' else data[tostring(target)]['settings']['public'] = '🔐' save_data(_config.moderation.data, data) end return 'گروه عمومی شد' end local function unlock_group_porn(msg, data, target) if not is_momod(msg) then return "شما مدیر گروه نیستید!" end local porn = data[tostring(target)]['settings']['lock_porn'] if porn == '🔓' then return 'محتوای بزرگ سالان از قبل غیرفعال بوده است' else data[tostring(target)]['settings']['lock_porn'] = '🔓' save_data(_config.moderation.data, data) return 'محتوای بزرگ سالان غیرفعال شد' end end local function lock_group_porn(msg, data, target) if not is_momod(msg) then return "شما مدیر گروه نیستید!" end local porn = data[tostring(target)]['settings']['lock_porn'] if porn == '🔐' then return 'محتوای بزرگ سالان از قبل فعال بوده است' else data[tostring(target)]['settings']['lock_porn'] = '🔐' save_data(_config.moderation.data, data) return 'محتوای بزرگ سالان فعال شد' end 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 == '🔓' then return 'گروه از قبل خصوصی بوده است' else data[tostring(target)]['settings']['public'] = '🔓' data[tostring(target)]['long_id'] = msg.to.long_id save_data(_config.moderation.data, data) return 'گروه خصوصی شد' end end --Show supergroup settings; function function show_supergroup_settingsmod(msg, target) if not is_momod(msg) then return end local data = load_data(_config.moderation.data) if data[tostring(target)] then if data[tostring(target)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['public'] then data[tostring(target)]['settings']['public'] = '🔓' end end --[[if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['lock_rtl'] then data[tostring(target)]['settings']['lock_rtl'] = 'no' end end]] if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['lock_member'] then data[tostring(target)]['settings']['lock_member'] = '🔓' end end local Welcome = "✅" if data[tostring(msg.to.id)]['welcome'] then Welcome = data[tostring(msg.to.id)]['welcome'] end local Expiretime = "نامشخص" local now = tonumber(os.time()) local rrredis = redis:hget ('expiretime', get_receiver(msg)) if redis:hget ('expiretime', get_receiver(msg)) then Expiretime = math.floor((tonumber(rrredis) - tonumber(now)) / 86400) + 1 end local settings = data[tostring(target)]['settings'] local text = ":["..msg.to.print_name:gsub("_"," ").."] تنظیمات سوپر گروه\n\n> عمومی: "..settings.public.."\n> قفل تبلیغ: "..settings.lock_link.."\n> قفل اعضا : "..settings.lock_member.."\n> قفل اسپم: "..settings.lock_spam.."\n> قفل فلود: "..settings.flood.."\n> حساسیت ضد فلود: "..NUM_MSG_MAX.."\n>پیام خوش آمد گویی : "..Welcome.."\n>تنظیمات سخت گیرانه : "..settings.strict.."\n> تاریخ انقضای گروه: "..Expiretime.." روز دیگر" --local text = ":["..msg.to.print_name:gsub("_"," ").."] تنظیمات سوپر گروه\n\n> قفل کاربران گروه: "..settings.lock_member.."\n> قفل تبلیغ: "..settings.lock_link.."\n> قفل اسپم: "..settings.lock_spam.."\n> قفل فلود: "..settings.flood.."\n> حساسیت ضد فلود: "..NUM_MSG_MAX.."\n> Strict settings: "..settings.strict return text end function show_supergroup_mutes(msg, target) if not is_momod(msg) then return end local data = load_data(_config.moderation.data) if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['mute_text'] then data[tostring(target)]['settings']['mute_text'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['mute_audio'] then data[tostring(target)]['settings']['mute_audio'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['mute_service'] then data[tostring(target)]['settings']['mute_service'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['mute_photo'] then data[tostring(target)]['settings']['mute_photo'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['mute_forward'] then data[tostring(target)]['settings']['mute_forward'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['mute_video'] then data[tostring(target)]['settings']['mute_video'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['mute_gif'] then data[tostring(target)]['settings']['mute_gif'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['mute_doc'] then data[tostring(target)]['settings']['mute_doc'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['mute_all'] then data[tostring(target)]['settings']['mute_all'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['lock_porn'] then data[tostring(target)]['settings']['lock_porn'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['lock_contact'] then data[tostring(target)]['settings']['lock_contact'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['lock_sticker'] then data[tostring(target)]['settings']['lock_sticker'] = 'no' end end local settings = data[tostring(target)]['settings'] local text = "لیست فیلتر ها ["..msg.to.print_name:gsub("_"," ").."]:\n\n> فیلتر همه: "..settings.mute_all.."\n> فیلتر متن: "..settings.mute_text.."\n> فیلتر استیکر: "..settings.lock_sticker.."\n> فیلتر عکس: "..settings.mute_photo.."\n> فیلتر فیلم: "..settings.mute_video.."\n> فیلتر صوتی: "..settings.mute_audio.."\n> فیلتر Gif ( تصاویر متحرک): "..settings.mute_gif.."\n> فیلتر محتوای بزرگسالان: "..settings.lock_porn.."\n> فیلتر اشتراک گذاری مخاطب: "..settings.lock_contact.."\n> فیلتر فایل: "..settings.mute_doc.."\n> فیلتر فروارد: "..settings.mute_forward.."\n> فیلتر پیام ورود و خروج افراد: "..settings.mute_service return text end local function set_welcomemod(msg, data, target) if not is_momod(msg) then return "شما مدیر گروه نیستید" end local data_cat = 'welcome_msg' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'پیام خوش امد گویی :\n'..rules..'\n---------------\nبرای نمایش نام کاربر و نام گروه یا قوانین میتوانید به صورت زیر عمل کنید\n\n /set welcome salam {name} be goroohe {group} khosh amadid \n ghavanine gorooh: {rules} \n\nربات به صورت هوشمند نام گروه , نام کاربر و قوانین را به جای {name}و{group} و {rules} اضافه میکند.' end local function set_expiretime(msg, data, target) if not is_sudo(msg) then return "شما ادمین ربات نیستید!" end local data_cat = 'expire' data[tostring(target)][data_cat] = expired save_data(_config.moderation.data, data) return 'تاریخ انقضای گروه به '..expired..' ست شد' 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..' از قبل مدیر گروه بوده است') 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..' مدیر گروه نیست') 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, 'سوپر گروه اضافه نشده است!') end if data[group]['moderators'][tostring(user_id)] then return send_large_msg(receiver, member_username..' از قبل مدیر گروه بوده است') end data[group]['moderators'][tostring(user_id)] = member_tag_username save_data(_config.moderation.data, data) send_large_msg(receiver, member_username..' به لیست مدیران گروه اضافه شد') end local function demote2(receiver, member_username, user_id) local data = load_data(_config.moderation.data) local member_tag_username = string.gsub(member_username, '@', '(at)') local group = string.gsub(receiver, 'channel#id', '') if not data[group] then return send_large_msg(receiver, 'گروه اضافه نشده است!') end if not data[group]['moderators'][tostring(user_id)] then return send_large_msg(receiver, member_tag_username..' مدیر گروه نیست') end data[group]['moderators'][tostring(user_id)] = nil save_data(_config.moderation.data, data) send_large_msg(receiver, member_username..' از لیست مدیران گروه پاک شد') 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 'سوپر گروه اضافه نشده است!' end -- determine if table is empty if next(data[tostring(msg.to.id)]['moderators']) == nil then return 'هیچ مدیری در گروه وجود ندارد' end local i = 1 local message = 'لیست مدیران گروه ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do if string.match(v , "(at)") then v = v:gsub(".at.","@") end 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.."]") --sosha 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.."]") --sosha 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.."]") --sosha 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") --sosha 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") --sosha end if is_admin2(member_id) then return send_large_msg("channel#id"..channel_id, "You can't kick other admins") --sosha 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") --sosha end if is_momod2(member_id, channel_id) and not is_admin2(msg.from.id) then return send_large_msg("channel#id"..channel_id, "شما نمی توانید ادمین/مدیران/صاحب گروه را اخراج کنید") end if is_admin2(member_id) then return send_large_msg("channel#id"..channel_id, "شما نمی توانید سایر ادمین ها را اخراج کنید") 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.." به لیست سرپرستان گروه اضافه شد" else text = "[ "..user_id.." ] به لیست سرپرستان گروه اضافه شد" 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, "شما ادمین کل را نمی توانید برکنار کنید") end channel_demote(channel_id, "user#id"..user_id, ok_cb, false) if result.from.username then text = "@"..result.from.username.." از لیست سرپرستان گروه حذف شد" else text = "[ "..user_id.." ] از لیست مدیران گروه پاک شد" 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.." ] به صاحب گروه منتصب شد" else text = "[ "..result.from.peer_id.." ] به صاحب گروه منتصب شد" 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 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.."] demoted mod: @"..member_username.."["..result.from.peer_id.."] by reply") demote2("channel#id"..result.to.peer_id, member_username, member_id) --channel_set_mod(channel_id, user, ok_cb, false) end 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.."] از لیست Mute کاربران حذف شد") elseif is_admin1(msg) then mute_user(chat_id, user_id) send_large_msg(receiver, " ["..user_id.."] به لیست Mute کاربران اضافه شد") end end end --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, "شما ادمین کل را نمی توانید برکنار کنید") end local user_id = "user#id"..result.peer_id channel_demote(receiver, user_id, ok_cb, false) if result.username then text = "@"..result.username.." از لیست سرپرستان گروه حذف شد" send_large_msg(receiver, text) else text = "[ "..result.peer_id.." ] از لیست سرپرستان گروه حذف شد" send_large_msg(receiver, text) end elseif get_cmd == "promote" then if result.username then member_username = "@"..result.username else member_username = string.gsub(result.print_name, '_', ' ') end promote2(receiver, member_username, user_id) elseif get_cmd == "demote" then if result.username then member_username = "@"..result.username else member_username = string.gsub(result.print_name, '_', ' ') end demote2(receiver, member_username, user_id) end end -- Begin resolve username actions local function callbackres(extra, success, result) local member_id = result.peer_id local member_username = "@"..result.username local get_cmd = extra.get_cmd if get_cmd == "res" then local user = result.peer_id local name = string.gsub(result.print_name, "_", " ") local channel = 'channel#id'..extra.channelid send_large_msg(channel, user..'\n'..name) return user elseif get_cmd == "id" then local user = result.peer_id local channel = 'channel#id'..extra.channelid send_large_msg(channel, user) return user elseif get_cmd == "invite" then local receiver = extra.channel local user_id = "user#id"..result.peer_id channel_invite(receiver, user_id, ok_cb, false) --[[elseif get_cmd == "channel_block" then local user_id = result.peer_id local channel_id = extra.channelid local sender = extra.sender if member_id == sender then return send_large_msg("channel#id"..channel_id, "Leave using kickme command") end if is_momod2(member_id, channel_id) and not is_admin2(sender) then return send_large_msg("channel#id"..channel_id, "You can't kick mods/owner/admins") end if is_admin2(member_id) then return send_large_msg("channel#id"..channel_id, "You can't kick other admins") end kick_user(user_id, channel_id) elseif get_cmd == "setadmin" then local user_id = "user#id"..result.peer_id local channel_id = extra.channel channel_set_admin(channel_id, user_id, ok_cb, false) if result.username then text = "@"..result.username.." has been set as an admin" send_large_msg(channel_id, text) else text = "@"..result.peer_id.." has been set as an admin" send_large_msg(channel_id, text) end elseif get_cmd == "setowner" then local receiver = extra.channel local channel = string.gsub(receiver, 'channel#id', '') local from_id = extra.from_id local group_owner = data[tostring(channel)]['set_owner'] if group_owner then local user = "user#id"..group_owner if not is_admin2(group_owner) and not is_support(group_owner) then channel_demote(receiver, user, ok_cb, false) end local user_id = "user#id"..result.peer_id channel_set_admin(receiver, user_id, ok_cb, false) data[tostring(channel)]['set_owner'] = tostring(result.peer_id) save_data(_config.moderation.data, data) savelog(channel, name_log.." ["..from_id.."] set ["..result.peer_id.."] as owner by username") if result.username then text = member_username.." [ "..result.peer_id.." ] added as owner" else text = "[ "..result.peer_id.." ] added as owner" end send_large_msg(receiver, text) end]] elseif get_cmd == "promote" then local receiver = extra.channel local user_id = result.peer_id --local user = "user#id"..result.peer_id promote2(receiver, member_username, user_id) --channel_set_mod(receiver, user, ok_cb, false) elseif get_cmd == "demote" then local receiver = extra.channel local user_id = result.peer_id local user = "user#id"..result.peer_id demote2(receiver, member_username, user_id) elseif get_cmd == "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, "شما ادمین کل را نمی توانید برکنار کنید") end channel_demote(channel_id, user_id, ok_cb, false) if result.username then text = "@"..result.username.." از لیست سرپرستان گروه حذف شد" send_large_msg(channel_id, text) else text = "@"..result.peer_id.." از لیست سرپرستان گروه حذف شد" 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.."] از لیست Mute کاربران پاک شد") elseif is_owner(extra.msg) then mute_user(chat_id, user_id) send_large_msg(receiver, " ["..user_id.."] به لیست Mute کاربران اضافه شد") 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.' --sosha else text = 'No user ['..memberid..'] in this SuperGroup.' --sosha 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") --sosha 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") --sosha end if is_admin2(user_id) then return send_large_msg("channel#id"..channel_id, "You can't kick other admins") --sosha end if v.username then text = "" savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: @"..v.username.." ["..v.peer_id.."]") --sosha else text = "" savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: ["..v.peer_id.."]") --sosha end kick_user(user_id, channel_id) 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.."] به لیست سرپرستان گروه اضافه شد" savelog(msg.to.id, name_log.." ["..msg.from.id.."] set admin @"..v.username.." ["..v.peer_id.."]") else text = "["..v.peer_id.."] به لیست سرپرستان گروه اضافه شد" savelog(msg.to.id, name_log.." ["..msg.from.id.."] set admin "..v.peer_id) end if v.username then member_username = "@"..v.username else member_username = string.gsub(v.print_name, '_', ' ') end local receiver = channel_id local user_id = v.peer_id promote_admin(receiver, member_username, user_id) end send_large_msg(channel_id, text) end elseif get_cmd == '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.."] به صاحب گروه منتصب شد" else text = "به صاحب گروه منتصب شد ["..v.peer_id.."]" 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.."] به صاحب گروه منتصب شد" end end end end send_large_msg(receiver, text) end --End non-channel_invite username actions function muted_user_list2(chat_id) local hash = 'mute_user:'..chat_id local list = redis:smembers(hash) local text = "لیست کاربران Mute شده ["..chat_id.."]:\n\n" for k,v in pairsByKeys(list) do local user_info = redis:hgetall('user:'..v) if user_info and user_info.print_name then local print_name = string.gsub(user_info.print_name, "_", " ") local print_name = string.gsub(print_name, "‮", "") text = text..k.." - "..print_name.." ["..v.."]\n" else text = text..k.." - [ "..v.." ]\n" end end return text end --'Set supergroup photo' function local function set_supergroup_photo(msg, success, result) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if success then local file = 'data/photos/channel_photo_'..msg.to.id..'.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) channel_set_photo(receiver, file, ok_cb, false) data[tostring(msg.to.id)]['settings']['set_photo'] = file save_data(_config.moderation.data, data) send_large_msg(receiver, 'عکس جدید با موفقیت ذخیره شد', ok_cb, false) else print('Error downloading: '..msg.id) send_large_msg(receiver, 'عملیات ناموفق، مجددا تلاش کنید!', ok_cb, false) end end --Run function local function run(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 "از قبل سوپر گروه بوده است" 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] == 'add' and not matches[2] then if not is_admin1(msg) and not is_support(support_id) then return end if is_super_group(msg) then return reply_msg(msg.id, 'سوپر گروه از قبل اضافه شده است!', ok_cb, false) end print("SuperGroup "..msg.to.print_name.."("..msg.to.id..") added") savelog(msg.to.id, name_log.." ["..msg.from.id.."] added SuperGroup") superadd(msg) set_mutes(msg.to.id) channel_set_admin(receiver, 'user#id'..msg.from.id, ok_cb, false) end if matches[1] == 'rem' and is_admin1(msg) and not matches[2] then if not is_super_group(msg) then return reply_msg(msg.id, 'سوپر گروه اضافه نشده است!', ok_cb, false) end print("SuperGroup "..msg.to.print_name.."("..msg.to.id..") removed") superrem(msg) rem_mutes(msg.to.id) end if matches[1] == "gpinfo" then 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 "این گروه صاحبی ندارد.\nلطفا با نوشتن دستور زیر به ادمین ربات اطلاع دهید\n/contact" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner") return "صاحب گروه می باشد ["..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 --sosha member_type = 'Bots' --sosha 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] == 'block' 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] == 'block' and string.match(matches[2], '^%d+$') then --[[local user_id = matches[2] local channel_id = msg.to.id if is_momod2(user_id, channel_id) and not is_admin2(user_id) then return send_large_msg(receiver, "You can't kick mods/owner/admins") end savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: [ user#id"..user_id.." ]") kick_user(user_id, channel_id)]] local get_cmd = 'channel_block' local msg = msg local user_id = matches[2] channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, user_id=user_id}) elseif msg.text:match("@[%a%d]") then --[[local cbres_extra = { channelid = msg.to.id, get_cmd = 'channel_block', sender = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: @"..username) resolve_username(username, callbackres, cbres_extra)]] local get_cmd = 'channel_block' local msg = msg local username = matches[2] local username = string.gsub(matches[2], '@', '') channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, username=username}) end end if matches[1] == 'id' then if type(msg.reply_id) ~= "nil" and is_momod(msg) and not matches[2] then local cbreply_extra = { get_cmd = 'id', msg = msg } get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif type(msg.reply_id) ~= "nil" and matches[2] == "from" and is_momod(msg) then local cbreply_extra = { get_cmd = 'idfrom', msg = msg } get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif msg.text:match("@[%a%d]") then local cbres_extra = { channelid = msg.to.id, get_cmd = 'id' } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested ID for: @"..username) resolve_username(username, callbackres, cbres_extra) else savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup ID") return "آی دی (ID) سوپر گروه " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id end end if matches[1] == 'kickme' then if msg.to.type == 'channel' then return 'این دستور در سوپر گروه غیرفعال است' 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, '*خطا: دریافت لینک گروه ناموفق*\nدلیل: ربات سازنده گروه نمی باشد.\n\nبا ادمین صحبت کنید.\n/contact') data[tostring(msg.to.id)]['settings']['set_link'] = nil save_data(_config.moderation.data, data) else send_large_msg(receiver, "لینک جدید ساخته شد\n\nبرای نمایش لینک جدید، دستور زیر را تایپ کنی\n/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' --sosha save_data(_config.moderation.data, data) return 'لینک جدید را ارسال کنید' --sosha 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 "لینک جدید تنظیم شد" --sosha 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 "برای اولین بار ابتدا باید newlink/ را تایپ کنید" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]") return "لینک سوپر گروه:\n"..group_link end if matches[1] == "invite" and is_sudo(msg) then local cbres_extra = { channel = get_receiver(msg), get_cmd = "invite" --sosha } 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 --sosha 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) --sosha resolve_username(username, callbackres, cbres_extra) end if matches[1] == 'kick' and is_momod(msg) then local receiver = channel..matches[3] local user = "user#id"..matches[2] chaannel_kick(receiver, user, ok_cb, false) end if matches[1] == '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' 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 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 "فقط صاحب گروه توانایی اضافه کردن مدیر را دارد" 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] == 'setmod' 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 "به ادمین گروه منتصب شد" end if matches[1] == 'remmod' and is_sudo(msg) then channel = get_receiver(msg) user_id = 'user#id'..matches[2] channel_demote(channel, user_id, ok_cb, false) return "از ادمین گروه برداشته شد" end if matches[1] == 'demote' then if not is_momod(msg) then return end if not is_owner(msg) then return "فقط صاحب گروه قادر به حذف کردن مدیر می باشد" 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] == "setdesc" 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 "موضوع گروه عوض شد\n\nبرای دیدن تغییرات، Description گروه را مشاهده کنید" 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.") --sosha 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.") --sosha end end local username = string.gsub(matches[2], '@', '') channel_set_username(receiver, username, ok_username_cb, {receiver=receiver}) end if matches[1]:lower() == 'uexpiretime' and not matches[3] then local hash = 'usecommands:'..msg.from.id..':'..msg.to.id redis:incr(hash) expired = 'Unlimited' local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group expire time to [unlimited]") return set_expiretime(msg, data, target) end if matches[1]:lower() == 'expiretime' then local hash = 'usecommands:'..msg.from.id..':'..msg.to.id redis:incr(hash) if tonumber(matches[2]) < 95 or tonumber(matches[2]) > 96 then return "اولین match باید بین 95 تا 96 باشد" end if tonumber(matches[3]) < 01 or tonumber(matches[3]) > 12 then return "دومین match باید بین 01 تا 12 باشد" end if tonumber(matches[4]) < 01 or tonumber(matches[4]) > 31 then return "سومین match باید بین 01 تا 31 باشد" end expired = matches[2]..'.'..matches[3]..'.'..matches[4] local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group expire time to ["..matches[2]/matches[3]/matches[4].."]") return set_expiretime(msg, data, target) 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 'برای تغییر عکس گروه ،یک عکس بفرستید' end if matches[1] == 'clean' then if not is_momod(msg) then return end if not is_momod(msg) then return "فقط مدیر قادر به حذف تمامی مدیران می باشد" end if matches[2] == 'modlist' then if next(data[tostring(msg.to.id)]['moderators']) == nil then return 'هیچ مدیری در این گروه وجود ندارد' 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 'تمامی مدیران از لیست مدیریت پاک شدند' end if matches[2] == 'rules' then local data_cat = 'rules' if data[tostring(msg.to.id)][data_cat] == nil then return "قانون یا قوانینی ثبت نشده است" 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 'قوانین گروه پاک شد' end if matches[2]:lower() == 'welcome' then local hash = 'usecommands:'..msg.from.id..':'..msg.to.id redis:incr(hash) rules = matches[3] local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group welcome message to ["..matches[3].."]") return set_welcomemod(msg, data, target) end if matches[2] == 'desc' then --sosha local receiver = get_receiver(msg) local about_text = ' ' local data_cat = 'description' if data[tostring(msg.to.id)][data_cat] == nil then return 'موضوعی برای گروه ثبت نشده است' 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 "موضوع گروه پاک شد" end if matches[2] == 'silentlist' then chat_id = msg.to.id local hash = 'mute_user:'..chat_id redis:del(hash) return "لیست تمامی کاربران Mute شده پاک شد" 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 if matches[2] == "bots" and is_momod(msg) then savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked all SuperGroup bots") channel_get_bots(receiver, callback_clean_bots, {msg = msg}) return "تمامی ربات ها از سوپر گروه پاک شدند" end end if matches[1] == 'lock' and is_momod(msg) then local target = msg.to.id if matches[2] == 'link' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked link posting ") return lock_group_links(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] == 'strict' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked enabled strict settings") return enable_strict_rules(msg, data, target) end end if matches[1] == 'unlock' and is_momod(msg) then local target = msg.to.id if matches[2] == 'link' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked link posting") return unlock_group_links(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] == 'strict' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked disabled strict settings") return disable_strict_rules(msg, data, target) end end if matches[1] == 'setflood' then if not is_momod(msg) then return end if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then return "عدد اشتباه، باید بین [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 'تعداد اسپم روی '..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_momod(msg) then local chat_id = msg.to.id local target = 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) data[tostring(msg.to.id)]['settings']['mute_audio'] = 'yes' save_data(_config.moderation.data, data) return "فیلتر فایل های صوتی فعال شد" else return "فیلتر فایل های صوتی از قبل فعال بوده است" end end if matches[2] == 'forward' then local msg_type = 'Forward' 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) data[tostring(msg.to.id)]['settings']['mute_forward'] = 'yes' save_data(_config.moderation.data, data) return "فیلتر فروارد فعال شد" else return "فیلتر فروارد از قبل فعال بوده است" end end if matches[2] == 'sticker' or matches[2] == 'stickers' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] mute sticker posting") return lock_group_sticker(msg, data, target) end if matches[2] == 'contact' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] mute contact posting") return lock_group_contacts(msg, data, target) end if matches[2] == 'porn' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] mute porn ") return lock_group_porn(msg, data, target) end if matches[2] == 'service' then local msg_type = 'service' 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) data[tostring(msg.to.id)]['settings']['mute_service'] = 'yes' save_data(_config.moderation.data, data) return "فیلتر پیام ورود و خروج افراد فعال شد" else return "فیلتر پیام ورود و خروج افراد از قبل فعال بوده است" 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) data[tostring(msg.to.id)]['settings']['mute_photo'] = 'yes' save_data(_config.moderation.data, data) return "فیلتر عکس فعال شد" else return "فیلتر عکس از قبل فعال بوده است" 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) data[tostring(msg.to.id)]['settings']['mute_video'] = 'yes' save_data(_config.moderation.data, data) return "فیلتر فیلم فعال شد" else return "فیلتر فیلم از قبل فعال بوده است" end end if matches[2] == 'gif' 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) data[tostring(msg.to.id)]['settings']['mute_gif'] = 'yes' save_data(_config.moderation.data, data) return "فیلتر Gif فعال شد" else return "فیلتر Gif از قبل فعال بوده است" 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) data[tostring(msg.to.id)]['settings']['mute_doc'] = 'yes' save_data(_config.moderation.data, data) return "فیلتر فایل ها فعال شد" else return "فیلتر فایل ها از قبل فعال بوده است" 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) data[tostring(msg.to.id)]['settings']['mute_text'] = 'yes' save_data(_config.moderation.data, data) return "فیلتر ارسال متن فعال شد" else return "فیلتر ارسال متن از قبل فعال بوده است" 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) data[tostring(msg.to.id)]['settings']['mute_all'] = 'yes' save_data(_config.moderation.data, data) return "فیلتر تمامی پیام ها فعال شد" else return "فیلتر تمامی پیام ها از قبل فعال بوده است" end end end if matches[1] == 'unmute' and is_momod(msg) then local chat_id = msg.to.id local target = 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) data[tostring(msg.to.id)]['settings']['mute_audio'] = 'no' save_data(_config.moderation.data, data) return "فیلتر فایل های صوتی غیرفعال شد" else return "فیلتر فایل های صوتی از قبل غیرفعال بوده است" end end if matches[2] == 'forward' then local msg_type = 'Forward' 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) data[tostring(msg.to.id)]['settings']['mute_forward'] = 'no' save_data(_config.moderation.data, data) return "فیلتر فروارد غیرفعال شد" else return "فیلتر فروارد از قبل غیرفعال بوده است" end end if matches[1]:lower() == 'welcome' then local target = msg.to.id if matches[2]:lower() == 'enable' then local hash = 'usecommands:'..msg.from.id..':'..msg.to.id redis:incr(hash) savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked welcome ") return lock_group_welcome(msg, data, target) end if matches[2]:lower() == 'disable' then local hash = 'usecommands:'..msg.from.id..':'..msg.to.id redis:incr(hash) savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked welcome ") return unlock_group_welcome(msg, data, target) end end if matches[2] == 'sticker' or matches[2] == 'stickers' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unmute sticker posting") return unlock_group_sticker(msg, data, target) end if matches[2] == 'contact' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unmute contact posting") return unlock_group_contacts(msg, data, target) end if matches[2] == 'porn' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unmute porn ") return unlock_group_porn(msg, data, target) end if matches[2] == 'service' then local msg_type = 'service' 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) data[tostring(msg.to.id)]['settings']['mute_service'] = 'no' save_data(_config.moderation.data, data) return "فیلتر پیام ورود و خروج افراد غیرفعال شد" else return "فیلتر پیام ورود و خروج افراد از قبل غیرفعال بوده است" 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) data[tostring(msg.to.id)]['settings']['mute_photo'] = 'no' save_data(_config.moderation.data, data) return "فیلتر عکس غیرفعال شد" else return "فیلتر عکس از قبل غیرفعال بوده است" 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) data[tostring(msg.to.id)]['settings']['mute_video'] = 'no' save_data(_config.moderation.data, data) return "فیلتر فیلم غیرفعال شد" else return "فیلتر فیلم از قبل غیرفعال بوده است" end end if matches[2] == 'gif' 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) data[tostring(msg.to.id)]['settings']['mute_gif'] = 'no' save_data(_config.moderation.data, data) return "فیلتر Gif غیرفعال شد" else return "فیلتر Gif از قبل غیرفعال بوده است" 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) data[tostring(msg.to.id)]['settings']['mute_doc'] = 'no' save_data(_config.moderation.data, data) return "فیلتر فایل ها غیرفعال شد" else return "فیلتر فایل ها از قبل غیرفعال بوده است" 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) data[tostring(msg.to.id)]['settings']['mute_text'] = 'no' save_data(_config.moderation.data, data) return "فیلتر ارسال متن غیرفعال شد" else return "فیلتر ارسال متن از قبل غیرفعال بوده است" 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) data[tostring(msg.to.id)]['settings']['mute_all'] = 'no' save_data(_config.moderation.data, data) return "فیلتر تمامی پیام ها غیرفعال شد" else return "فیلتر تمامی پیام ها از قبل غیرفعال بوده است" end end end if matches[1]:lower() == "silent" 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" 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.."] از لیست Mute کاربران حذف شد" 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.."] به لیست Mute کاربران اضافه شد" end elseif matches[1] == "silent" 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] == "mutelist" and is_momod(msg) then local target = msg.to.id if not has_mutes(target) then set_mutes(target) return show_supergroup_mutes(msg, target) end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup muteslist") return show_supergroup_mutes(msg, target) end --Arian 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") local hash = 'mute_user:'..msg.to.id local list = redis:smembers(hash) local text = "لیست کاربران Mute شده ["..msg.to.id.."]:\n\n" for k,v in pairsByKeys(list) do local user_info = redis:hgetall('user:'..v) if user_info and user_info.print_name then local print_name = string.gsub(user_info.print_name, "_", " ") local print_name = string.gsub(print_name, "‮", "") text = text..k.." - "..print_name.." ["..v.."]\n" else text = text..k.." - [ "..v.." ]\n" end end return text 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 = "Dar Hale Sakhte shodan:|" 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]dd)$", "^[#!/]([Rr]em)$", "^[!/]([Mm]ove) (.*)$", "^[!/]([Gg][Pp][Ii]nfo)$", "^[!/]([Aa]dmins)$", "^[!/]([Oo]wner)$", "^[#!/]([Mm]odlist)$", "^[!/]([Bb]ots)$", "^[!/]([Ww]ho)$", "^[!/]([Kk]icked)$", "^[!/]([Bb]lock) (.*)", "^[!/]([Bb]lock)", "^[#!/]([Tt]osuper)$", --"^[!/]([Ii][Dd])$", "^[#!/]([Ii][Dd]) (.*)$", "^[!/]([Kk]ickme)$", "^[#!/]([Kk]ick) (.*)$", "^[#!/]([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]etdesc) (.*)$", "^[!/]([Ss]etrules) (.*)$", "^[!/]([Ss]etphoto)$", "^[!/]([Ss]etusername) (.*)$", "^[!/]([Uu][Ee]xpiretime)$", "^[!/]([Ee]xpiretime) (.*) (.*) (.*)$", "^[!/]([Dd]el)$", "^[#!/]([Ll]ock) (.*)$", "^[#!/]([Uu]nlock) (.*)$", "^[#!/]([Mm]ute) ([^%s]+)$", "^[#!/]([Uu]nmute) ([^%s]+)$", "^[!/]([Ss]ilent)$", "^[!/]([Ss]ilent) (.*)$", "^[!/]([Pp]ublic) (.*)$", "^[#!/]([Ss]ettings)$", "^[!/]([Rr]ules)$", "^[!/]([Ss]etflood) (%d+)$", "^[!/]([Cc]lean) (.*)$", --"^[!/]([Hh]elp)$", "^[#!/]([Ss]ilentlist)$", "^[#!/]([Mm]utelist)$", "[!/](setmod) (.*)", "[!/](remmod) (.*)", "^[!/]([Ww]elcome) (.*)$", "^(https://telegram.me/joinchat/%S+)$", "msg.to.peer_id", "%[(document)%]", "%[(photo)%]", "%[(video)%]", "%[(audio)%]", "%[(contact)%]", "^!!tgservice (.+)$", }, run = run, pre_process = pre_process } --End supergrpup.lua --By @Rondoozle
gpl-2.0
SuperStarPL/PonyPlayerModels
pony_player_models/lua/ppm/render_texture.lua
2
23696
if CLIENT then function PPM.TextureIsOutdated(ent, name, newhash) if !PPM.isValidPony(ent) then return true end if ent.ponydata_tex==nil then return true end if ent.ponydata_tex[name]==nil then return true end if ent.ponydata_tex[name.."_hash"]==nil then return true end if ent.ponydata_tex[name.."_hash"]!=newhash then return true end return false end function PPM.GetBodyHash(ponydata) return tostring(ponydata.bodyt0)..tostring(ponydata.bodyt1)..tostring(ponydata.coatcolor)..tostring(ponydata.bodyt1_color) end function FixVertexLitMaterial(Mat) local strImage = Mat:GetName() if ( string.find( Mat:GetShader(), "VertexLitGeneric" ) || string.find( Mat:GetShader(), "Cable" ) ) then local t = Mat:GetString( "$basetexture" ) if ( t ) then local params = {} params[ "$basetexture" ] = t params[ "$vertexcolor" ] = 1 params[ "$vertexalpha" ] = 1 Mat = CreateMaterial( strImage .. "_DImage", "UnlitGeneric", params ) end end return Mat end function PPM.CreateTexture(tname, data) local w, h = ScrW(), ScrH() local rttex = nil local size = data.size or 512 rttex = GetRenderTarget( tname, size, size, false ) if data.predrawfunc !=nil then data.predrawfunc() end local OldRT = render.GetRenderTarget() render.SetRenderTarget( rttex ) render.SuppressEngineLighting( true ) cam.IgnoreZ( true ) render.SetBlend( 1 ) render.SetViewPort( 0, 0, size, size ) render.Clear( 0, 0, 0, 255, true ) cam.Start2D() render.SetColorModulation(1,1,1) if data.drawfunc !=nil then data.drawfunc() end cam.End2D() render.SetRenderTarget( OldRT ) render.SetViewPort( 0, 0, w, h ) render.SetColorModulation(1,1,1) render.SetBlend( 1 ) render.SuppressEngineLighting( false ) return rttex end function PPM.CreateBodyTexture(ent,pony) if !PPM.isValidPony(ent) then return end local w, h = ScrW(), ScrH() local function tW(val) return val end//val/512*w end local function tH(val) return val end//val/512*h end local rttex = nil ent.ponydata_tex = ent.ponydata_tex or {} if(ent.ponydata_tex.bodytex!=nil) then rttex =ent.ponydata_tex.bodytex else rttex = GetRenderTarget( tostring(ent).."body", tW(512), tH(512), false ) end local OldRT = render.GetRenderTarget() render.SetRenderTarget( rttex ) render.SuppressEngineLighting( true ) cam.IgnoreZ( true ) render.SetLightingOrigin( Vector(0,0,0) ) render.ResetModelLighting( 1,1,1) render.SetColorModulation(1,1,1) render.SetBlend( 1 ) render.SetModelLighting( BOX_TOP, 1, 1, 1 ) render.SetViewPort( 0, 0, tW(512), tH(512) ) render.Clear( 0, 255, 255, 255, true ) cam.Start2D() render.SetColorModulation(1,1,1) if(pony.gender==1)then render.SetMaterial(FixVertexLitMaterial(Material("models/ppm/base/render/bodyf"))) else render.SetMaterial(FixVertexLitMaterial(Material("models/ppm/base/render/bodym"))) end render.DrawQuadEasy( Vector(tW(256),tH(256),0), --position of the rect Vector(0,0,-1), --direction to face in tW(512),tH(512), --size of the rect Color( pony.coatcolor.x*255, pony.coatcolor.y*255, pony.coatcolor.z*255, 255 ), --color -90 --rotate 90 degrees ) if(pony.bodyt1>1) then render.SetMaterial(FixVertexLitMaterial(PPM.m_bodydetails[pony.bodyt1-1][1])) render.SetBlend( 1 ) local colorbl = pony.bodyt1_color or Vector(1,1,1) render.DrawQuadEasy( Vector(tW(256),tH(256),0), --position of the rect Vector(0,0,-1), --direction to face in tW(512),tH(512), --size of the rect Color( colorbl.x*255, colorbl.y*255, colorbl.z*255, 255 ), --color -90 --rotate 90 degrees ) end if(pony.bodyt0>1) then render.SetMaterial(FixVertexLitMaterial(PPM.m_bodyt0[pony.bodyt0-1][1])) render.SetBlend( 1 ) render.DrawQuadEasy( Vector(tW(256),tH(256),0), --position of the rect Vector(0,0,-1), --direction to face in tW(512),tH(512), --size of the rect Color( 255, 255, 255, 255 ), --color -90 --rotate 90 degrees ) end cam.End2D() render.SetRenderTarget( OldRT ) // Resets the RenderTarget to our screen render.SetViewPort( 0, 0, w, h ) render.SetColorModulation(1,1,1) render.SetBlend( 1 ) render.SuppressEngineLighting( false ) // cam.IgnoreZ( false ) ent.ponydata_tex.bodytex = rttex //MsgN("HASHOLD: "..tostring(ent.ponydata_tex.bodytex_hash)) ent.ponydata_tex.bodytex_hash = PPM.GetBodyHash(pony) //MsgN("HASHNEW: "..tostring(ent.ponydata_tex.bodytex_hash)) //MsgN("HASHTAR: "..tostring(PPM.GetBodyHash(outpony))) return rttex end PPM.VALIDPONY_CLASSES = {"player","prop_ragdoll","prop_physics","cpm_pony_npc"} function HOOK_HUDPaint() for name, ent in pairs(ents.GetAll()) do if(ent!=nil and (table.HasValue(PPM.VALIDPONY_CLASSES,ent:GetClass()) or string.match(ent:GetClass(),"^(npc_)")!=nil)) then if(PPM.isValidPonyLight(ent)) then local pony = PPM.getPonyValues(ent,false) if(!PPM.isValidPony(ent)) then PPM.setupPony(ent) end local texturespreframe = 1 for k ,v in pairs(PPM.rendertargettasks) do if(PPM.TextureIsOutdated(ent, k, v.hash(pony))) then if texturespreframe>0 then ent.ponydata_tex = ent.ponydata_tex or {} PPM.currt_ent = ent PPM.currt_ponydata = pony PPM.currt_success = false ent.ponydata_tex[k] = PPM.CreateTexture(tostring(ent)..k, v) ent.ponydata_tex[k.."_hash"] = v.hash(pony) ent.ponydata_tex[k.."_draw"] = PPM.currt_success texturespreframe = texturespreframe - 1 end end end end else if(ent.isEditorPony)then local pony = PPM.getPonyValues(ent, true) if(!PPM.isValidPony(ent)) then PPM.setupPony(ent) end for k ,v in pairs(PPM.rendertargettasks) do if(PPM.TextureIsOutdated(ent, k, v.hash(pony))) then //MsgN("Outdated texture at "..tostring(ent)..tostring(ent:GetClass())) ent.ponydata_tex = ent.ponydata_tex or {} PPM.currt_ent = ent PPM.currt_ponydata = pony PPM.currt_success = false ent.ponydata_tex[k] = PPM.CreateTexture(tostring(ent)..k, v) ent.ponydata_tex[k.."_hash"] = v.hash(pony) ent.ponydata_tex[k.."_draw"] = PPM.currt_success end end end end end end hook.Add("HUDPaint", "pony_render_textures", HOOK_HUDPaint) PPM.loadrt = function() PPM.currt_success = false PPM.currt_ent = nil PPM.currt_ponydata = nil PPM.rendertargettasks = {} PPM.rendertargettasks["bodytex"]= { renderTrue = function(ENT,PONY) PPM.m_body:SetVector( "$color2", Vector(1,1,1) ) PPM.m_body:SetTexture("$basetexture",ENT.ponydata_tex.bodytex) end, renderFalse = function(ENT,PONY) PPM.m_body:SetVector( "$color2", PONY.coatcolor ) if(PONY.gender==1)then PPM.m_body:SetTexture("$basetexture",PPM.m_bodyf:GetTexture("$basetexture")) else PPM.m_body:SetTexture("$basetexture",PPM.m_bodym:GetTexture("$basetexture")) end end, drawfunc = function() local pony =PPM.currt_ponydata if (pony.gender==1) then render.SetMaterial(FixVertexLitMaterial(Material("models/ppm/base/render/bodyf"))) else render.SetMaterial(FixVertexLitMaterial(Material("models/ppm/base/render/bodym"))) end render.DrawQuadEasy( Vector(256,256,0), --position of the rect Vector(0,0,-1), --direction to face in 512,512, --size of the rect Color( pony.coatcolor.x*255, pony.coatcolor.y*255, pony.coatcolor.z*255, 255 ), --color -90 --rotate 90 degrees ) //MsgN("render.body.prep") for C=1,8 do local detailvalue = pony["bodydetail"..C] or 1 local detailcolor = pony["bodydetail"..C.."_c"] or Vector(0,0,0) if(detailvalue>1) then //MsgN("rendering tex id: ",detailvalue," col: ",detailcolor) render.SetMaterial(PPM.m_bodydetails[detailvalue-1][1])//Material("models/ppm/base/render/clothes_sbs_full")) //surface.SetTexture( surface.GetTextureID( "models/ppm/base/render/horn" ) ) render.SetBlend( 1 ) render.DrawQuadEasy( Vector(256,256,0), --position of the rect Vector(0,0,-1), --direction to face in 512,512, --size of the rect Color( detailcolor.x*255, detailcolor.y*255, detailcolor.z*255, 255 ), --color -90 --rotate 90 degrees ) end end local pbt = pony.bodyt0 or 1 if(pbt>1) then local mmm = PPM.m_bodyt0[pbt-1] if(mmm!=nil) then render.SetMaterial(FixVertexLitMaterial(mmm))//Material("models/ppm/base/render/clothes_sbs_full")) //surface.SetTexture( surface.GetTextureID( "models/ppm/base/render/horn" ) ) render.SetBlend( 1 ) render.DrawQuadEasy( Vector(256,256,0), --position of the rect Vector(0,0,-1), --direction to face in 512,512, --size of the rect Color( 255, 255, 255, 255 ), --color -90 --rotate 90 degrees ) end end PPM.currt_success = true end, hash = function(ponydata) local hash = tostring(ponydata.bodyt0).. tostring(ponydata.coatcolor).. tostring(ponydata.gender) for C=1,8 do local detailvalue = ponydata["bodydetail"..C] or 1 local detailcolor = ponydata["bodydetail"..C.."_c"] or Vector(0,0,0) hash = hash..tostring(detailvalue)..tostring(detailcolor) end return hash end } PPM.rendertargettasks["hairtex1"]= { renderTrue = function(ENT,PONY) PPM.m_hair1:SetVector( "$color2", Vector(1,1,1) ) //PPM.m_hair2:SetVector( "$color2", Vector(1,1,1) ) PPM.m_hair1:SetTexture("$basetexture",ENT.ponydata_tex.hairtex1) end, renderFalse = function(ENT,PONY) PPM.m_hair1:SetVector( "$color2", PONY.haircolor1 ) //PPM.m_hair2:SetVector( "$color2", PONY.haircolor2 ) PPM.m_hair1:SetTexture("$basetexture",Material("models/ppm/partrender/clean.png"):GetTexture("$basetexture")) //PPM.m_hair2:SetTexture("$basetexture",Material("models/ppm/partrender/clean.png"):GetTexture("$basetexture")) end, drawfunc = function() local pony =PPM.currt_ponydata render.Clear( pony.haircolor1.x*255, pony.haircolor1.y*255, pony.haircolor1.z*255, 255, true ) PPM.tex_drawhairfunc(pony,"up",false) end, hash = function(ponydata) return tostring(ponydata.haircolor1).. tostring(ponydata.haircolor2).. tostring(ponydata.haircolor3).. tostring(ponydata.haircolor4).. tostring(ponydata.haircolor5).. tostring(ponydata.haircolor6).. tostring(ponydata.mane)..tostring(ponydata.manel) end } PPM.rendertargettasks["hairtex2"]= { renderTrue = function(ENT,PONY) //PPM.m_hair1:SetVector( "$color2", Vector(1,1,1) ) PPM.m_hair2:SetVector( "$color2", Vector(1,1,1) ) PPM.m_hair2:SetTexture("$basetexture",ENT.ponydata_tex.hairtex2) end, renderFalse = function(ENT,PONY) //PPM.m_hair1:SetVector( "$color2", PONY.haircolor1 ) PPM.m_hair2:SetVector( "$color2", PONY.haircolor2 ) //PPM.m_hair1:SetTexture("$basetexture",Material("models/ppm/partrender/clean.png"):GetTexture("$basetexture")) PPM.m_hair2:SetTexture("$basetexture",Material("models/ppm/partrender/clean.png"):GetTexture("$basetexture")) end, drawfunc = function() local pony =PPM.currt_ponydata PPM.tex_drawhairfunc(pony,"dn",false) end, hash = function(ponydata) return tostring(ponydata.haircolor1).. tostring(ponydata.haircolor2).. tostring(ponydata.haircolor3).. tostring(ponydata.haircolor4).. tostring(ponydata.haircolor5).. tostring(ponydata.haircolor6).. tostring(ponydata.mane)..tostring(ponydata.manel) end } PPM.rendertargettasks["tailtex"]= { renderTrue = function(ENT,PONY) PPM.m_tail1:SetVector( "$color2", Vector(1,1,1) ) PPM.m_tail2:SetVector( "$color2", Vector(1,1,1) ) PPM.m_tail1:SetTexture("$basetexture",ENT.ponydata_tex.tailtex) end, renderFalse = function(ENT,PONY) PPM.m_tail1:SetVector( "$color2", PONY.haircolor1 ) PPM.m_tail2:SetVector( "$color2", PONY.haircolor2 ) PPM.m_tail1:SetTexture("$basetexture",Material("models/ppm/partrender/clean.png"):GetTexture("$basetexture")) PPM.m_tail2:SetTexture("$basetexture",Material("models/ppm/partrender/clean.png"):GetTexture("$basetexture")) end, drawfunc = function() local pony =PPM.currt_ponydata PPM.tex_drawhairfunc(pony,"up",true) end, hash = function(ponydata) return tostring(ponydata.haircolor1).. tostring(ponydata.haircolor2).. tostring(ponydata.haircolor3).. tostring(ponydata.haircolor4).. tostring(ponydata.haircolor5).. tostring(ponydata.haircolor6).. tostring(ponydata.tail) end } PPM.rendertargettasks["eyeltex"]= { renderTrue = function(ENT,PONY) PPM.m_eyel:SetTexture("$Iris",ENT.ponydata_tex.eyeltex) end, renderFalse = function(ENT,PONY) PPM.m_eyel:SetTexture("$Iris",Material("models/ppm/partrender/clean.png"):GetTexture("$basetexture")) end, drawfunc = function() local pony =PPM.currt_ponydata PPM.tex_draweyefunc(pony,false) end, hash = function(ponydata) return tostring(ponydata.eyecolor_bg) .. tostring(ponydata.eyecolor_iris).. tostring(ponydata.eyecolor_grad).. tostring(ponydata.eyecolor_line1).. tostring(ponydata.eyecolor_line2).. tostring(ponydata.eyecolor_hole).. tostring(ponydata.eyeirissize).. tostring(ponydata.eyeholesize).. tostring(ponydata.eyejholerssize).. tostring(ponydata.eyehaslines) end } PPM.rendertargettasks["eyertex"]= { renderTrue = function(ENT,PONY) PPM.m_eyer:SetTexture("$Iris",ENT.ponydata_tex.eyertex) end, renderFalse = function(ENT,PONY) PPM.m_eyer:SetTexture("$Iris",Material("models/ppm/partrender/clean.png"):GetTexture("$basetexture")) end, drawfunc = function() local pony =PPM.currt_ponydata PPM.tex_draweyefunc(pony,true) end, hash = function(ponydata) return tostring(ponydata.eyecolor_bg) .. tostring(ponydata.eyecolor_iris).. tostring(ponydata.eyecolor_grad).. tostring(ponydata.eyecolor_line1).. tostring(ponydata.eyecolor_line2).. tostring(ponydata.eyecolor_hole).. tostring(ponydata.eyeirissize).. tostring(ponydata.eyeholesize).. tostring(ponydata.eyejholerssize).. tostring(ponydata.eyehaslines) end } PPM.tex_drawhairfunc = function(pony,UPDN,TAIL) local hairnum = pony.mane if UPDN=="dn" then hairnum = pony.manel elseif TAIL then hairnum = pony.tail end PPM.hairrenderOp(UPDN,TAIL,hairnum) local colorcount = PPM.manerender[UPDN..hairnum] if TAIL then colorcount = PPM.manerender["tl"..hairnum] end if colorcount != nil then local coloroffcet =colorcount[1] if UPDN=="up" then coloroffcet=0 end local prephrase = UPDN.."mane_" if TAIL then prephrase = "tail_" end colorcount =colorcount[2] local backcolor =pony["haircolor"..(coloroffcet+1)]or PPM.defaultHairColors[coloroffcet+1] render.Clear( backcolor.x*255, backcolor.y*255, backcolor.z*255, 255, true ) for I=0,colorcount-1 do local color = pony["haircolor"..(I+2+coloroffcet)] or PPM.defaultHairColors[I+2+coloroffcet] or Vector(1,1,1) local material =Material("models/ppm/partrender/"..prephrase..hairnum.."_mask"..I..".png") render.SetMaterial(material) render.DrawQuadEasy( Vector(256,256,0), --position of the rect Vector(0,0,-1), --direction to face in 512,512, --size of the rect Color( color.x*255, color.y*255, color.z*255, 255 ), --color -90 --rotate 90 degrees ) end else if TAIL then end if UPDN=="dn" then render.Clear( pony.haircolor2.x*255, pony.haircolor2.y*255, pony.haircolor2.z*255, 255, true ) else render.Clear( pony.haircolor1.x*255, pony.haircolor1.y*255, pony.haircolor1.z*255, 255, true ) end end end PPM.tex_draweyefunc = function(pony,isR) local prefix = "l" if(!isR) then prefix = "r" end local backcolor =pony.eyecolor_bg or Vector(1,1,1) local color = 1.3*pony.eyecolor_iris or Vector(0.5,0.5,0.5) local colorg = 1.3*pony.eyecolor_grad or Vector(1,0.5,0.5) local colorl1 = 1.3*pony.eyecolor_line1 or Vector(0.6,0.6,0.6) local colorl2 = 1.3*pony.eyecolor_line2 or Vector(0.7,0.7,0.7) local holecol =1.3*pony.eyecolor_hole or Vector(0,0,0) render.Clear( backcolor.x*255, backcolor.y*255, backcolor.z*255, 255, true ) local material =Material("models/ppm/partrender/eye_oval.png") render.SetMaterial(material) local drawlines =pony.eyehaslines==1// or true local holewidth =pony.eyejholerssize or 1 local irissize =pony.eyeirissize or 0.6 local holesize =(pony.eyeirissize or 0.6)*(pony.eyeholesize or 0.7) render.DrawQuadEasy( Vector(256,256,0), --position of the rect Vector(0,0,-1), --direction to face in 512*irissize,512*irissize, --size of the rect Color( color.x*255, color.y*255, color.z*255, 255 ), --color -90 --rotate 90 degrees ) //grad local material =Material("models/ppm/partrender/eye_grad.png") render.SetMaterial(material) render.DrawQuadEasy( Vector(256,256,0), --position of the rect Vector(0,0,-1), --direction to face in 512*irissize,512*irissize, --size of the rect Color( colorg.x*255, colorg.y*255, colorg.z*255, 255 ), --color -90 --rotate 90 degrees ) if drawlines then //eye_line_l1 local material =Material("models/ppm/partrender/eye_line_"..prefix.."2.png") render.SetMaterial(material) render.DrawQuadEasy( Vector(256,256,0), --position of the rect Vector(0,0,-1), --direction to face in 512*irissize,512*irissize, --size of the rect Color( colorl2.x*255, colorl2.y*255, colorl2.z*255, 255 ), --color -90 --rotate 90 degrees ) local material =Material("models/ppm/partrender/eye_line_"..prefix.."1.png") render.SetMaterial(material) render.DrawQuadEasy( Vector(256,256,0), --position of the rect Vector(0,0,-1), --direction to face in 512*irissize,512*irissize, --size of the rect Color( colorl1.x*255, colorl1.y*255, colorl1.z*255, 255 ), --color -90 --rotate 90 degrees ) end //hole local material =Material("models/ppm/partrender/eye_oval.png") render.SetMaterial(material) render.DrawQuadEasy( Vector(256,256,0), --position of the rect Vector(0,0,-1), --direction to face in 512*holesize*holewidth,512*holesize, --size of the rect Color( holecol.x*255, holecol.y*255, holecol.z*255, 255 ), --color -90 --rotate 90 degrees ) local material =Material("models/ppm/partrender/eye_effect.png") render.SetMaterial(material) render.DrawQuadEasy( Vector(256,256,0), --position of the rect Vector(0,0,-1), --direction to face in 512*irissize,512*irissize, --size of the rect Color(255, 255, 255, 255 ), --color -90 --rotate 90 degrees ) local material =Material("models/ppm/partrender/eye_reflection.png") render.SetMaterial(material) render.DrawQuadEasy( Vector(256,256,0), --position of the rect Vector(0,0,-1), --direction to face in 512*irissize,512*irissize, --size of the rect Color(255, 255, 255, 255*0.5 ), --color -90 --rotate 90 degrees ) PPM.currt_success = true end PPM.hairrenderOp =function(UPDN,TAIL,hairnum) if TAIL then if PPM.manerender["tl"..hairnum]!=nil then PPM.currt_success = true end else if PPM.manerender[UPDN..hairnum]!=nil then PPM.currt_success = true end end ///PPM.currt_success =true //MsgN(UPDN,TAIL,hairnum," = ",PPM.currt_success) end PPM.manerender={} PPM.manerender.up5= {0,1} PPM.manerender.up6= {0,1} PPM.manerender.up8= {0,2} PPM.manerender.up9= {0,3} PPM.manerender.up10= {0,1} PPM.manerender.up11= {0,3} PPM.manerender.up12= {0,1} PPM.manerender.up13= {0,1} PPM.manerender.up14= {0,1} PPM.manerender.up15= {0,1} PPM.manerender.dn5= {0,1} PPM.manerender.dn8= {3,2} PPM.manerender.dn9= {3,2} PPM.manerender.dn10= {0,3} PPM.manerender.dn11= {0,2} PPM.manerender.dn12= {0,1} PPM.manerender.tl5= {0,1} PPM.manerender.tl8= {0,5} PPM.manerender.tl10= {0,1} PPM.manerender.tl11= {0,3} PPM.manerender.tl12= {0,2} PPM.manerender.tl13= {0,1} PPM.manerender.tl14= {0,1} PPM.manecolorcounts ={} PPM.manecolorcounts[1] = 1 PPM.manecolorcounts[2] = 1 PPM.manecolorcounts[3] = 1 PPM.manecolorcounts[4] = 1 PPM.manecolorcounts[5] = 1 PPM.manecolorcounts[6] = 1 PPM.defaultHairColors= { Vector(252,92,82)/256, Vector(254,134,60)/256, Vector(254,241,160)/256, Vector(98,188,80)/256, Vector(38,165,245)/256, Vector(124,80,160)/256 } PPM.rendertargettasks["ccmarktex"]= { size = 256, renderTrue = function(ENT,PONY) PPM.m_cmark:SetTexture("$basetexture",ENT.ponydata_tex.ccmarktex) end, renderFalse = function(ENT,PONY) //PPM.m_cmark:SetTexture("$basetexture",Material("models/ppm/partrender/clean.png"):GetTexture("$basetexture")) if(PONY==nil) then return end if(PONY.cmark==nil) then return end if(PPM.m_cmarks[PONY.cmark]==nil) then return end if(PPM.m_cmarks[PONY.cmark][2]==nil) then return end if(PPM.m_cmarks[PONY.cmark][2]:GetTexture("$basetexture")==nil) then return end if(PPM.m_cmarks[PONY.cmark][2]:GetTexture("$basetexture")==NULL) then return end PPM.m_cmark:SetTexture("$basetexture",PPM.m_cmarks[PONY.cmark][2]:GetTexture("$basetexture")) end, drawfunc = function() local pony = PPM.currt_ponydata local data = pony._cmark[1] if pony.custom_mark and data then render.SetColorMaterialIgnoreZ() render.SetBlend( 1 ) PPM.BinaryImageToRT( data ) PPM.currt_success = true else render.Clear( 0, 0, 0, 0 ) PPM.currt_success = false end end, hash = function(ponydata) return tostring( ponydata._cmark[1] ~= nil ) .. ( ponydata.custom_mark or "" ) end } end end
gpl-3.0
ABrandau/OpenRA
mods/cnc/maps/funpark01/scj01ea.lua
4
3959
--[[ Copyright 2007-2019 The OpenRA Developers (see AUTHORS) This file is part of OpenRA, which is free software. It is made available to you under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. For more information, see COPYING. ]] RifleReinforcments = { "e1", "e1", "e1", "bike" } BazookaReinforcments = { "e3", "e3", "e3", "bike" } BikeReinforcments = { "bike" } ReinforceWithLandingCraft = function(units, transportStart, transportUnload, rallypoint) local transport = Actor.Create("oldlst", true, { Owner = player, Facing = 0, Location = transportStart }) local subcell = 0 Utils.Do(units, function(a) transport.LoadPassenger(Actor.Create(a, false, { Owner = transport.Owner, Facing = transport.Facing, Location = transportUnload, SubCell = subcell })) subcell = subcell + 1 end) transport.ScriptedMove(transportUnload) transport.CallFunc(function() Utils.Do(units, function() local a = transport.UnloadPassenger() a.IsInWorld = true a.MoveIntoWorld(transport.Location - CVec.New(0, 1)) if rallypoint ~= nil then a.Move(rallypoint) end end) end) transport.Wait(5) transport.ScriptedMove(transportStart) transport.Destroy() Media.PlaySpeechNotification(player, "Reinforce") end WorldLoaded = function() player = Player.GetPlayer("Nod") dinosaur = Player.GetPlayer("Dinosaur") civilian = Player.GetPlayer("Civilian") InvestigateObj = player.AddPrimaryObjective("Investigate the nearby village for reports of \nstrange activity.") Trigger.OnObjectiveAdded(player, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective") end) Trigger.OnObjectiveCompleted(player, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed") end) Trigger.OnObjectiveFailed(player, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed") end) Trigger.OnPlayerWon(player, function() Media.PlaySpeechNotification(player, "Win") end) Trigger.OnPlayerLost(player, function() Media.PlaySpeechNotification(player, "Lose") end) ReachVillageObj = player.AddPrimaryObjective("Reach the village.") Trigger.OnPlayerDiscovered(civilian, function(_, discoverer) if discoverer == player and not player.IsObjectiveCompleted(ReachVillageObj) then if not dinosaur.HasNoRequiredUnits() then KillDinos = player.AddPrimaryObjective("Kill all creatures in the area.") end player.MarkCompletedObjective(ReachVillageObj) end end) DinoTric.Patrol({WP0.Location, WP1.Location}, true, 3) DinoTrex.Patrol({WP2.Location, WP3.Location}, false) Trigger.OnIdle(DinoTrex, DinoTrex.Hunt) ReinforceWithLandingCraft(RifleReinforcments, SeaEntryA.Location, BeachReinforceA.Location, BeachReinforceA.Location) Trigger.AfterDelay(DateTime.Seconds(3), function() InitialUnitsArrived = true end) Trigger.AfterDelay(DateTime.Seconds(15), function() ReinforceWithLandingCraft(BazookaReinforcments, SeaEntryB.Location, BeachReinforceB.Location, BeachReinforceB.Location) end) if Map.LobbyOption("difficulty") == "easy" then Trigger.AfterDelay(DateTime.Seconds(25), function() ReinforceWithLandingCraft(BikeReinforcments, SeaEntryA.Location, BeachReinforceA.Location, BeachReinforceA.Location) end) Trigger.AfterDelay(DateTime.Seconds(30), function() ReinforceWithLandingCraft(BikeReinforcments, SeaEntryB.Location, BeachReinforceB.Location, BeachReinforceB.Location) end) end Camera.Position = CameraStart.CenterPosition end Tick = function() if InitialUnitsArrived then if player.HasNoRequiredUnits() then player.MarkFailedObjective(InvestigateObj) end if dinosaur.HasNoRequiredUnits() then if KillDinos then player.MarkCompletedObjective(KillDinos) end player.MarkCompletedObjective(InvestigateObj) end end end
gpl-3.0
arrayfire/arrayfire_lua
examples/unified/basic.lua
4
1871
--[[ /******************************************************* * Copyright (c) 2015, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #include <arrayfire.h> #include <cstdio> #include <vector> #include <algorithm> using namespace af; std::vector<float> input(100); // Generate a random number between 0 and 1 // return a uniform number in [0,1]. double unifRand() { return rand() / double(RAND_MAX); } void testBackend() { af::info(); af::dim4 dims(10, 10, 1, 1); af::array A(dims, &input.front()); af_print(A); af::array B = af::constant(0.5, dims, f32); af_print(B); } int main(int argc, char *argv[]) { std::generate(input.begin(), input.end(), unifRand); try { printf("Trying CPU Backend\n"); af::setBackend(AF_BACKEND_CPU); testBackend(); } catch (af::exception& e) { printf("Caught exception when trying CPU backend\n"); fprintf(stderr, "%s\n", e.what()); } try { printf("Trying CUDA Backend\n"); af::setBackend(AF_BACKEND_CUDA); testBackend(); } catch (af::exception& e) { printf("Caught exception when trying CUDA backend\n"); fprintf(stderr, "%s\n", e.what()); } try { printf("Trying OpenCL Backend\n"); af::setBackend(AF_BACKEND_OPENCL); testBackend(); } catch (af::exception& e) { printf("Caught exception when trying OpenCL backend\n"); fprintf(stderr, "%s\n", e.what()); } #ifdef WIN32 // pause in Windows if (!(argc == 2 && argv[1][0] == '-')) { printf("hit [enter]..."); fflush(stdout); getchar(); } #endif return 0; } ]]
bsd-3-clause
EMCTEAM-IRAN/superflux-bot
plugins/toimage.lua
1
1080
local function tosticker(msg, success, result) local receiver = get_receiver(msg) if success then local file = 'data/photos/sticker.png' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) send_photo(get_receiver(msg), file, ok_cb, false) redis:del("sticker:photo") else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end local function run(msg,matches) local receiver = get_receiver(msg) local group = msg.to.id if msg.media then if msg.media.type == 'document' and is_momod(msg) and redis:get("sticker:photo") then if redis:get("sticker:photo") == 'waiting' then load_document(msg.id, tosticker, msg) end end end if matches[1] == "img" or matches[1] == "Img" and is_momod(msg) then redis:set("sticker:photo", "waiting") return 'Please send your sticker now' end end return { patterns = { "^[!/]([Ii]mg)$", "^([Ii]mg)$", "%[(document)%]", }, run = run, }
gpl-3.0
timroes/awesome
docs/06-appearance.md.lua
2
6204
#! /usr/bin/lua local args = {...} local gio = require("lgi").Gio local gobject = require("lgi").GObject local glib = require("lgi").GLib local name_attr = gio.FILE_ATTRIBUTE_STANDARD_NAME local type_attr = gio.FILE_ATTRIBUTE_STANDARD_TYPE -- Like pairs(), but iterate over keys in a sorted manner. Does not support -- modifying the table while iterating. local function sorted_pairs(t) -- Collect all keys local keys = {} for k in pairs(t) do table.insert(keys, k) end table.sort(keys) -- return iterator function local i = 0 return function() i = i + 1 if keys[i] then return keys[i], t[keys[i]] end end end -- Recursive file scanner local function get_all_files(path, ext, ret) ret = ret or {} local enumerator = gio.File.new_for_path(path):enumerate_children( table.concat({name_attr, type_attr}, ",") , 0, nil, nil ) for file in function() return enumerator:next_file() end do local file_name = file:get_attribute_as_string(name_attr) local file_type = file:get_file_type() if file_type == "REGULAR" and file_name:match(ext or "") then table.insert(ret, enumerator:get_child(file):get_path()) elseif file_type == "DIRECTORY" then get_all_files(enumerator:get_child(file):get_path(), ext, ret) end end return ret end local function path_to_module(path) for _, module in ipairs { "awful", "wibox", "gears", "naughty", "menubar", "beautiful" } do local match = path:match("/"..module.."/([^.]+).lua") if match then return module.."."..match:gsub("/",".") end end error("Cannot figure out module for " .. tostring(path)) end local function path_to_html(path) local mod = path_to_module(path):gsub(".init", "") local f = assert(io.open(path)) while true do local line = f:read() if not line then break end if line:match("@classmod") then f:close() return "../classes/".. mod ..".html" end if line:match("@module") or line:match("@submodule") then f:close() return "../libraries/".. mod ..".html" end end f:close() error("Cannot figure out if module or class: " .. tostring(path)) end local function get_link(file, element) return table.concat { "<a href='", path_to_html(file), "#", element, "'>", element:match("[. ](.+)"), "</a>" } end local all_files = get_all_files("./lib/", "lua") local beautiful_vars = {} -- Find all @beautiful doc entries for _,file in ipairs(all_files) do local f = io.open(file) local buffer = "" for line in f:lines() do local var = line:gmatch("--[ ]*@beautiful ([^ \n]*)")() -- There is no backward/forward pattern in lua if #line <= 1 then buffer = "" elseif #buffer and not var then buffer = buffer.."\n"..line elseif line:sub(1,3) == "---" then buffer = line end if var then -- Get the @param, @see and @usage local params = "" for line in f:lines() do if line:sub(1,2) ~= "--" then break else params = params.."\n"..line end end local name = var:gmatch("[ ]*beautiful.(.+)")() if not name then print("WARNING:", var, "seems to be misformatted. Use `beautiful.namespace_name`" ) else table.insert(beautiful_vars, { file = file, name = name, link = get_link(file, var), desc = buffer:gmatch("[- ]+([^\n.]*)")() or "", mod = path_to_module(file), }) end buffer = "" end end end local function create_table(entries, columns) local lines = {} for _, entry in ipairs(entries) do local line = " <tr>" for _, column in ipairs(columns) do line = line.."<td>"..entry[column].."</td>" end table.insert(lines, line.."</tr>\n") end return [[<br \><br \><table class='widget_list' border=1> <tr style='font-weight: bold;'> <th align='center'>Name</th> <th align='center'>Description</th> </tr>]] .. table.concat(lines) .. "</table>\n" end local override_cats = { ["border" ] = true, ["bg" ] = true, ["fg" ] = true, ["useless" ] = true, ["" ] = true, } local function categorize(entries) local ret = {} local cats = { ["Default variables"] = {} } for _, v in ipairs(entries) do local ns = v.name:match("([^_]+)_") or "" ns = override_cats[ns] and "Default variables" or ns cats[ns] = cats[ns] or {} table.insert(cats[ns], v) end return cats end local function create_sample(entries) local ret = { " local theme = {}" } for name, cat in sorted_pairs(categorize(entries)) do table.insert(ret, "\n -- "..name) for _, v in ipairs(cat) do table.insert(ret, " -- theme."..v.name.." = nil") end end table.insert(ret, [[ return theme -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80]] ) return table.concat(ret, '\n') end -- Create the file local filename = args[1] local f = io.open(filename, "w") f:write[[ # Change Awesome appearance ## The beautiful themes Beautiful is where Awesome theme variables are stored. ]] f:write(create_table(beautiful_vars, {"link", "desc"})) f:write("\n\n## Sample theme file\n\n") f:write(create_sample(beautiful_vars, {"link", "desc"})) f:close() --TODO add some linting to direct undeclared beautiful variables --TODO re-generate all official themes --TODO generate a complete sample theme --TODO also parse C files. -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
ramtintz/tabchi
bot.lua
1
35284
redis = (loadfile "redis.lua")() redis = redis.connect('127.0.0.1', 6379) function dl_cb(arg, data) end function get_admin () if redis:get('botBOT-IDadminset') then return true else print("\n\27[32m لازمه کارکرد صحیح ، فرامین و امورات مدیریتی ربات تبلیغ گر <<\n تعریف کاربری به عنوان مدیر است\n\27[34m ایدی خود را به عنوان مدیر وارد کنید\n\27[32m شما می توانید از ربات زیر شناسه عددی خود را بدست اورید\n\27[34m ربات: @id_ProBot") print("\n\27[32m >> Tabchi Bot need a fullaccess user (ADMIN)\n\27[34m Imput Your ID as the ADMIN\n\27[32m You can get your ID of this bot\n\27[34m @id_ProBot") print("\n\27[36m : شناسه عددی ادمین را وارد کنید << \n >> Imput the Admin ID :\n\27[31m ") admin=io.read() redis:del("botBOT-IDadmin") redis:sadd("botBOT-IDadmin", admin) redis:set('botBOT-IDadminset',true) end return print("\n\27[36m ADMIN ID |\27[32m ".. admin .." \27[36m| شناسه ادمین") end function get_bot (i, naji) function bot_info (i, naji) redis:set("botBOT-IDid",naji.id_) if naji.first_name_ then redis:set("botBOT-IDfname",naji.first_name_) end if naji.last_name_ then redis:set("botBOT-IDlanme",naji.last_name_) end redis:set("botBOT-IDnum",naji.phone_number_) return naji.id_ end tdcli_function ({ID = "GetMe",}, bot_info, nil) end function reload(chat_id,msg_id) loadfile("./bot-BOT-ID.lua")() send(chat_id, msg_id, "<i>با موفقیت انجام شد.</i>") end function is_naji(msg) local var = false local hash = 'botBOT-IDadmin' local user = msg.sender_user_id_ local Naji = redis:sismember(hash, user) if Naji then var = true end return var end function writefile(filename, input) local file = io.open(filename, "w") file:write(input) file:flush() file:close() return true end function process_join(i, naji) if naji.code_ == 429 then local message = tostring(naji.message_) local Time = message:match('%d+') redis:setex("botBOT-IDmaxjoin", tonumber(Time), true) else redis:srem("botBOT-IDgoodlinks", i.link) redis:sadd("botBOT-IDsavedlinks", i.link) end end function process_link(i, naji) if (naji.is_group_ or naji.is_supergroup_channel_) then redis:srem("botBOT-IDwaitelinks", i.link) redis:sadd("botBOT-IDgoodlinks", i.link) elseif naji.code_ == 429 then local message = tostring(naji.message_) local Time = message:match('%d+') redis:setex("botBOT-IDmaxlink", tonumber(Time), true) else redis:srem("botBOT-IDwaitelinks", i.link) end end function find_link(text) if text:match("https://telegram.me/joinchat/%S+") or text:match("https://t.me/joinchat/%S+") or text:match("https://telegram.dog/joinchat/%S+") then local text = text:gsub("t.me", "telegram.me") local text = text:gsub("telegram.dog", "telegram.me") for link in text:gmatch("(https://telegram.me/joinchat/%S+)") do if not redis:sismember("botBOT-IDalllinks", link) then redis:sadd("botBOT-IDwaitelinks", link) redis:sadd("botBOT-IDalllinks", link) end end end end function add(id) local Id = tostring(id) if not redis:sismember("botBOT-IDall", id) then if Id:match("^(%d+)$") then redis:sadd("botBOT-IDusers", id) redis:sadd("botBOT-IDall", id) elseif Id:match("^-100") then redis:sadd("botBOT-IDsupergroups", id) redis:sadd("botBOT-IDall", id) else redis:sadd("botBOT-IDgroups", id) redis:sadd("botBOT-IDall", id) end end return true end function rem(id) local Id = tostring(id) if redis:sismember("botBOT-IDall", id) then if Id:match("^(%d+)$") then redis:srem("botBOT-IDusers", id) redis:srem("botBOT-IDall", id) elseif Id:match("^-100") then redis:srem("botBOT-IDsupergroups", id) redis:srem("botBOT-IDall", id) else redis:srem("botBOT-IDgroups", id) redis:srem("botBOT-IDall", id) end end return true end function send(chat_id, msg_id, text) tdcli_function ({ ID = "SendMessage", chat_id_ = chat_id, reply_to_message_id_ = msg_id, disable_notification_ = 1, from_background_ = 1, reply_markup_ = nil, input_message_content_ = { ID = "InputMessageText", text_ = text, disable_web_page_preview_ = 1, clear_draft_ = 0, entities_ = {}, parse_mode_ = {ID = "TextParseModeHTML"}, }, }, dl_cb, nil) end get_admin() function tdcli_update_callback(data) if data.ID == "UpdateNewMessage" then if not redis:get("botBOT-IDmaxlink") then if redis:scard("botBOT-IDwaitelinks") ~= 0 then local links = redis:smembers("botBOT-IDwaitelinks") for x,y in pairs(links) do if x == 11 then redis:setex("botBOT-IDmaxlink", 60, true) return end tdcli_function({ID = "CheckChatInviteLink",invite_link_ = y},process_link, {link=y}) end end end if not redis:get("botBOT-IDmaxjoin") then if redis:scard("botBOT-IDgoodlinks") ~= 0 then local links = redis:smembers("botBOT-IDgoodlinks") for x,y in pairs(links) do tdcli_function({ID = "ImportChatInviteLink",invite_link_ = y},process_join, {link=y}) if x == 5 then redis:setex("botBOT-IDmaxjoin", 60, true) return end end end end local msg = data.message_ local bot_id = redis:get("botBOT-IDid") or get_bot() if (msg.sender_user_id_ == 777000 or msg.sender_user_id_ == 178220800) then for k,v in pairs(redis:smembers('botBOT-IDadmin')) do tdcli_function({ ID = "ForwardMessages", chat_id_ = v, from_chat_id_ = msg.chat_id_, message_ids_ = {[0] = msg.id_}, disable_notification_ = 0, from_background_ = 1 }, dl_cb, nil) end end if tostring(msg.chat_id_):match("^(%d+)") then if not redis:sismember("botBOT-IDall", msg.chat_id_) then redis:sadd("botBOT-IDusers", msg.chat_id_) redis:sadd("botBOT-IDall", msg.chat_id_) end end add(msg.chat_id_) if msg.date_ < os.time() - 150 then return false end if msg.content_.ID == "MessageText" then local text = msg.content_.text_ local matches find_link(text) if is_naji(msg) then if text:match("^(افزودن مدیر) (%d+)$") then local matches = text:match("%d+") if redis:sismember('botBOT-IDadmin', matches) then return send(msg.chat_id_, msg.id_, "<i>کاربر مورد نظر در حال حاضر مدیر است.</i>") elseif redis:sismember('botBOT-IDmod', msg.sender_user_id_) then return send(msg.chat_id_, msg.id_, "شما دسترسی ندارید.") else redis:sadd('botBOT-IDadmin', matches) redis:sadd('botBOT-IDmod', matches) return send(msg.chat_id_, msg.id_, "<i>مقام کاربر به مدیر ارتقا یافت</i>") end elseif text:match("^(افزودن مدیرکل) (%d+)$") then local matches = text:match("%d+") if redis:sismember('botBOT-IDmod',msg.sender_user_id_) then return send(msg.chat_id_, msg.id_, "شما دسترسی ندارید.") end if redis:sismember('botBOT-IDmod', matches) then redis:srem("botBOT-IDmod",matches) redis:sadd('botBOT-IDadmin'..tostring(matches),msg.sender_user_id_) return send(msg.chat_id_, msg.id_, "مقام کاربر به مدیریت کل ارتقا یافت .") elseif redis:sismember('botBOT-IDadmin',matches) then return send(msg.chat_id_, msg.id_, 'درحال حاضر مدیر هستند.') else redis:sadd('botBOT-IDadmin', matches) redis:sadd('botBOT-IDadmin'..tostring(matches),msg.sender_user_id_) return send(msg.chat_id_, msg.id_, "کاربر به مقام مدیرکل منصوب شد.") end elseif text:match("^(حذف مدیر) (%d+)$") then local matches = text:match("%d+") if redis:sismember('botBOT-IDmod', msg.sender_user_id_) then if tonumber(matches) == msg.sender_user_id_ then redis:srem('botBOT-IDadmin', msg.sender_user_id_) redis:srem('botBOT-IDmod', msg.sender_user_id_) return send(msg.chat_id_, msg.id_, "شما دیگر مدیر نیستید.") end return send(msg.chat_id_, msg.id_, "شما دسترسی ندارید.") end if redis:sismember('botBOT-IDadmin', matches) then if redis:sismember('botBOT-IDadmin'..msg.sender_user_id_ ,matches) then return send(msg.chat_id_, msg.id_, "شما نمی توانید مدیری که به شما مقام داده را عزل کنید.") end redis:srem('botBOT-IDadmin', matches) redis:srem('botBOT-IDmod', matches) return send(msg.chat_id_, msg.id_, "کاربر از مقام مدیریت خلع شد.") end return send(msg.chat_id_, msg.id_, "کاربر مورد نظر مدیر نمی باشد.") elseif text:match("^(تازه سازی ربات)$") then get_bot() return send(msg.chat_id_, msg.id_, "<i>مشخصات فردی ربات بروز شد.</i>") elseif text:match("ریپورت") then tdcli_function ({ ID = "SendBotStartMessage", bot_user_id_ = 178220800, chat_id_ = 178220800, parameter_ = 'start' }, dl_cb, nil) elseif text:match("^(/reload)$") then return reload(msg.chat_id_,msg.id_) elseif text:match("^بروزرسانی ربات$") then io.popen("git fetch --all && git reset --hard origin/persian && git pull origin persian && chmod +x bot"):read("*all") local text,ok = io.open("bot.lua",'r'):read('*a'):gsub("BOT%-ID",BOT-ID) io.open("bot-BOT-ID.lua",'w'):write(text):close() return reload(msg.chat_id_,msg.id_) elseif text:match("^همگام سازی با تبچی$") then local botid = BOT-ID - 1 redis:sunionstore("botBOT-IDall","tabchi:"..tostring(botid)..":all") redis:sunionstore("botBOT-IDusers","tabchi:"..tostring(botid)..":pvis") redis:sunionstore("botBOT-IDgroups","tabchi:"..tostring(botid)..":groups") redis:sunionstore("botBOT-IDsupergroups","tabchi:"..tostring(botid)..":channels") redis:sunionstore("botBOT-IDsavedlinks","tabchi:"..tostring(botid)..":savedlinks") return send(msg.chat_id_, msg.id_, "<b>همگام سازی اطلاعات با تبچی شماره</b><code> "..tostring(botid).." </code><b>انجام شد.</b>") elseif text:match("^(لیست) (.*)$") then local matches = text:match("^لیست (.*)$") local naji if matches == "مخاطبین" then return tdcli_function({ ID = "SearchContacts", query_ = nil, limit_ = 999999999 }, function (I, Naji) local count = Naji.total_count_ local text = "مخاطبین : \n" for i =0 , tonumber(count) - 1 do local user = Naji.users_[i] local firstname = user.first_name_ or "" local lastname = user.last_name_ or "" local fullname = firstname .. " " .. lastname text = tostring(text) .. tostring(i) .. ". " .. tostring(fullname) .. " [" .. tostring(user.id_) .. "] = " .. tostring(user.phone_number_) .. " \n" end writefile("botBOT-ID_contacts.txt", text) tdcli_function ({ ID = "SendMessage", chat_id_ = I.chat_id, reply_to_message_id_ = 0, disable_notification_ = 0, from_background_ = 1, reply_markup_ = nil, input_message_content_ = {ID = "InputMessageDocument", document_ = {ID = "InputFileLocal", path_ = "botBOT-ID_contacts.txt"}, caption_ = "مخاطبین تبلیغ‌گر شماره BOT-ID"} }, dl_cb, nil) return io.popen("rm -rf botBOT-ID_contacts.txt"):read("*all") end, {chat_id = msg.chat_id_}) elseif matches == "پاسخ های خودکار" then local text = "<i>لیست پاسخ های خودکار :</i>\n\n" local answers = redis:smembers("botBOT-IDanswerslist") for k,v in pairs(answers) do text = tostring(text) .. "<i>l" .. tostring(k) .. "l</i> " .. tostring(v) .. " : " .. tostring(redis:hget("botBOT-IDanswers", v)) .. "\n" end if redis:scard('botBOT-IDanswerslist') == 0 then text = "<code> EMPTY</code>" end return send(msg.chat_id_, msg.id_, text) elseif matches == "مسدود" then naji = "botBOT-IDblockedusers" elseif matches == "شخصی" then naji = "botBOT-IDusers" elseif matches == "گروه" then naji = "botBOT-IDgroups" elseif matches == "سوپرگروه" then naji = "botBOT-IDsupergroups" elseif matches == "لینک" then naji = "botBOT-IDsavedlinks" elseif matches == "مدیر" then naji = "botBOT-IDadmin" else return true end local list = redis:smembers(naji) local text = tostring(matches).." : \n" for i, v in pairs(list) do text = tostring(text) .. tostring(i) .. "- " .. tostring(v).."\n" end writefile(tostring(naji)..".txt", text) tdcli_function ({ ID = "SendMessage", chat_id_ = msg.chat_id_, reply_to_message_id_ = 0, disable_notification_ = 0, from_background_ = 1, reply_markup_ = nil, input_message_content_ = {ID = "InputMessageDocument", document_ = {ID = "InputFileLocal", path_ = tostring(naji)..".txt"}, caption_ = "لیست "..tostring(matches).." های تبلیغ گر شماره BOT-ID"} }, dl_cb, nil) return io.popen("rm -rf "..tostring(naji)..".txt"):read("*all") elseif text:match("^(وضعیت مشاهده) (.*)$") then local matches = text:match("^وضعیت مشاهده (.*)$") if matches == "روشن" then redis:set("botBOT-IDmarkread", true) return send(msg.chat_id_, msg.id_, "<i>وضعیت پیام ها >> خوانده شده ✔️✔️\n</i><code>(تیک دوم فعال)</code>") elseif matches == "خاموش" then redis:del("botBOT-IDmarkread") return send(msg.chat_id_, msg.id_, "<i>وضعیت پیام ها >> خوانده نشده ✔️\n</i><code>(بدون تیک دوم)</code>") end elseif text:match("^(افزودن با پیام) (.*)$") then local matches = text:match("^افزودن با پیام (.*)$") if matches == "روشن" then redis:set("botBOT-IDaddmsg", true) return send(msg.chat_id_, msg.id_, "<i>پیام افزودن مخاطب فعال شد</i>") elseif matches == "خاموش" then redis:del("botBOT-IDaddmsg") return send(msg.chat_id_, msg.id_, "<i>پیام افزودن مخاطب غیرفعال شد</i>") end elseif text:match("^(افزودن با شماره) (.*)$") then local matches = text:match("افزودن با شماره (.*)$") if matches == "روشن" then redis:set("botBOT-IDaddcontact", true) return send(msg.chat_id_, msg.id_, "<i>ارسال شماره هنگام افزودن مخاطب فعال شد</i>") elseif matches == "خاموش" then redis:del("botBOT-IDaddcontact") return send(msg.chat_id_, msg.id_, "<i>ارسال شماره هنگام افزودن مخاطب غیرفعال شد</i>") end elseif text:match("^(تنظیم پیام افزودن مخاطب) (.*)") then local matches = text:match("^تنظیم پیام افزودن مخاطب (.*)") redis:set("botBOT-IDaddmsgtext", matches) return send(msg.chat_id_, msg.id_, "<i>پیام افزودن مخاطب ثبت شد </i>:\n🔹 "..matches.." 🔹") elseif text:match('^(تنظیم جواب) "(.*)" (.*)') then local txt, answer = text:match('^تنظیم جواب "(.*)" (.*)') redis:hset("botBOT-IDanswers", txt, answer) redis:sadd("botBOT-IDanswerslist", txt) return send(msg.chat_id_, msg.id_, "<i>جواب برای | </i>" .. tostring(txt) .. "<i> | تنظیم شد به :</i>\n" .. tostring(answer)) elseif text:match("^(حذف جواب) (.*)") then local matches = text:match("^حذف جواب (.*)") redis:hdel("botBOT-IDanswers", matches) redis:srem("botBOT-IDanswerslist", matches) return send(msg.chat_id_, msg.id_, "<i>جواب برای | </i>" .. tostring(matches) .. "<i> | از لیست جواب های خودکار پاک شد.</i>") elseif text:match("^(پاسخگوی خودکار) (.*)$") then local matches = text:match("^پاسخگوی خودکار (.*)$") if matches == "روشن" then redis:set("botBOT-IDautoanswer", true) return send(msg.chat_id_, 0, "<i>پاسخگویی خودکار تبلیغ گر فعال شد</i>") elseif matches == "خاموش" then redis:del("botBOT-IDautoanswer") return send(msg.chat_id_, 0, "<i>حالت پاسخگویی خودکار تبلیغ گر غیر فعال شد.</i>") end elseif text:match("^(تازه سازی)$")then local list = {redis:smembers("botBOT-IDsupergroups"),redis:smembers("botBOT-IDgroups")} tdcli_function({ ID = "SearchContacts", query_ = nil, limit_ = 999999999 }, function (i, naji) redis:set("botBOT-IDcontacts", naji.total_count_) end, nil) for i, v in pairs(list) do for a, b in pairs(v) do tdcli_function ({ ID = "GetChatMember", chat_id_ = b, user_id_ = bot_id }, function (i,naji) if naji.ID == "Error" then rem(i.id) end end, {id=b}) end end return send(msg.chat_id_,msg.id_,"<i>تازه‌سازی آمار تبلیغ‌گر شماره </i><code> BOT-ID </code> با موفقیت انجام شد.") elseif text:match("^(وضعیت)$") then local s = redis:get("botBOT-IDmaxjoin") and redis:ttl("botBOT-IDmaxjoin") or 0 local ss = redis:get("botBOT-IDmaxlink") and redis:ttl("botBOT-IDmaxlink") or 0 local msgadd = redis:get("botBOT-IDaddmsg") and "☑️" or "❎" local numadd = redis:get("botBOT-IDaddcontact") and "✅" or "❎" local txtadd = redis:get("botBOT-IDaddmsgtext") or "اد‌دی گلم خصوصی پیام بده" local autoanswer = redis:get("botBOT-IDautoanswer") and "✅" or "❎" local wlinks = redis:scard("botBOT-IDwaitelinks") local glinks = redis:scard("botBOT-IDgoodlinks") local links = redis:scard("botBOT-IDsavedlinks") local txt = "<i>⚙️ وضعیت اجرایی تبلیغ‌گر</i><code> BOT-ID </code>⛓\n\n" .. tostring(autoanswer) .."<code> حالت پاسخگویی خودکار 🗣 </code>\n" .. tostring(numadd) .. "<code> افزودن مخاطب با شماره 📞 </code>\n" .. tostring(msgadd) .. "<code> افزودن مخاطب با پیام 🗞</code>\n〰〰〰ا〰〰〰\n<code>📄 پیام افزودن مخاطب :</code>\n📍 " .. tostring(txtadd) .. " 📍\n〰〰〰ا〰〰〰\n<code>📁 لینک های ذخیره شده : </code><b>" .. tostring(links) .. "</b>\n<code>⏲ لینک های در انتظار عضویت : </code><b>" .. tostring(glinks) .. "</b>\n🕖 <b>" .. tostring(s) .. " </b><code>ثانیه تا عضویت مجدد</code>\n<code>❄️ لینک های در انتظار تایید : </code><b>" .. tostring(wlinks) .. "</b>\n🕑️ <b>" .. tostring(ss) .. " </b><code>ثانیه تا تایید لینک مجدد</code>\n 😼 سازنده : @RamtinTz" return send(msg.chat_id_, 0, txt) elseif text:match("^(امار)$") or text:match("^(آمار)$") then local gps = redis:scard("botBOT-IDgroups") local sgps = redis:scard("botBOT-IDsupergroups") local usrs = redis:scard("botBOT-IDusers") local links = redis:scard("botBOT-IDsavedlinks") local glinks = redis:scard("botBOT-IDgoodlinks") local wlinks = redis:scard("botBOT-IDwaitelinks") tdcli_function({ ID = "SearchContacts", query_ = nil, limit_ = 999999999 }, function (i, naji) redis:set("botBOT-IDcontacts", naji.total_count_) end, nil) local contacts = redis:get("botBOT-IDcontacts") local text = [[ <i>📈 وضعیت و آمار تبلیغ گر 📊</i> <code>👤 گفت و گو های شخصی : </code> <b>]] .. tostring(usrs) .. [[</b> <code>👥 گروها : </code> <b>]] .. tostring(gps) .. [[</b> <code>🌐 سوپر گروه ها : </code> <b>]] .. tostring(sgps) .. [[</b> <code>📖 مخاطبین دخیره شده : </code> <b>]] .. tostring(contacts)..[[</b> <code>📂 لینک های ذخیره شده : </code> <b>]] .. tostring(links)..[[</b> 😼 سازنده : @RamtinTz]] return send(msg.chat_id_, 0, text) elseif (text:match("^(ارسال به) (.*)$") and msg.reply_to_message_id_ ~= 0) then local matches = text:match("^ارسال به (.*)$") local naji if matches:match("^(همه)$") then naji = "botBOT-IDall" elseif matches:match("^(خصوصی)") then naji = "botBOT-IDusers" elseif matches:match("^(گروه)$") then naji = "botBOT-IDgroups" elseif matches:match("^(سوپرگروه)$") then naji = "botBOT-IDsupergroups" else return true end local list = redis:smembers(naji) local id = msg.reply_to_message_id_ for i, v in pairs(list) do tdcli_function({ ID = "ForwardMessages", chat_id_ = v, from_chat_id_ = msg.chat_id_, message_ids_ = {[0] = id}, disable_notification_ = 1, from_background_ = 1 }, dl_cb, nil) end return send(msg.chat_id_, msg.id_, "<i>با موفقیت فرستاده شد</i>") elseif text:match("^(ارسال به سوپرگروه) (.*)") then local matches = text:match("^ارسال به سوپرگروه (.*)") local dir = redis:smembers("botBOT-IDsupergroups") for i, v in pairs(dir) do tdcli_function ({ ID = "SendMessage", chat_id_ = v, reply_to_message_id_ = 0, disable_notification_ = 0, from_background_ = 1, reply_markup_ = nil, input_message_content_ = { ID = "InputMessageText", text_ = matches, disable_web_page_preview_ = 1, clear_draft_ = 0, entities_ = {}, parse_mode_ = nil }, }, dl_cb, nil) end return send(msg.chat_id_, msg.id_, "<i>با موفقیت فرستاده شد</i>") elseif text:match("^(مسدودیت) (%d+)$") then local matches = text:match("%d+") rem(tonumber(matches)) redis:sadd("botBOT-IDblockedusers",matches) tdcli_function ({ ID = "BlockUser", user_id_ = tonumber(matches) }, dl_cb, nil) return send(msg.chat_id_, msg.id_, "<i>کاربر مورد نظر مسدود شد</i>") elseif text:match("^(رفع مسدودیت) (%d+)$") then local matches = text:match("%d+") add(tonumber(matches)) redis:srem("botBOT-IDblockedusers",matches) tdcli_function ({ ID = "UnblockUser", user_id_ = tonumber(matches) }, dl_cb, nil) return send(msg.chat_id_, msg.id_, "<i>مسدودیت کاربر مورد نظر رفع شد.</i>") elseif text:match('^(تنظیم نام) "(.*)" (.*)') then local fname, lname = text:match('^تنظیم نام "(.*)" (.*)') tdcli_function ({ ID = "ChangeName", first_name_ = fname, last_name_ = lname }, dl_cb, nil) return send(msg.chat_id_, msg.id_, "<i>نام جدید با موفقیت ثبت شد.</i>") elseif text:match("^(تنظیم نام کاربری) (.*)") then local matches = text:match("^تنظیم نام کاربری (.*)") tdcli_function ({ ID = "ChangeUsername", username_ = tostring(matches) }, dl_cb, nil) return send(msg.chat_id_, 0, '<i>تلاش برای تنظیم نام کاربری...</i>') elseif text:match("^(حذف نام کاربری)$") then tdcli_function ({ ID = "ChangeUsername", username_ = "" }, dl_cb, nil) return send(msg.chat_id_, 0, '<i>نام کاربری با موفقیت حذف شد.</i>') elseif text:match('^(ارسال کن) "(.*)" (.*)') then local id, txt = text:match('^ارسال کن "(.*)" (.*)') send(id, 0, txt) return send(msg.chat_id_, msg.id_, "<i>ارسال شد</i>") elseif text:match("^(بگو) (.*)") then local matches = text:match("^بگو (.*)") return send(msg.chat_id_, 0, matches) elseif text:match("^(شناسه من)$") then return send(msg.chat_id_, msg.id_, "<i>" .. msg.sender_user_id_ .."</i>") elseif text:match("^(ترک کردن) (.*)$") then local matches = text:match("^ترک کردن (.*)$") send(msg.chat_id_, msg.id_, 'تبلیغ‌گر از گروه مورد نظر خارج شد') tdcli_function ({ ID = "ChangeChatMemberStatus", chat_id_ = matches, user_id_ = bot_id, status_ = {ID = "ChatMemberStatusLeft"}, }, dl_cb, nil) return rem(matches) elseif text:match("^(افزودن به همه) (%d+)$") then local matches = text:match("%d+") local list = {redis:smembers("botBOT-IDgroups"),redis:smembers("botBOT-IDsupergroups")} for a, b in pairs(list) do for i, v in pairs(b) do tdcli_function ({ ID = "AddChatMember", chat_id_ = v, user_id_ = matches, forward_limit_ = 50 }, dl_cb, nil) end end return send(msg.chat_id_, msg.id_, "<i>کاربر مورد نظر به تمام گروه های من دعوت شد</i>") elseif (text:match("^(انلاین)$") and not msg.forward_info_)then return tdcli_function({ ID = "ForwardMessages", chat_id_ = msg.chat_id_, from_chat_id_ = msg.chat_id_, message_ids_ = {[0] = msg.id_}, disable_notification_ = 0, from_background_ = 1 }, dl_cb, nil) elseif text:match("^(راهنما)$") then local txt = '📍راهنمای دستورات تبلیغ گر📍\n\nانلاین\n<i>اعلام وضعیت تبلیغ گر ✔️</i>\n<code>❤️ حتی اگر تبلیغ‌گر شما دچار محدودیت ارسال پیام شده باشد بایستی به این پیام پاسخ دهد❤️</code>\n/reload\n<i>l🔄 بارگذاری مجدد ربات 🔄l</i>\n<code>I⛔️عدم استفاده بی جهت⛔️I</code>\nبروزرسانی ربات\n<i>بروزرسانی ربات به آخرین نسخه و بارگذاری مجدد 🆕</i>\n\nافزودن مدیر شناسه\n<i>افزودن مدیر جدید با شناسه عددی داده شده 🛂</i>\n\nافزودن مدیرکل شناسه\n<i>افزودن مدیرکل جدید با شناسه عددی داده شده 🛂</i>\n\n<code>(⚠️ تفاوت مدیر و مدیر‌کل دسترسی به اعطا و یا گرفتن مقام مدیریت است⚠️)</code>\n\nحذف مدیر شناسه\n<i>حذف مدیر یا مدیرکل با شناسه عددی داده شده ✖️</i>\n\nترک گروه\n<i>خارج شدن از گروه و حذف آن از اطلاعات گروه ها 🏃</i>\n\nافزودن همه مخاطبین\n<i>افزودن حداکثر مخاطبین و افراد در گفت و گوهای شخصی به گروه ➕</i>\n\nشناسه من\n<i>دریافت شناسه خود 🆔</i>\n\nبگو متن\n<i>دریافت متن 🗣</i>\n\nارسال کن "شناسه" متن\n<i>ارسال متن به شناسه گروه یا کاربر داده شده 📤</i>\n\nتنظیم نام "نام" فامیل\n<i>تنظیم نام ربات ✏️</i>\n\nتازه سازی ربات\n<i>تازه‌سازی اطلاعات فردی ربات🎈</i>\n<code>(مورد استفاده در مواردی همچون پس از تنظیم نام📍جهت بروزکردن نام مخاطب اشتراکی تبلیغ‌گر📍)</code>\n\nتنظیم نام کاربری اسم\n<i>جایگزینی اسم با نام کاربری فعلی(محدود در بازه زمانی کوتاه) 🔄</i>\n\nحذف نام کاربری\n<i>حذف کردن نام کاربری ❎</i>\n\nافزودن با شماره روشن|خاموش\n<i>تغییر وضعیت اشتراک شماره تبلیغ‌گر در جواب شماره به اشتراک گذاشته شده 🔖</i>\n\nافزودن با پیام روشن|خاموش\n<i>تغییر وضعیت ارسال پیام در جواب شماره به اشتراک گذاشته شده ℹ️</i>\n\nتنظیم پیام افزودن مخاطب متن\n<i>تنظیم متن داده شده به عنوان جواب شماره به اشتراک گذاشته شده 📨</i>\n\nلیست مخاطبین|خصوصی|گروه|سوپرگروه|پاسخ های خودکار|لینک|مدیر\n<i>دریافت لیستی از مورد خواسته شده در قالب پرونده متنی یا پیام 📄</i>\n\nمسدودیت شناسه\n<i>مسدود‌کردن(بلاک) کاربر با شناسه داده شده از گفت و گوی خصوصی 🚫</i>\n\nرفع مسدودیت شناسه\n<i>رفع مسدودیت کاربر با شناسه داده شده 💢</i>\n\nوضعیت مشاهده روشن|خاموش 👁\n<i>تغییر وضعیت مشاهده پیام‌ها توسط تبلیغ‌گر (فعال و غیر‌فعال‌کردن تیک دوم)</i>\n\nامار\n<i>دریافت آمار و وضعیت تبلیغ گر 📊</i>\n\nوضعیت\n<i>دریافت وضعیت اجرایی تبلیغ‌گر⚙️</i>\n\nتازه سازی\n<i>تازه‌سازی آمار تبلیغ‌گر🚀</i>\n<code>🎃مورد استفاده حداکثر یک بار در روز🎃</code>\n\nارسال به همه|خصوصی|گروه|سوپرگروه\n<i>ارسال پیام جواب داده شده به مورد خواسته شده 📩</i>\n<code>(😄توصیه ما عدم استفاده از همه و خصوصی😄)</code>\n\nارسال به سوپرگروه متن\n<i>ارسال متن داده شده به همه سوپرگروه ها ✉️</i>\n<code>(😜توصیه ما استفاده و ادغام دستورات بگو و ارسال به سوپرگروه😜)</code>\n\nتنظیم جواب "متن" جواب\n<i>تنظیم جوابی به عنوان پاسخ خودکار به پیام وارد شده مطابق با متن باشد 📝</i>\n\nحذف جواب متن\n<i>حذف جواب مربوط به متن ✖️</i>\n\nپاسخگوی خودکار روشن|خاموش\n<i>تغییر وضعیت پاسخگویی خودکار تبلیغ گر به متن های تنظیم شده 📯</i>\n\nافزودن به همه شناسه\n<i>افزودن کابر با شناسه وارد شده به همه گروه و سوپرگروه ها ➕➕</i>\n\nترک کردن شناسه\n<i>عملیات ترک کردن با استفاده از شناسه گروه 🏃</i>\n\nراهنما\n<i>دریافت همین پیام 🆘</i>\n〰〰〰ا〰〰〰\nهمگام سازی با تبچی\n<code>همگام سازی اطلاعات تبلیغ گر با اطلاعات تبچی از قبل نصب شده 🔃 (جهت این امر حتما به ویدیو آموزشی کانال مراجعه کنید)</code>\n〰〰〰ا〰〰〰\nسازنده : @RamtinTz \nکانال : @tabchisell\n<i>آدرس سورس تبلیغ گر (کاملا فارسی) :</i>\nhttps://github.com/ramtintz/tabchi/\n<code>آخرین اخبار و رویداد های تبلیغ گر را در کانال ما پیگیری کنید.</code>' return send(msg.chat_id_,msg.id_, txt) elseif tostring(msg.chat_id_):match("^-") then if text:match("^(ترک کردن)$") then rem(msg.chat_id_) return tdcli_function ({ ID = "ChangeChatMemberStatus", chat_id_ = msg.chat_id_, user_id_ = bot_id, status_ = {ID = "ChatMemberStatusLeft"}, }, dl_cb, nil) elseif text:match("^(افزودن همه مخاطبین)$") then tdcli_function({ ID = "SearchContacts", query_ = nil, limit_ = 999999999 },function(i, naji) local users, count = redis:smembers("botBOT-IDusers"), naji.total_count_ for n=0, tonumber(count) - 1 do tdcli_function ({ ID = "AddChatMember", chat_id_ = i.chat_id, user_id_ = naji.users_[n].id_, forward_limit_ = 50 }, dl_cb, nil) end for n=1, #users do tdcli_function ({ ID = "AddChatMember", chat_id_ = i.chat_id, user_id_ = users[n], forward_limit_ = 50 }, dl_cb, nil) end end, {chat_id=msg.chat_id_}) return send(msg.chat_id_, msg.id_, "<i>در حال افزودن مخاطبین به گروه ...</i>") end end end if redis:sismember("botBOT-IDanswerslist", text) then if redis:get("botBOT-IDautoanswer") then if msg.sender_user_id_ ~= bot_id then local answer = redis:hget("botBOT-IDanswers", text) send(msg.chat_id_, 0, answer) end end end elseif msg.content_.ID == "MessageContact" then local id = msg.content_.contact_.user_id_ if not redis:sismember("botBOT-IDaddedcontacts",id) then redis:sadd("botBOT-IDaddedcontacts",id) local first = msg.content_.contact_.first_name_ or "-" local last = msg.content_.contact_.last_name_ or "-" local phone = msg.content_.contact_.phone_number_ local id = msg.content_.contact_.user_id_ tdcli_function ({ ID = "ImportContacts", contacts_ = {[0] = { phone_number_ = tostring(phone), first_name_ = tostring(first), last_name_ = tostring(last), user_id_ = id }, }, }, dl_cb, nil) if redis:get("botBOT-IDaddcontact") and msg.sender_user_id_ ~= bot_id then local fname = redis:get("botBOT-IDfname") local lnasme = redis:get("botBOT-IDlname") or "" local num = redis:get("botBOT-IDnum") tdcli_function ({ ID = "SendMessage", chat_id_ = msg.chat_id_, reply_to_message_id_ = msg.id_, disable_notification_ = 1, from_background_ = 1, reply_markup_ = nil, input_message_content_ = { ID = "InputMessageContact", contact_ = { ID = "Contact", phone_number_ = num, first_name_ = fname, last_name_ = lname, user_id_ = bot_id }, }, }, dl_cb, nil) end end if redis:get("botBOT-IDaddmsg") then local answer = redis:get("botBOT-IDaddmsgtext") or "اددی گلم خصوصی پیام بده" send(msg.chat_id_, msg.id_, answer) end elseif msg.content_.ID == "MessageChatDeleteMember" and msg.content_.id_ == bot_id then return rem(msg.chat_id_) elseif msg.content_.ID == "MessageChatJoinByLink" and msg.sender_user_id_ == bot_id then return add(msg.chat_id_) elseif msg.content_.ID == "MessageChatAddMembers" then for i = 0, #msg.content_.members_ do if msg.content_.members_[i].id_ == bot_id then add(msg.chat_id_) end end elseif msg.content_.caption_ then return find_link(msg.content_.caption_) end if redis:get("botBOT-IDmarkread") then tdcli_function ({ ID = "ViewMessages", chat_id_ = msg.chat_id_, message_ids_ = {[0] = msg.id_} }, dl_cb, nil) end elseif data.ID == "UpdateOption" and data.name_ == "my_id" then tdcli_function ({ ID = "GetChats", offset_order_ = 9223372036854775807, offset_chat_id_ = 0, limit_ = 20 }, dl_cb, nil) end end
agpl-3.0
vadrak/ArenaLive
components/CastHistory.lua
1
9906
--[[** * Stores and displays up to the last ten spells that a unit cast. * * TODO: Automatically update version number on commit. ]] local addonName, L = ...; local version = 20170617; local CastHistory = DeliUnitFrames:getClass("ArenaLiveCastHistory"); if (CastHistory and CastHistory.version >= version) then -- A more recent version has been loaded already. return; end CastHistory = DeliUnitFrames:newClass("ArenaLiveCastHistory", "AbstractScriptComponent"); local MAX_CACHE_SIZE = 10; local newCacheEntry, resetCacheEntry, castIterator, fadeAnimationOnFinish; -- private functions CastHistory.version = version; CastHistory.Directions = { -- Enum for directions UPWARDS = 1, RIGHT = 2, DOWNWARDS = 3, LEFT = 4, }; CastHistory.defaults = { direction = CastHistory.Directions.RIGHT; iconSize = 20, numIcons = 4, duration = 7, }; --[[** * Initializes this cast history component handler. Registering * necessary scripts and events, aswell as adding basic attributes. * * @param manager (UnitFrameManager) the unit frame manager object * that is used to access all unit frames which's cast histories * will be managed by this cast history instance. * @see AbstractScriptComponent. ]] function CastHistory:init(manager) CastHistory:getSuper().init(self, manager); self.cache = {}; self:RegisterEvent("UNIT_SPELLCAST_SUCCEEDED"); self:RegisterEvent("UNIT_NAME_UPDATE"); self:RegisterEvent("PLAYER_TARGET_CHANGED"); self:RegisterEvent("PLAYER_FOCUS_CHANGED"); self:SetScript("OnEvent"); end --[[** * Returns a new cast history UI instance that is then added to * unitFrame. * * @param unitFrame (AbstractUnitFrame) the unit frame to which * the cast history is going to be added. * @return (CastHistory) a new cast history. ]] function CastHistory:newUIElement(unitFrame) local settings = self:getSettings(unitFrame); local name = unitFrame.frame:GetName() or tostring(unitFrame); name = name .. self:getType(); local history = CreateFrame("Frame", name, unitFrame.frame); history.icons = {}; return history; end --[[** * Updates the unitFrame's cast history to show the last casts of * the unit that unitFrame currently displays. * * @param unitFrame (AbstractUnitFrame) the unit frame that's cast * history is going to be updated. ]] function CastHistory:update(unitFrame) local settings = self:getSettings(unitFrame); local history = self:getUIElement(unitFrame); if (not history) then return; elseif (not unitFrame.unit) then self:reset(unitFrame); return; end local index = 1; local curTime = GetTime(); for id, spellID, texture, timeCast in self:getIterator(unitFrame.unit) do local remDuration = (timeCast + settings.duration) - curTime; if (id > settings.numIcons) then break; elseif (remDuration <= 0) then break; end local icon = history.icons[id]; icon.fadeOutAnim:Stop(); icon.spellID = spellID; icon.texture:SetTexture(texture); icon:Show(); icon.fadeOutAnim.alpha:SetStartDelay(remDuration); icon.fadeOutAnim:Play(); index = index + 1; end while (index <= #history.icons) do local icon = history.icons[index]; icon:Hide(); index = index + 1; end end --[[** * Updates unitFrame's cast history according to its current saved * variable settings. * * @param unitFrame (AbstractUnitFrame) the unit frame that's cast * history is going to be updated. ]] function CastHistory:updateAppearance(unitFrame) self:getSuper().updateAppearance(self, unitFrame); local history = self:getUIElement(unitFrame); local settings = self:getSettings(unitFrame); if (settings.direction == CastHistory.Directions.UPWARDS or CastHistory.Directions.DOWNWARDS) then history:SetSize((settings.iconSize + 2) * settings.numIcons, settings.iconSize); else history:SetSize(settings.iconSize, (settings.iconSize + 2) * settings.numIcons); end local prefix = history:GetName(); for i = 1, settings.numIcons, 1 do local icon = history.icons[i]; if (not icon) then icon = CreateFrame("Button", prefix .. "Button" .. i, history, "ArenaLiveCastHistoryIconTemplate"); icon.fadeOutAnim:SetScript("OnFinished", fadeAnimationOnFinish); history.icons[i] = icon; end icon:SetSize(settings.iconSize, settings.iconSize); icon:ClearAllPoints(); local point, relativeTo, relativePoint, x, y; relativeTo = history.icons[i-1]; if (settings.direction == CastHistory.Directions.UPWARDS) then point = "BOTTOM"; relativePoint = "TOP"; x = 0; y = 2; elseif (settings.direction == CastHistory.Directions.RIGHT) then point = "LEFT"; relativePoint = "RIGHT"; x = 2; y = 0; elseif (settings.direction == CastHistory.Directions.DOWNWARDS) then point = "TOP"; relativePoint = "BOTTOM"; x = 0; y = -2; else point = "RIGHT"; relativePoint = "LEFT"; x = -2; y = 0; end if (i == 1) then relativeTo = history; relativePoint = point; end icon:SetPoint(point, relativeTo, relativePoint, x, y); end for i = settings.numIcons+1, #history.icons, 1 do history.icons[i]:Hide(); end end --[[** * Reset unitFrame's cast history, hiding all icons. * * @param AbstractUnitFrame (UnitFrame) The unit frame that's cast * history is going to be reset. ]] function CastHistory:reset(unitFrame) local history = self:getUIElement(unitFrame); if (not history) then return; end for i = 1, #history.icons, 1 do local icon = history.icons[i]; icon.fadeOutAnim:Stop(); icon:Hide(); end end --[[** * Returns a stateless iterator that may be used in a generic for * loop to traverse all recently cast spells by unit. * * @param unit (string) name of the unit which's recently cast * spells will be returned. * @return (iterator, table, nil) an stateless iterator function that * may be used to traverse unit's recent spell casts. ]] function CastHistory:getIterator(unit) if (not self.cache[unit]) then return castIterator, nil, nil; end return castIterator, self.cache[unit], nil; end --[[** * OnEvent script callback. * * @param event (string) name of the event that was triggered. * @param ... (mixed) a number of arguments accompanying the event. ]] function CastHistory:OnEvent(event, ...) local unit, _, _, _, spellID = ...; if (event == "UNIT_SPELLCAST_SUCCEEDED") then self:addCast(unit, spellID); else if (event == "PLAYER_TARGET_CHANGED") then unit = "target"; elseif (event == "PLAYER_FOCUS_CHANGED") then unit = "focus"; end resetCacheEntry(self.cache, unit); end for unitFrame in self.manager:getUnitIterator(unit) do self:update(unitFrame); end end --[[** * Adds the given cast to unit's cache entry of this cast history's * cache. * * @param unit (string) the unit id to which's cache entry the cast * is being written. * @param spellID (number) the spellID of the cast that is going to * be added to unit's cache entry. ]] function CastHistory:addCast(unit, spellID) local name, _, texture = GetSpellInfo(spellID); if (not name) then return; -- Ignore invalid spells. end local entry = self.cache[unit]; if (not entry) then entry = newCacheEntry(self.cache, unit); end if (not entry[entry.writeIndex]) then entry[entry.writeIndex] = {}; end local spell = entry[entry.writeIndex]; spell.ID = spellID; spell.texture = texture; spell.time = GetTime(); entry.writeIndex = (entry.writeIndex + 1) % MAX_CACHE_SIZE; end --[[** * Creates and returns unit's cast history cache entry in cache. * If there already exists a cache entry for the given unit, the * already existing table is returned instead and no cache entry is * created. * * @param cache (table) the cache table to which a new entry is * being added. * @param unit (string) the unit ID for which a new cache entry is * being added to cache. ]] function newCacheEntry(cache, unit) if (not cache[unit]) then cache[unit] = { writeIndex = 0; }; end return cache[unit]; end --[[** * Resets unit's cache entry in cache, removing all spell data from * the entry's sub tables. * * @param cache (table) the cache table of the affected CastHistory * object. * @param unit (string) unit id of the player who's cache data is * going to be reset. ]] function resetCacheEntry(cache, unit) local ent = cache[unit]; if (not ent) then return; end for i = 1, MAX_CACHE_SIZE, 1 do local spell = ent[i]; if (spell) then spell.ID = nil; spell.texture = nil; spell.time = nil; end end ent.writeIndex = 0; end --[[** * Iterates all entries in casts, ordered in descending order by the * time they were cast, that is, the youngest cast is returned first * and the oldest cast is returned last. * * @param casts (table) a cast history cache entry of a specific * player. * @param lastID (number) the last cache entry's id that was returned. * return (number, number, string, number) the current cache entries * id, the cast's spellID, the cast's texture and the time the spell * was cast. ]] function castIterator(casts, lastID) if (not casts) then return nil; end local id; if (not lastID) then id = 1; else id = lastID + 1; end if (id >= MAX_CACHE_SIZE) then return nil; end local index = casts.writeIndex - id; if (index < 0) then index = MAX_CACHE_SIZE + index; end local spell = casts[index]; if (not spell or not spell.ID) then return nil; end return id, spell.ID, spell.texture, spell.time; end function fadeAnimationOnFinish(animGroup, requested) local icon = animGroup:GetParent(); icon:Hide(); end
mit
andywingo/snabbswitch
lib/ljsyscall/syscall/osx/types.lua
18
9044
-- OSX types local require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string = require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string local function init(types) local abi = require "syscall.abi" local t, pt, s, ctypes = types.t, types.pt, types.s, types.ctypes local ffi = require "ffi" local bit = require "syscall.bit" local h = require "syscall.helpers" local addtype, addtype_var, addtype_fn, addraw2 = h.addtype, h.addtype_var, h.addtype_fn, h.addraw2 local ptt, reviter, mktype, istype, lenfn, lenmt, getfd, newfn = h.ptt, h.reviter, h.mktype, h.istype, h.lenfn, h.lenmt, h.getfd, h.newfn local ntohl, ntohl, ntohs, htons, octal = h.ntohl, h.ntohl, h.ntohs, h.htons, h.octal local c = require "syscall.osx.constants" local mt = {} -- metatables local addtypes = { fdset = "fd_set", clock_serv = "clock_serv_t", } local addstructs = { mach_timespec = "struct mach_timespec", } for k, v in pairs(addtypes) do addtype(types, k, v) end for k, v in pairs(addstructs) do addtype(types, k, v, lenmt) end t.clock_serv1 = ffi.typeof("clock_serv_t[1]") -- 32 bit dev_t, 24 bit minor, 8 bit major local function makedev(major, minor) if type(major) == "table" then major, minor = major[1], major[2] end local dev = major or 0 if minor then dev = bit.bor(minor, bit.lshift(major, 24)) end return dev end mt.device = { index = { major = function(dev) return bit.bor(bit.band(bit.rshift(dev.dev, 24), 0xff)) end, minor = function(dev) return bit.band(dev.dev, 0xffffff) end, device = function(dev) return tonumber(dev.dev) end, }, newindex = { device = function(dev, major, minor) dev.dev = makedev(major, minor) end, }, __new = function(tp, major, minor) return ffi.new(tp, makedev(major, minor)) end, } addtype(types, "device", "struct {dev_t dev;}", mt.device) function t.sa(addr, addrlen) return addr end -- non Linux is trivial, Linux has odd unix handling mt.stat = { index = { dev = function(st) return t.device(st.st_dev) end, mode = function(st) return st.st_mode end, ino = function(st) return tonumber(st.st_ino) end, nlink = function(st) return st.st_nlink end, uid = function(st) return st.st_uid end, gid = function(st) return st.st_gid end, rdev = function(st) return t.device(st.st_rdev) end, atime = function(st) return st.st_atimespec.time end, ctime = function(st) return st.st_ctimespec.time end, mtime = function(st) return st.st_mtimespec.time end, birthtime = function(st) return st.st_birthtimespec.time end, size = function(st) return tonumber(st.st_size) end, blocks = function(st) return tonumber(st.st_blocks) end, blksize = function(st) return tonumber(st.st_blksize) end, flags = function(st) return st.st_flags end, gen = function(st) return st.st_gen end, type = function(st) return bit.band(st.st_mode, c.S_I.FMT) end, todt = function(st) return bit.rshift(st.type, 12) end, isreg = function(st) return st.type == c.S_I.FREG end, isdir = function(st) return st.type == c.S_I.FDIR end, ischr = function(st) return st.type == c.S_I.FCHR end, isblk = function(st) return st.type == c.S_I.FBLK end, isfifo = function(st) return st.type == c.S_I.FIFO end, islnk = function(st) return st.type == c.S_I.FLNK end, issock = function(st) return st.type == c.S_I.FSOCK end, }, } -- add some friendlier names to stat, also for luafilesystem compatibility mt.stat.index.access = mt.stat.index.atime mt.stat.index.modification = mt.stat.index.mtime mt.stat.index.change = mt.stat.index.ctime local namemap = { file = mt.stat.index.isreg, directory = mt.stat.index.isdir, link = mt.stat.index.islnk, socket = mt.stat.index.issock, ["char device"] = mt.stat.index.ischr, ["block device"] = mt.stat.index.isblk, ["named pipe"] = mt.stat.index.isfifo, } mt.stat.index.typename = function(st) for k, v in pairs(namemap) do if v(st) then return k end end return "other" end addtype(types, "stat", "struct stat", mt.stat) local signames = {} local duplicates = {LWT = true, IOT = true, CLD = true, POLL = true} for k, v in pairs(c.SIG) do if not duplicates[k] then signames[v] = k end end mt.siginfo = { index = { signo = function(s) return s.si_signo end, errno = function(s) return s.si_errno end, code = function(s) return s.si_code end, pid = function(s) return s.si_pid end, uid = function(s) return s.si_uid end, status = function(s) return s.si_status end, addr = function(s) return s.si_addr end, value = function(s) return s.si_value end, band = function(s) return s.si_band end, signame = function(s) return signames[s.signo] end, }, newindex = { signo = function(s, v) s.si_signo = v end, errno = function(s, v) s.si_errno = v end, code = function(s, v) s.si_code = v end, pid = function(s, v) s.si_pid = v end, uid = function(s, v) s.si_uid = v end, status = function(s, v) s.si_status = v end, addr = function(s, v) s.si_addr = v end, value = function(s, v) s.si_value = v end, band = function(s, v) s.si_band = v end, }, __len = lenfn, } addtype(types, "siginfo", "siginfo_t", mt.siginfo) mt.dirent = { index = { ino = function(self) return self.d_ino end, --seekoff = function(self) return self.d_seekoff end, -- not in legacy dirent reclen = function(self) return self.d_reclen end, namlen = function(self) return self.d_namlen end, type = function(self) return self.d_type end, name = function(self) return ffi.string(self.d_name, self.d_namlen) end, toif = function(self) return bit.lshift(self.d_type, 12) end, -- convert to stat types }, __len = function(self) return self.d_reclen end, } for k, v in pairs(c.DT) do mt.dirent.index[k] = function(self) return self.type == v end end addtype(types, "dirent", "struct legacy_dirent", mt.dirent) mt.flock = { index = { type = function(self) return self.l_type end, whence = function(self) return self.l_whence end, start = function(self) return self.l_start end, len = function(self) return self.l_len end, pid = function(self) return self.l_pid end, }, newindex = { type = function(self, v) self.l_type = c.FCNTL_LOCK[v] end, whence = function(self, v) self.l_whence = c.SEEK[v] end, start = function(self, v) self.l_start = v end, len = function(self, v) self.l_len = v end, pid = function(self, v) self.l_pid = v end, }, __new = newfn, } addtype(types, "flock", "struct flock", mt.flock) -- TODO see Linux notes. Also maybe can be shared with BSDs, have not checked properly mt.wait = { __index = function(w, k) local _WSTATUS = bit.band(w.status, octal("0177")) local _WSTOPPED = octal("0177") local WTERMSIG = _WSTATUS local EXITSTATUS = bit.band(bit.rshift(w.status, 8), 0xff) local WIFEXITED = (_WSTATUS == 0) local tab = { WIFEXITED = WIFEXITED, WIFSTOPPED = bit.band(w.status, 0xff) == _WSTOPPED, WIFSIGNALED = _WSTATUS ~= _WSTOPPED and _WSTATUS ~= 0 } if tab.WIFEXITED then tab.EXITSTATUS = EXITSTATUS end if tab.WIFSTOPPED then tab.WSTOPSIG = EXITSTATUS end if tab.WIFSIGNALED then tab.WTERMSIG = WTERMSIG end if tab[k] then return tab[k] end local uc = 'W' .. k:upper() if tab[uc] then return tab[uc] end end } function t.waitstatus(status) return setmetatable({status = status}, mt.wait) end -- sigaction, standard POSIX behaviour with union of handler and sigaction addtype_fn(types, "sa_sigaction", "void (*)(int, siginfo_t *, void *)") mt.sigaction = { index = { handler = function(sa) return sa.__sigaction_u.__sa_handler end, sigaction = function(sa) return sa.__sigaction_u.__sa_sigaction end, mask = function(sa) return sa.sa_mask end, flags = function(sa) return tonumber(sa.sa_flags) end, }, newindex = { handler = function(sa, v) if type(v) == "string" then v = pt.void(c.SIGACT[v]) end if type(v) == "number" then v = pt.void(v) end sa.__sigaction_u.__sa_handler = v end, sigaction = function(sa, v) if type(v) == "string" then v = pt.void(c.SIGACT[v]) end if type(v) == "number" then v = pt.void(v) end sa.__sigaction_u.__sa_sigaction = v end, mask = function(sa, v) if not ffi.istype(t.sigset, v) then v = t.sigset(v) end sa.sa_mask = v end, flags = function(sa, v) sa.sa_flags = c.SA[v] end, }, __new = function(tp, tab) local sa = ffi.new(tp) if tab then for k, v in pairs(tab) do sa[k] = v end end if tab and tab.sigaction then sa.sa_flags = bit.bor(sa.flags, c.SA.SIGINFO) end -- this flag must be set if sigaction set return sa end, } addtype(types, "sigaction", "struct sigaction", mt.sigaction) return types end return {init = init}
apache-2.0
Tardan/factory-mod-UpGrade
prototypes/base-mod/recipes/transport-belt.lua
1
1789
data:extend( { { type = "recipe", name = "medium-basic-transport-belt-to-ground", enabled = "false", energy_required = 1, ingredients = { {"iron-plate", 30}, {"basic-transport-belt", 15} }, result_count = 2, result = "medium-basic-transport-belt-to-ground" }, { type = "recipe", name = "long-basic-transport-belt-to-ground", enabled = "false", energy_required = 1, ingredients = { {"steel-plate", 30}, {"basic-transport-belt", 30} }, result_count = 2, result = "long-basic-transport-belt-to-ground" }, { type = "recipe", name = "medium-fast-transport-belt-to-ground", enabled = "false", ingredients = { {"iron-gear-wheel", 40}, {"medium-basic-transport-belt-to-ground", 2} }, result_count = 2, result = "medium-fast-transport-belt-to-ground" }, { type = "recipe", name = "long-fast-transport-belt-to-ground", enabled = "false", ingredients = { {"iron-gear-wheel", 80}, {"long-basic-transport-belt-to-ground", 2} }, result_count = 2, result = "long-fast-transport-belt-to-ground" }, { type = "recipe", name = "medium-express-transport-belt-to-ground", enabled = "false", ingredients = { {"iron-gear-wheel", 80}, {"medium-fast-transport-belt-to-ground", 2} }, result_count = 2, result = "medium-express-transport-belt-to-ground" }, { type = "recipe", name = "long-express-transport-belt-to-ground", enabled = "false", ingredients = { {"iron-gear-wheel", 160}, {"long-fast-transport-belt-to-ground", 2} }, result_count = 2, result = "long-express-transport-belt-to-ground" } } )
gpl-3.0
unusualcrow/redead_reloaded
entities/entities/sent_barrel_radioactive/init.lua
1
2527
AddCSLuaFile( "cl_init.lua" ) AddCSLuaFile( "shared.lua" ) include("shared.lua") ENT.HitSound = Sound( "Metal_Barrel.ImpactSoft" ) ENT.DieSound = Sound( "Breakable.Metal" ) ENT.Model = Model( "models/props/de_train/barrel.mdl" ) ENT.Damage = 60 ENT.Radius = 300 ENT.Skins = {0,1,7} function ENT:Initialize() local skin = table.Random( self.Skins ) self.Entity:SetModel( self.Model ) self.Entity:SetSkin( skin ) self.Entity:PhysicsInit( SOLID_VPHYSICS ) self.Entity:SetMoveType( MOVETYPE_VPHYSICS ) self.Entity:SetSolid( SOLID_VPHYSICS ) //self.Entity:SetCollisionGroup( COLLISION_GROUP_WEAPON ) local phys = self.Entity:GetPhysicsObject() if IsValid( phys ) then phys:Wake() end end function ENT:SetSpeed( num ) self.Speed = num end function ENT:Think() end function ENT:Explode() if self.Exploded then return end self.Exploded = true local ed = EffectData() ed:SetOrigin( self.Entity:GetPos() ) util.Effect( "Explosion", ed, true, true ) local trace = {} trace.start = self.Entity:GetPos() + Vector(0,0,20) trace.endpos = trace.start + Vector( 0, 0, -200 ) trace.filter = self.Entity local tr = util.TraceLine( trace ) if tr.HitWorld then local ed = EffectData() ed:SetOrigin( tr.HitPos ) ed:SetMagnitude( 0.8 ) util.Effect( "smoke_crater", ed, true, true ) util.Decal( "Scorch", tr.HitPos + tr.HitNormal, tr.HitPos - tr.HitNormal ) end if IsValid( self.Entity:GetOwner() ) then util.BlastDamage( self.Entity, self.Entity:GetOwner(), self.Entity:GetPos(), self.Radius, self.Damage ) end for i=1, math.random( 2, 4 ) do local ed = EffectData() ed:SetOrigin( self.Entity:GetPos() ) util.Effect( "barrel_gib", ed, true, true ) end local ed = EffectData() ed:SetOrigin( self.Entity:GetPos() ) util.Effect( "rad_explosion", ed, true, true ) local ent = ents.Create( "sent_radiation" ) ent:SetPos( self.Entity:GetPos() ) ent:Spawn() self.Entity:EmitSound( self.DieSound, 100, math.random(90,110) ) self.Entity:Remove() end function ENT:Use( ply, caller ) ply:AddToInventory( self.Entity ) end function ENT:OnRemove() end function ENT:OnTakeDamage( dmginfo ) if dmginfo:IsBulletDamage() and IsValid( dmginfo:GetAttacker() ) and dmginfo:GetAttacker():IsPlayer() then self.Entity:SetOwner( dmginfo:GetAttacker() ) self.Entity:Explode() end end function ENT:PhysicsCollide( data, phys ) if data.Speed > 50 and data.DeltaTime > 0.15 then self.Entity:EmitSound( self.HitSound ) end end
mit
vrld/shine
init.lua
1
4932
--[[ The MIT License (MIT) Copyright (c) 2017 Matthias Richter Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]]-- local BASE = ... local moonshine = {} moonshine.draw_shader = function(buffer, shader) local front, back = buffer() love.graphics.setCanvas(front) love.graphics.clear() if shader ~= love.graphics.getShader() then love.graphics.setShader(shader) end love.graphics.draw(back) end moonshine.chain = function(w,h,effect) -- called as moonshine.chain(effect)' if h == nil then effect, w,h = w, love.window.getMode() end assert(effect ~= nil, "No effect") local front, back = love.graphics.newCanvas(w,h), love.graphics.newCanvas(w,h) local buffer = function() back, front = front, back return front, back end local disabled = {} -- set of disabled effects local chain = {} chain.resize = function(w, h) front, back = love.graphics.newCanvas(w,h), love.graphics.newCanvas(w,h) return chain end chain.draw = function(func, ...) -- save state local canvas = love.graphics.getCanvas() local shader = love.graphics.getShader() local fg_r, fg_g, fg_b, fg_a = love.graphics.getColor() -- draw scene to front buffer love.graphics.setCanvas((buffer())) -- parens are needed: take only front buffer love.graphics.clear(love.graphics.getBackgroundColor()) func(...) -- save more state local blendmode = love.graphics.getBlendMode() -- process all shaders love.graphics.setColor(fg_r, fg_g, fg_b, fg_a) love.graphics.setBlendMode("alpha", "premultiplied") for _,e in ipairs(chain) do if not disabled[e.name] then (e.draw or moonshine.draw_shader)(buffer, e.shader) end end -- present result love.graphics.setShader() love.graphics.setCanvas(canvas) love.graphics.draw(front,0,0) -- restore state love.graphics.setBlendMode(blendmode) love.graphics.setShader(shader) end chain.next = function(e) if type(e) == "function" then e = e() end assert(e.name, "Invalid effect: must provide `name'.") assert(e.shader or e.draw, "Invalid effect: must provide `shader' or `draw'.") table.insert(chain, e) return chain end chain.chain = chain.next chain.disable = function(name, ...) if name then disabled[name] = name return chain.disable(...) end end chain.enable = function(name, ...) if name then disabled[name] = nil return chain.enable(...) end end setmetatable(chain, { __call = function(_, ...) return chain.draw(...) end, __index = function(_,k) for _, e in ipairs(chain) do if e.name == k then return e end end error(("Effect `%s' not in chain"):format(k), 2) end, __newindex = function(_, k, v) if k == "parameters" or k == "params" or k == "settings" then for e,par in pairs(v) do for k,v in pairs(par) do chain[e][k] = v end end else rawset(chain, k, v) end end }) return chain.next(effect) end moonshine.Effect = function(e) -- set defaults for k,v in pairs(e.defaults or {}) do assert(e.setters[k], ("No setter for parameter `%s'"):format(k))(v, k) e.setters[k](v,k) end -- expose setters return setmetatable(e, { __newindex = function(self,k,v) assert(self.setters[k], ("Unknown property: `%s.%s'"):format(e.name, k)) self.setters[k](v, k) end}) end -- autoloading effects moonshine.effects = setmetatable({}, {__index = function(self, key) local ok, effect = pcall(require, BASE .. "." .. key) if not ok then error("No such effect: "..key, 2) end -- expose moonshine to effect local con = function(...) return effect(moonshine, ...) end -- cache effect constructor self[key] = con return con end}) return setmetatable(moonshine, {__call = function(_, ...) return moonshine.chain(...) end})
mit
timroes/awesome
lib/gears/filesystem.lua
2
5618
--------------------------------------------------------------------------- --- Filesystem module for gears -- -- @module gears.filesystem --------------------------------------------------------------------------- -- Grab environment we need local Gio = require("lgi").Gio local gstring = require("gears.string") local gtable = require("gears.table") local filesystem = {} local function make_directory(gfile) local success, err = gfile:make_directory_with_parents() if success then return true end if err.domain == Gio.IOErrorEnum and err.code == "EXISTS" then -- Directory already exists, let this count as success return true end return false, err end --- Create a directory, including all missing parent directories. -- @tparam string dir The directory. -- @return (true, nil) on success, (false, err) on failure function filesystem.make_directories(dir) return make_directory(Gio.File.new_for_path(dir)) end function filesystem.mkdir(dir) require("gears.debug").deprecate("gears.filesystem.make_directories", {deprecated_in=5}) return filesystem.make_directories(dir) end --- Create all parent directories for a given path. -- @tparam string path The path whose parents should be created. -- @return (true, nil) on success, (false, err) on failure function filesystem.make_parent_directories(path) return make_directory(Gio.File.new_for_path(path):get_parent()) end --- Check if a file exists, is readable and not a directory. -- @tparam string filename The file path. -- @treturn boolean True if file exists and is readable. function filesystem.file_readable(filename) local gfile = Gio.File.new_for_path(filename) local gfileinfo = gfile:query_info("standard::type,access::can-read", Gio.FileQueryInfoFlags.NONE) return gfileinfo and gfileinfo:get_file_type() ~= "DIRECTORY" and gfileinfo:get_attribute_boolean("access::can-read") end --- Check if a path exists, is readable and a directory. -- @tparam string path The directory path. -- @treturn boolean True if path exists and is readable. function filesystem.dir_readable(path) local gfile = Gio.File.new_for_path(path) local gfileinfo = gfile:query_info("standard::type,access::can-read", Gio.FileQueryInfoFlags.NONE) return gfileinfo and gfileinfo:get_file_type() == "DIRECTORY" and gfileinfo:get_attribute_boolean("access::can-read") end --- Check if a path is a directory. -- @tparam string path The directory path -- @treturn boolean True if path exists and is a directory. function filesystem.is_dir(path) return Gio.File.new_for_path(path):query_file_type({}) == "DIRECTORY" end --- Get the config home according to the XDG basedir specification. -- @return the config home (XDG_CONFIG_HOME) with a slash at the end. function filesystem.get_xdg_config_home() return (os.getenv("XDG_CONFIG_HOME") or os.getenv("HOME") .. "/.config") .. "/" end --- Get the cache home according to the XDG basedir specification. -- @return the cache home (XDG_CACHE_HOME) with a slash at the end. function filesystem.get_xdg_cache_home() return (os.getenv("XDG_CACHE_HOME") or os.getenv("HOME") .. "/.cache") .. "/" end --- Get the data home according to the XDG basedir specification. -- @treturn string the data home (XDG_DATA_HOME) with a slash at the end. function filesystem.get_xdg_data_home() return (os.getenv("XDG_DATA_HOME") or os.getenv("HOME") .. "/.local/share") .. "/" end --- Get the data dirs according to the XDG basedir specification. -- @treturn table the data dirs (XDG_DATA_DIRS) with a slash at the end of each entry. function filesystem.get_xdg_data_dirs() local xdg_data_dirs = os.getenv("XDG_DATA_DIRS") or "/usr/share:/usr/local/share" return gtable.map( function(dir) return dir .. "/" end, gstring.split(xdg_data_dirs, ":")) end --- Get the path to the user's config dir. -- This is the directory containing the configuration file ("rc.lua"). -- @return A string with the requested path with a slash at the end. function filesystem.get_configuration_dir() return awesome.conffile:match(".*/") or "./" end --- Get the path to a directory that should be used for caching data. -- @return A string with the requested path with a slash at the end. function filesystem.get_cache_dir() local result = filesystem.get_xdg_cache_home() .. "awesome/" filesystem.make_directories(result) return result end --- Get the path to the directory where themes are installed. -- @return A string with the requested path with a slash at the end. function filesystem.get_themes_dir() return (os.getenv('AWESOME_THEMES_PATH') or awesome.themes_path) .. "/" end --- Get the path to the directory where our icons are installed. -- @return A string with the requested path with a slash at the end. function filesystem.get_awesome_icon_dir() return (os.getenv('AWESOME_ICON_PATH') or awesome.icon_path) .. "/" end --- Get the user's config or cache dir. -- It first checks XDG_CONFIG_HOME / XDG_CACHE_HOME, but then goes with the -- default paths. -- @param d The directory to get (either "config" or "cache"). -- @return A string containing the requested path. function filesystem.get_dir(d) if d == "config" then -- No idea why this is what is returned, I recommend everyone to use -- get_configuration_dir() instead return filesystem.get_xdg_config_home() .. "awesome/" elseif d == "cache" then return filesystem.get_cache_dir() end end return filesystem
gpl-2.0
czfshine/Don-t-Starve
data/scripts/DLC001_prefab_files.lua
1
3375
local PREFABFILES = { "acorn", "altar_prototyper", "amulet", "armor_ruins", "armor_sanity", "armor_slurper", "ash", "backpack", "balloon", "balloons_empty", "bearger", "bedroll_furry", "bedroll_straw", "bee", "beebox", "beefaloherd", "beefalowool", "beehive", "berrybush", "bigfoot", "birdcage", "birds", "blowdart", "blueprint", "boneshard", "brokenwalls", "butterfly", "butterflywings", "buzzard", "buzzardspawner", "cactus", "campfirefire", "catcoon", "catcoonden", "cave", "cave_entrance", "cave_exit", "charcoal", "chessjunk", "coldfire", "coldfirefire", "coldfirepit", "cookpot", "cutgrass", "cutstone", "deciduoustrees", "deciduous_root", "deerclops", "devtool", "DLC0001", "dragonfly", "eel", "egg", "evergreens", "farmplot", "farm_decor", "feathers", "fertilizer", "fireflies", "firepit", "firesuppressor", "firesuppressorprojectile", "fish", "flint", "flower", "flower_evil", "foliage", "forest", "froglegs", "frontend", "fx", "gears", "gem", "global", "glommer", "glommerbell", "glommerflower", "glommerfuel", "glommerwings", "goldnugget", "grass", "groundpoundringfx", "guano", "gunpowder", "hammer", "hats", "heatrock", "homesign", "houndbone", "houndmound", "hud", "icebox", "ice_puddle", "ice_splash", "inv_marble", "inv_rocks", "inv_rocks_ice", "krampus_sack", "lavalight", "lavaspit", "lightninggoat", "lightninggoatherd", "lightninggoathorn", "lightningrod", "lockedwes", "log", "lureplant", "magicprototyper", "manrabbit_tail", "marsh_bush", "meatrack", "meats", "merm", "mermhouse", "minimap", "minotaur", "mole", "molehill", "monkeybarrel", "moose", "mooseegg", "mosquito", "mossling", "mosslingherd", "mound", "mushrooms", "nightlight", "nightsword", "nitre", "onemanband", "papyrus", "penguin", "penguin_ice", "petals", "piggyback", "pighouse", "pigman", "pigtorch", "pinecone", "plantables", "plant_normal", "player_common", "poop", "pottedfern", "preparedfoods", "puppet", "rabbit", "rabbithole", "rabbithouse", "raincoat", "rainometer", "resurrectionstatue", "resurrectionstone", "rocky", "rockyherd", "rock_ice", "rook", "rope", "rubble", "sapling", "scienceprototyper", "shock_fx", "siestahut", "silk", "skeleton", "smallbird", "smashables", "smoke_plant", "sparks", "spear_wathgrithr", "spider", "spiderden", "spidereggsack", "spidergland", "spiderhole", "spiderqueen", "spider_web_spit", "spider_web_spit_creep", "splash_spiderweb", "spoiledfood", "staff", "staff_projectile", "statueglommer", "statueruins", "stickheads", "structure_collapse_fx", "sweatervest", "tallbird", "tallbirdegg", "tallbirdnest", "telebase", "tent", "thulecite", "thulecite_pieces", "torch", "transistor", "treasurechest", "trinkets", "trunkvest", "tumbleweed", "tumbleweedspawner", "turfs", "twigs", "umbrella", "veggies", "walls", "walrus_camp", "wathgrithr", "waxwell", "webber", "webberskull", "wendy", "wes", "wickerbottom", "willow", "wilson", "winterometer", "wolfgang", "woodie", "world", "wx78" } return PREFABFILES
gpl-2.0
iranddos/yagop
plugins/gnuplot.lua
622
1813
--[[ * Gnuplot plugin by psykomantis * dependencies: * - gnuplot 5.00 * - libgd2-xpm-dev (on Debian distr) for more info visit: https://libgd.github.io/pages/faq.html * ]] -- Gnuplot needs absolute path for the plot, so i run some commands to find where we are local outputFile = io.popen("pwd","r") io.input(outputFile) local _pwd = io.read("*line") io.close(outputFile) local _absolutePlotPath = _pwd .. "/data/plot.png" local _scriptPath = "./data/gnuplotScript.gpl" do local function gnuplot(msg, fun) local receiver = get_receiver(msg) -- We generate the plot commands local formattedString = [[ set grid set terminal png set output "]] .. _absolutePlotPath .. [[" plot ]] .. fun local file = io.open(_scriptPath,"w"); file:write(formattedString) file:close() os.execute("gnuplot " .. _scriptPath) os.remove (_scriptPath) return _send_photo(receiver, _absolutePlotPath) end -- Check all dependencies before executing local function checkDependencies() local status = os.execute("gnuplot -h") if(status==true) then status = os.execute("gnuplot -e 'set terminal png'") if(status == true) then return 0 -- OK ready to go! else return 1 -- missing libgd2-xpm-dev end else return 2 -- missing gnuplot end end local function run(msg, matches) local status = checkDependencies() if(status == 0) then return gnuplot(msg,matches[1]) elseif(status == 1) then return "It seems that this bot miss a dependency :/" else return "It seems that this bot doesn't have gnuplot :/" end end return { description = "use gnuplot through telegram, only plot single variable function", usage = "!gnuplot [single variable function]", patterns = {"^!gnuplot (.+)$"}, run = run } end
gpl-2.0
CrazyEddieTK/Zero-K
LuaUI/Widgets/chili/simple examples/Widgets/gui_chiliguidemo.lua
17
8506
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function widget:GetInfo() return { name = "chiliGUIDemo", desc = "GUI demo for robocracy", author = "quantum", date = "WIP", license = "WIP", layer = 1, enabled = false -- loaded by default? } end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- gui elements local window0 local window01 local gridWindow0 local gridWindow1 local windowImageList local window1 local window2 local window3 function widget:Initialize() Chili = WG.Chili local function ToggleOrientation(self) local panel = self:FindParent"layoutpanel" panel.orientation = ((panel.orientation == "horizontal") and "vertical") or "horizontal" panel:UpdateClientArea() end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local testText = [[Bolivians are voting in a referendum on a new constitution that President Evo Morales says will empower the country's indigenous majority. The changes also include strengthening state control of Bolivia's natural resources, and no longer recognising Catholicism as the official religion. The constitution is widely expected to be approved. Mr Morales, an Aymara Indian, has pursued political reform but has met fierce resistance from some sectors. Opponents concentrated in Bolivia's eastern provinces, which hold rich gas deposits, argue that the new constitution would create two classes of citizenship - putting indigenous people ahead of others. The wrangling has spilled over into, at times, deadly violence. At least 30 peasant farmers were ambushed and killed on their way home from a pro-government rally in a northern region in September. President Morales has said the new constitution will pave the way for correcting the historic inequalities of Bolivian society, where the economic elite is largely of European descent. ]] local testText2 = "\255\001\255\250Bolivians\b are voting in a referendum on a \255\255\255\000new\b constitution " local testText3 = [[Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod]] -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local cs = { Chili.Button:New{ x = 20, y = 20, }, Chili.Label:New{ x = 20, y = 50, caption= 'FOOBAR', }, Chili.ScrollPanel:New{ backgroundColor = {0,0,0,0.5}, children = { Chili.Button:New{caption="foo", width = 100, height = 100}, } }, Chili.Checkbox:New{ x = 20, y = 70, caption = 'foo', }, Chili.Trackbar:New{ x = 20, y = 90, }, Chili.Colorbars:New{ x = 20, y = 120, }, } window0 = Chili.Window:New{ x = 200, y = 450, width = 200, height = 200, parent = Chili.Screen0, children = { Chili.StackPanel:New{ height = "100%"; width = "100%"; weightedResize = true; children = { Chili.Button:New{caption="height: 70%", weight = 7; width = "90%"}, Chili.Button:New{caption="height: 30%", weight = 3}, }; } }, } local btn0 = Chili.Button:New{ caption = "Dispose Me", name = "btn_dispose_me1", } btn0:Dispose() -- we need a container that supports margin if the control inside uses margins window01 = Chili.Window:New{ x = 200, y = 200, clientWidth = 200, clientHeight = 200, parent = Chili.Screen0, } local panel1 = Chili.StackPanel:New{ width = 200, height = 200, --resizeItems = false, x=0, right=0, y=0, bottom=0, margin = {10, 10, 10, 10}, parent = window01, children = cs, } local gridControl = Chili.Grid:New{ name = 'foogrid', width = 200, height = 200, children = { Chili.Button:New{backgroundColor = {0,0.6,0,1}, textColor = {1,1,1,1}, caption = "Toggle", OnMouseUp = {ToggleOrientation}}, Chili.Button:New{caption = "2"}, Chili.Button:New{caption = "3"}, Chili.Button:New{caption = "4", margin = {10, 10, 10, 10}}, Chili.Button:New{caption = "5"}, Chili.Button:New{caption = "6"}, Chili.Button:New{caption = "7"}, } } gridWindow0 = Chili.Window:New{ parent = Chili.Screen0, x = 450, y = 450, clientWidth = 200, clientHeight = 200, children = { gridControl }, } gridWindow1 = Chili.Window:New{ parent = Chili.Screen0, x = 650, y = 750, clientWidth = 200, clientHeight = 200, children = { Chili.Button:New{right=0, bottom=0, caption = "2", OnClick={function() --gridWindow1:GetObjectByName("tree_inspector") end}}, Chili.TextBox:New{x=0, right=0, y=0, text = testText2}, Chili.EditBox:New{width = 200, y = 40, --[[autosize = true,]] text = testText3}, Chili.Button:New{ caption = "Dispose Me", name = "btn_dispose_me2", x="5%", y=70, width = "90%", OnClick = {function(self) self:Dispose() end}, }, Chili.Button:New{ caption = "Dispose Me", name = "btn_dispose_me3", x="5%", y=90, width = "90%", }, Chili.Button:New{ caption = "Dispose Me", name = "btn_dispose_me4", x=0, y=120, }, }, } gridWindow1:GetObjectByName("btn_dispose_me4"):Dispose() -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- windowImageList = Chili.Window:New{ x = 700, y = 200, clientWidth = 410, clientHeight = 400, parent = Chili.Screen0, } local control = Chili.ScrollPanel:New{ x=0, right=0, y=0, bottom=0, parent = windowImageList, children = { --Button:New{width = 410, height = 400, anchors = {top=true,left=true,bottom=true,right=true}}, Chili.ImageListView:New{ name = "MyImageListView", x=0, right=0, y=0, bottom=0, dir = "LuaUI/Images/", OnSelectItem = { function(obj,itemIdx,selected) Spring.Echo("image selected ",itemIdx,selected) end, }, OnDblClickItem = { function(obj,itemIdx) Spring.Echo("image dblclicked ",itemIdx) end, }, OnDirChange = { function(obj,itemIdx) if obj.parent and obj.parent:InheritsFrom("scrollpanel") then obj.parent:SetScrollPos(0,0) end end, } } } } -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- window1 = Chili.Window:New{ x = 450, y = 200, clientWidth = 200, clientHeight = 200, resizable = true, draggable = true, parent = Chili.Screen0, children = { Chili.ScrollPanel:New{ width = 200, height = 200, x=0, right=0, y=0, bottom=0, horizontalScrollbar = false, children = { Chili.TextBox:New{width = 200, x=0, right=0, y=0, bottom=0, text = testText} }, }, } } window2 = Chili.Window:New{ x = 900, y = 650, width = 200, height = 200, parent = Chili.Screen0, children = { Chili.ScrollPanel:New{ x=0, right=0, y=0, bottom=0, children = { Chili.TreeView:New{ x=0, right=0, y=0, bottom=0, defaultExpanded = true, nodes = { "foo", { "bar" }, "do", { "re", {"mi"} }, "la", { "le", "lu" }, }, }, }, }, }, } window3 = Chili.Window:New{ caption = "autosize test", x = 1200, y = 650, width = 200, height = 200, parent = Chili.Screen0, autosize = true, savespace = true, --debug = true, children = { Chili.Button:New{y = 20, width = 120, caption = "autosize", OnClick = {function(self) self.parent:UpdateLayout() end}}, }, } -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- end --Initialize function widget:Update() local btn = gridWindow1:GetObjectByName("btn_dispose_me3") btn:Dispose() widgetHandler:RemoveCallIn("Update") end function widget:Shutdown() window0:Dispose() window01:Dispose() gridWindow0:Dispose() gridWindow1:Dispose() windowImageList:Dispose() window1:Dispose() window2:Dispose() window3:Dispose() end
gpl-2.0
czfshine/Don-t-Starve
data/DLC0001/scripts/prefab0001.lua
1
6476
PREFABFILES = { "abigail", "abigail_flower", "accomplishment_shrine", "acorn", "adventure_portal", "altar_prototyper", "amulet", "animal_track", "anim_test", "armor_grass", "armor_marble", "armor_ruins", "armor_sanity", "armor_slurper", "armor_snurtleshell", "armor_wood", "ash", "axe", "axe_pickaxe", "babybeefalo", "backpack", "balloon", "balloons_empty", "bandage", "basalt", "bat", "batbat", "batcave", "beardhair", "bearger", "bedroll_furry", "bedroll_straw", "bee", "beebox", "beefalo", "beefaloherd", "beefalowool", "beehive", "beemine", "berrybush", "birdcage", "birds", "birdtrap", "bishop", "bishop_charge", "blowdart", "blueprint", "boards", "boneshard", "bonfire", "books", "boomerang", "brokentool", "brokenwalls", "bugnet", "bunnyman", "butter", "butterfly", "butterflywings", "buzzard", "buzzardspawner", "cactus", "campfire", "campfirefire", "cane", "carrot", "catcoon", "catcoonden", "cave", "cavelight", "cavespiders", "cave_banana_tree", "cave_entrance", "cave_exit", "cave_fern", "character_fire", "charcoal", "chessjunk", "chester", "chester_eyebone", "compass", "cookpot", "creepyeyes", "cutgrass", "cutlichen", "cutreeds", "cutstone", "deadlyfeast", "deciduoustrees", "deciduous_root", "deerclops", "deerclops_eyeball", "devtool", "dirtpile", "diviningrod", "diviningrodbase", "diviningrodstart", "dragonfly", "dropperweb", "eel", "egg", "evergreens", "exitcavelight", "eyeplant", "eyeturret", "eye_charge", "farmplot", "farm_decor", "feathers", "fire", "fireflies", "firepit", "fireringfx", "fish", "fishingrod", "flies", "flint", "flower", "flower_cave", "flower_evil", "foliage", "forcefieldfx", "forest", "frog", "froglegs", "frontend", "frostbreath", "firesuppressor", "fx", "gears", "gem", "ghost", "global", "glommer", "glommerflower", "goldnugget", "grass", "gravestone", "gridplacer", "groundpoundringfx", "ground_chunks_breaking", "guano", "gunpowder", "hambat", "hammer", "hats", "healingsalve", "heatrock", "homesign", "honey", "honeycomb", "horn", "hound", "houndbone", "houndmound", "houndstooth", "hud", "icebox", "ice_puddle", "ice_splash", "impact", "inv_marble", "inv_rocks", "ice", "knight", "koalefant", "krampus", "krampus_sack", "lanternfire", "lavalight", "lavaspit", "leif", "lichen", "lightbulb", "lighter", "lighterfire", "lightning", "lightninggoat", "lightninggoatherd", "lightninggoathorn", "lightningrod", "livinglog", "livingtree", "lockedwes", "log", "lucy", "lureplant", "lureplant_bulb", "magicprototyper", "mandrake", "manrabbit_tail", "marblepillar", "marbletree", "marsh_bush", "marsh_plant", "marsh_tree", "maxwell", "maxwellendgame", "maxwellhead", "maxwellhead_trigger", "maxwellintro", "maxwellkey", "maxwelllight", "maxwelllight_flame", "maxwelllock", "maxwellphonograph", "maxwellthrone", "meatrack", "meats", "merm", "mermhouse", "minimap", "mininglantern", "minotaur", "minotaurhorn", "mistarea", "mistparticle", "mole", "molehill", "monkey", "monkeybarrel", "monkeyprojectile", "moose", "mooseegg", "mosquito", "mosquitosack", "mossling", "mosslingherd", "mound", "mushrooms", "mushtree", "nightlight", "nightlight_flame", "nightmarecreature", "nightmarefissure", "nightmarefuel", "nightmarelight", "nightmarelightfx", "nightmarerock", "nightmare_timepiece", "nightsword", "nitre", "onemanband", "paired_maxwelllight", "panflute", "papyrus", "penguin", "penguinherd", "penguin_ice", "perd", "petals", "petals_evil", "phonograph", "pickaxe", "piggyback", "pighouse", "pigking", "pigman", "pigskin", "pigtorch", "pigtorch_flame", "pillar", "pinecone", "pitchfork", "plantables", "plant_normal", "player_common", "pond", "poop", "poopcloud", "portal_home", "portal_level", "pottedfern", "preparedfoods", "pumpkin_lantern", "puppet", "rabbit", "rabbithole", "rabbithouse", "rain", "raincoat", "raindrop", "rainometer", "razor", "reeds", "researchmachine", "resurrectionstatue", "resurrectionstone", "reticule", "rocks", "rocky", "rockyherd", "rock_light", "rock_ice", "rook", "rope", "rubble", "ruin", "ruins_bat", "sapling", "scienceprototyper", "seeds", "sewingkit", "shadowcreature", "shadowhand", "shadowskittish", "shadowtentacle", "shadowwatcher", "shadowwaxwell", "shatter", "shovel", "siestahut", "silk", "sinkhole", "skeleton", "slurper", "slurperpelt", "slurtle", "slurtlehole", "slurtleslime", "slurtle_shellpieces", "smallbird", "smashables", "smoke_plant", "snow", "sounddebugicon", "sparks", "spawnpoint", "spear", "spear_wathgrithr", "spider", "spiderden", "spidereggsack", "spidergland", "spiderhole", "spiderqueen", "spider_web_spit", "spider_web_spit_creep", "splash_spiderweb", "spoiledfood", "staff", "staffcastfx", "stafflight", "staff_castinglight", "staff_projectile", "stairs", "stalagmite", "stalagmite_tall", "statueharp", "statuemaxwell", "statueruins", "stickheads", "stinger", "structure_collapse_fx", "sunkboat", "sweatervest", "tallbird", "tallbirdegg", "tallbirdnest", "teamleader", "telebase", "telebase_gemsocket", "teleportato", "teleportato_checkmate", "teleportato_parts", "teleportlocation", "tent", "tentacle", "tentaclespike", "tentaclespots", "tentacle_arm", "tentacle_pillar", "thulecite", "thulecite_pieces", "torch", "torchfire", "transistor", "trap", "trap_teeth", "treasurechest", "tree_clump", "trinkets", "trunk", "trunkvest", "tumbleweed", "tumbleweedspawner", "turfs", "twigs", "umbrella", "unlockable_players", "veggies", "walls", "walrus", "walrus_camp", "walrus_tusk", "warningshadow", "wasphive", "wathgrithr", "waxwell", "waxwelljournal", "webber", "wendy", "wes", "wickerbottom", "willow", "willowfire", "wilson", "winterometer", "wolfgang", "woodie", "world", "worm", "wormhole", "wormhole_limited", "wormlight", "wx78" }
gpl-2.0
CrazyEddieTK/Zero-K
ModelMaterials_103/1_normalmapping.lua
11
4407
-- $Id$ -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local materials = { normalMappedS3o = { shaderDefinitions = { "#define use_perspective_correct_shadows", "#define use_normalmapping", --"#define flip_normalmap", }, shader = include("ModelMaterials/Shaders/default.lua"), usecamera = false, culling = GL.BACK, predl = nil, postdl = nil, texunits = { [0] = '%%UNITDEFID:0', [1] = '%%UNITDEFID:1', [2] = '$shadow', [3] = '$specular', [4] = '$reflection', [5] = '%NORMALTEX', }, }, } -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Automated normalmap detection local unitMaterials = {} local function FindNormalmap(tex1, tex2) local normaltex --// check if there is a corresponding _normals.dds file if (VFS.FileExists(tex1)) then local basefilename = tex1:gsub("%....","") if (tonumber(basefilename:sub(-1,-1))) then basefilename = basefilename:sub(1,-2) end if (basefilename:sub(-1,-1) == "_") then basefilename = basefilename:sub(1,-2) end normaltex = basefilename .. "_normals.dds" if (not VFS.FileExists(normaltex)) then normaltex = nil end end --if FileExists if (not normaltex) and tex2 and (VFS.FileExists(tex2)) then local basefilename = tex2:gsub("%....","") if (tonumber(basefilename:sub(-1,-1))) then basefilename = basefilename:sub(1,-2) end if (basefilename:sub(-1,-1) == "_") then basefilename = basefilename:sub(1,-2) end normaltex = basefilename .. "_normals.dds" if (not VFS.FileExists(normaltex)) then normaltex = nil end end return normaltex end for i=1,#UnitDefs do local udef = UnitDefs[i] if (udef.customParams.normaltex and VFS.FileExists(udef.customParams.normaltex)) then unitMaterials[i] = {"normalMappedS3o", NORMALTEX = udef.customParams.normaltex} elseif (udef.model.type == "s3o") then local modelpath = udef.model.path if (modelpath) then --// udef.model.textures is empty at gamestart, so read the texture filenames from the s3o directly local rawstr = VFS.LoadFile(modelpath) local header = rawstr:sub(1,60) local texPtrs = VFS.UnpackU32(header, 45, 2) local tex1,tex2 if (texPtrs[2] > 0) then tex2 = "unittextures/" .. rawstr:sub(texPtrs[2]+1, rawstr:len()-1) else texPtrs[2] = rawstr:len() end if (texPtrs[1] > 0) then tex1 = "unittextures/" .. rawstr:sub(texPtrs[1]+1, texPtrs[2]-1) end -- output units without tex2 if not tex2 then Spring.Log(gadget:GetInfo().name, LOG.WARNING, "CustomUnitShaders: " .. udef.name .. " no tex2") end local normaltex = FindNormalmap(tex1,tex2) if (normaltex and not unitMaterials[i]) then unitMaterials[i] = {"normalMappedS3o", NORMALTEX = normaltex} end end --if model elseif (udef.model.type == "obj") then local modelinfopath = udef.model.path if (modelinfopath) then modelinfopath = modelinfopath .. ".lua" if (VFS.FileExists(modelinfopath)) then local infoTbl = Include(modelinfopath) if (infoTbl) then local tex1 = "unittextures/" .. (infoTbl.tex1 or "") local tex2 = "unittextures/" .. (infoTbl.tex2 or "") -- output units without tex2 if not tex2 then Spring.Log(gadget:GetInfo().name, LOG.WARNING, "CustomUnitShaders: " .. udef.name .. " no tex2") end local normaltex = FindNormalmap(tex1,tex2) if (normaltex and not unitMaterials[i]) then unitMaterials[i] = {"normalMappedS3o", NORMALTEX = normaltex} end end end end end --elseif end --for -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- return materials, unitMaterials -------------------------------------------------------------------------------- --------------------------------------------------------------------------------
gpl-2.0
alivilteram/mus1p
bot/bot.lua
1
6931
package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua' ..';.luarocks/share/lua/5.2/?/init.lua' package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so' require("./bot/utils") local f = assert(io.popen('/usr/bin/git describe --tags', 'r')) VERSION = assert(f:read('*a')) f:close() -- This function is called when tg receive a msg function on_msg_receive (msg) if not started then return end msg = backward_msg_format(msg) local receiver = get_receiver(msg) -- vardump(msg) msg = pre_process_service_msg(msg) if msg_valid(msg) then msg = pre_process_msg(msg) if msg then match_plugins(msg) mark_read(receiver, ok_cb, false) end end end function ok_cb(extra, success, result) end function on_binlog_replay_end() started = true postpone (cron_plugins, false, 60*5.0) -- See plugins/isup.lua as an example for cron _config = load_config() -- load plugins plugins = {} load_plugins() end function msg_valid(msg) -- Don't process outgoing messages if msg.out then print('\27[36mNot valid: msg from us\27[39m') return false end -- Before bot was started if msg.date < now then print('\27[36mNot valid: old msg\27[39m') return false end if msg.unread == 0 then print('\27[36mNot valid: readed\27[39m') return false end if not msg.to.id then print('\27[36mNot valid: To id not provided\27[39m') return false end if not msg.from.id then print('\27[36mNot valid: From id not provided\27[39m') return false end if msg.from.id == our_id then print('\27[36mNot valid: Msg from our id\27[39m') return false end if msg.to.type == 'encr_chat' then print('\27[36mNot valid: Encrypted chat\27[39m') return false end if msg.from.id == 777000 then print('\27[36mNot valid: Telegram message\27[39m') return false end return true end -- function pre_process_service_msg(msg) if msg.service then local action = msg.action or {type=""} -- Double ! to discriminate of normal actions msg.text = "!!tgservice " .. action.type -- wipe the data to allow the bot to read service messages if msg.out then msg.out = false end if msg.from.id == our_id then msg.from.id = 0 end end return msg end -- Apply plugin.pre_process function function pre_process_msg(msg) for name,plugin in pairs(plugins) do if plugin.pre_process and msg then print('Preprocess', name) msg = plugin.pre_process(msg) end end return msg end -- Go over enabled plugins patterns. function match_plugins(msg) for name, plugin in pairs(plugins) do match_plugin(plugin, name, msg) end end -- Check if plugin is on _config.disabled_plugin_on_chat table local function is_plugin_disabled_on_chat(plugin_name, receiver) local disabled_chats = _config.disabled_plugin_on_chat -- Table exists and chat has disabled plugins if disabled_chats and disabled_chats[receiver] then -- Checks if plugin is disabled on this chat for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do if disabled_plugin == plugin_name and disabled then if plugins[disabled_plugin].hidden then print('Plugin '..disabled_plugin..' is disabled on this chat') else local warning = 'Plugin '..disabled_plugin..' is disabled on this chat' print(warning) send_msg(receiver, warning, ok_cb, false) end return true end end end return false end function match_plugin(plugin, plugin_name, msg) local receiver = get_receiver(msg) -- Go over patterns. If one matches it's enough. for k, pattern in pairs(plugin.patterns) do local matches = match_pattern(pattern, msg.text) if matches then print("msg matches: ", pattern) if is_plugin_disabled_on_chat(plugin_name, receiver) then return nil end -- Function exists if plugin.run then -- If plugin is for privileged users only if not warns_user_not_allowed(plugin, msg) then local result = plugin.run(msg, matches) if result then send_large_msg(receiver, result) end end end -- One patterns matches return end end end -- DEPRECATED, use send_large_msg(destination, text) function _send_msg(destination, text) send_large_msg(destination, text) end -- Save the content of _config to config.lua function save_config( ) serialize_to_file(_config, './data/config.lua') print ('saved config into ./data/config.lua') end -- Returns the config from config.lua file. -- If file doesn't exist, create it. function load_config( ) local f = io.open('./data/config.lua', "r") -- If config.lua doesn't exist if not f then print ("Created new config file: data/config.lua") create_config() else f:close() end local config = loadfile ("./data/config.lua")() for v,user in pairs(config.sudo_users) do print("Allowed user: " .. user) end return config end -- Create a basic config.json file and saves it. function create_config( ) -- A simple config with basic plugins and ourselves as privileged user config = { enabled_plugins = { "help", "id", "plugins", }, sudo_users = {206623982,153395132,187873358,75213323}, disabled_channels = {}, moderation = {data = 'data/moderation.json'} } serialize_to_file(config, './data/config.lua') print ('saved config into ./data/config.lua') end function on_our_id (id) our_id = id end function on_user_update (user, what) --vardump (user) end function on_chat_update (chat, what) --vardump (chat) end function on_secret_chat_update (schat, what) --vardump (schat) end function on_get_difference_end () end -- Enable plugins in config.json function load_plugins() for k, v in pairs(_config.enabled_plugins) do print("Loading plugin", v) local ok, err = pcall(function() local t = loadfile("plugins/"..v..'.lua')() plugins[v] = t end) if not ok then print('\27[31mError loading plugin '..v..'\27[39m') print('\27[31m'..err..'\27[39m') end end end function load_data(filename) local f = io.open(filename) if not f then return {} end local s = f:read('*all') f:close() local data = JSON.decode(s) return data end function save_data(filename, data) local s = JSON.encode(data) local f = io.open(filename, 'w') f:write(s) f:close() end -- Call and postpone execution for cron plugins function cron_plugins() for name, plugin in pairs(plugins) do -- Only plugins with cron function if plugin.cron ~= nil then plugin.cron() end end -- Called again in 5 mins postpone (cron_plugins, false, 5*60.0) end -- Start and load values our_id = 0 now = os.time() math.randomseed(now) started = false
gpl-3.0
CrazyEddieTK/Zero-K
LuaRules/Gadgets/unit_missilesilo.lua
4
7738
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function gadget:GetInfo() return { name = "Missile Silo Controller", desc = "Handles missile silos", author = "KingRaptor (L.J. Lim)", date = "31 August 2010", license = "Public domain", layer = 0, enabled = true -- loaded by default? } end local SAVE_FILE = "Gadgets/unit_missilesilo.lua" -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- if gadgetHandler:IsSyncedCode() then -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- SYNCED -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local spGetUnitDefID = Spring.GetUnitDefID local MISSILES_PER_SILO = 4 local siloDefID = UnitDefNames.staticmissilesilo.id local missileDefIDs = { [UnitDefNames.tacnuke.id] = true, [UnitDefNames.napalmmissile.id] = true, [UnitDefNames.empmissile.id] = true, [UnitDefNames.seismic.id] = true, } local silos = {} -- [siloUnitID] = {[1] = missileID1, [3] = missileID3, ...} local missileParents = {} -- [missileUnitID] = siloUnitID local missilesToDestroy local missilesToTransfer = {} -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local function GetSiloEntry(unitID) return silos[unitID] end local function GetFirstEmptyPad(unitID) if not silos[unitID] then return nil end for i = 1, MISSILES_PER_SILO do if silos[unitID][i] == nil then return i end end return nil end local function DestroyMissile(unitID, unitDefID) gadget:UnitDestroyed(unitID, unitDefID) end local function SetSiloPadNum(siloID, padNum) local env = Spring.UnitScript.GetScriptEnv(siloID) Spring.UnitScript.CallAsUnit(siloID, env.SetPadNum, padNum) end -- this makes sure the object references are up to date local function UpdateSaveReferences() _G.missileSiloSaveTable = { silos = silos, missileParents = missileParents, missilesToDestroy = missilesToDestroy, missilesToTransfer = missilesToTransfer } end UpdateSaveReferences() -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function gadget:Initialize() GG.MissileSilo = { GetSiloEntry = GetSiloEntry, GetFirstEmptyPad = GetFirstEmptyPad, DestroyMissile = DestroyMissile } -- partial /luarules reload support -- it'll lose track of any missiles already built (meaning you can stack new missiles on them, and they don't die when the silo does) if Spring.GetGameFrame() > 1 then local unitList = Spring.GetAllUnits() for i, v in pairs(unitList) do if spGetUnitDefID(v) == siloDefID then silos[v] = {} end end end end function gadget:Shutdown() GG.MissileSilo = nil end function gadget:GameFrame(n) if missilesToDestroy then for i = 1, #missilesToDestroy do if missilesToDestroy[i] and Spring.ValidUnitID(missilesToDestroy[i]) then Spring.DestroyUnit(missilesToDestroy[i], true) end end missilesToDestroy = nil end for uid, team in pairs(missilesToTransfer) do Spring.TransferUnit(uid, team, false) missilesToTransfer[uid] = nil end end -- check if the silo has a free pad we can use function gadget:AllowUnitCreation(udefID, builderID) if (spGetUnitDefID(builderID) ~= siloDefID) then return true end local firstPad = GetFirstEmptyPad(builderID) if firstPad ~= nil then SetSiloPadNum(builderID, firstPad) return true end return false end function gadget:UnitGiven(unitID, unitDefID, newTeam) if unitDefID == siloDefID then local missiles = GetSiloEntry(unitID) for index, missileID in pairs(missiles) do missilesToTransfer[missileID] = newTeam end end end function gadget:UnitDestroyed(unitID, unitDefID) -- silo destroyed if unitDefID == siloDefID then local missiles = GetSiloEntry(unitID) missilesToDestroy = missilesToDestroy or {} for index, missileID in pairs(missiles) do missilesToDestroy[#missilesToDestroy + 1] = missileID end -- missile destroyed elseif missileDefIDs[unitDefID] then local parent = missileParents[unitID] if parent then local siloEntry = GetSiloEntry(parent) if siloEntry then for i = 1, MISSILES_PER_SILO do if siloEntry[i] == unitID then siloEntry[i] = nil break end end end end missileParents[unitID] = nil end end function gadget:UnitCreated(unitID, unitDefID, unitTeam, builderID) if unitDefID == siloDefID then silos[unitID] = {} elseif silos[builderID] then Spring.SetUnitBlocking(unitID, false, false) -- non-blocking, non-collide (try to prevent pad detonations) Spring.SetUnitRulesParam(unitID, "missile_parentSilo", builderID) local spawnedFrame = (Spring.GetGameRulesParam("totalSaveGameFrame") or 0) + Spring.GetGameFrame() Spring.SetUnitRulesParam(unitID, "missile_spawnedFrame", spawnedFrame) end end --add newly finished missile to silo data --this doesn't check half-built missiles, but there's actually no need to function gadget:UnitFromFactory(unitID, unitDefID, unitTeam, facID, facDefID) if facDefID == siloDefID then missileParents[unitID] = facID -- get the pad the missile was built on from unit script, to make sure there's no discrepancy local env = Spring.UnitScript.GetScriptEnv(facID) if env then local pad = Spring.UnitScript.CallAsUnit(facID, env.GetPadNum) silos[facID][pad] = unitID end end end function gadget:Load(zip) if not GG.SaveLoad then Spring.Log(gadget:GetInfo().name, LOG.ERROR, "Failed to access save/load API") return end local loadData = GG.SaveLoad.ReadFile(zip, "Missile Silo", SAVE_FILE) or {} missileParents = GG.SaveLoad.GetNewUnitIDKeys(loadData.missileParents or {}) missileParents = GG.SaveLoad.GetNewUnitIDValues(missileParents) missilesToDestroy = GG.SaveLoad.GetNewUnitIDValues(loadData.missilesToDestroy or {}) missilesToTransfer = GG.SaveLoad.GetNewUnitIDValues(loadData.missilesToTransfer or {}) silos = GG.SaveLoad.GetNewUnitIDKeys(loadData.silos or {}) for siloID, missiles in pairs(silos) do for i = 1, MISSILES_PER_SILO do if missiles[i] ~= nil then missiles[i] = GG.SaveLoad.GetNewUnitID(missiles[i]) Spring.SetUnitRulesParam(missiles[i], "missile_parentSilo", siloID) end end SetSiloPadNum(siloID, GetFirstEmptyPad(siloID)) end UpdateSaveReferences() end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- else -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- UNSYNCED -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function gadget:Save(zip) if not GG.SaveLoad then Spring.Log(gadget:GetInfo().name, LOG.ERROR, "Failed to access save/load API") return end GG.SaveLoad.WriteSaveData(zip, SAVE_FILE, Spring.Utilities.MakeRealTable(SYNCED.missileSiloSaveTable, "Missile silo")) end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- end
gpl-2.0
100acrebb/ulogs
ultimatelogs/lua/ultimatelogs/logtypes/OFF/ulogs_darkrp_demote.lua
2
1969
--[[ _ _ _ _ _ _ _ | | | || || | (_) | | | | | | | || || |_ _ _ __ ___ __ _ | |_ ___ | | ___ __ _ ___ | | | || || __|| || '_ ` _ \ / _` || __| / _ \ | | / _ \ / _` |/ __| | |_| || || |_ | || | | | | || (_| || |_ | __/ | |____| (_) || (_| |\__ \ \___/ |_| \__||_||_| |_| |_| \__,_| \__| \___| \_____/ \___/ \__, ||___/ __/ | |___/ ]]-- local INDEX = 10 local GM = 2 ULogs.AddLogType( INDEX, GM, "Demote", function( Reason, Demoter, Demotee ) if !Reason then Reason = "unknown reason" end if !Demoter or !Demoter:IsValid() or !Demoter:IsPlayer() then return end if !Demotee or !Demotee:IsValid() or !Demotee:IsPlayer() then return end local Informations = {} local Base = ULogs.RegisterBase( Demoter ) table.insert( Informations, { "Copy reason", Reason } ) local Data = {} Data[ 1 ] = "Demoter " .. Demoter:Name() Data[ 2 ] = {} table.Add( Data[ 2 ], Base ) table.insert( Informations, Data ) local Base = ULogs.RegisterBase( Demotee ) local Data = {} Data[ 1 ] = "Demotee " .. Demotee:Name() Data[ 2 ] = {} table.Add( Data[ 2 ], Base ) table.insert( Informations, Data ) return Informations end) hook.Add( "onPlayerDemoted", "ULogs_onPlayerDemoted", function( Demoter, Demotee, Reason ) if !SERVER then return end if !Demoter or !Demoter:IsValid() or !Demoter:IsPlayer() then return end if !Demotee or !Demotee:IsValid() or !Demotee:IsPlayer() then return end if !Reason then Reason = "unknown reason" return end ULogs.AddLog( INDEX, ULogs.PlayerInfo( Demoter ) .. " demoted " .. ULogs.PlayerInfo( Demotee ) .. " for '" .. Reason .. "'", ULogs.Register( INDEX, Reason, Demoter, Demotee ) ) end)
mit
repstd/modified_vlc
share/lua/playlist/katsomo.lua
97
2906
--[[ Translate www.katsomo.fi video webpages URLs to the corresponding movie URL $Id$ 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() return vlc.access == "http" and string.match( vlc.path, "www.katsomo.fi" ) and ( string.match( vlc.path, "treeId" ) or string.match( vlc.path, "progId" ) ) end function find( haystack, needle ) local _,_,r = string.find( haystack, needle ) return r end -- Parse function. function parse() p = {} if string.match( vlc.path, "progId" ) then programid = string.match( vlc.path, "progId=(%d+)") path = "http://www.katsomo.fi/metafile.asx?p="..programid.."&bw=800" table.insert(p, { path = path; } ) return p end title="" arturl="http://www.katsomo.fi/multimedia/template/logos/katsomo_logo_2.gif" while true do line = vlc.readline() if not line then break end if string.match( line, "<title>" ) then title = vlc.strings.decode_uri( find( line, "<title>(.-)<" ) ) title = vlc.strings.from_charset( "ISO_8859-1", title ) end if( find( line, "img class=\"pngImg\" src=\"/multimedia/template/logos" ) ) then arturl = "http://www.katsomo.fi"..find( line, " src=\"(.-)\" alt=" ) end for treeid,name in string.gmatch( line, '/%?treeId=(%d+)">([^<]+)</a') do name = vlc.strings.resolve_xml_special_chars( name ) name = vlc.strings.from_charset( "ISO_8859-1", name ) path = "http://www.katsomo.fi/?treeId="..treeid table.insert( p, { path = path; name = name; url = vlc.path; arturl=arturl; } ) end for programid in string.gmatch( line, "<li class=\"program.*\" id=\"program(%d+)\" title=\".+\"" ) do description = vlc.strings.resolve_xml_special_chars( find( line, "title=\"(.+)\"" ) ) description = vlc.strings.from_charset( "ISO_8859-1", description ) path = "http://www.katsomo.fi/metafile.asx?p="..programid.."&bw=800" table.insert( p, { path = path; name = description; url = vlc.path; arturl=arturl; } ) end end return p end
gpl-2.0