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
lichtl/darkstar
scripts/zones/Southern_San_dOria/npcs/Esmallegue.lua
14
1536
----------------------------------- -- Area: Southern San d'Oria -- NPC: Esmallegue -- General Info NPC -- @zone 230 -- @pos 0 2 -83 ------------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Southern_San_dOria/TextIDs"); require("scripts/globals/settings"); require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script local FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then local count = trade:getItemCount(); local MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) -- player:startEvent(0x37e);-- cavernous maw player:startEvent(0x0375) 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
DrYaling/eluna-trinitycore
src/server/scripts/Scripts-master/Blizzlike/EasternKingdoms/zone_eversong_woods.lua
1
4849
--[[ EmuDevs <http://emudevs.com/forum.php> Eluna Lua Engine <https://github.com/ElunaLuaEngine/Eluna> Eluna Scripts <https://github.com/ElunaLuaEngine/Scripts> Eluna Wiki <http://wiki.emudevs.com/doku.php?id=eluna> -= Script Information =- * Zone: Eversong Woods * QuestId: 8488 / 8490 * Script Type: Gossip, CreatureAI and Quest * Npc: Apprentice Mirveda <15402>, Infused Crystal <16364> --]] local killCount = 0 local playerGUID = 0 -- Apprentice Mirveda function Mirveda_QuestAccept(event, player, creature, quest) if (quest:GetId() == 8488) then playerGUID = player:GetGUIDLow() creature:RegisterEvent(Mirveda_SpawnCreature, 1200, 1) creature:RegisterEvent(Mirveda_QuestComplete, 1000, 0) end end function Mirveda_SpawnCreature(event, delay, pCall, creature) creature:SpawnCreature(15958, 8725, -7153.93, 35.23, 0, 2, 4000) creature:SpawnCreature(15656, 8725, -7153.93, 35.23, 0, 2, 4000) creature:SpawnCreature(15656, 8725, -7153.93, 35.23, 0, 2, 4000) end function Mirveda_QuestComplete(event, delay, pCall, creature) if (killCount >= 3 and playerGUID > 0) then creature:RemoveEventById(event) local player = GetPlayerByGUID(playerGUID) if (player ~= nil) then player:CompleteQuest(8488) end end end function Mirveda_Reset() killCount = 0 playerGUID = 0 end function Mirveda_Died(event, creature, killer) creature:RemoveEvents() if (playerGUID > 0) then local player = GetPlayerByGUID(playerGUID) if (player ~= nil) then player:FailQuest(8488) end end end function Mirveda_JustSummoned(event, creature, summoned) summoned:AttackStart(creature) summoned:MoveChase(creature) end function Mirveda_SummonedDespawn(event, creature, summoned) killCount = killCount + 1 end RegisterCreatureEvent(15402, 4, Mirveda_Died) RegisterCreatureEvent(15402, 19, Mirveda_JustSummoned) RegisterCreatureEvent(15402, 20, Mirveda_SummonedDespawn) RegisterCreatureEvent(15402, 23, Mirveda_Reset) RegisterCreatureEvent(15402, 31, Mirveda_QuestAccept) -- Infused Crystal local Spawns = { { 8270.68, -7188.53, 139.619 }, { 8284.27, -7187.78, 139.603 }, { 8297.43, -7193.53, 139.603 }, { 8303.5, -7201.96, 139.577 }, { 8273.22, -7241.82, 139.382 }, { 8254.89, -7222.12, 139.603 }, { 8278.51, -7242.13, 139.162 }, { 8267.97, -7239.17, 139.517 } } local completed = false local started = false local crystalPlayerGUID = 0 function Crystal_Died(event, creature, killer) creature:RemoveEvents() if (crystalPlayerGUID > 0 and not completed) then local player = GetPlayerByGUID(crystalPlayerGUID) if (player ~= nil) then player:FailQuest(8490) end end end function Crystal_Reset(event, creature) crystalPlayerGUID = 0 started = false completed = false end function Crystal_MoveLOS(event, creature, unit) if (unit:GetUnitType() == "Player" and creature:IsWithinDistInMap(unit, 10) and not started) then if (unit:GetQuestStatus(8490) == 3) then crystalPlayerGUID = unit:GetGUIDLow() creature:RegisterEvent(Crystal_WaveStart, 1000, 1) creature:RegisterEvent(Crystal_Completed, 60000, 1) started = true end end end function Crystal_WaveStart(event, delay, pCall, creature) if (started and not completed) then local rand1 = math.random(8) local rand2 = math.random(8) local rand3 = math.random(8) creature:SpawnCreature(17086, Spawns[rand1][1], Spawns[rand1][2], Spawns[rand1][3], 0, 2, 10000) creature:SpawnCreature(17086, Spawns[rand2][1], Spawns[rand2][2], Spawns[rand2][3], 0, 2, 10000) creature:SpawnCreature(17086, Spawns[rand3][1], Spawns[rand3][2], Spawns[rand3][3], 0, 2, 10000) creature:RegisterEvent(Crystal_WaveStart, 30000, 0) end end function Crystal_Completed(event, delay, pCall, creature) if (started) then creature:RemoveEvents() creature:SendCreatureTalk(0, crystalPlayerGUID) completed = true if (crystalPlayerGUID > 0) then local player = GetPlayerByGUID(crystalPlayerGUID) if (player ~= nil) then player:CompleteQuest(8490) end end creature:DealDamage(creature, creature:GetHealth()) creature:RemoveCorpse() end end function Crystal_Summoned(event, creature, summoned) local player = GetPlayerByGUID(crystalPlayerGUID) if (player ~= nil) then summoned:AttackStart(player) end end RegisterCreatureEvent(16364, 4, Crystal_Died) RegisterCreatureEvent(16364, 19, Crystal_Summoned) RegisterCreatureEvent(16364, 23, Crystal_Reset) RegisterCreatureEvent(16364, 27, Crystal_MoveLOS)
gpl-2.0
LuaDist2/luchia
src/luchia/utilities.lua
2
2734
--- High-level utilities class. -- -- Contains all high-level utility methods. This module should be used instead -- of the core modules when possible. -- -- See the @{utilities.lua} example for more detail. -- -- @classmod luchia.utilities -- @author Chad Phillips -- @copyright 2011-2015 Chad Phillips require "luchia.conf" local logger = require "luchia.core.log" local log = logger.logger local server = require "luchia.core.server" local string = require "string" local setmetatable = setmetatable local _M = {} --- Create a new utilities handler object. -- -- @param server_params -- Optional. A table of server connection parameters (identical to -- <code>default.server</code> in @{luchia.conf}. If not provided, -- a server object will be generated from the default server -- configuration. -- @return A utilities handler object. -- @usage util = luchia.utilities:new(server_params) function _M.new(self, server_params) local utilities = {} utilities.server = server:new(server_params) setmetatable(utilities, self) self.__index = self log:debug(string.format([[New utilities handler]])) return utilities end --- Make a utilities-related request to the server. -- -- @param self -- @param path -- Optional. The server path. -- @return The following four values, in this order: response_data, -- response_code, headers, status_code. local function utilities_get_call(self, path) local params = { path = path, } local response, response_code, headers, status = self.server:request(params) return response, response_code, headers, status end --- Get the database server version. -- -- @return The database server version string. -- @usage util:version() function _M:version() local response = utilities_get_call(self, "") if response and response.version then return response.version end end --- Get the database server configuration. -- -- @return Same values as @{utilities_get_call}, response_data is a table of -- database server configuration information. -- @usage util:config() -- @see utilities_get_call function _M:config() return utilities_get_call(self, "_config") end --- Get the database server statistics. -- -- @return Same values as @{utilities_get_call}, response_data is a table of -- database server statistics information. -- @usage util:stats() -- @see utilities_get_call function _M:stats() return utilities_get_call(self, "_stats") end --- Get the database server active tasks. -- -- @return Same values as @{utilities_get_call}, response_data is a list of -- database server active tasks. -- @usage util:active_tasks() -- @see utilities_get_call function _M:active_tasks() return utilities_get_call(self, "_active_tasks") end return _M
bsd-3-clause
meepdarknessmeep/hash.js
plugins/lua/sand_modules/hook.lua
2
2004
local persist = true local javascript_call = true local override_callstate = true local persistHooks = {} local hooks = {} local function Add( event, id, callback ) if ( type( callback ) ~= "function" ) then error( "bad argument #3 to 'Add' (function expected, got " .. type( callback ) .. ")", 2 ) end if persistHooks[ event ] and persistHooks[ event ][ id ] then error( "attempt to override persistent hook", 2 ) end hooks[ event ] = hooks[ event ] or {} hooks[ event ][ id ] = callback if persist then persistHooks[ event ] = persistHooks[ event ] or {} persistHooks[ event ][ id ] = true end end local function Remove( event, id ) if not hooks[ event ] then error( "attempt to remove non-existent hook", 2 ) end if persistHooks[ event ] and persistHooks[ event ][ id ] then error( "attempt to remove persistent hook", 2 ) end hooks[ event ][ id ] = nil end local function Call( event, ... ) local before = javascript_call if not override_callstate then javascript_call = false end override_callstate = false if not hooks[ event ] then javascript_call = before return end for k, v in pairs( hooks[ event ] ) do local success, err = pcall( v, ... ) if not success then print( err ) hooks[ event ][ k ] = nil -- Even remove persistent hooks end end javascript_call = before end local function GetTable() local ret = {} for k, v in pairs( hooks ) do ret[ k ] = {}; for name in pairs(v) do table.insert( ret[ k ], name ) end end return ret end local function StopPersist() persist = false end local function CalledFromSandbox() return not javascript_call end -- called from javascript function HookCall( event, ... ) override_callstate = true javascript_call = true Call ( event, ... ) javascript_call = false end return { Add = Add, Remove = Remove, RemoveAll = RemoveAll, Call = Call, GetTable = GetTable, StopPersist = StopPersist, CalledFromSandbox = CalledFromSandbox, }
cc0-1.0
lichtl/darkstar
scripts/zones/Aht_Urhgan_Whitegate/npcs/Sorrowful_Sage.lua
14
2481
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Sorrowful Sage -- Type: Assault Mission Giver -- @pos 134.096 0.161 -30.401 50 ----------------------------------- package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs"); require("scripts/globals/besieged"); require("scripts/globals/missions"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local rank = getMercenaryRank(player); local haveimperialIDtag; local tokens = 3;--player:getAssaultPoint(ILRUSI_ASSAULT_POINT); if (player:hasKeyItem(IMPERIAL_ARMY_ID_TAG)) then haveimperialIDtag = 1; else haveimperialIDtag = 0; end --[[ if (rank > 0) then player:startEvent(278,rank,haveimperialIDtag,tokens,player:getCurrentAssault()); else]] player:startEvent(284); -- no rank --end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 278) then local categorytype = bit.band(option, 0x0F); if (categorytype == 3) then -- low grade item local item = bit.rshift(option, 16); elseif (categorytype == 4) then -- medium grade item local item = bit.rshift(option, 16); elseif (categorytype == 5) then -- high grade item local item = bit.rshift(option, 16); end end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 278) then local selectiontype = bit.band(option, 0xF); if (selectiontype == 1) then -- taken assault mission player:addAssault(bit.rshift(option,4)); player:delKeyItem(IMPERIAL_ARMY_ID_TAG); player:addKeyItem(NYZUL_ISLE_ASSAULT_ORDERS); player:messageSpecial(KEYITEM_OBTAINED,NYZUL_ISLE_ASSAULT_ORDERS); end end end;
gpl-3.0
OctoEnigma/shiny-octo-system
gamemodes/terrortown/entities/entities/ttt_hat_deerstalker.lua
2
3484
AddCSLuaFile() ENT.Type = "anim" ENT.Base = "base_anim" ENT.Model = Model("models/ttt/deerstalker.mdl") ENT.CanHavePrints = false ENT.CanUseKey = true AccessorFuncDT(ENT, "worn", "BeingWorn") function ENT:SetupDataTables() self:DTVar("Bool", 0, "worn") end function ENT:Initialize() self:SetBeingWorn(true) self:SetModel(self.Model) self:DrawShadow(false) -- don't physicsinit the ent here, because physicsing and then setting -- movetype none is 1) a waste of memory, 2) broken self:SetMoveType(MOVETYPE_NONE) self:SetSolid(SOLID_NONE) self:SetCollisionGroup(COLLISION_GROUP_DEBRIS) if SERVER then self.Wearer = self:GetParent() self:AddEffects(bit.bor(EF_BONEMERGE, EF_BONEMERGE_FASTCULL, EF_PARENT_ANIMATES)) end end if SERVER then local ttt_hats_reclaim = CreateConVar("ttt_detective_hats_reclaim", "1") local ttt_hats_innocent = CreateConVar("ttt_detective_hats_reclaim_any", "0") function ENT:OnRemove() self:SetBeingWorn(false) end function ENT:Drop(dir) local ply = self:GetParent() ply.hat = nil self:SetParent(nil) self:SetBeingWorn(false) self:SetUseType(SIMPLE_USE) -- only now physics this entity self:PhysicsInit(SOLID_VPHYSICS) self:SetSolid(SOLID_VPHYSICS) self:SetMoveType(MOVETYPE_VPHYSICS) -- position at head if IsValid(ply) then local bone = ply:LookupBone("ValveBiped.Bip01_Head1") if bone then local pos, ang = ply:GetBonePosition(bone) self:SetPos(pos) self:SetAngles(ang) else local pos = ply:GetPos() pos.z = pos.z + 68 self:SetPos(pos) end end -- physics push local phys = self:GetPhysicsObject() if IsValid(phys) then phys:SetMass(10) if IsValid(ply) then phys:SetVelocityInstantaneous(ply:GetVelocity()) end if not dir then phys:ApplyForceCenter(Vector(0, 0, 1200)) else phys:ApplyForceCenter(Vector(0, 0, 700) + dir * 500) end phys:AddAngleVelocity(VectorRand() * 200) phys:Wake() end end local function CanEquipHat(ply) return not IsValid(ply.hat) and (ttt_hats_innocent:GetBool() or ply:GetRole() == ROLE_DETECTIVE) end function ENT:UseOverride(ply) if not ttt_hats_reclaim:GetBool() then return end if IsValid(ply) and not self:GetBeingWorn() then if GetRoundState() != ROUND_ACTIVE then SafeRemoveEntity(self) return elseif not CanEquipHat(ply) then return end sound.Play("weapon.ImpactSoft", self:GetPos(), 75, 100, 1) self:SetMoveType(MOVETYPE_NONE) self:SetSolid(SOLID_NONE) self:SetCollisionGroup(COLLISION_GROUP_DEBRIS) self:SetParent(ply) self.Wearer = ply ply.hat = self.Entity self:SetBeingWorn(true) LANG.Msg(ply, "hat_retrieve") end end local function TestHat(ply, cmd, args) if cvars.Bool("sv_cheats", 0) then local hat = ents.Create("ttt_hat_deerstalker") hat:SetPos(ply:GetPos() + Vector(0,0,70)) hat:SetAngles(ply:GetAngles()) hat:SetParent(ply) ply.hat = hat hat:Spawn() end end concommand.Add("ttt_debug_testhat", TestHat) end
mit
lichtl/darkstar
scripts/globals/spells/sinewy_etude.lua
27
1843
----------------------------------------- -- Spell: Sinewy Etude -- Static STR Boost, BRD 24 ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local sLvl = caster:getSkillLevel(SKILL_SNG); -- Gets skill level of Singing local iLvl = caster:getWeaponSkillLevel(SLOT_RANGED); local power = 0; if (sLvl+iLvl <= 181) then power = 3; elseif ((sLvl+iLvl >= 182) and (sLvl+iLvl <= 235)) then power = 4; elseif ((sLvl+iLvl >= 236) and (sLvl+iLvl <= 288)) then power = 5; elseif ((sLvl+iLvl >= 289) and (sLvl+iLvl <= 342)) then power = 6; elseif ((sLvl+iLvl >= 343) and (sLvl+iLvl <= 396)) then power = 7; elseif ((sLvl+iLvl >= 397) and (sLvl+iLvl <= 449)) then power = 8; elseif (sLvl+iLvl >= 450) then power = 9; end local iBoost = caster:getMod(MOD_ETUDE_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT); power = power + iBoost; if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then power = power * 2; elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then power = power * 1.5; end caster:delStatusEffect(EFFECT_MARCATO); local duration = 120; duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1); if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then duration = duration * 2; end if not (target:addBardSong(caster,EFFECT_ETUDE,power,0,duration,caster:getID(), MOD_STR, 1)) then spell:setMsg(75); end return EFFECT_ETUDE; end;
gpl-3.0
OctoEnigma/shiny-octo-system
gamemodes/darkrp/entities/entities/drug/cl_init.lua
12
1493
include("shared.lua") function ENT:Initialize() end function ENT:Draw() self:DrawModel() local Pos = self:GetPos() local Ang = self:GetAngles() local owner = self:Getowning_ent() owner = (IsValid(owner) and owner:Nick()) or DarkRP.getPhrase("unknown") surface.SetFont("HUDNumber5") local text = DarkRP.getPhrase("drugs") local text2 = DarkRP.getPhrase("priceTag", DarkRP.formatMoney(self:Getprice()), "") local TextWidth = surface.GetTextSize(text) local TextWidth2 = surface.GetTextSize(text2) Ang:RotateAroundAxis(Ang:Forward(), 90) local TextAng = Ang TextAng:RotateAroundAxis(TextAng:Right(), CurTime() * -180) cam.Start3D2D(Pos + Ang:Right() * -15, TextAng, 0.1) draw.WordBox(2, -TextWidth * 0.5 + 5, -30, text, "HUDNumber5", Color(140, 0, 0, 100), Color(255, 255, 255, 255)) draw.WordBox(2, -TextWidth2 * 0.5 + 5, 18, text2, "HUDNumber5", Color(140, 0, 0, 100), Color(255, 255, 255, 255)) cam.End3D2D() end function ENT:Think() end local function drugEffects(um) local toggle = um:ReadBool() LocalPlayer().isDrugged = toggle if toggle then hook.Add("RenderScreenspaceEffects", "drugged", function() DrawSharpen(-1, 2) DrawMaterialOverlay("models/props_lab/Tank_Glass001", 0) DrawMotionBlur(0.13, 1, 0.00) end) else hook.Remove("RenderScreenspaceEffects", "drugged") end end usermessage.Hook("DrugEffects", drugEffects)
mit
RunAwayDSP/darkstar
scripts/zones/Bastok_Markets/npcs/Ciqala.lua
12
1058
----------------------------------- -- Area: Bastok Markets -- NPC: Ciqala -- Type: Merchant -- !pos -283.147 -11.319 -143.680 235 ----------------------------------- local ID = require("scripts/zones/Bastok_Markets/IDs") require("scripts/globals/shop") function onTrigger(player,npc) local stock = { 16392, 4818, 1, -- Metal Knuckles 17044, 6033, 1, -- Warhammer 16390, 224, 3, -- Bronze Knuckles 16391, 828, 3, -- Brass Knuckles 16385, 129, 3, -- Cesti 16407, 1521, 3, -- Brass Baghnakhs 16405, 104, 3, -- Cat Baghnakhs 17042, 312, 3, -- Bronze Hammer 17043, 2083, 3, -- Brass Hammer 17049, 47, 3, -- Maple Wand 17024, 66, 3, -- Ash Club 17059, 90, 3, -- Bronze Rod 17081, 621, 3, -- Brass Rod 17088, 57, 3, -- Ash Staff 17095, 386, 3, -- Ash Pole } player:showText(npc, ID.text.CIQALA_SHOP_DIALOG) dsp.shop.nation(player, stock, dsp.nation.BASTOK) end
gpl-3.0
AntiSpamTelegram/Anti
plugins/stats.lua
866
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() == 'teleseed' 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 /teleseed ") 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] == "teleseed" 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) (teleseed)",-- Put everything you like :) "^[!/]([Tt]eleseed)"-- Put everything you like :) }, run = run } end
agpl-3.0
lichtl/darkstar
scripts/zones/Northern_San_dOria/npcs/Commojourt.lua
17
1568
----------------------------------- -- Area: Northern San d'Oria -- NPC: Commojourt -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Northern_San_dOria/TextIDs"); require("scripts/globals/settings"); require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script local FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then local count = trade:getItemCount(); local MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) rand = math.random(1,2); if (rand == 1) then player:startEvent(0x028d); else player:startEvent(0x0291); 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
Startg/permag
plugins/groupmanager-fa.lua
1
106896
local function modadd(msg) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_admin(msg) then if not lang then return '_You are not bot admin_' else return 'شما مدیر ربات نمیباشید😁' end end local data = load_data(_config.moderation.data) if data[tostring(msg.chat_id_)] then if not lang then return '_Group is already added_' else return 'گروه در لیست گروه های مدیریتی ربات هم اکنون موجود است' end end -- create data array in moderation.json data[tostring(msg.chat_id_)] = { owners = {}, mods ={}, banned ={}, is_silent_users ={}, filterlist ={}, settings = { lock_link = 'yes', lock_tag = 'yes', lock_fosh = 'yes', lock_spam = 'no', lock_webpage = 'yes', lock_arabic = 'no', lock_markdown = 'yes', flood = 'yes', lock_bots = 'yes', welcome = 'yes' }, mutes = { mute_forward = 'no', mute_audio = 'no', mute_video = 'no', mute_contact = 'no', mute_text = 'no', mute_photos = 'no', mute_gif = 'no', mute_location = 'no', mute_document = 'no', mute_sticker = 'no', mute_voice = 'no', mute_all = 'no' } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.chat_id_)] = msg.chat_id_ save_data(_config.moderation.data, data) if not lang then return '*Group has been added*' else return 'گروه با موفقیت به لیست گروه های مدیریتی ربات افزوده شد' end end local function modrem(msg) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then if not lang then return '_You are not bot admin_' else return 'شما مدیر ربات نمیباشید' end end local data = load_data(_config.moderation.data) local receiver = msg.chat_id_ if not data[tostring(msg.chat_id_)] then if not lang then return '_Group is not added_' else return 'گروه به لیست گروه های مدیریتی ربات اضافه نشده است' end end data[tostring(msg.chat_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.chat_id_)] = nil save_data(_config.moderation.data, data) if not lang then return '*Group has been removed*' else return 'گروه با موفیت از لیست گروه های مدیریتی ربات حذف شد' end end local function filter_word(msg, word) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) local data = load_data(_config.moderation.data) if not data[tostring(msg.chat_id_)]['filterlist'] then data[tostring(msg.chat_id_)]['filterlist'] = {} save_data(_config.moderation.data, data) end if data[tostring(msg.chat_id_)]['filterlist'][(word)] then if not lang then return "_Word_ *"..word.."* _is already filtered_" else return "_کلمه_ *"..word.."* _از قبل فیلتر بود_" end end data[tostring(msg.chat_id_)]['filterlist'][(word)] = true save_data(_config.moderation.data, data) if not lang then return "_Word_ *"..word.."* _added to filtered words list_" else return "_کلمه_ *"..word.."* _به لیست کلمات فیلتر شده اضافه شد_" end end local function unfilter_word(msg, word) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) local data = load_data(_config.moderation.data) if not data[tostring(msg.chat_id_)]['filterlist'] then data[tostring(msg.chat_id_)]['filterlist'] = {} save_data(_config.moderation.data, data) end if data[tostring(msg.chat_id_)]['filterlist'][word] then data[tostring(msg.chat_id_)]['filterlist'][(word)] = nil save_data(_config.moderation.data, data) if not lang then return "_Word_ *"..word.."* _removed from filtered words list_" elseif lang then return "_کلمه_ *"..word.."* _از لیست کلمات فیلتر شده حذف شد_" end else if not lang then return "_Word_ *"..word.."* _is not filtered_" elseif lang then return "_کلمه_ *"..word.."* _از قبل فیلتر نبود_" end end end local function modlist(msg) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) local data = load_data(_config.moderation.data) local i = 1 if not data[tostring(msg.chat_id_)] then if not lang then return "_Group is not added_" else return "گروه به لیست گروه های مدیریتی ربات اضافه نشده است" end end -- determine if table is empty if next(data[tostring(msg.chat_id_)]['mods']) == nil then --fix way if not lang then return "_No_ *moderator* _in this group_" else return "در حال حاضر هیچ مدیری برای گروه انتخاب نشده است" end end if not lang then message = '*List of moderators :*\n' else message = '*لیست مدیران گروه :*\n' end for k,v in pairs(data[tostring(msg.chat_id_)]['mods']) do message = message ..i.. '- '..v..' [' ..k.. '] \n' i = i + 1 end return message end local function ownerlist(msg) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) local data = load_data(_config.moderation.data) local i = 1 if not data[tostring(msg.chat_id_)] then if not lang then return "_Group is not added_" else return "گروه به لیست گروه های مدیریتی ربات اضافه نشده است" end end -- determine if table is empty if next(data[tostring(msg.chat_id_)]['owners']) == nil then --fix way if not lang then return "_No_ *owner* _in this group_" else return "در حال حاضر هیچ مالکی برای گروه انتخاب نشده است" end end if not lang then message = '*List of moderators :*\n' else message = '*لیست مدیران گروه :*\n' end for k,v in pairs(data[tostring(msg.chat_id_)]['owners']) do message = message ..i.. '- '..v..' [' ..k.. '] \n' i = i + 1 end return message end local function action_by_reply(arg, data) local hash = "gp_lang:"..data.chat_id_ local lang = redis:get(hash) local cmd = arg.cmd local administration = load_data(_config.moderation.data) if not tonumber(data.sender_user_id_) then return false end if data.sender_user_id_ then if not administration[tostring(data.chat_id_)] then if not lang then return tdcli.sendMessage(data.chat_id_, "", 0, "_Group is not added_", 0, "md") else return tdcli.sendMessage(data.chat_id_, "", 0, "_گروه به لیست گروه های مدیریتی ربات اضافه نشده است_", 0, "md") end end if cmd == "setowner" then local function owner_cb(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) local administration = load_data(_config.moderation.data) if data.username_ then user_name = '@'..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *group owner*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل صاحب گروه بود*", 0, "md") end end administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] = user_name save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is now the_ *group owner*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *به مقام صاحب گروه منتصب شد*", 0, "md") end end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, owner_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end if cmd == "promote" then local function promote_cb(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) local administration = load_data(_config.moderation.data) if data.username_ then user_name = '@'..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *moderator*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل مدیر گروه بود*", 0, "md") end end administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] = user_name save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *promoted*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *به مقام مدیر گروه منتصب شد*", 0, "md") end end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, promote_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end if cmd == "remowner" then local function rem_owner_cb(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) local administration = load_data(_config.moderation.data) if data.username_ then user_name = '@'..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if not administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *group owner*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* *از قبل صاحب گروه نبود*", 0, "md") end end administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] = nil save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is no longer a_ *group owner*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از مقام صاحب گروه برکنار شد*", 0, "md") end end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, rem_owner_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end if cmd == "demote" then local function demote_cb(arg, data) local administration = load_data(_config.moderation.data) if data.username_ then user_name = '@'..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if not administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *moderator*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل مدیر گروه نبود*", 0, "md") end end administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] = nil save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *demoted*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از مقام مدیر گروه برکنار شد*", 0, "md") end end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, demote_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end if cmd == "id" then local function id_cb(arg, data) return tdcli.sendMessage(arg.chat_id, "", 0, "*"..data.id_.."*", 0, "md") end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, id_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end else if lang then return tdcli.sendMessage(data.chat_id_, "", 0, "_کاربر یافت نشد_", 0, "md") else return tdcli.sendMessage(data.chat_id_, "", 0, "*User Not Found*", 0, "md") end end end local function action_by_username(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) local cmd = arg.cmd local administration = load_data(_config.moderation.data) if not administration[tostring(arg.chat_id)] then if not lang then return tdcli.sendMessage(data.chat_id_, "", 0, "_Group is not added_", 0, "md") else return tdcli.sendMessage(data.chat_id_, "", 0, "_گروه به لیست گروه های مدیریتی ربات اضافه نشده است_", 0, "md") end end if not arg.username then return false end if data.id_ then if data.type_.user_.username_ then user_name = '@'..check_markdown(data.type_.user_.username_) else user_name = check_markdown(data.title_) end if cmd == "setowner" then if administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *group owner*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل صاحب گروه بود*", 0, "md") end end administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] = user_name save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is now the_ *group owner*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *به مقام صاحب گروه منتصب شد*", 0, "md") end end if cmd == "promote" then if administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *moderator*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل مدیر گروه بود*", 0, "md") end end administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] = user_name save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *promoted*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *به مقام مدیر گروه منتصب شد*", 0, "md") end end if cmd == "remowner" then if not administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *group owner*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* *از قبل صاحب گروه نبود*", 0, "md") end end administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] = nil save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is no longer a_ *group owner*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از مقام صاحب گروه برکنار شد*", 0, "md") end end if cmd == "demote" then if not administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *moderator*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل مدیر گروه نبود*", 0, "md") end end administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] = nil save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *demoted*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از مقام مدیر گروه برکنار شد*", 0, "md") end end if cmd == "id" then return tdcli.sendMessage(arg.chat_id, "", 0, "*"..data.id_.."*", 0, "md") end if cmd == "res" then if not lang then text = "Result for [ ".. check_markdown(data.type_.user_.username_) .." ] :\n" .. "".. check_markdown(data.title_) .."\n" .. " [".. data.id_ .."]" else text = "اطلاعات برای [ ".. check_markdown(data.type_.user_.username_) .." ] :\n" .. "".. check_markdown(data.title_) .."\n" .. " [".. data.id_ .."]" return tdcli.sendMessage(arg.chat_id, 0, 1, text, 1, 'md') end end else if lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر یافت نشد_", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "*User Not Found*", 0, "md") end end end local function action_by_id(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) local cmd = arg.cmd local administration = load_data(_config.moderation.data) if not administration[tostring(arg.chat_id)] then if not lang then return tdcli.sendMessage(data.chat_id_, "", 0, "_Group is not added_", 0, "md") else return tdcli.sendMessage(data.chat_id_, "", 0, "_گروه به لیست گروه های مدیریتی ربات اضافه نشده است_", 0, "md") end end if not tonumber(arg.user_id) then return false end if data.id_ then if data.first_name_ then if data.username_ then user_name = '@'..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if cmd == "setowner" then if administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *group owner*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل صاحب گروه بود*", 0, "md") end end administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] = user_name save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is now the_ *group owner*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *به مقام صاحب گروه منتصب شد*", 0, "md") end end if cmd == "promote" then if administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *moderator*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل مدیر گروه بود*", 0, "md") end end administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] = user_name save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *promoted*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *به مقام مدیر گروه منتصب شد*", 0, "md") end end if cmd == "remowner" then if not administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *group owner*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* *از قبل صاحب گروه نبود*", 0, "md") end end administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] = nil save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is no longer a_ *group owner*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از مقام صاحب گروه برکنار شد*", 0, "md") end end if cmd == "demote" then if not administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *moderator*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل مدیر گروه نبود*", 0, "md") end end administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] = nil save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *demoted*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از مقام مدیر گروه برکنار شد*", 0, "md") end end if cmd == "whois" then if data.username_ then username = '@'..check_markdown(data.username_) else if not lang then username = 'not found' else username = 'ندارد' end end if not lang then return tdcli.sendMessage(arg.chat_id, 0, 1, 'Info for [ '..data.id_..' ] :\nUserName : '..username..'\nName : '..data.first_name_, 1) else return tdcli.sendMessage(arg.chat_id, 0, 1, 'اطلاعات برای [ '..data.id_..' ] :\nیوزرنیم : '..username..'\nنام : '..data.first_name_, 1) end end else if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User not founded_", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر یافت نشد_", 0, "md") end end else if lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر یافت نشد_", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "*User Not Found*", 0, "md") end end end ---------------Lock Link------------------- local function lock_link(msg, data, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_link = data[tostring(target)]["settings"]["lock_link"] if lock_link == "yes" then if not lang then return "🔒*Link* _Posting Is Already Locked_🔒" elseif lang then return "🔒ارسال لینک در گروه هم اکنون ممنوع است🔒" end else data[tostring(target)]["settings"]["lock_link"] = "yes" save_data(_config.moderation.data, data) if not lang then return "🔒*Link* _Posting Has Been Locked_🔒" else return "🔒ارسال لینک در گروه ممنوع شد🔒" end end end local function unlock_link(msg, data, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_link = data[tostring(target)]["settings"]["lock_link"] if lock_link == "no" then if not lang then return "🔓*Link* _Posting Is Not Locked_🔓" elseif lang then return "🔓ارسال لینک در گروه ممنوع نمیباشد🔓" end else data[tostring(target)]["settings"]["lock_link"] = "no" save_data(_config.moderation.data, data) if not lang then return "🔓*Link* _Posting Has Been Unlocked_🔓" else return "🔓ارسال لینک در گروه آزاد شد🔓" end end end ---------------Lock fosh------------------- local function lock_fosh(msg, data, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_fosh = data[tostring(target)]["settings"]["lock_fosh"] if lock_fosh == "yes" then if not lang then return "🔒*Fosh* _Posting Is Already Locked_🔒" elseif lang then return "🔒قفل فحش فعال است🔒" end else data[tostring(target)]["settings"]["lock_fosh"] = "yes" save_data(_config.moderation.data, data) if not lang then return "🔒*Fosh* _ Has Been Locked_🔒" else return "🔒قفل فحش فعال شد🔒" end end end local function unlock_fosh(msg, data, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_fosh = data[tostring(target)]["settings"]["lock_fosh"] if lock_fosh == "no" then if not lang then return "🔓*Fosh* _Is Not Locked_🔓" elseif lang then return "🔓قفل فحش غیرفعال میباشد🔓" end else data[tostring(target)]["settings"]["lock_fosh"] = "no" save_data(_config.moderation.data, data) if not lang then return "🔓*Fosh* _Has Been Unlocked_🔓" else return "🔓قفل فحش غیرفعال شد🔓" end end end ---------------Lock Tag------------------- local function lock_tag(msg, data, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_tag = data[tostring(target)]["settings"]["lock_tag"] if lock_tag == "yes" then if not lang then return "🔒*Tag* _Posting Is Already Locked_🔒" elseif lang then return "🔒ارسال تگ در گروه هم اکنون ممنوع است🔒" end else data[tostring(target)]["settings"]["lock_tag"] = "yes" save_data(_config.moderation.data, data) if not lang then return "🔒*Tag* _Posting Has Been Locked_🔒" else return "🔒ارسال تگ در گروه ممنوع شد🔒" end end end local function unlock_tag(msg, data, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_tag = data[tostring(target)]["settings"]["lock_tag"] if lock_tag == "no" then if not lang then return "🔓*Tag* _Posting Is Not Locked_🔓" elseif lang then return "🔓ارسال تگ در گروه ممنوع نمیباشد🔓" end else data[tostring(target)]["settings"]["lock_tag"] = "no" save_data(_config.moderation.data, data) if not lang then return "🔓*Tag* _Posting Has Been Unlocked_🔓" else return "🔓ارسال تگ در گروه آزاد شد🔓" end end end ---------------Lock Mention------------------- local function lock_mention(msg, data, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_mention = data[tostring(target)]["settings"]["lock_mention"] if lock_mention == "yes" then if not lang then return "🔒*Mention* _Posting Is Already Locked_🔒" elseif lang then return "🔒ارسال فراخوانی افراد هم اکنون ممنوع است🔒" end else data[tostring(target)]["settings"]["lock_mention"] = "yes" save_data(_config.moderation.data, data) if not lang then return "🔒*Mention* _Posting Has Been Locked_🔒" else return "🔒ارسال فراخوانی افراد در گروه ممنوع شد🔒" end end end local function unlock_mention(msg, data, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_mention = data[tostring(target)]["settings"]["lock_mention"] if lock_mention == "no" then if not lang then return "🔓*Mention* _Posting Is Not Locked_🔓" elseif lang then return "🔓ارسال فراخوانی افراد در گروه ممنوع نمیباشد🔓" end else data[tostring(target)]["settings"]["lock_mention"] = "no" save_data(_config.moderation.data, data) if not lang then return "🔓*Mention* _Posting Has Been Unlocked_🔓" else return "🔓ارسال فراخوانی افراد در گروه آزاد شد🔓" end end end ---------------Lock Arabic-------------- local function lock_arabic(msg, data, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_arabic = data[tostring(target)]["settings"]["lock_arabic"] if lock_arabic == "yes" then if not lang then return "🔒*Arabic/Persian* _Posting Is Already Locked_🔒" elseif lang then return "🔒ارسال کلمات عربی/فارسی در گروه هم اکنون ممنوع است🔒" end else data[tostring(target)]["settings"]["lock_arabic"] = "yes" save_data(_config.moderation.data, data) if not lang then return "🔒*Arabic/Persian* _Posting Has Been Locked_🔒" else return "🔒ارسال کلمات عربی/فارسی در گروه ممنوع شد🔒" end end end local function unlock_arabic(msg, data, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_arabic = data[tostring(target)]["settings"]["lock_arabic"] if lock_arabic == "no" then if not lang then return "🔓*Arabic/Persian* _Posting Is Not Locked_🔓" elseif lang then return "🔓ارسال کلمات عربی/فارسی در گروه ممنوع نمیباشد🔓" end else data[tostring(target)]["settings"]["lock_arabic"] = "no" save_data(_config.moderation.data, data) if not lang then return "🔓*Arabic/Persian* _Posting Has Been Unlocked_🔓" else return "🔓ارسال کلمات عربی/فارسی در گروه آزاد شد🔓" end end end ---------------Lock Edit------------------- local function lock_edit(msg, data, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_edit = data[tostring(target)]["settings"]["lock_edit"] if lock_edit == "yes" then if not lang then return "🔒*Editing* _Is Already Locked_🔒" elseif lang then return "🔒ویرایش پیام هم اکنون ممنوع است🔒" end else data[tostring(target)]["settings"]["lock_edit"] = "yes" save_data(_config.moderation.data, data) if not lang then return "🔒*Editing* _Has Been Locked_🔒" else return "🔒ویرایش پیام در گروه ممنوع شد🔒" end end end local function unlock_edit(msg, data, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_edit = data[tostring(target)]["settings"]["lock_edit"] if lock_edit == "no" then if not lang then return "🔓*Editing* _Is Not Locked_🔓" elseif lang then return "🔓ویرایش پیام در گروه ممنوع نمیباشد🔓" end else data[tostring(target)]["settings"]["lock_edit"] = "no" save_data(_config.moderation.data, data) if not lang then return "🔓*Editing* _Has Been Unlocked_🔓" else return "🔓ویرایش پیام در گروه آزاد شد🔓" end end end ---------------Lock spam------------------- local function lock_spam(msg, data, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_spam = data[tostring(target)]["settings"]["lock_spam"] if lock_spam == "yes" then if not lang then return "🔒*Spam* _Is Already Locked_🔒" elseif lang then return "🔒ارسال هرزنامه در گروه هم اکنون ممنوع است🔒" end else data[tostring(target)]["settings"]["lock_spam"] = "yes" save_data(_config.moderation.data, data) if not lang then return "🔒*Spam* _Has Been Locked_🔒" else return "🔒ارسال هرزنامه در گروه ممنوع شد🔒" end end end local function unlock_spam(msg, data, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_spam = data[tostring(target)]["settings"]["lock_spam"] if lock_spam == "no" then if not lang then return "🔓*Spam* _Posting Is Not Locked_🔓" elseif lang then return "🔓ارسال هرزنامه در گروه ممنوع نمیباشد🔓" end else data[tostring(target)]["settings"]["lock_spam"] = "no" save_data(_config.moderation.data, data) if not lang then return "🔓*Spam* _Posting Has Been Unlocked_🔓" else return "🔓ارسال هرزنامه در گروه آزاد شد🔓" end end end ---------------Lock Flood------------------- local function lock_flood(msg, data, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_flood = data[tostring(target)]["settings"]["flood"] if lock_flood == "yes" then if not lang then return "🔒*Flooding* _Is Already Locked_🔒" elseif lang then return "🔒ارسال پیام مکرر در گروه هم اکنون ممنوع است🔒" end else data[tostring(target)]["settings"]["flood"] = "yes" save_data(_config.moderation.data, data) if not lang then return "🔒*Flooding* _Has Been Locked_🔒" else return "🔒ارسال پیام مکرر در گروه ممنوع شد🔒" end end end local function unlock_flood(msg, data, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_flood = data[tostring(target)]["settings"]["flood"] if lock_flood == "no" then if not lang then return "🔓*Flooding* _Is Not Locked_🔓" elseif lang then return "🔓ارسال پیام مکرر در گروه ممنوع نمیباشد🔓" end else data[tostring(target)]["settings"]["flood"] = "no" save_data(_config.moderation.data, data) if not lang then return "🔓*Flooding* _Has Been Unlocked_🔓" else return "🔓ارسال پیام مکرر در گروه آزاد شد🔓" end end end ---------------Lock Bots------------------- local function lock_bots(msg, data, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_bots = data[tostring(target)]["settings"]["lock_bots"] if lock_bots == "yes" then if not lang then return "🔒*Bots* _Protection Is Already Enabled_🔒" elseif lang then return "🔒محافظت از گروه در برابر ربات ها هم اکنون فعال است🔒" end else data[tostring(target)]["settings"]["lock_bots"] = "yes" save_data(_config.moderation.data, data) if not lang then return "🔒*Bots* _Protection Has Been Enabled_🔒" else return "🔒محافظت از گروه در برابر ربات ها فعال شد🔒" end end end local function unlock_bots(msg, data, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_bots = data[tostring(target)]["settings"]["lock_bots"] if lock_bots == "no" then if not lang then return "🔓*Bots* _Protection Is Not Enabled_🔓" elseif lang then return "🔓محافظت از گروه در برابر ربات ها غیر فعال است🔓" end else data[tostring(target)]["settings"]["lock_bots"] = "no" save_data(_config.moderation.data, data) if not lang then return "🔓*Bots* _Protection Has Been Disabled_🔓" else return "🔓محافظت از گروه در برابر ربات ها غیر فعال شد🔓" end end end ---------------Lock Markdown------------------- local function lock_markdown(msg, data, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_markdown = data[tostring(target)]["settings"]["lock_markdown"] if lock_markdown == "yes" then if not lang then return "🔒*Markdown* _Posting Is Already Locked_🔒" elseif lang then return "🔒ارسال پیام های دارای فونت در گروه هم اکنون ممنوع است🔒" end else data[tostring(target)]["settings"]["lock_markdown"] = "yes" save_data(_config.moderation.data, data) if not lang then return "🔒*Markdown* _Posting Has Been Locked_🔒" else return "🔒ارسال پیام های دارای فونت در گروه ممنوع شد🔒" end end end local function unlock_markdown(msg, data, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_markdown = data[tostring(target)]["settings"]["lock_markdown"] if lock_markdown == "no" then if not lang then return "🔓*Markdown* _Posting Is Not Locked_🔓" elseif lang then return "🔓ارسال پیام های دارای فونت در گروه ممنوع نمیباشد🔓" end else data[tostring(target)]["settings"]["lock_markdown"] = "no" save_data(_config.moderation.data, data) if not lang then return "🔓*Markdown* _Posting Has Been Unlocked_🔓" else return "🔓ارسال پیام های دارای فونت در گروه آزاد شد🔓" end end end ---------------Lock Webpage------------------- local function lock_webpage(msg, data, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_webpage = data[tostring(target)]["settings"]["lock_webpage"] if lock_webpage == "yes" then if not lang then return "🔒*Webpage* _Is Already Locked_🔒" elseif lang then return "🔒ارسال صفحات وب در گروه هم اکنون ممنوع است🔒" end else data[tostring(target)]["settings"]["lock_webpage"] = "yes" save_data(_config.moderation.data, data) if not lang then return "🔒*Webpage* _Has Been Locked_🔒" else return "🔒ارسال صفحات وب در گروه ممنوع شد🔒" end end end local function unlock_webpage(msg, data, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_webpage = data[tostring(target)]["settings"]["lock_webpage"] if lock_webpage == "no" then if not lang then return "🔓*Webpage* _Is Not Locked_🔓" elseif lang then return "🔓ارسال صفحات وب در گروه ممنوع نمیباشد🔓" end else data[tostring(target)]["settings"]["lock_webpage"] = "no" save_data(_config.moderation.data, data) if not lang then return "🔓*Webpage* _Has Been Unlocked_🔓" else return "🔓ارسال صفحات وب در گروه آزاد شد🔓" end end end function group_settings(msg, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local data = load_data(_config.moderation.data) local target = msg.chat_id_ if data[tostring(target)] then if data[tostring(target)]["settings"]["num_msg_max"] then NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['num_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"]["lock_link"] then data[tostring(target)]["settings"]["lock_link"] = "yes" end end if data[tostring(target)]["settings"] then if not data[tostring(target)]["settings"]["lock_tag"] then data[tostring(target)]["settings"]["lock_tag"] = "yes" end end if data[tostring(target)]["settings"] then if not data[tostring(target)]["settings"]["lock_fosh"] then data[tostring(target)]["settings"]["lock_fosh"] = "yes" end end if data[tostring(target)]["settings"] then if not data[tostring(target)]["settings"]["lock_mention"] then data[tostring(target)]["settings"]["lock_mention"] = "no" end end if data[tostring(target)]["settings"] then if not data[tostring(target)]["settings"]["lock_arabic"] then data[tostring(target)]["settings"]["lock_arabic"] = "no" end end if data[tostring(target)]["settings"] then if not data[tostring(target)]["settings"]["lock_edit"] then data[tostring(target)]["settings"]["lock_edit"] = "no" end end if data[tostring(target)]["settings"] then if not data[tostring(target)]["settings"]["lock_spam"] then data[tostring(target)]["settings"]["lock_spam"] = "yes" end end if data[tostring(target)]["settings"] then if not data[tostring(target)]["settings"]["lock_flood"] then data[tostring(target)]["settings"]["lock_flood"] = "yes" end end if data[tostring(target)]["settings"] then if not data[tostring(target)]["settings"]["lock_bots"] then data[tostring(target)]["settings"]["lock_bots"] = "yes" end end if data[tostring(target)]["settings"] then if not data[tostring(target)]["settings"]["lock_markdown"] then data[tostring(target)]["settings"]["lock_markdown"] = "no" end end if data[tostring(target)]["settings"] then if not data[tostring(target)]["settings"]["lock_webpage"] then data[tostring(target)]["settings"]["lock_webpage"] = "no" end end if data[tostring(target)]["settings"] then if not data[tostring(target)]["settings"]["welcome"] then data[tostring(target)]["settings"]["welcome"] = "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"]["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_text"] then data[tostring(target)]["settings"]["mute_text"] = "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_video"] then data[tostring(target)]["settings"]["mute_video"] = "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_voice"] then data[tostring(target)]["settings"]["mute_voice"] = "no" end end if data[tostring(target)]["settings"] then if not data[tostring(target)]["settings"]["mute_sticker"] then data[tostring(target)]["settings"]["mute_sticker"] = "no" end end if data[tostring(target)]["settings"] then if not data[tostring(target)]["settings"]["mute_contact"] then data[tostring(target)]["settings"]["mute_contact"] = "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_location"] then data[tostring(target)]["settings"]["mute_location"] = "no" end end if data[tostring(target)]["settings"] then if not data[tostring(target)]["settings"]["mute_document"] then data[tostring(target)]["settings"]["mute_document"] = "no" end end if data[tostring(target)]["settings"] then if not data[tostring(target)]["settings"]["mute_tgservice"] then data[tostring(target)]["settings"]["mute_tgservice"] = "no" end end if data[tostring(target)]["settings"] then if not data[tostring(target)]["settings"]["mute_inline"] then data[tostring(target)]["settings"]["mute_inline"] = "no" end end if data[tostring(target)]["settings"] then if not data[tostring(target)]["settings"]["mute_game"] then data[tostring(target)]["settings"]["mute_game"] = "no" end end local expiretime = redis:hget('expiretime', msg.chat_id_) local expire = '' if not expiretime then expire = expire..'Unlimited' else local now = tonumber(os.time()) expire = expire..math.floor((tonumber(expiretime) - tonumber(now)) / 86400) + 1 end if not lang then local settings = data[tostring(target)]["settings"] text = "🔰*Group Settings*🔰\n\n🔐_Lock edit :_ *"..settings.lock_edit.."*\n🔐_Lock links :_ *"..settings.lock_link.."*\n🔐_Lock fosh :_ *"..settings.lock_fosh.."*\n🔐_Lock tags :_ *"..settings.lock_tag.."*\n🔐_Lock Persian* :_ *"..settings.lock_arabic.."*\n🔐_Lock flood :_ *"..settings.flood.."*\n🔐_Lock spam :_ *"..settings.lock_spam.."*\n🔐_Lock mention :_ *"..settings.lock_mention.."*\n🔐_Lock webpage :_ *"..settings.lock_webpage.."*\n🔐_Lock markdown :_ *"..settings.lock_markdown.."*\n🔐_Bots protection :_ *"..settings.lock_bots.."*\n🔐_Flood sensitivity :_ *"..NUM_MSG_MAX.."*\n✋_welcome :_ *"..settings.welcome.."*\n\n 🔊Group Mute List 🔊 \n\n🔇_Mute all : _ *"..settings.mute_all.."*\n🔇_Mute gif :_ *"..settings.mute_gif.."*\n🔇_Mute text :_ *"..settings.mute_text.."*\n🔇_Mute inline :_ *"..settings.mute_inline.."*\n🔇_Mute game :_ *"..settings.mute_game.."*\n🔇_Mute photo :_ *"..settings.mute_photo.."*\n🔇_Mute video :_ *"..settings.mute_video.."*\n🔇_Mute audio :_ *"..settings.mute_audio.."*\n🔇_Mute voice :_ *"..settings.mute_voice.."*\n🔇_Mute sticker :_ *"..settings.mute_sticker.."*\n🔇_Mute contact :_ *"..settings.mute_contact.."*\n🔇_Mute forward :_ *"..settings.mute_forward.."*\n🔇_Mute location :_ *"..settings.mute_location.."*\n🔇_Mute document :_ *"..settings.mute_document.."*\n🔇_Mute TgService :_ *"..settings.mute_tgservice.."*\n*__________________*\n⏱_expire time :_ *"..expire.."*\n*____________________*\n*Language* : *EN*" else local settings = data[tostring(target)]["settings"] text = "🔰*تنظیمات گروه*🔰\n\n🔐_قفل ویرایش پیام :_ *"..settings.lock_edit.."*\n🔐_قفل لینک :_ *"..settings.lock_link.."*\n🔐_قفل فحش :_ *"..settings.lock_fosh.."*\n🔐_قفل تگ :_ *"..settings.lock_tag.."*\n🔐_قفل فارسی* :_ *"..settings.lock_arabic.."*\n🔐_قفل پیام مکرر :_ *"..settings.flood.."*\n🔐_قفل هرزنامه :_ *"..settings.lock_spam.."*\n🔐_قفل فراخوانی :_ *"..settings.lock_mention.."*\n🔐_قفل صفحات وب :_ *"..settings.lock_webpage.."*\n🔐_قفل فونت :_ *"..settings.lock_markdown.."*\n🔐_محافظت در برابر ربات ها :_ *"..settings.lock_bots.."*\n🔐_حداکثر پیام مکرر :_ *"..NUM_MSG_MAX.."*\n✋_پیام خوش آمد گویی :_ *"..settings.welcome.."*\n\n 🔊لیست ممنوعیت ها 🔊 \n\n🔇_ممنوع کردن همه : _ *"..settings.mute_all.."*\n🔇_ممنوع کردن تصاویر متحرک :_ *"..settings.mute_gif.."*\n🔇_ممنوع کردن متن :_ *"..settings.mute_text.."*\n🔇_تبلیغات شیشه ای ممنوع :_ *"..settings.mute_inline.."*\n🔇_ممنوع کردن بازی :_ *"..settings.mute_game.."*\n🔇_ممنوع کردن عکس :_ *"..settings.mute_photo.."*\n🔇_ممنوع کردن فیلم :_ *"..settings.mute_video.."*\n🔇_ممنوع کردن آهنگ :_ *"..settings.mute_audio.."*\n🔇_ممنوع کردن صدا :_ *"..settings.mute_voice.."*\n🔇_ممنوع کردن استیکر :_ *"..settings.mute_sticker.."*\n🔇_ممنوع کردن ارسال اطلاعات :_ *"..settings.mute_contact.."*\n🔇_ممنوع کردن فوروارد :_ *"..settings.mute_forward.."*\n🔇_ممنوع کردن ارسال مکان :_ *"..settings.mute_location.."*\n🔇_ممنوع کردن ارسال فایل :_ *"..settings.mute_document.."*\n🔇_ممنوع کردن اعلانات :_ *"..settings.mute_tgservice.."*\n*__________________*\n⏱_تاریخ انقضا :_ *"..expire.."*\n*____________________*\n*زبان ربات* : *فارسی*" end return text end --------Mutes--------- --------Mute all------------------------ local function mute_all(msg, data, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_all = data[tostring(target)]["settings"]["mute_all"] if mute_all == "yes" then if not lang then return "🔇*Mute All* _Is Already Enabled_🔇" elseif lang then return "🔇بیصدا کردن همه فعال است🔇" end else data[tostring(target)]["settings"]["mute_all"] = "yes" save_data(_config.moderation.data, data) if not lang then return "🔇*Mute All* _Has Been Enabled_🔇" else return "🔇بیصدا کردن همه فعال شد🔇" end end end local function unmute_all(msg, data, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_all = data[tostring(target)]["settings"]["mute_all"] if mute_all == "no" then if not lang then return "🔊*Mute All* _Is Already Disabled_🔊" elseif lang then return "🔊بیصدا کردن همه غیر فعال است🔊" end else data[tostring(target)]["settings"]["mute_all"] = "no" save_data(_config.moderation.data, data) if not lang then return "🔊*Mute All* _Has Been Disabled_🔊" else return "🔊بیصدا کردن همه غیر فعال شد🔊" end end end ---------------Mute Gif------------------- local function mute_gif(msg, data, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_gif = data[tostring(target)]["settings"]["mute_gif"] if mute_gif == "yes" then if not lang then return "🔇*Mute Gif* _Is Already Enabled_🔇" elseif lang then return "🔇بیصدا کردن تصاویر متحرک فعال است🔇" end else data[tostring(target)]["settings"]["mute_gif"] = "yes" save_data(_config.moderation.data, data) if not lang then return "🔊*Mute Gif* _Has Been Enabled_🔊" else return "🔊بیصدا کردن تصاویر متحرک فعال شد🔊" end end end local function unmute_gif(msg, data, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_gif = data[tostring(target)]["settings"]["mute_gif"] if mute_gif == "no" then if not lang then return "🔇*Mute Gif* _Is Already Disabled_🔇" elseif lang then return "🔇بیصدا کردن تصاویر متحرک غیر فعال بود🔇" end else data[tostring(target)]["settings"]["mute_gif"] = "no" save_data(_config.moderation.data, data) if not lang then return "🔇*Mute Gif* _Has Been Disabled_🔇" else return "🔇بیصدا کردن تصاویر متحرک غیر فعال شد🔇" end end end ---------------Mute Game------------------- local function mute_game(msg, data, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_game = data[tostring(target)]["settings"]["mute_game"] if mute_game == "yes" then if not lang then return "🔇*Mute Game* _Is Already Enabled_🔇" elseif lang then return "🔇بیصدا کردن بازی های تحت وب فعال است🔇" end else data[tostring(target)]["settings"]["mute_game"] = "yes" save_data(_config.moderation.data, data) if not lang then return "🔇*Mute Game* _Has Been Enabled_🔇" else return "🔇بیصدا کردن بازی های تحت وب فعال شد🔇" end end end local function unmute_game(msg, data, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_game = data[tostring(target)]["settings"]["mute_game"] if mute_game == "no" then if not lang then return "🔊*Mute Game* _Is Already Disabled_🔊" elseif lang then return "🔊بیصدا کردن بازی های تحت وب غیر فعال است🔊" end else data[tostring(target)]["settings"]["mute_game"] = "no" save_data(_config.moderation.data, data) if not lang then return "🔊*Mute Game* _Has Been Disabled_🔊" else return "🔊بیصدا کردن بازی های تحت وب غیر فعال شد🔊" end end end ---------------Mute Inline------------------- local function mute_inline(msg, data, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_inline = data[tostring(target)]["settings"]["mute_inline"] if mute_inline == "yes" then if not lang then return "🔇*Mute Inline* _Is Already Enabled_🔇" elseif lang then return "🔇بیصدا کردن کیبورد شیشه ای فعال است🔇" end else data[tostring(target)]["settings"]["mute_inline"] = "yes" save_data(_config.moderation.data, data) if not lang then return "🔇*Mute Inline* _Has Been Enabled_🔇" else return "🔇بیصدا کردن کیبورد شیشه ای فعال شد🔇" end end end local function unmute_inline(msg, data, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_inline = data[tostring(target)]["settings"]["mute_inline"] if mute_inline == "no" then if not lang then return "🔊*Mute Inline* _Is Already Disabled_🔊" elseif lang then return "🔊بیصدا کردن کیبورد شیشه ای غیر فعال است🔊" end else data[tostring(target)]["settings"]["mute_inline"] = "no" save_data(_config.moderation.data, data) if not lang then return "🔊*Mute Inline* _Has Been Disabled_🔊" else return "🔊بیصدا کردن کیبورد شیشه ای غیر فعال شد🔊" end end end ---------------Mute Text------------------- local function mute_text(msg, data, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_text = data[tostring(target)]["settings"]["mute_text"] if mute_text == "yes" then if not lang then return "🔇*Mute Text* _Is Already Enabled_🔇" elseif lang then return "🔇بیصدا کردن متن فعال است🔇" end else data[tostring(target)]["settings"]["mute_text"] = "yes" save_data(_config.moderation.data, data) if not lang then return "🔇*Mute Text* _Has Been Enabled_🔇" else return "🔇بیصدا کردن متن فعال شد🔇" end end end local function unmute_text(msg, data, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_text = data[tostring(target)]["settings"]["mute_text"] if mute_text == "no" then if not lang then return "🔊*Mute Text* _Is Already Disabled_🔊" elseif lang then return "🔊بیصدا کردن متن غیر فعال است🔊" end else data[tostring(target)]["settings"]["mute_text"] = "no" save_data(_config.moderation.data, data) if not lang then return "🔊*Mute Text* _Has Been Disabled_🔊" else return "🔊بیصدا کردن متن غیر فعال شد🔊" end end end ---------------Mute photo------------------- local function mute_photo(msg, data, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "🔇_You're Not_ *Moderator*🔇" else return "🔇شما مدیر گروه نمیباشید🔇" end end local mute_photo = data[tostring(target)]["settings"]["mute_photo"] if mute_photo == "yes" then if not lang then return "🔇*Mute Photo* _Is Already Enabled_🔇" elseif lang then return "🔇بیصدا کردن عکس فعال است🔇" end else data[tostring(target)]["settings"]["mute_photo"] = "yes" save_data(_config.moderation.data, data) if not lang then return "🔇*Mute Photo* _Has Been Enabled_🔇" else return "🔇بیصدا کردن عکس فعال شد🔇" end end end local function unmute_photo(msg, data, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_photo = data[tostring(target)]["settings"]["mute_photo"] if mute_photo == "no" then if not lang then return "🔊*Mute Photo* _Is Already Disabled_🔊" elseif lang then return "🔊بیصدا کردن عکس غیر فعال است🔊" end else data[tostring(target)]["settings"]["mute_photo"] = "no" save_data(_config.moderation.data, data) if not lang then return "🔊*Mute Photo* _Has Been Disabled_🔊" else return "🔊بیصدا کردن عکس غیر فعال شد🔊" end end end ---------------Mute Video------------------- local function mute_video(msg, data, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_video = data[tostring(target)]["settings"]["mute_video"] if mute_video == "yes" then if not lang then return "🔇*Mute Video* _Is Already Enabled_🔇" elseif lang then return "🔇بیصدا کردن فیلم فعال است🔇" end else data[tostring(target)]["settings"]["mute_video"] = "yes" save_data(_config.moderation.data, data) if not lang then return "🔇*Mute Video* _Has Been Enabled_🔇" else return "🔇بیصدا کردن فیلم فعال شد🔇" end end end local function unmute_video(msg, data, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_video = data[tostring(target)]["settings"]["mute_video"] if mute_video == "no" then if not lang then return "🔊*Mute Video* _Is Already Disabled_🔊" elseif lang then return "🔊بیصدا کردن فیلم غیر فعال است🔊" end else data[tostring(target)]["settings"]["mute_video"] = "no" save_data(_config.moderation.data, data) if not lang then return "🔊*Mute Video* _Has Been Disabled_🔊" else return "🔊بیصدا کردن فیلم غیر فعال شد🔊" end end end ---------------Mute Audio------------------- local function mute_audio(msg, data, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_audio = data[tostring(target)]["settings"]["mute_audio"] if mute_audio == "yes" then if not lang then return "🔇*Mute Audio* _Is Already Enabled_🔇" elseif lang then return "🔇بیصدا کردن آهنگ فعال است🔇" end else data[tostring(target)]["settings"]["mute_audio"] = "yes" save_data(_config.moderation.data, data) if not lang then return "🔇*Mute Audio* _Has Been Enabled_🔇" else return "🔇بیصدا کردن آهنگ فعال شد🔇" end end end local function unmute_audio(msg, data, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_audio = data[tostring(target)]["settings"]["mute_audio"] if mute_audio == "no" then if not lang then return "🔊*Mute Audio* _Is Already Disabled_🔊" elseif lang then return "🔊بیصدا کردن آهنک غیر فعال است🔊" end else data[tostring(target)]["settings"]["mute_audio"] = "no" save_data(_config.moderation.data, data) if not lang then return "🔊*Mute Audio* _Has Been Disabled_🔊" else return "🔊بیصدا کردن آهنگ غیر فعال شد🔊" end end end ---------------Mute Voice------------------- local function mute_voice(msg, data, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_voice = data[tostring(target)]["settings"]["mute_voice"] if mute_voice == "yes" then if not lang then return "🔇*Mute Voice* _Is Already Enabled_🔇" elseif lang then return "🔇بیصدا کردن صدا فعال است🔇" end else data[tostring(target)]["settings"]["mute_voice"] = "yes" save_data(_config.moderation.data, data) if not lang then return "🔇*Mute Voice* _Has Been Enabled_🔇" else return "🔇بیصدا کردن صدا فعال شد🔇" end end end local function unmute_voice(msg, data, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_voice = data[tostring(target)]["settings"]["mute_voice"] if mute_voice == "no" then if not lang then return "🔊*Mute Voice* _Is Already Disabled_🔊" elseif lang then return "🔊بیصدا کردن صدا غیر فعال است🔊" end else data[tostring(target)]["settings"]["mute_voice"] = "no" save_data(_config.moderation.data, data) if not lang then return "🔊*Mute Voice* _Has Been Disabled_🔊" else return "🔊بیصدا کردن صدا غیر فعال شد🔊" end end end ---------------Mute Sticker------------------- local function mute_sticker(msg, data, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_sticker = data[tostring(target)]["settings"]["mute_sticker"] if mute_sticker == "yes" then if not lang then return "🔇*Mute Sticker* _Is Already Enabled_🔇" elseif lang then return "🔇بیصدا کردن برچسب فعال است🔇" end else data[tostring(target)]["settings"]["mute_sticker"] = "yes" save_data(_config.moderation.data, data) if not lang then return "🔇*Mute Sticker* _Has Been Enabled_🔇" else return "🔇بیصدا کردن برچسب فعال شد🔇" end end end local function unmute_sticker(msg, data, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_sticker = data[tostring(target)]["settings"]["mute_sticker"] if mute_sticker == "no" then if not lang then return "🔊*Mute Sticker* _Is Already Disabled_🔊" elseif lang then return "🔊بیصدا کردن برچسب غیر فعال است🔊" end else data[tostring(target)]["settings"]["mute_sticker"] = "no" save_data(_config.moderation.data, data) if not lang then return "🔊*Mute Sticker* _Has Been Disabled_🔊" else return "🔊بیصدا کردن برچسب غیر فعال شد🔊" end end end ---------------Mute Contact------------------- local function mute_contact(msg, data, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_contact = data[tostring(target)]["settings"]["mute_contact"] if mute_contact == "yes" then if not lang then return "🔇*Mute Contact* _Is Already Enabled_🔇" elseif lang then return "🔇بیصدا کردن مخاطب فعال است🔇" end else data[tostring(target)]["settings"]["mute_contact"] = "yes" save_data(_config.moderation.data, data) if not lang then return "🔇*Mute Contact* _Has Been Enabled_🔇" else return "🔇بیصدا کردن مخاطب فعال شد🔇" end end end local function unmute_contact(msg, data, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_contact = data[tostring(target)]["settings"]["mute_contact"] if mute_contact == "no" then if not lang then return "🔊*Mute Contact* _Is Already Disabled_🔊" elseif lang then return "🔊بیصدا کردن مخاطب غیر فعال است🔊" end else data[tostring(target)]["settings"]["mute_contact"] = "no" save_data(_config.moderation.data, data) if not lang then return "🔊*Mute Contact* _Has Been Disabled_🔊" else return "🔊بیصدا کردن مخاطب غیر فعال شد🔊" end end end ---------------Mute Forward------------------- local function mute_forward(msg, data, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_forward = data[tostring(target)]["settings"]["mute_forward"] if mute_forward == "yes" then if not lang then return "🔇*Mute Forward* _Is Already Enabled_🔇" elseif lang then return "🔇بیصدا کردن نقل قول فعال است🔇" end else data[tostring(target)]["settings"]["mute_forward"] = "yes" save_data(_config.moderation.data, data) if not lang then return "🔇*Mute Forward* _Has Been Enabled_🔇" else return "🔇بیصدا کردن نقل قول فعال شد🔇" end end end local function unmute_forward(msg, data, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_forward = data[tostring(target)]["settings"]["mute_forward"] if mute_forward == "no" then if not lang then return "🔊*Mute Forward* _Is Already Disabled_🔊" elseif lang then return "🔊بیصدا کردن نقل قول غیر فعال است🔊" end else data[tostring(target)]["settings"]["mute_forward"] = "no" save_data(_config.moderation.data, data) if not lang then return "🔊*Mute Forward* _Has Been Disabled_🔊" else return "🔊بیصدا کردن نقل قول غیر فعال شد🔊" end end end ---------------Mute Location------------------- local function mute_location(msg, data, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_location = data[tostring(target)]["settings"]["mute_location"] if mute_location == "yes" then if not lang then return "🔇*Mute Location* _Is Already Enabled_🔇" elseif lang then return "🔇بیصدا کردن موقعیت فعال است🔇" end else data[tostring(target)]["settings"]["mute_location"] = "yes" save_data(_config.moderation.data, data) if not lang then return "🔇*Mute Location* _Has Been Enabled_🔇" else return "🔇بیصدا کردن موقعیت فعال شد🔇" end end end local function unmute_location(msg, data, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_location = data[tostring(target)]["settings"]["mute_location"] if mute_location == "no" then if not lang then return "🔊*Mute Location* _Is Already Disabled_🔊" elseif lang then return "🔊بیصدا کردن موقعیت غیر فعال است🔊" end else data[tostring(target)]["settings"]["mute_location"] = "no" save_data(_config.moderation.data, data) if not lang then return "🔊*Mute Location* _Has Been Disabled_🔊" else return "🔊بیصدا کردن موقعیت غیر فعال شد🔊" end end end ---------------Mute Document------------------- local function mute_document(msg, data, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_document = data[tostring(target)]["settings"]["mute_document"] if mute_document == "yes" then if not lang then return "🔇*Mute Document* _Is Already Enabled_🔇" elseif lang then return "🔇بیصدا کردن اسناد فعال است🔇" end else data[tostring(target)]["settings"]["mute_document"] = "yes" save_data(_config.moderation.data, data) if not lang then return "🔇*Mute Document* _Has Been Enabled_🔇" else return "🔇بیصدا کردن اسناد فعال شد🔇" end end end local function unmute_document(msg, data, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_document = data[tostring(target)]["settings"]["mute_document"] if mute_document == "no" then if not lang then return "🔊*Mute Document* _Is Already Disabled_🔊" elseif lang then return "🔊بیصدا کردن اسناد غیر فعال است🔊" end else data[tostring(target)]["settings"]["mute_document"] = "no" save_data(_config.moderation.data, data) if not lang then return "🔊*Mute Document* _Has Been Disabled_🔊" else return "🔊بیصدا کردن اسناد غیر فعال شد🔊" end end end ---------------Mute TgService------------------- local function mute_tgservice(msg, data, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_tgservice = data[tostring(target)]["settings"]["mute_tgservice"] if mute_tgservice == "yes" then if not lang then return "🔇*Mute TgService* _Is Already Enabled_🔇" elseif lang then return "🔇بیصدا کردن خدمات تلگرام فعال است🔇" end else data[tostring(target)]["settings"]["mute_tgservice"] = "yes" save_data(_config.moderation.data, data) if not lang then return "🔇*Mute TgService* _Has Been Enabled_🔇" else return "🔇بیصدا کردن خدمات تلگرام فعال شد🔇" end end end local function unmute_tgservice(msg, data, target) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نیستید" end end local mute_tgservice = data[tostring(target)]["settings"]["mute_tgservice"] if mute_tgservice == "no" then if not lang then return "🔊*Mute TgService* _Is Already Disabled_🔊" elseif lang then return "🔊بیصدا کردن خدمات تلگرام غیر فعال است🔊" end else data[tostring(target)]["settings"]["mute_tgservice"] = "no" save_data(_config.moderation.data, data) if not lang then return "🔊*Mute TgService* _Has Been Disabled_🔊" else return "🔊بیصدا کردن خدمات تلگرام غیر فعال شد🔊" end end end local function run(msg, matches) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) local data = load_data(_config.moderation.data) local chat = msg.chat_id_ local user = msg.sender_user_id_ if matches[1] == "ایدی" then if not matches[2] and tonumber(msg.reply_to_message_id_) == 0 then if not lang then return "*Chat ID :* _"..chat.."_\n*User ID :* _"..user.."_" else return "*شناسه گروه :* _"..chat.."_\n*شناسه شما :* _"..user.."_" end end if not matches[2] and tonumber(msg.reply_to_message_id_) ~= 0 then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.reply_to_message_id_ }, action_by_reply, {chat_id=msg.chat_id_,cmd="id"}) end if matches[2] and tonumber(msg.reply_to_message_id_) == 0 then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, action_by_username, {chat_id=msg.chat_id_,username=matches[2],cmd="id"}) end end if matches[1] == "سنجاق کردن" and is_owner(msg) then tdcli.pinChannelMessage(msg.chat_id_, msg.reply_to_message_id_, 1) if not lang then return "*Message Has Been Pinned*" else return "پیام سجاق شد" end end if matches[1] == 'حذف سنجاق' and is_mod(msg) then tdcli.unpinChannelMessage(msg.chat_id_) if not lang then return "*Pin message has been unpinned*" else return "پیام سنجاق شده پاک شد" end end if matches[1] == "نصب" then return modadd(msg) end if matches[1] == "حذف" then return modrem(msg) end if matches[1] == "انتخاب مدیر" and is_admin(msg) then if not matches[2] and tonumber(msg.reply_to_message_id_) ~= 0 then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.reply_to_message_id_ }, action_by_reply, {chat_id=msg.chat_id_,cmd="setowner"}) end if matches[2] and string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "GetUser", user_id_ = matches[2], }, action_by_id, {chat_id=msg.chat_id_,user_id=matches[2],cmd="setowner"}) end if matches[2] and not string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, action_by_username, {chat_id=msg.chat_id_,username=matches[2],cmd="setowner"}) end end if matches[1] == "حذف مدیر" and is_admin(msg) then if not matches[2] and tonumber(msg.reply_to_message_id_) ~= 0 then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.reply_to_message_id_ }, action_by_reply, {chat_id=msg.chat_id_,cmd="remowner"}) end if matches[2] and string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "GetUser", user_id_ = matches[2], }, action_by_id, {chat_id=msg.chat_id_,user_id=matches[2],cmd="remowner"}) end if matches[2] and not string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, action_by_username, {chat_id=msg.chat_id_,username=matches[2],cmd="remowner"}) end end if matches[1] == "انتخاب ناظر" and is_owner(msg) then if not matches[2] and tonumber(msg.reply_to_message_id_) ~= 0 then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.reply_to_message_id_ }, action_by_reply, {chat_id=msg.chat_id_,cmd="promote"}) end if matches[2] and string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "GetUser", user_id_ = matches[2], }, action_by_id, {chat_id=msg.chat_id_,user_id=matches[2],cmd="promote"}) end if matches[2] and not string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, action_by_username, {chat_id=msg.chat_id_,username=matches[2],cmd="promote"}) end end if matches[1] == "حذف ناظر" and is_owner(msg) then if not matches[2] and tonumber(msg.reply_to_message_id_) ~= 0 then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.reply_to_message_id_ }, action_by_reply, {chat_id=msg.chat_id_,cmd="demote"}) end if matches[2] and string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "GetUser", user_id_ = matches[2], }, action_by_id, {chat_id=msg.chat_id_,user_id=matches[2],cmd="demote"}) end if matches[2] and not string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, action_by_username, {chat_id=msg.chat_id_,username=matches[2],cmd="demote"}) end end if matches[1] == "قفل" and is_mod(msg) then local target = msg.chat_id_ if matches[2] == "لینک" then return lock_link(msg, data, target) end if matches[2] == "فحش" then return lock_fosh(msg, data, target) end if matches[2] == "تگ" then return lock_tag(msg, data, target) end if matches[2] == "هایپرلینک" then return lock_mention(msg, data, target) end if matches[2] == "عربی" then return lock_arabic(msg, data, target) end if matches[2] == "ویرایش" then return lock_edit(msg, data, target) end if matches[2] == "اسپم" then return lock_spam(msg, data, target) end if matches[2] == "فلود" then return lock_flood(msg, data, target) end if matches[2] == "ربات" then return lock_bots(msg, data, target) end if matches[2] == "فونت" then return lock_markdown(msg, data, target) end if matches[2] == "وبسایت" then return lock_webpage(msg, data, target) end end if matches[1] == "باز کردن" and is_mod(msg) then local target = msg.chat_id_ if matches[2] == "لینک" then return unlock_link(msg, data, target) end if matches[2] == "فحش" then return unlock_fosh(msg, data, target) end if matches[2] == "تگ" then return unlock_tag(msg, data, target) end if matches[2] == "هایپرلینک" then return unlock_mention(msg, data, target) end if matches[2] == "عربی" then return unlock_arabic(msg, data, target) end if matches[2] == "ویرایش" then return unlock_edit(msg, data, target) end if matches[2] == "اسپم" then return unlock_spam(msg, data, target) end if matches[2] == "فلود" then return unlock_flood(msg, data, target) end if matches[2] == "ربات" then return unlock_bots(msg, data, target) end if matches[2] == "فونت" then return unlock_markdown(msg, data, target) end if matches[2] == "وبسایت" then return unlock_webpage(msg, data, target) end end if matches[1] == "ممنوعیت" and is_mod(msg) then local target = msg.chat_id_ if matches[2] == "همه چیز" then return mute_all(msg, data, target) end if matches[2] == "گیف" then return mute_gif(msg, data, target) end if matches[2] == "متن" then return mute_text(msg ,data, target) end if matches[2] == "عکس" then return mute_photo(msg ,data, target) end if matches[2] == "فیلم" then return mute_video(msg ,data, target) end if matches[2] == "موزیک" then return mute_audio(msg ,data, target) end if matches[2] == "صدا" then return mute_voice(msg ,data, target) end if matches[2] == "استیکر" then return mute_sticker(msg ,data, target) end if matches[2] == "اطلاعات تماس" then return mute_contact(msg ,data, target) end if matches[2] == "فوروارد" then return mute_forward(msg ,data, target) end if matches[2] == "مکان" then return mute_location(msg ,data, target) end if matches[2] == "فایل" then return mute_document(msg ,data, target) end if matches[2] == "اعلانات" then return mute_tgservice(msg ,data, target) end if matches[2] == "اینلاین" then return mute_inline(msg ,data, target) end if matches[2] == "بازی" then return mute_game(msg ,data, target) end end if matches[1] == "رفع ممنوعیت" and is_mod(msg) then local target = msg.chat_id_ if matches[2] == "همه چیز" then return unmute_all(msg, data, target) end if matches[2] == "گیف" then return unmute_gif(msg, data, target) end if matches[2] == "متن" then return unmute_text(msg, data, target) end if matches[2] == "عکس" then return unmute_photo(msg ,data, target) end if matches[2] == "فیلم" then return unmute_video(msg ,data, target) end if matches[2] == "موزیک" then return unmute_audio(msg ,data, target) end if matches[2] == "صدا" then return unmute_voice(msg ,data, target) end if matches[2] == "استیکر" then return unmute_sticker(msg ,data, target) end if matches[2] == "مخاطب" then return unmute_contact(msg ,data, target) end if matches[2] == "فوروارد" then return unmute_forward(msg ,data, target) end if matches[2] == "مکان" then return unmute_location(msg ,data, target) end if matches[2] == "فایل" then return unmute_document(msg ,data, target) end if matches[2] == "اعلانات" then return unmute_tgservice(msg ,data, target) end if matches[2] == "اینلاین" then return unmute_inline(msg ,data, target) end if matches[2] == "بازی" then return unmute_game(msg ,data, target) end end if matches[1] == "اطلاعات گروه" and is_mod(msg) and gp_type(msg.chat_id_) == "channel" then local function group_info(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) if not lang then ginfo = "*📢Group Info :*📢\n👲_Admin Count :_ *"..data.administrator_count_.."*\n👥_Member Count :_ *"..data.member_count_.."*\n👿_Kicked Count :_ *"..data.kicked_count_.."*\n🆔_Group ID :_ *"..data.channel_.id_.."*" print(serpent.block(data)) elseif lang then ginfo = "📢*اطلاعات گروه *📢\n👲_تعداد مدیران :_ *"..data.administrator_count_.."*\n👥_تعداد اعضا :_ *"..data.member_count_.."*\n👿_تعداد اعضای حذف شده :_ *"..data.kicked_count_.."*\n🆔_شناسه گروه :_ *"..data.channel_.id_.."*" print(serpent.block(data)) end tdcli.sendMessage(arg.chat_id, arg.msg_id, 1, ginfo, 1, 'md') end tdcli.getChannelFull(msg.chat_id_, group_info, {chat_id=msg.chat_id_,msg_id=msg.id_}) end if matches[1] == 'تنظیم لینک' and is_owner(msg) then data[tostring(chat)]['settings']['linkgp'] = 'waiting' save_data(_config.moderation.data, data) if not lang then return '_Please send the new group_ *link* _now_' else return 'لطفا لینک گروه خود را ارسال کنید' end end if msg.content_.text_ then local is_link = msg.content_.text_:match("^([https?://w]*.?telegram.me/joinchat/%S+)$") or msg.content_.text_:match("^([https?://w]*.?t.me/joinchat/%S+)$") if is_link and data[tostring(chat)]['settings']['linkgp'] == 'waiting' and is_owner(msg) then data[tostring(chat)]['settings']['linkgp'] = msg.content_.text_ save_data(_config.moderation.data, data) if not lang then return "*Newlink* _has been set_" else return "لینک جدید ذخیره شد" end end end if matches[1] == 'لینک' and is_mod(msg) then local linkgp = data[tostring(chat)]['settings']['linkgp'] if not linkgp then if not lang then return "_First set a link for group with using_ /setlink" else return "اول لینک گروه خود را ذخیره کنید با /setlink" end end if not lang then text = "<b>Group Link :</b>\n"..linkgp else text = "<b>لینک گروه :</b>\n"..linkgp end return tdcli.sendMessage(chat, msg.id_, 1, text, 1, 'html') end if matches[1] == "تنظیم قوانین" and matches[2] and is_mod(msg) then data[tostring(chat)]['rules'] = matches[2] save_data(_config.moderation.data, data) if not lang then return "*Group rules* _has been set_" else return "قوانین گروه ثبت شد" end end if matches[1] == "قوانین" then if not data[tostring(chat)]['rules'] then if not lang then rules = "ℹ️ The Default Rules :\n1⃣ No Flood.\n2⃣ No Spam.\n3⃣ No Advertising.\n4⃣ Try to stay on topic.\n5⃣ Forbidden any racist, sexual, homophobic or gore content.\n➡️ Repeated failure to comply with these rules will cause ban.\n" elseif lang then rules = "ℹ️ قوانین پپیشفرض:\n1⃣ ارسال پیام مکرر ممنوع.\n2⃣ اسپم ممنوع.\n3⃣ تبلیغ ممنوع.\n4⃣ سعی کنید از موضوع خارج نشید.\n5⃣ هرنوع نژاد پرستی, شاخ بازی و پورنوگرافی ممنوع .\n➡️ از قوانین پیروی کنید, در صورت عدم رعایت قوانین اول اخطار و در صورت تکرار مسدود.\n" end else rules = "*Group Rules :*\n"..data[tostring(chat)]['rules'] end return rules end if matches[1] == "رس" and matches[2] and is_mod(msg) then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, action_by_username, {chat_id=msg.chat_id_,username=matches[2],cmd="res"}) end if matches[1] == "چه کسی" and matches[2] and is_mod(msg) then tdcli_function ({ ID = "GetUser", user_id_ = matches[2], }, action_by_id, {chat_id=msg.chat_id_,user_id=matches[2],cmd="whois"}) end if matches[1] == 'تنظیم فلود' and is_mod(msg) then if tonumber(matches[2]) < 1 or tonumber(matches[2]) > 50 then return "_Wrong number, range is_ *[1-50]*" end local flood_max = matches[2] data[tostring(chat)]['settings']['num_msg_max'] = flood_max save_data(_config.moderation.data, data) return "_Group_ *flood* _sensitivity has been set to :_ *[ "..matches[2].." ]*" end if matches[1]:lower() == 'پاک کردن' and is_owner(msg) then if matches[2] == 'mods' then if next(data[tostring(chat)]['mods']) == nil then if not lang then return "_No_ *moderators* _in this group_" else return "هیچ مدیری برای گروه انتخاب نشده است" end end for k,v in pairs(data[tostring(chat)]['mods']) do data[tostring(chat)]['mods'][tostring(k)] = nil save_data(_config.moderation.data, data) end if not lang then return "_All_ *moderators* _has been demoted_" else return "تمام مدیران گروه تنزیل مقام شدند" end end if matches[2] == 'لیست فیلترها' then if next(data[tostring(chat)]['filterlist']) == nil then if not lang then return "*Filtered words list* _is empty_" else return "_لیست کلمات فیلتر شده خالی است_" end end for k,v in pairs(data[tostring(chat)]['filterlist']) do data[tostring(chat)]['filterlist'][tostring(k)] = nil save_data(_config.moderation.data, data) end if not lang then return "*Filtered words list* _has been cleaned_" else return "_لیست کلمات فیلتر شده پاک شد_" end end if matches[2] == 'قوانین' then if not data[tostring(chat)]['rules'] then if not lang then return "_No_ *rules* _available_" else return "قوانین برای گروه ثبت نشده است" end end data[tostring(chat)]['rules'] = nil save_data(_config.moderation.data, data) if not lang then return "*Group rules* _has been cleaned_" else return "قوانین گروه پاک شد" end end if matches[2] == 'ولکام' then if not data[tostring(chat)]['setwelcome'] then if not lang then return "*Welcome Message not set*" else return "پیام خوشآمد گویی ثبت نشده است" end end data[tostring(chat)]['setwelcome'] = nil save_data(_config.moderation.data, data) if not lang then return "*Welcome message* _has been cleaned_" else return "پیام خوشآمد گویی پاک شد" end end if matches[2] == 'درباره' then if gp_type(chat) == "chat" then if not data[tostring(chat)]['about'] then if not lang then return "_No_ *description* _available_" else return "پیامی مبنی بر درباره گروه ثبت نشده است" end end data[tostring(chat)]['about'] = nil save_data(_config.moderation.data, data) elseif gp_type(chat) == "channel" then tdcli.changeChannelAbout(chat, "", dl_cb, nil) end if not lang then return "*Group description* _has been cleaned_" else return "پیام مبنی بر درباره گروه پاک شد" end end end if matches[1]:lower() == 'پاک کردن' and is_admin(msg) then if matches[2] == 'owners' then if next(data[tostring(chat)]['owners']) == nil then if not lang then return "_No_ *owners* _in this group_" else return "مالکی برای گروه انتخاب نشده است" end end for k,v in pairs(data[tostring(chat)]['owners']) do data[tostring(chat)]['owners'][tostring(k)] = nil save_data(_config.moderation.data, data) end if not lang then return "_All_ *owners* _has been demoted_" else return "تمامی مالکان گروه تنزیل مقام شدند" end end end if matches[1] == "تنظیم نام" and matches[2] and is_mod(msg) then local gp_name = matches[2] tdcli.changeChatTitle(chat, gp_name, dl_cb, nil) end if matches[1] == "تنظیم درباره" and matches[2] and is_mod(msg) then if gp_type(chat) == "channel" then tdcli.changeChannelAbout(chat, matches[2], dl_cb, nil) elseif gp_type(chat) == "chat" then data[tostring(chat)]['about'] = matches[2] save_data(_config.moderation.data, data) end if not lang then return "*Group description* _has been set_" else return "پیام مبنی بر درباره گروه ثبت شد" end end if matches[1] == "درباره" and gp_type(chat) == "chat" then if not data[tostring(chat)]['about'] then if not lang then about = "_No_ *description* _available_" elseif lang then about = "پیامی مبنی بر درباره گروه ثبت نشده است" end else about = "*Group Description :*\n"..data[tostring(chat)]['about'] end return about end if matches[1] == 'فیلتر' and is_mod(msg) then return filter_word(msg, matches[2]) end if matches[1] == 'رفع فیلتر' and is_mod(msg) then return unfilter_word(msg, matches[2]) end if matches[1] == 'لیست فیلتر' and is_mod(msg) then return filter_list(msg) end if matches[1] == "تنظیمات" then return group_settings(msg, target) end if matches[1] == "لیست ممنوعیت" then return mutes(msg, target) end if matches[1] == "لیست ناظران" then return modlist(msg) end if matches[1] == "لیست مدیران" and is_owner(msg) then return ownerlist(msg) end if matches[1] == "setlang" and is_owner(msg) then if matches[2] == "en" then local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) redis:del(hash) return "_Group Language Set To:_ EN" elseif matches[2] == "fa" then redis:set(hash, true) return "*زبان گروه تنظیم شد به : فارسی*" end end if matches[1] == "راهنما" and is_mod(msg) then if not lang then text = [[ 🔰*Bot Commands:*🔰 در حال حاضر زبان ربات انگلیسی میباشد برای تغییر زبان دستور زیر را ارسال کنید *!setlang fa* 👑*!setowner* `[username|id|reply]` _Set Group Owner(Multi Owner)_ 👑*!remowner* `[username|id|reply]` _Remove User From Owner List_ 🤖*!promote* `[username|id|reply]` _Promote User To Group Admin_ 🤖*!demote* `[username|id|reply]` _Demote User From Group Admins List_ 🗣*!setflood* `[1-50]` _Set Flooding Number_ 🔇*!silent* `[username|id|reply]` _Silent User From Group_ 🔊*!unsilent* `[username|id|reply]` _Unsilent User From Group_ 👽*!kick* `[username|id|reply]` _Kick User From Group_ 👽*!ban* `[username|id|reply]` _Ban User From Group_ 👽*!unban* `[username|id|reply]` _UnBan User From Group_ 🔹*!res* `[username]` _Show User ID_ 🔹*!id* `[reply]` _Show User ID_ 🔹*!whois* `[id]` _Show User's Username And Name_ 🔒*!lock* `[link | tag | arabic | edit | fosh | webpage | bots | spam | flood | markdown | mention]` _If This Actions Lock, Bot Check Actions And Delete Them_ 🔓*!unlock* `[link | tag | arabic | edit | fosh | webpage | bots | spam | flood | markdown | mention]` _If This Actions Unlock, Bot Not Delete Them_ 🔕*!mute* `[gifs | photo | tgservice | document | sticker | video | text | forward | location | audio | voice | contact | all]` _If This Actions Lock, Bot Check Actions And Delete Them_ 🔔*!unmute* `[gif | photo | tgservice | document | sticker | video | tgservice | text | forward | inline | location | audio | voice | contact | all]` _If This Actions Unlock, Bot Not Delete Them_ 🔹*!set*`[rules | name | photo | link | about]` _Bot Set Them_ 🔹*!clean* `[bans | mods | bots | rules | about | silentlist]` _Bot Clean Them_ 🔹*!pin* `[reply]` _Pin Your Message_ 🔹*!unpin* _Unpin Pinned Message_ 🛡*!settings* _Show Group Settings_ 🔕*!silentlist* _Show Silented Users List_ 🔕*!banlist* _Show Banned Users List_ 👑*!ownerlist* _Show Group Owners List_ 🤖*!modlist* _Show Group Moderators List_ 🎖*!rules* _Show Group Rules_ ⚜*!gpinfo* _Show Group Information_ ⚜*!link* _Show Group Link_ 🔇*!mt 0 1* (0h 1m) 🔊*!unmt* _Mute All With Time_ 🚫*!filter* 🚫*!unfilter* _filter word_ 🚫*!filterlist* _Show Filter List_ 〰〰〰〰〰 ♻️*!del* 1-100 ♻️*!delall* `[reply]` _Delete Message_ 〰〰〰〰〰 ⏱*!setexpire* 30 ⏱*!expire* _set expire for group_ 〰〰〰〰〰 🎗*!setwelcome* متن پیام ➕*!welcome enable* ➖*!welcome disable* _set welcome for group_ 〰〰〰〰〰 📣*!broadcast* text _Send Msg To All Groups_ 〰〰〰〰〰 ⚙*!autoleave enable* ⚙*!autoleave disable* _set Auto leave_ ⚙channel : @OnAlfa _You Can Use_ *[!/#]* _To Run The Commands_ _Change the language to farsi : !setlang fa_ ]] elseif lang then text = [[ 📝A L F A B O T ➖➖➖➖➖➖➖➖➖➖ راهنمای کار با ربات 🔹دستورات مدیریت ربات و گروه 《مدیریت 》 🔹 دستورات قفلی 《قفل ها》 🔹دستورات ممنوعیت امکانات 《ممنوع》 🔹آگاهی از آنلاین بودن 《انلاینی》 🔹مشاهده لینک درگاه پرداخت 《درگاه》 ▪▪▪▪ 💢اعضای محترم گروه میتوانند با ارسال دستور 《خریدربات》این ربات را سفارش دهند . 🔷 web : www.onemizban.ir 🔷 channel : @OnAlfa]] end return text end if matches[1] == "قفل ها" and is_mod(msg) then text2 = [[ 💎لیست قفل ها 💎 💎دستور قفل کردن لینک گروه ها -قفل لینک -باز کردن لینک •°•°•°•°•°•°•°•° 💎 قفل کردن یوزرنیم -قفل تگ -باز کردن تگ •°•°•°•°•°•°•°•° 💎دستور قفل کردن متن فارسی و عربی -قفل عربی -باز کردن عربی •°•°•°•°•°•°•°•° 💎دستور قفل کردن لینک سایت ها -قفل وبسایت -باز کردن وبسایت •°•°•°•°•°•°•°•° 💎دستور جلوگیری از ویرایش متن -قفل ویرایش -باز کردن ویرایش •°•°•°•°•°•°•°•° 💎دستور جلوگیری از وارد کردن ربات -قفل ربات -باز کردن ربات •°•°•°•°•°•°•°•° 💎 دستور قفل پیام های طولانی -قفل اسپم -باز کردن اسپم •°•°•°•°•°•°•°•° 💎دستور قفل پیام های رگباری -قفل فلود -باز کردن فلود •°•°•°•°•°•°•°•° 💎دستور قفل بولد و ایتالیک متن -قفل فونت -باز کردن فونت •°•°•°•°•°•°•°•° 💎دستور قفل هایپرلینک -قفل هایپرلینک -باز کردن هایپرلینک •°•°•°•°•°•°•°•° 💎دستور قفل فحش -قفل فحش -باز کردن فحش ➖➖➖➖➖➖➖➖➖➖ گروه طراحی یک میزبان : ✳web : www.onemizban.ir ✳channel : @OnAlfa ... ]] return text2 end if matches[1] == "ممنوع" and is_mod(msg) then text3 = [[ 🔷 لیست ممنوع 🔶 _دستورارسال گیف ممنوع -ممنوعیت گیف -رفع ممنوعیت گیف 〰〰〰〰〰 🔸دستور ارسال عکس ممنوع -ممنوعیت عکس -رفع ممنوعیت عکس 〰〰〰〰〰 🔹دستور ارسال فایل ممنوع -ممنوعیت فایل -رفع ممنوعیت فایل 〰〰〰〰〰 🔸دستور ارسال استیکر ممنوع -ممنوعیت استیکر -رفع ممنوعیت استیکر 〰〰〰〰〰 🔹دستور ارسال ویدیو ممنوع -ممنوعیت فیلم -رفع ممنوعیت فیلم 〰〰〰〰〰 🔸دستور ارسال متن ممنوع -ممنوعیت متن -رفع ممنوعیت متن 〰〰〰〰〰 🔹دستور ارسال فوروارد ممنوع -ممنوعیت فوروارد -رفع ممنوعیت فوروارد 〰〰〰〰〰 🔸دستور ارسال بازی به گروه -ممنوعیت بازی -رفع ممنوعیت بازی 〰〰〰〰〰 🔹دستور ارسال مکان ممنوع -ممنوعیت مکان -رفع ممنوعیت مکان 〰〰〰〰〰 🔸دستور ارسال موزیک ممنوع -ممنوعیت موزیک -رفع ممنوعیت موزیک 〰〰〰〰〰 🔹دستور ارسال فایل ضبط شده ممنوع -ممنوعیت صدا -رفع ممنوعیت صدا 〰〰〰〰〰 🔸دستور ارسال اطلاعات تماس ممنوع -ممنوعیت اطلاعات تماس -رفع ممنوعیت اطلاعات تماس 〰〰〰〰〰 🔹دستور اعلانات گروه ممنوع -ممنوعیت اعلانات -رفع ممنوعیت اعلانات 〰〰〰〰〰 🔸 دستور ارسال تبلیغات شیشه ای ممنوع -ممنوعیت اینلاین -رفع ممنوعیت اینلاین 〰〰〰〰〰 🔹دستور همه چیز ممنوع -ممنوعیت همه چیز -رفع ممنوعیت همه چیز 〰〰〰〰〰 🔸دستور میوت تایم دار عدد اول ساعت عدد دوم دقیقه 🔇!mt 0 1 🔊!unmt_ ➖➖➖➖➖➖➖➖➖➖ گروه طراحی یک میزبان : ♻*web*: www.onemizban.ir ♻*channel*: @OnAlfa ... ]] return text3 end if matches[1] == "خریدربات" then text99 = [[ 🎈جهت ثبت سفارش ربات به ادرس زیر مراجعه کنید Http://onemizban.ir/bot و یا به کانال زیر مراجعه کنید : Https://t.me/OnAlfa]] return text99 end if matches[1] == "مدیریت" and is_mod(msg) then text4 = [[ 🔰 لیست دستورات مدیریت 🔰 ➰شما میتوانید از '/' یا '!' یا '#' برای اجرای دستورات استفاده کنید. 〰〰〰〰〰 🔰 *تنظیمات* 💬 نمایش تنظیمات گروه 〰〰〰〰〰 🔕 *لیست سایلنت* 💬 نمایش لیست سایلنت شده ها 〰〰〰〰〰 🔕 *لیست مسدود* 💬 نمایش لیست مسدود شده ها 〰〰〰〰〰 👑 *لیست مدیران* 💬 نمایش لیست مدیران 〰〰〰〰〰 🤖 *لیست ناظران* 💬 نمایش لیست ناظران 〰〰〰〰〰 🎖 *اطلاعات گروه* 💬 نمایش اطلاعات گروه 〰〰〰〰〰 👑 *انتخاب مدیر* `[username|id|reply]` 💬 تعیین مدیر اصلی گروه 〰〰〰〰〰 👑 *حذف مدیر* `[username|id|reply]` 💬 حذف مدیر اصلی 〰〰〰〰〰 🤖 *انتخاب ناظر* `[username|id|reply]` 💬 تعیین ناظر گروه 〰〰〰〰〰 🤖 *حذف ناظر* `[username|id|reply]` 💬 حذف ناظر گروه 〰〰〰〰〰 🗣 *تنظیم فلود* `[1-50]` 💬 تعیین میزان مجاز پست های رگباری 〰〰〰〰〰 🔹 *رس* `[username]` 🔹 *ایدی* `[reply]` 💬 نمایش آیدی یوزر 〰〰〰〰〰 🔹 *چه کسی* `[id]` 💬 نمایش یوزر آیدی 〰〰〰〰〰 🔕 *سایلنت* `[username|id|reply]` 🔔 *رفع سایلنت* `[username|id|reply]` 💬 ساکت کردن یک کاربر 〰〰〰〰〰 👊 *اخراج* `[username|id|reply]` 💬 اخراج کردن یک کاربر 〰〰〰〰〰 👊 *مسدود کردن* `[username|id|reply]` ✋ *رفع مسدودیت* `[username|id|reply]` 💬 مسدود کردن یک کاربر 〰〰〰〰〰 ✍ *!تنظیم لینک* 🔹 *لینک* نمایش لینک ✍ *تنظیم قوانین* قوانین را بنویسید 🔹 *قوانین* نمایش قوانین 💬 ثبت لینک و قوانین و نمایش آنها 〰〰〰〰〰 🚿 *!پاک کردن قوانین* 💬 پاک کردن قوانین گروه 〰〰〰〰〰 🚿 *پاک کردن لیست سایلنت* 💬 پاک کردن لیست سایلنت شده ها 〰〰〰〰〰 📍 *سنجاق کردن* `[reply]` 📍 *حذف سنجاق* 💬 سنجاق کردن متن در گروه 〰〰〰〰〰 🚫 *فیلتر* 🚫 *رفع فیلتر* 💬 فیلتر کلمات 🚫 *لیست فیلتر* 💬 نمایش لیست فیلتر 〰〰〰〰〰 🎗*تنظیم ولکام* متن پیام ➕*ولکام نصب* ➖*ولکام حذف* 💬 ست کردن و فعال و غیرفعال کردن خوش آمد گویی 〰〰〰〰〰 ♻️ *!del* 1-100 ♻️ *!delall* `[reply]` 💬 حذف پیام های گروه حداکثر 100 〰〰〰〰〰 ⏱ *!setexpire* 30 ⏱ *!expire* 💬 تنظیم انقضای گروه 〰〰〰〰〰 📣 *!broadcast* متن پیام 💬 ارسال یک پیام به همه گروهایی که ربات مدیر است 〰〰〰〰〰 ⚙*!autoleave enable* ⚙*!autoleave disable* 💬 تنظیم خارج شدن ربات 💬*web*: www.onemizban.ir ♻*channel*: @OnAlfa ... در زدن دستورات به فاصله حروف دقت کنید ]] return text4 end if matches[1] == "انلاینی" and is_mod(msg) then text5 = [[ 😎اره انلاینم✅ ]] return text5 end end return { patterns ={ "^(مدیریت)$", "^(انلاینی)$", "^(ممنوع)$", "^(قفل ها)$", "^(ایدی)$", "^(ایدی) (.*)$", "^(سنجاق کردن)$", "^(حذف سنجاق)$", "^(اطلاعات گروه)$", "^(تست)$", "^(نصب)$", "^(حذف)$", "^(انتخاب مدیر)$", "^(انتخاب مدیر) (.*)$", "^(حذف مدیر)$", "^(حذف مدیر) (.*)$", "^(انتخاب ناظر)$", "^(انتخاب ناظر) (.*)$", "^(حذف ناظر)$", "^(حذف ناظر) (.*)$", "^(لیست ناظران)$", "^(لیست مدیران)$", "^(قفل) (.*)$", "^(باز کردن) (.*)$", "^(تنظیمات)$", "^(لیست ممنوعیت)$", "^(ممنوعیت) (.*)$", "^(رفع ممنوعیت) (.*)$", "^(لینک)$", "^(تنظیم لینک)$", "^(درباره)$", "^(راهنما فان)$", "^(تنظیم درباره) (.*)$", "^(تنظیم نام) (.*)$", "^(پاک کردن) (.*)$", "^(تنظیم فلود) (%d+)$", "^(رس) (.*)$", "^(خریدربات)$", "^(چه کسی) (%d+)$", "^(راهنما)$", "^(setlang) (.*)$", "^(فیلتر) (.*)$", "^(رفع فیلتر) (.*)$", "^(لیست فیلتر)$", "^([https?://w]*.?t.me/joinchat/%S+)$", "^([https?://w]*.?telegram.me/joinchat/%S+)$", }, run=run, pre_process = pre_process } -- کد های پایین در ربات نشان داده نمیشوند -- http://permag.ir -- @permag_ir -- @permag_bots -- @permag
gpl-3.0
lichtl/darkstar
scripts/zones/Bastok-Jeuno_Airship/TextIDs.lua
22
1080
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6379; -- You cannot obtain the item <item> come back again after sorting your inventory ITEM_OBTAINED = 6384; -- Obtained: <item> GIL_OBTAINED = 6385; -- Obtained <number> gil KEYITEM_OBTAINED = 6387; -- Obtained key item: <keyitem> -- Other WILL_REACH_JEUNO = 7204; -- The airship will reach Jeuno in Multiple Choice (Parameter 1)[less than an hour/about 1 hour/about 2 hours/about 3 hours/about 4 hours/about 5 hours/about 6 hours/about 7 hours] ( Singular/Plural Choice (Parameter 0)[minute/minutes] in Earth time). WILL_REACH_BASTOK = 7205; -- The airship will reach Bastok in Multiple Choice (Parameter 1)[less than an hour/about 1 hour/about 2 hours/about 3 hours/about 4 hours/about 5 hours/about 6 hours/about 7 hours] ( Singular/Plural Choice (Parameter 0)[minute/minutes] in Earth time). IN_JEUNO_MOMENTARILY = 7206; -- We will be arriving in Jeuno momentarily. IN_BASTOK_MOMENTARILY = 7207; -- We will be arriving in Bastok momentarily.
gpl-3.0
RunAwayDSP/darkstar
scripts/zones/Halvung/IDs.lua
8
1525
----------------------------------- -- Area: Halvung ----------------------------------- require("scripts/globals/zone") ----------------------------------- zones = zones or {} zones[dsp.zone.HALVUNG] = { text = { NOTHING_HAPPENS = 119, -- Nothing happens... ITEM_CANNOT_BE_OBTAINED = 6382, -- You cannot obtain the <item>. Come back after sorting your inventory. ITEM_OBTAINED = 6388, -- Obtained: <item>. GIL_OBTAINED = 6389, -- Obtained <number> gil. KEYITEM_OBTAINED = 6391, -- Obtained key item: <keyitem>. MINING_IS_POSSIBLE_HERE = 7924, -- Mining is possible here if you have <item>. BLUE_FLAMES = 7963, -- You can see blue flames flickering from a hole in the ground here... COMMON_SENSE_SURVIVAL = 8102, -- It appears that you have arrived at a new survival guide provided by the Adventurers' Mutual Aid Network. Common sense dictates that you should now be able to teleport here from similar tomes throughout the world. }, mob = { BIG_BOMB = 17031401, GURFURLUR_THE_MENACING = 17031592, DEXTROSE = 17031598, REACTON = 17031599, ACHAMOTH = 17031600, }, npc = { MINING = { 17031715, 17031716, 17031717, 17031718, 17031719, 17031720, }, }, } return zones[dsp.zone.HALVUNG]
gpl-3.0
dani-sj/botevil
plugins/location.lua
185
1565
-- Implement a command !loc [area] which uses -- the static map API to get a location image -- Not sure if this is the proper way -- Intent: get_latlong is in time.lua, we need it here -- loadfile "time.lua" -- Globals -- If you have a google api key for the geocoding/timezone api do local api_key = nil local base_api = "https://maps.googleapis.com/maps/api" function get_staticmap(area) local api = base_api .. "/staticmap?" -- Get a sense of scale local lat,lng,acc,types = get_latlong(area) local scale = types[1] if scale=="locality" then zoom=8 elseif scale=="country" then zoom=4 else zoom = 13 end local parameters = "size=600x300" .. "&zoom=" .. zoom .. "&center=" .. URL.escape(area) .. "&markers=color:red"..URL.escape("|"..area) if api_key ~=nil and api_key ~= "" then parameters = parameters .. "&key="..api_key end return lat, lng, api..parameters end function run(msg, matches) local receiver = get_receiver(msg) local lat,lng,url = get_staticmap(matches[1]) -- Send the actual location, is a google maps link send_location(receiver, lat, lng, ok_cb, false) -- Send a picture of the map, which takes scale into account send_photo_from_url(receiver, url) -- Return a link to the google maps stuff is now not needed anymore return nil end return { description = "Gets information about a location, maplink and overview", usage = "!loc (location): Gets information about a location, maplink and overview", patterns = {"^!loc (.*)$"}, run = run } end
gpl-2.0
sjznxd/lc-20130222
libs/nixio/docsrc/nixio.lua
151
15824
--- General POSIX IO library. module "nixio" --- Look up a hostname and service via DNS. -- @class function -- @name nixio.getaddrinfo -- @param host hostname to lookup (optional) -- @param family address family [<strong>"any"</strong>, "inet", "inet6"] -- @param service service name or port (optional) -- @return Table containing one or more tables containing: <ul> -- <li>family = ["inet", "inet6"]</li> -- <li>socktype = ["stream", "dgram", "raw"]</li> -- <li>address = Resolved IP-Address</li> -- <li>port = Resolved Port (if service was given)</li> -- </ul> --- Reverse look up an IP-Address via DNS. -- @class function -- @name nixio.getnameinfo -- @param ipaddr IPv4 or IPv6-Address -- @return FQDN --- (Linux, BSD) Get a list of available network interfaces and their addresses. -- @class function -- @name nixio.getifaddrs -- @return Table containing one or more tables containing: <ul> -- <li>name = Interface Name</li> -- <li>family = ["inet", "inet6", "packet"]</li> -- <li>addr = Interface Address (IPv4, IPv6, MAC, ...)</li> -- <li>broadaddr = Broadcast Address</li> -- <li>dstaddr = Destination Address (Point-to-Point)</li> -- <li>netmask = Netmask (if available)</li> -- <li>prefix = Prefix (if available)</li> -- <li>flags = Table of interface flags (up, multicast, loopback, ...)</li> -- <li>data = Statistics (Linux, "packet"-family)</li> -- <li>hatype = Hardware Type Identifier (Linix, "packet"-family)</li> -- <li>ifindex = Interface Index (Linux, "packet"-family)</li> -- </ul> --- Get protocol entry by name. -- @usage This function returns nil if the given protocol is unknown. -- @class function -- @name nixio.getprotobyname -- @param name protocol name to lookup -- @return Table containing the following fields: <ul> -- <li>name = Protocol Name</li> -- <li>proto = Protocol Number</li> -- <li>aliases = Table of alias names</li> -- </ul> --- Get protocol entry by number. -- @usage This function returns nil if the given protocol is unknown. -- @class function -- @name nixio.getprotobynumber -- @param proto protocol number to lookup -- @return Table containing the following fields: <ul> -- <li>name = Protocol Name</li> -- <li>proto = Protocol Number</li> -- <li>aliases = Table of alias names</li> -- </ul> --- Get all or a specifc proto entry. -- @class function -- @name nixio.getproto -- @param proto protocol number or name to lookup (optional) -- @return Table (or if no parameter is given, a table of tables) -- containing the following fields: <ul> -- <li>name = Protocol Name</li> -- <li>proto = Protocol Number</li> -- <li>aliases = Table of alias names</li> -- </ul> --- Create a new socket and bind it to a network address. -- This function is a shortcut for calling nixio.socket and then bind() -- on the socket object. -- @usage This functions calls getaddrinfo(), socket(), -- setsockopt() and bind() but NOT listen(). -- @usage The <em>reuseaddr</em>-option is automatically set before binding. -- @class function -- @name nixio.bind -- @param host Hostname or IP-Address (optional, default: all addresses) -- @param port Port or service description -- @param family Address family [<strong>"any"</strong>, "inet", "inet6"] -- @param socktype Socket Type [<strong>"stream"</strong>, "dgram"] -- @return Socket Object --- Create a new socket and connect to a network address. -- This function is a shortcut for calling nixio.socket and then connect() -- on the socket object. -- @usage This functions calls getaddrinfo(), socket() and connect(). -- @class function -- @name nixio.connect -- @param host Hostname or IP-Address (optional, default: localhost) -- @param port Port or service description -- @param family Address family [<strong>"any"</strong>, "inet", "inet6"] -- @param socktype Socket Type [<strong>"stream"</strong>, "dgram"] -- @return Socket Object --- Open a file. -- @class function -- @name nixio.open -- @usage Although this function also supports the traditional fopen() -- file flags it does not create a file stream but uses the open() syscall. -- @param path Filesystem path to open -- @param flags Flag string or number (see open_flags). -- [<strong>"r"</strong>, "r+", "w", "w+", "a", "a+"] -- @param mode File mode for newly created files (see chmod, umask). -- @see nixio.umask -- @see nixio.open_flags -- @return File Object --- Generate flags for a call to open(). -- @class function -- @name nixio.open_flags -- @usage This function cannot fail and will never return nil. -- @usage The "nonblock" and "ndelay" flags are aliases. -- @usage The "nonblock", "ndelay" and "sync" flags are no-ops on Windows. -- @param flag1 First Flag ["append", "creat", "excl", "nonblock", "ndelay", -- "sync", "trunc", "rdonly", "wronly", "rdwr"] -- @param ... More Flags [-"-] -- @return flag to be used as second paramter to open --- Duplicate a file descriptor. -- @class function -- @name nixio.dup -- @usage This funcation calls dup2() if <em>newfd</em> is set, otherwise dup(). -- @param oldfd Old descriptor [File Object, Socket Object (POSIX only)] -- @param newfd New descriptor to serve as copy (optional) -- @return File Object of new descriptor --- Create a pipe. -- @class function -- @name nixio.pipe -- @return File Object of the read end -- @return File Object of the write end --- Get the last system error code. -- @class function -- @name nixio.errno -- @return Error code --- Get the error message for the corresponding error code. -- @class function -- @name nixio.strerror -- @param errno System error code -- @return Error message --- Sleep for a specified amount of time. -- @class function -- @usage Not all systems support nanosecond precision but you can expect -- to have at least maillisecond precision. -- @usage This function is not signal-protected and may fail with EINTR. -- @param seconds Seconds to wait (optional) -- @param nanoseconds Nanoseconds to wait (optional) -- @name nixio.nanosleep -- @return true --- Generate events-bitfield or parse revents-bitfield for poll. -- @class function -- @name nixio.poll_flags -- @param mode1 revents-Flag bitfield returned from poll to parse OR -- ["in", "out", "err", "pri" (POSIX), "hup" (POSIX), "nval" (POSIX)] -- @param ... More mode strings for generating the flag [-"-] -- @see nixio.poll -- @return table with boolean fields reflecting the mode parameter -- <strong>OR</strong> bitfield to use for the events-Flag field --- Wait for some event on a file descriptor. -- poll() sets the revents-field of the tables provided by fds to a bitfield -- indicating the events that occured. -- @class function -- @usage This function works in-place on the provided table and only -- writes the revents field, you can use other fields on your demand. -- @usage All metamethods on the tables provided as fds are ignored. -- @usage The revents-fields are not reset when the call times out. -- You have to check the first return value to be 0 to handle this case. -- @usage If you want to wait on a TLS-Socket you have to use the underlying -- socket instead. -- @usage On Windows poll is emulated through select(), can only be used -- on socket descriptors and cannot take more than 64 descriptors per call. -- @usage This function is not signal-protected and may fail with EINTR. -- @param fds Table containing one or more tables containing <ul> -- <li> fd = I/O Descriptor [Socket Object, File Object (POSIX)]</li> -- <li> events = events to wait for (bitfield generated with poll_flags)</li> -- </ul> -- @param timeout Timeout in milliseconds -- @name nixio.poll -- @see nixio.poll_flags -- @return number of ready IO descriptors -- @return the fds-table with revents-fields set --- (POSIX) Clone the current process. -- @class function -- @name nixio.fork -- @return the child process id for the parent process, 0 for the child process --- (POSIX) Send a signal to one or more processes. -- @class function -- @name nixio.kill -- @param target Target process of process group. -- @param signal Signal to send -- @return true --- (POSIX) Get the parent process id of the current process. -- @class function -- @name nixio.getppid -- @return parent process id --- (POSIX) Get the user id of the current process. -- @class function -- @name nixio.getuid -- @return process user id --- (POSIX) Get the group id of the current process. -- @class function -- @name nixio.getgid -- @return process group id --- (POSIX) Set the group id of the current process. -- @class function -- @name nixio.setgid -- @param gid New Group ID -- @return true --- (POSIX) Set the user id of the current process. -- @class function -- @name nixio.setuid -- @param gid New User ID -- @return true --- (POSIX) Change priority of current process. -- @class function -- @name nixio.nice -- @param nice Nice Value -- @return true --- (POSIX) Create a new session and set the process group ID. -- @class function -- @name nixio.setsid -- @return session id --- (POSIX) Wait for a process to change state. -- @class function -- @name nixio.waitpid -- @usage If the "nohang" is given this function becomes non-blocking. -- @param pid Process ID (optional, default: any childprocess) -- @param flag1 Flag (optional) ["nohang", "untraced", "continued"] -- @param ... More Flags [-"-] -- @return process id of child or 0 if no child has changed state -- @return ["exited", "signaled", "stopped"] -- @return [exit code, terminate signal, stop signal] --- (POSIX) Get process times. -- @class function -- @name nixio.times -- @return Table containing: <ul> -- <li>utime = user time</li> -- <li>utime = system time</li> -- <li>cutime = children user time</li> -- <li>cstime = children system time</li> -- </ul> --- (POSIX) Get information about current system and kernel. -- @class function -- @name nixio.uname -- @return Table containing: <ul> -- <li>sysname = operating system</li> -- <li>nodename = network name (usually hostname)</li> -- <li>release = OS release</li> -- <li>version = OS version</li> -- <li>machine = hardware identifier</li> -- </ul> --- Change the working directory. -- @class function -- @name nixio.chdir -- @param path New working directory -- @return true --- Ignore or use set the default handler for a signal. -- @class function -- @name nixio.signal -- @param signal Signal -- @param handler ["ign", "dfl"] -- @return true --- Get the ID of the current process. -- @class function -- @name nixio.getpid -- @return process id --- Get the current working directory. -- @class function -- @name nixio.getcwd -- @return workign directory --- Get the current environment table or a specific environment variable. -- @class function -- @name nixio.getenv -- @param variable Variable (optional) -- @return environment table or single environment variable --- Set or unset a environment variable. -- @class function -- @name nixio.setenv -- @usage The environment variable will be unset if value is ommited. -- @param variable Variable -- @param value Value (optional) -- @return true --- Execute a file to replace the current process. -- @class function -- @name nixio.exec -- @usage The name of the executable is automatically passed as argv[0] -- @usage This function does not return on success. -- @param executable Executable -- @param ... Parameters --- Invoke the shell and execute a file to replace the current process. -- @class function -- @name nixio.execp -- @usage The name of the executable is automatically passed as argv[0] -- @usage This function does not return on success. -- @param executable Executable -- @param ... Parameters --- Execute a file with a custom environment to replace the current process. -- @class function -- @name nixio.exece -- @usage The name of the executable is automatically passed as argv[0] -- @usage This function does not return on success. -- @param executable Executable -- @param arguments Argument Table -- @param environment Environment Table (optional) --- Sets the file mode creation mask. -- @class function -- @name nixio.umask -- @param mask New creation mask (see chmod for format specifications) -- @return the old umask as decimal mode number -- @return the old umask as mode string --- (Linux) Get overall system statistics. -- @class function -- @name nixio.sysinfo -- @return Table containing: <ul> -- <li>uptime = system uptime in seconds</li> -- <li>loads = {loadavg1, loadavg5, loadavg15}</li> -- <li>totalram = total RAM</li> -- <li>freeram = free RAM</li> -- <li>sharedram = shared RAM</li> -- <li>bufferram = buffered RAM</li> -- <li>totalswap = total SWAP</li> -- <li>freeswap = free SWAP</li> -- <li>procs = number of running processes</li> -- </ul> --- Create a new socket. -- @class function -- @name nixio.socket -- @param domain Domain ["inet", "inet6", "unix"] -- @param type Type ["stream", "dgram", "raw"] -- @return Socket Object --- (POSIX) Send data from a file to a socket in kernel-space. -- @class function -- @name nixio.sendfile -- @param socket Socket Object -- @param file File Object -- @param length Amount of data to send (in Bytes). -- @return bytes sent --- (Linux) Send data from / to a pipe in kernel-space. -- @class function -- @name nixio.splice -- @param fdin Input I/O descriptor -- @param fdout Output I/O descriptor -- @param length Amount of data to send (in Bytes). -- @param flags (optional, bitfield generated by splice_flags) -- @see nixio.splice_flags -- @return bytes sent --- (Linux) Generate a flag bitfield for a call to splice. -- @class function -- @name nixio.splice_flags -- @param flag1 First Flag ["move", "nonblock", "more"] -- @param ... More flags [-"-] -- @see nixio.splice -- @return Flag bitfield --- (POSIX) Open a connection to the system logger. -- @class function -- @name nixio.openlog -- @param ident Identifier -- @param flag1 Flag 1 ["cons", "nowait", "pid", "perror", "ndelay", "odelay"] -- @param ... More flags [-"-] --- (POSIX) Close the connection to the system logger. -- @class function -- @name nixio.closelog --- (POSIX) Write a message to the system logger. -- @class function -- @name nixio.syslog -- @param priority Priority ["emerg", "alert", "crit", "err", "warning", -- "notice", "info", "debug"] -- @param message --- (POSIX) Set the logmask of the system logger for current process. -- @class function -- @name nixio.setlogmask -- @param priority Priority ["emerg", "alert", "crit", "err", "warning", -- "notice", "info", "debug"] --- (POSIX) Encrypt a user password. -- @class function -- @name nixio.crypt -- @param key Key -- @param salt Salt -- @return password hash --- (POSIX) Get all or a specific user group. -- @class function -- @name nixio.getgr -- @param group Group ID or groupname (optional) -- @return Table containing: <ul> -- <li>name = Group Name</li> -- <li>gid = Group ID</li> -- <li>passwd = Password</li> -- <li>mem = {Member #1, Member #2, ...}</li> -- </ul> --- (POSIX) Get all or a specific user account. -- @class function -- @name nixio.getpw -- @param user User ID or username (optional) -- @return Table containing: <ul> -- <li>name = Name</li> -- <li>uid = ID</li> -- <li>gid = Group ID</li> -- <li>passwd = Password</li> -- <li>dir = Home directory</li> -- <li>gecos = Information</li> -- <li>shell = Shell</li> -- </ul> --- (Linux, Solaris) Get all or a specific shadow password entry. -- @class function -- @name nixio.getsp -- @param user username (optional) -- @return Table containing: <ul> -- <li>namp = Name</li> -- <li>expire = Expiration Date</li> -- <li>flag = Flags</li> -- <li>inact = Inactivity Date</li> -- <li>lstchg = Last change</li> -- <li>max = Maximum</li> -- <li>min = Minimum</li> -- <li>warn = Warning</li> -- <li>pwdp = Password Hash</li> -- </ul> --- Create a new TLS context. -- @class function -- @name nixio.tls -- @param mode TLS-Mode ["client", "server"] -- @return TLSContext Object
apache-2.0
lichtl/darkstar
scripts/zones/Al_Zahbi/npcs/Danaaba.lua
14
1038
----------------------------------- -- Area: Al Zahbi -- NPC: Danaaba -- Type: Standard NPC -- @zone 48 -- @pos -17.375 -6.999 59.161 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Al_Zahbi/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x00f8); 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
RunAwayDSP/darkstar
scripts/zones/Riverne-Site_B01/npcs/Unstable_Displacement.lua
9
1230
----------------------------------- -- Area: Riverne Site #B01 -- NPC: Unstable Displacement ----------------------------------- local ID = require("scripts/zones/Riverne-Site_B01/IDs"); require("scripts/globals/settings") require("scripts/globals/quests") require("scripts/globals/status") require("scripts/globals/bcnm") function onTrade(player,npc,trade) local offset = npc:getID() - ID.npc.DISPLACEMENT_OFFSET; if (offset == 5 and TradeBCNM(player,npc,trade)) then -- The Wyrmking Descends return; end end function onTrigger(player,npc) local offset = npc:getID() - ID.npc.DISPLACEMENT_OFFSET; -- STORMS OF FATE if offset == 5 and player:getQuestStatus(JEUNO,dsp.quest.id.jeuno.STORMS_OF_FATE) == QUEST_ACCEPTED and player:getCharVar('StormsOfFate') == 1 then player:startEvent(1) elseif offset == 5 and EventTriggerBCNM(player,npc) then return elseif offset == 5 then player:messageSpecial(ID.text.SPACE_SEEMS_DISTORTED) end end function onEventUpdate(player,csid,option,extras) EventUpdateBCNM(player,csid,option,extras) end function onEventFinish(player,csid,option) if csid == 1 then player:setCharVar('StormsOfFate',2) end end
gpl-3.0
taiha/luci
modules/luci-mod-admin-mini/luasrc/controller/mini/index.lua
74
1261
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. module("luci.controller.mini.index", package.seeall) function index() local root = node() if not root.lock then root.target = alias("mini") root.index = true end entry({"about"}, template("about")) local page = entry({"mini"}, alias("mini", "index"), _("Essentials"), 10) page.sysauth = "root" page.sysauth_authenticator = "htmlauth" page.index = true entry({"mini", "index"}, alias("mini", "index", "index"), _("Overview"), 10).index = true entry({"mini", "index", "index"}, form("mini/index"), _("General"), 1).ignoreindex = true entry({"mini", "index", "luci"}, cbi("mini/luci", {autoapply=true}), _("Settings"), 10) entry({"mini", "index", "logout"}, call("action_logout"), _("Logout")) end function action_logout() local dsp = require "luci.dispatcher" local utl = require "luci.util" if dsp.context.authsession then utl.ubus("session", "destroy", { ubus_rpc_session = dsp.context.authsession }) dsp.context.urltoken.stok = nil end luci.http.header("Set-Cookie", "sysauth=; path=" .. dsp.build_url()) luci.http.redirect(luci.dispatcher.build_url()) end
apache-2.0
we20/ping
plugins/id.lua
355
2795
local function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end local function returnids(cb_extra, success, result) local receiver = cb_extra.receiver --local chat_id = "chat#id"..result.id local chat_id = result.id local chatname = result.print_name local text = 'IDs for chat '..chatname ..' ('..chat_id..')\n' ..'There are '..result.members_num..' members' ..'\n---------\n' i = 0 for k,v in pairs(result.members) do i = i+1 text = text .. i .. ". " .. string.gsub(v.print_name, "_", " ") .. " (" .. v.id .. ")\n" end send_large_msg(receiver, text) end local function username_id(cb_extra, success, result) local receiver = cb_extra.receiver local qusername = cb_extra.qusername local text = 'User '..qusername..' not found in this group!' for k,v in pairs(result.members) do vusername = v.username if vusername == qusername then text = 'ID for username\n'..vusername..' : '..v.id end end send_large_msg(receiver, text) end local function run(msg, matches) local receiver = get_receiver(msg) if matches[1] == "!id" then local text = 'Name : '.. string.gsub(user_print_name(msg.from),'_', ' ') .. '\nID : ' .. msg.from.id if is_chat_msg(msg) then text = text .. "\n\nYou are in group " .. string.gsub(user_print_name(msg.to), '_', ' ') .. " (ID: " .. msg.to.id .. ")" end return text elseif matches[1] == "chat" then -- !ids? (chat) (%d+) if matches[2] and is_sudo(msg) then local chat = 'chat#id'..matches[2] chat_info(chat, returnids, {receiver=receiver}) else if not is_chat_msg(msg) then return "You are not in a group." end local chat = get_receiver(msg) chat_info(chat, returnids, {receiver=receiver}) end else if not is_chat_msg(msg) then return "Only works in group" end local qusername = string.gsub(matches[1], "@", "") local chat = get_receiver(msg) chat_info(chat, username_id, {receiver=receiver, qusername=qusername}) end end return { description = "Know your id or the id of a chat members.", usage = { "!id: Return your ID and the chat id if you are in one.", "!ids chat: Return the IDs of the current chat members.", "!ids chat <chat_id>: Return the IDs of the <chat_id> members.", "!id <username> : Return the id from username given." }, patterns = { "^!id$", "^!ids? (chat) (%d+)$", "^!ids? (chat)$", "^!id (.*)$" }, run = run }
gpl-2.0
punisherbot/he
plugins/id.lua
355
2795
local function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end local function returnids(cb_extra, success, result) local receiver = cb_extra.receiver --local chat_id = "chat#id"..result.id local chat_id = result.id local chatname = result.print_name local text = 'IDs for chat '..chatname ..' ('..chat_id..')\n' ..'There are '..result.members_num..' members' ..'\n---------\n' i = 0 for k,v in pairs(result.members) do i = i+1 text = text .. i .. ". " .. string.gsub(v.print_name, "_", " ") .. " (" .. v.id .. ")\n" end send_large_msg(receiver, text) end local function username_id(cb_extra, success, result) local receiver = cb_extra.receiver local qusername = cb_extra.qusername local text = 'User '..qusername..' not found in this group!' for k,v in pairs(result.members) do vusername = v.username if vusername == qusername then text = 'ID for username\n'..vusername..' : '..v.id end end send_large_msg(receiver, text) end local function run(msg, matches) local receiver = get_receiver(msg) if matches[1] == "!id" then local text = 'Name : '.. string.gsub(user_print_name(msg.from),'_', ' ') .. '\nID : ' .. msg.from.id if is_chat_msg(msg) then text = text .. "\n\nYou are in group " .. string.gsub(user_print_name(msg.to), '_', ' ') .. " (ID: " .. msg.to.id .. ")" end return text elseif matches[1] == "chat" then -- !ids? (chat) (%d+) if matches[2] and is_sudo(msg) then local chat = 'chat#id'..matches[2] chat_info(chat, returnids, {receiver=receiver}) else if not is_chat_msg(msg) then return "You are not in a group." end local chat = get_receiver(msg) chat_info(chat, returnids, {receiver=receiver}) end else if not is_chat_msg(msg) then return "Only works in group" end local qusername = string.gsub(matches[1], "@", "") local chat = get_receiver(msg) chat_info(chat, username_id, {receiver=receiver, qusername=qusername}) end end return { description = "Know your id or the id of a chat members.", usage = { "!id: Return your ID and the chat id if you are in one.", "!ids chat: Return the IDs of the current chat members.", "!ids chat <chat_id>: Return the IDs of the <chat_id> members.", "!id <username> : Return the id from username given." }, patterns = { "^!id$", "^!ids? (chat) (%d+)$", "^!ids? (chat)$", "^!id (.*)$" }, run = run }
gpl-2.0
RunAwayDSP/darkstar
scripts/zones/Port_San_dOria/npcs/Ceraulian.lua
9
5082
----------------------------------- -- Area: Port San d'Oria -- NPC: Ceraulian -- Involved in Quest: The Holy Crest -- !pos 0 -8 -122 232 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/globals/keyitems"); local ID = require("scripts/zones/Port_San_dOria/IDs"); ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(SANDORIA,dsp.quest.id.sandoria.CHASING_QUOTAS) == QUEST_ACCEPTED and player:getCharVar("ChasingQuotas_Progress") == 0 and trade:getItemCount() == 1 and trade:hasItemQty(12494,1) and trade:getGil() == 0) then -- Trading gold hairpin only player:tradeComplete(); player:startEvent(17); end end; function onTrigger(player,npc) local Quotas_Status = player:getQuestStatus(SANDORIA,dsp.quest.id.sandoria.CHASING_QUOTAS); local Quotas_Progress = player:getCharVar("ChasingQuotas_Progress"); local Quotas_No = player:getCharVar("ChasingQuotas_No"); local Stalker_Status = player:getQuestStatus(SANDORIA,dsp.quest.id.sandoria.KNIGHT_STALKER); local Stalker_Progress = player:getCharVar("KnightStalker_Progress"); if (player:getMainLvl() >= ADVANCED_JOB_LEVEL and player:getQuestStatus(SANDORIA,dsp.quest.id.sandoria.THE_HOLY_CREST) == QUEST_AVAILABLE) then player:startEvent(24); -- Chasing Quotas (DRG AF2) elseif (Quotas_Status == QUEST_AVAILABLE and player:getMainJob() == dsp.job.DRG and player:getMainLvl() >= AF1_QUEST_LEVEL and Quotas_No == 0) then player:startEvent(18); -- Long version of quest start elseif (Quotas_No == 1) then player:startEvent(14); -- Short version for those that said no. elseif (Quotas_Status == QUEST_ACCEPTED and Quotas_Progress == 0) then players:startEvent(13); -- Reminder to bring Gold Hairpin elseif (Quotas_Progress == 1) then if (player:getCharVar("ChasingQuotas_date") > os.time()) then player:startEvent(3); -- Fluff cutscene because you haven't waited a day else player:startEvent(7); -- Boss got mugged end elseif (Quotas_Progress == 2) then player:startEvent(8); -- Go investigate elseif (Quotas_Progress == 3) then player:startEvent(6); -- Earring is a clue, non-required CS elseif (Quotas_Progress == 4 or Quotas_Progress == 5) then player:startEvent(9); -- Fluff text until Ceraulian is necessary again elseif (Quotas_Progress == 6) then player:startEvent(15); -- End of AF2 elseif (Quotas_Status == QUEST_COMPLETED and Stalker_Status == QUEST_AVAILABLE) then player:startEvent(16); -- Fluff text until DRG AF3 -- Knight Stalker (DRG AF3) elseif (Stalker_Status == QUEST_ACCEPTED and Stalker_Progress == 0) then player:startEvent(19); -- Fetch the last Dragoon's helmet elseif (Stalker_Progress == 1) then if (player:hasKeyItem(dsp.ki.CHALLENGE_TO_THE_ROYAL_KNIGHTS) == false) then player:startEvent(23); -- Reminder to get helmet else player:startEvent(20); -- Response if you try to turn in the challenge to Ceraulian end elseif (player:getCharVar("KnightStalker_Option1") == 1) then player:startEvent(22); elseif (Stalker_Status == QUEST_COMPLETED) then player:startEvent(21); else player:startEvent(587); end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) if (csid == 24) then player:setCharVar("TheHolyCrest_Event",1); -- Chasing Quotas (DRG AF2) elseif (csid == 18) then if option == 0 then player:setCharVar("ChasingQuotas_No",1); else player:addQuest(SANDORIA,dsp.quest.id.sandoria.CHASING_QUOTAS); end elseif (csid == 14 and option == 1) then player:setCharVar("ChasingQuotas_No",0); player:addQuest(SANDORIA,dsp.quest.id.sandoria.CHASING_QUOTAS); elseif (csid == 17) then player:setCharVar("ChasingQuotas_Progress",1); player:setCharVar("ChasingQuotas_date", getMidnight()); elseif (csid == 7) then player:setCharVar("ChasingQuotas_Progress",2); player:setCharVar("ChasingQuotas_date",0); elseif (csid == 15) then if (player:getFreeSlotsCount() < 1) then player:messageSpecial(ID.text.ITEM_CANNOT_BE_OBTAINED,14227); else player:delKeyItem(dsp.ki.RANCHURIOMES_LEGACY); player:addItem(14227); player:messageSpecial(ID.text.ITEM_OBTAINED,14227); -- Drachen Brais player:addFame(SANDORIA,40); player:completeQuest(SANDORIA,dsp.quest.id.sandoria.CHASING_QUOTAS); player:setCharVar("ChasingQuotas_Progress",0); end -- Knight Stalker (DRG AF3) elseif (csid == 19) then player:setCharVar("KnightStalker_Progress",1); elseif (csid == 22) then player:setCharVar("KnightStalker_Option1",0); end end;
gpl-3.0
RunAwayDSP/darkstar
scripts/globals/mobskills/hydro_canon.lua
11
1388
--------------------------------------------------- -- Hydro_Canon -- Description: -- Type: Magical -- additional effect : 40hp/tick Poison --------------------------------------------------- require("scripts/globals/settings") require("scripts/globals/status") require("scripts/globals/monstertpmoves") --------------------------------------------------- function onMobSkillCheck(target,mob,skill) -- skillList 54 = Omega -- skillList 727 = Proto-Omega -- skillList 728 = Ultima -- skillList 729 = Proto-Ultima local skillList = mob:getMobMod(dsp.mobMod.SKILL_LIST) local mobhp = mob:getHPP() local phase = mob:getLocalVar("battlePhase") if ((skillList == 729 and phase >= 1 and phase <= 2) or (skillList == 728 and mobhp < 70 and mobhp >= 40)) then return 0 end return 1 end function onMobWeaponSkill(target, mob, skill) local typeEffect = dsp.effect.POISON local power = 40 MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, power, 3, 60) local dmgmod = 2 local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*3,dsp.magic.ele.WATER,dmgmod,TP_MAB_BONUS,1) local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,dsp.attackType.MAGICAL,dsp.damageType.WATER,MOBPARAM_IGNORE_SHADOWS) target:takeDamage(dmg, mob, dsp.attackType.MAGICAL, dsp.damageType.WATER) return dmg end
gpl-3.0
Wiladams/LJIT2RenderingManager
DRMFrameBuffer.lua
4
4803
local ffi = require("ffi") local bit = require("bit") local bor, band, lshift, rshift = bit.bor, bit.band, bit.lshift, bit.rshift local xf86drmMode = require("xf86drmMode_ffi") local xf86drm = require("xf86drm_ffi") local drm = require("drm") local libc = require("libc") -- just a little mmap helper local function emmap(addr, len, prot, flag, fd, offset) local mapPtr = libc.mmap(addr, len, prot, flag, fd, offset); local fp = ffi.cast("uint32_t *", mapPtr); if (fp == libc.MAP_FAILED) then error("mmap"); end --ffi.gc(fp, libc.munmap); return fp; end local DRMFrameBuffer = {} setmetatable(DRMFrameBuffer, { __call = function(self, ...) return self:new(...); end, }) local DRMFrameBuffer_mt = { __index = DRMFrameBuffer; __tostring = function(self) return self:toString(); end; } --[[ typedef struct _drmModeFB { uint32_t fb_id; uint32_t width, height; uint32_t pitch; uint32_t bpp; uint32_t depth; /* driver specific handle */ uint32_t handle; } drmModeFB, *drmModeFBPtr; --]] function DRMFrameBuffer.init(self, fd, rawInfo, dataPtr) local obj = { CardFd = fd; RawInfo = rawInfo; DataPtr = dataPtr; Id = rawInfo.fb_id; Width = rawInfo.width; Height = rawInfo.height; Pitch = rawInfo.pitch; BitsPerPixel = rawInfo.bpp; Depth = rawInfo.depth; DriverHandle = rawInfo.handle; } setmetatable(obj, DRMFrameBuffer_mt) return obj; end function DRMFrameBuffer.new(self, fd, bufferId, dataPtr) local rawInfo = xf86drmMode.drmModeGetFB(fd, bufferId); if rawInfo == nil then return nil, "could not get FB" end ffi.gc(rawInfo, xf86drmMode.drmModeFreeFB); return self:init(fd, rawInfo, dataPtr); end --[[ /* create a dumb scanout buffer */ struct drm_mode_create_dumb { uint32_t height; uint32_t width; uint32_t bpp; uint32_t flags; /* handle, pitch, size will be returned */ uint32_t handle; uint32_t pitch; uint64_t size; }; --]] function DRMFrameBuffer.newScanoutBuffer(self, card, width, height, bpp, depth) bpp = bpp or 32 depth = depth or 24 local fd = card.Handle; local creq = ffi.new("struct drm_mode_create_dumb"); -- We need to make a drmIoctl call passing in a partially filled -- in data structure. We need to find out the handle, pitch and size -- fields, for the given width and height creq.width = width; creq.height = height; creq.bpp = bpp; creq.flags = 0; if (xf86drm.drmIoctl(fd, drm.DRM_IOCTL_MODE_CREATE_DUMB, creq) < 0) then return nil, "drmIoctl DRM_IOCTL_MODE_CREATE_DUMB failed"; end -- Now that we have the pitch and size stuff filled out, -- we need to allocate the frame buffer, and get the -- new ID that is associated with it. local buf_idp = ffi.new("uint32_t[1]"); if (xf86drmMode.drmModeAddFB(fd, width, height, depth, bpp, creq.pitch, creq.handle, buf_idp) ~= 0) then error("drmModeAddFB failed"); end local buf_id = tonumber(buf_idp[0]); --print("buf_id: ", buf_id) -- With the framebuffer in hand, we now can allocate memory and -- map it, and local mreq = ffi.new("struct drm_mode_map_dumb"); mreq.handle = creq.handle; if (xf86drm.drmIoctl(fd, drm.DRM_IOCTL_MODE_MAP_DUMB, mreq) ~= 0) then error("drmIoctl DRM_IOCTL_MODE_MAP_DUMB failed"); end --print(string.format("mreq [handle, pad, offset]: %d %d %p", mreq.handle, mreq.pad, ffi.cast("intptr_t",mreq.offset))) local dataPtr = emmap(nil, creq.size, bor(libc.PROT_READ, libc.PROT_WRITE), libc.MAP_SHARED, fd, mreq.offset); --print("dataPtr: ", dataPtr) return DRMFrameBuffer(card.Handle, buf_id, dataPtr); end function DRMFrameBuffer.getDataPtr(self) local fd = self.CardFd; local fbcmd = ffi.new("struct drm_mode_fb_cmd"); fbcmd.fb_id = self.Id; local res = xf86drm.drmIoctl(fd, drm.DRM_IOCTL_MODE_GETFB, fbcmd) if res < 0 then return nil, "drmIoctl DRM_IOCTL_MODE_CREATE_DUMB failed"; end -- print("DRMFrameBuffer.getDataPtr(), [width, height, pitch, handle]: ", fbcmd.width, fbcmd.height, fbcmd.pitch, fbcmd.handle); local mreq = ffi.new("struct drm_mode_map_dumb"); mreq.handle = fbcmd.handle; if (xf86drm.drmIoctl(self.CardFd, drm.DRM_IOCTL_MODE_MAP_DUMB, mreq) ~= 0) then error("drmIoctl DRM_IOCTL_MODE_MAP_DUMB failed"); end --print(string.format("mreq [handle, pad, offset]: %d %d %p", mreq.handle, mreq.pad, ffi.cast("intptr_t",mreq.offset))) local size = fbcmd.pitch*fbcmd.height; local dataPtr = emmap(nil, size, bor(libc.PROT_READ, libc.PROT_WRITE), libc.MAP_SHARED, fd, mreq.offset); return dataPtr end function DRMFrameBuffer.toString(self) return string.format([[ Id: %d Size: %d X %d Pitch: %d BitsPerPixel: %d Depth: %d Driver Handle: %s Data: %p ]], self.Id, self.Width, self.Height, self.Pitch, self.BitsPerPixel, self.Depth, self.DriverHandle, self.DataPtr); end return DRMFrameBuffer
mit
lichtl/darkstar
scripts/zones/Jugner_Forest/npcs/Alexius.lua
14
1619
----------------------------------- -- Area: Jugner Forest -- NPC: Alexius -- Involved in Quest: A purchase of Arms & Sin Hunting -- @pos 105 1 382 104 ----------------------------------- package.loaded["scripts/zones/Jugner_Forest/TextIDs"] = nil; ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Jugner_Forest/TextIDs"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) local SinHunting = player:getVar("sinHunting"); -- RNG AF1 if (player:hasKeyItem(WEAPONS_ORDER) == true) then player:startEvent(0x0005); elseif (SinHunting == 3) then player:startEvent(0x000a); 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 == 0x0005) then player:delKeyItem(WEAPONS_ORDER); player:addKeyItem(WEAPONS_RECEIPT); player:messageSpecial(KEYITEM_OBTAINED,WEAPONS_RECEIPT); elseif (csid == 0x000a) then player:setVar("sinHunting",4); end end;
gpl-3.0
RunAwayDSP/darkstar
scripts/zones/The_Garden_of_RuHmet/npcs/Ebon_Panel.lua
9
3451
----------------------------------- -- Area: The Garden of RuHmet -- NPC: Ebon_Panel -- !pos 100.000 -5.180 -337.661 35 | Mithra Tower -- !pos 740.000 -5.180 -342.352 35 | Elvaan Tower -- !pos 257.650 -5.180 -699.999 35 | Tarutaru Tower -- !pos 577.648 -5.180 -700.000 35 | Galka Tower ----------------------------------- local ID = require("scripts/zones/The_Garden_of_RuHmet/IDs") require("scripts/globals/keyitems") require("scripts/globals/missions") require("scripts/globals/status") require("scripts/globals/titles") ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) local Race = player:getRace(); local xPos = npc:getXPos(); if (player:getCurrentMission(COP) == dsp.mission.id.cop.WHEN_ANGELS_FALL and player:getCharVar("PromathiaStatus") == 1) then player:startEvent(202); elseif (player:getCurrentMission(COP) == dsp.mission.id.cop.WHEN_ANGELS_FALL and player:getCharVar("PromathiaStatus") == 2) then if (xPos > 99 and xPos < 101) then -- Mithra Tower if ( Race==dsp.race.MITHRA ) then player:startEvent(124); else player:messageSpecial(ID.text.NO_NEED_INVESTIGATE); end elseif (xPos > 739 and xPos < 741) then -- Elvaan Tower if ( Race==dsp.race.ELVAAN_M or Race==dsp.race.ELVAAN_F) then player:startEvent(121); else player:messageSpecial(ID.text.NO_NEED_INVESTIGATE); end elseif (xPos > 256 and xPos < 258) then -- Tarutaru Tower if ( Race==dsp.race.TARU_M or Race==dsp.race.TARU_F ) then player:startEvent(123); else player:messageSpecial(ID.text.NO_NEED_INVESTIGATE); end elseif (xPos > 576 and xPos < 578) then -- Galka Tower if ( Race==dsp.race.GALKA) then player:startEvent(122); else player:messageSpecial(ID.text.NO_NEED_INVESTIGATE); end end else player:messageSpecial(ID.text.NO_NEED_INVESTIGATE); end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) if (csid == 202) then player:setCharVar("PromathiaStatus",2); elseif (124 and option ~=0) then -- Mithra player:addTitle(dsp.title.WARRIOR_OF_THE_CRYSTAL); player:setCharVar("PromathiaStatus",3); player:addKeyItem(dsp.ki.LIGHT_OF_DEM); player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.LIGHT_OF_DEM); elseif (121 and option ~=0) then -- Elvaan player:addTitle(dsp.title.WARRIOR_OF_THE_CRYSTAL); player:setCharVar("PromathiaStatus",3); player:addKeyItem(dsp.ki.LIGHT_OF_MEA); player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.LIGHT_OF_MEA); elseif (123 and option ~=0) then -- Tarutaru player:addTitle(dsp.title.WARRIOR_OF_THE_CRYSTAL); player:setCharVar("PromathiaStatus",3); player:addKeyItem(dsp.ki.LIGHT_OF_HOLLA); player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.LIGHT_OF_HOLLA); elseif (122 and option ~=0) then -- Galka player:addTitle(dsp.title.WARRIOR_OF_THE_CRYSTAL); player:setCharVar("PromathiaStatus",3); player:addKeyItem(dsp.ki.LIGHT_OF_ALTAIEU); player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.LIGHT_OF_ALTAIEU); end end;
gpl-3.0
batrick/lua-structure
structure.lua
1
6683
local math = require "math" local floor = math.floor local string = require "string" local format = string.format local table = require "table" local _G = _G local assert = assert local error = error local getmetatable = getmetatable local next = next local rawlen = rawlen local rawget = rawget local rawset = rawset local setmetatable = setmetatable local tostring = tostring local type = type _ENV = {} --[[ structure.new { probes = structure.table { { path = structure.STRING, matcher = structure.STRING + structure.FUNCTION, }, /* array! */ [S.STRING] = S.STRING + S.NIL, -- simple <string, string> pairs allowed } / function (v, s, c) return #v >= 1 and v or nil end, foo = structure.table { n = structure.NUMBER / function (a, structure, container) if a >= 0 and a <= 5 then return a else return nil end end, cacheable = structure.BOOLEAN + structure.NIL / function (a, s, c) return false end, host = structure.STRING / function (hostname, structure, container) return ishostname(hostname) end, } + structure.NIL, file = S.NOTNIL / function (v, s, c) if io.type(v) then return v else return nil end, } --]] local FAILURE = {} -- distinct from nil local function failed(r) return r == FAILURE end local S = {} local M = { __add = function (a, b) a = S.tostructure(a) b = S.tostructure(b) return S.new(function (self, ...) local result, error1 = a:checker(...) if not failed(result) then return result end local result, error2 = b:checker(...) if not failed(result) then return result end return FAILURE end, a.error.." or "..b.error ) end, __div = function (a, test) a = S.tostructure(a) assert(type(test) == "function", "structure divider must be function"); return S.new(function (self, value, ...) local result, error = a:checker(value, ...) if failed(result) then return FAILURE, error end local result, error = test(result, ...) -- cascade if failed(result) then return FAILURE, error end return result end, a.error ) end, __mul = function (a, b) a = S.tostructure(a) b = S.tostructure(b) return S.new(function (self, value, ...) local result, error = a:checker(value, ...) if failed(result) then return FAILURE, error end local result, error = b:checker(result, ...) -- cascade if failed(result) then return FAILURE, error end return result end, b.error.." and "..a.error ) end, __sub = function (a, b) return -b.tostructure(b) * a end, __unm = function (a) a = S.tostructure(a) return S.new(function (self, ...) local result, error = a:checker(value, ...) if not failed(result) then return FAILURE, a.error end return ... end, b.error.." and "..a.error ) end, __index = S, } local function stringify (value) if type(value) == "string" then return string.format("%q", value) else return tostring(value) end end function S.tostructure (value) if getmetatable(value) == M then return value end local t = type(value) if t == "boolean" or t == "nil" or t == "number" or t == "string" then return S.new(function (self, o) if o == value then return o else return FAILURE end end, stringify(value)) elseif t == "table" then if not (#value == 1 or #value == 0) then error "structure can only have one array entry to represent values for entire array" end local contents = {} for k, v in next, value do if k == 1 then -- array local sk = S.T.NUMBER / function (n, container) assert(type(n) == "number") if n >= 1 and n <= rawlen(container) and floor(n) == n then return n else return FAILURE end end local sv = S.tostructure(v) contents[sk] = sv else -- everything else contents[S.tostructure(k)] = S.tostructure(v) end end local structure = S.T.TABLE / function (t, container, key, chain) chain = chain or {stringify(t)} local found = {} for sk in next, contents do found[sk] = false end local n = rawlen(t) for k, v in next, t do chain[#chain+1] = "["..stringify(k).."]" local foundkey = false for sk, sv in next, contents do local kresult = sk:checker(k, t, k, chain) if not failed(kresult) then local vresult = sv:checker(v, t, k, chain) if not failed(vresult) then if kresult ~= k and vresult ~= v then rawset(t, kresult, vresult) elseif kresult ~= k then rawset(t, kresult, v) elseif vresult ~= v then rawset(t, k, vresult) end found[sk] = true foundkey = true else return FAILURE, stringify(v).." did not have expected value ("..sv.error..") in structure `"..table.concat(chain).."'" end end end chain[#chain] = nil if not foundkey then return FAILURE, "key "..stringify(k).." is not a valid member of structure `"..table.concat(chain).."'" end end for sk in next, contents do if not found[sk] and failed(contents[sk]:checker(nil, t)) then return FAILURE, "container `"..table.concat(chain).."' is missing required key ("..sk.error..")" end end return t end return structure else return assert(S.T[t:upper()]) end end function S.new (checker, error) assert(type(checker) == "function") local o = { checker = checker, error = error, } return setmetatable(o, M) end function S:check (...) local result, error = self:checker(...) if failed(result) then return nil, error else return result end end function new (structure) return S.tostructure(structure) end local function primitive (t) return S.new(function (self, o) if type(o) == t then return o else return FAILURE end end, "istype("..t..")") end S.T = {} S.T.BOOLEAN = primitive "boolean" S.T.FUNCTION = primitive "function" S.T.INTEGER = primitive "number" / function (o) if floor(o) == o then return o else return FAILURE end end S.T.NIL = primitive "nil" S.T.NOTNIL = S.new(function (self, o) if o ~= nil then return o else return FAILURE end end, "isnot(nil)") S.T.NUMBER = primitive "number" S.T.STRING = primitive "string" S.T.TABLE = primitive "table" S.T.THREAD = primitive "thread" S.T.USERDATA = primitive "userdata" for k, v in next, S.T do _ENV[k] = v end return _ENV
mit
Zariel/bollo2
lib/AceGUI-3.0/widgets/AceGUIWidget-Keybinding.lua
1
5537
local AceGUI = LibStub("AceGUI-3.0") -------------------------- -- Keybinding -- -------------------------- do local Type = "Keybinding" local Version = 11 local ControlBackdrop = { bgFile = "Interface\\Tooltips\\UI-Tooltip-Background", edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border", tile = true, tileSize = 16, edgeSize = 16, insets = { left = 3, right = 3, top = 3, bottom = 3 } } local function Control_OnEnter(this) this.obj:Fire("OnEnter") end local function Control_OnLeave(this) this.obj:Fire("OnLeave") end local function keybindingMsgFixWidth(this) this:SetWidth(this.msg:GetWidth()+10) this:SetScript("OnUpdate",nil) end local function Keybinding_OnClick(this, button) if button == "LeftButton" or button == "RightButton" then local self = this.obj if self.waitingForKey then this:EnableKeyboard(false) self.msgframe:Hide() this:UnlockHighlight() self.waitingForKey = nil else this:EnableKeyboard(true) self.msgframe:Show() this:LockHighlight() self.waitingForKey = true end end AceGUI:ClearFocus() end local ignoreKeys = nil local function Keybinding_OnKeyDown(this, key) local self = this.obj if self.waitingForKey then local keyPressed = key if keyPressed == "ESCAPE" then keyPressed = "" else if not ignoreKeys then ignoreKeys = { ["BUTTON1"] = true, ["BUTTON2"] = true, ["UNKNOWN"] = true, ["LSHIFT"] = true, ["LCTRL"] = true, ["LALT"] = true, ["RSHIFT"] = true, ["RCTRL"] = true, ["RALT"] = true, } end if ignoreKeys[keyPressed] then return end if IsShiftKeyDown() then keyPressed = "SHIFT-"..keyPressed end if IsControlKeyDown() then keyPressed = "CTRL-"..keyPressed end if IsAltKeyDown() then keyPressed = "ALT-"..keyPressed end end this:EnableKeyboard(false) self.msgframe:Hide() this:UnlockHighlight() self.waitingForKey = nil if not self.disabled then self:SetKey(keyPressed) self:Fire("OnKeyChanged",keyPressed) end end end local function Keybinding_OnMouseDown(this, button) if button == "LeftButton" or button == "RightButton" then return elseif button == "MiddleButton" then button = "BUTTON3" elseif button == "Button4" then button = "BUTTON4" elseif button == "Button5" then button = "BUTTON5" end Keybinding_OnKeyDown(this, button) end local function OnAcquire(self) self:SetLabel("") self:SetKey("") end local function OnRelease(self) self.frame:ClearAllPoints() self.frame:Hide() self.waitingForKey = nil self.msgframe:Hide() end local function SetDisabled(self, disabled) self.disabled = disabled if disabled then self.button:Disable() self.label:SetTextColor(0.5,0.5,0.5) else self.button:Enable() self.label:SetTextColor(1,1,1) end end local function SetKey(self, key) if (key or "") == "" then self.button:SetText(NOT_BOUND) self.button:SetNormalFontObject("GameFontNormal") else self.button:SetText(key) self.button:SetNormalFontObject("GameFontHighlight") end end local function SetLabel(self, label) self.label:SetText(label or "") if (label or "") == "" then self.alignoffset = nil self:SetHeight(24) else self.alignoffset = 30 self:SetHeight(44) end end local function Constructor() local num = AceGUI:GetNextWidgetNum(Type) local frame = CreateFrame("Frame",nil,UIParent) local button = CreateFrame("Button","AceGUI-3.0 KeybindingButton"..num,frame,"UIPanelButtonTemplate2") local self = {} self.type = Type self.num = num local text = button:GetFontString() text:SetPoint("LEFT",button,"LEFT",7,0) text:SetPoint("RIGHT",button,"RIGHT",-7,0) button:SetScript("OnClick",Keybinding_OnClick) button:SetScript("OnKeyDown",Keybinding_OnKeyDown) button:SetScript("OnEnter",Control_OnEnter) button:SetScript("OnLeave",Control_OnLeave) button:SetScript("OnMouseDown",Keybinding_OnMouseDown) button:RegisterForClicks("AnyDown") button:EnableMouse() button:SetHeight(24) button:SetWidth(200) button:SetPoint("BOTTOMLEFT", frame, "BOTTOMLEFT",0,0) button:SetPoint("BOTTOMRIGHT",frame,"BOTTOMRIGHT",0,0) frame:SetWidth(200) frame:SetHeight(44) self.alignoffset = 30 self.button = button local label = frame:CreateFontString(nil,"OVERLAY","GameFontHighlight") label:SetPoint("TOPLEFT",frame,"TOPLEFT",0,0) label:SetPoint("TOPRIGHT",frame,"TOPRIGHT",0,0) label:SetJustifyH("CENTER") label:SetHeight(18) self.label = label local msgframe = CreateFrame("Frame",nil,UIParent) msgframe:SetHeight(30) msgframe:SetBackdrop(ControlBackdrop) msgframe:SetBackdropColor(0,0,0) msgframe:SetFrameStrata("FULLSCREEN_DIALOG") msgframe:SetFrameLevel(1000) self.msgframe = msgframe local msg = msgframe:CreateFontString(nil,"OVERLAY","GameFontNormal") msg:SetText("Press a key to bind, ESC to clear the binding or click the button again to cancel") msgframe.msg = msg msg:SetPoint("TOPLEFT",msgframe,"TOPLEFT",5,-5) msgframe:SetScript("OnUpdate", keybindingMsgFixWidth) msgframe:SetPoint("BOTTOM",button,"TOP",0,0) msgframe:Hide() self.OnRelease = OnRelease self.OnAcquire = OnAcquire self.SetLabel = SetLabel self.SetDisabled = SetDisabled self.SetKey = SetKey self.frame = frame frame.obj = self button.obj = self AceGUI:RegisterAsWidget(self) return self end AceGUI:RegisterWidgetType(Type,Constructor,Version) end
bsd-3-clause
taiha/luci
modules/luci-base/luasrc/ltn12.lua
84
8954
--[[ LuaSocket 2.0.2 license Copyright � 2004-2007 Diego Nehab 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. ]]-- --[[ Changes made by LuCI project: * Renamed to luci.ltn12 to avoid collisions with luasocket * Added inline documentation ]]-- ----------------------------------------------------------------------------- -- LTN12 - Filters, sources, sinks and pumps. -- LuaSocket toolkit. -- Author: Diego Nehab -- RCS ID: $Id$ ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- -- Declare module ----------------------------------------------------------------------------- local string = require("string") local table = require("table") local base = _G -- See http://lua-users.org/wiki/FiltersSourcesAndSinks for design concepts module("luci.ltn12") filter = {} source = {} sink = {} pump = {} -- 2048 seems to be better in windows... BLOCKSIZE = 2048 _VERSION = "LTN12 1.0.1" ----------------------------------------------------------------------------- -- Filter stuff ----------------------------------------------------------------------------- -- by passing it each chunk and updating a context between calls. function filter.cycle(low, ctx, extra) base.assert(low) return function(chunk) local ret ret, ctx = low(ctx, chunk, extra) return ret end end -- (thanks to Wim Couwenberg) function filter.chain(...) local n = table.getn(arg) local top, index = 1, 1 local retry = "" return function(chunk) retry = chunk and retry while true do if index == top then chunk = arg[index](chunk) if chunk == "" or top == n then return chunk elseif chunk then index = index + 1 else top = top+1 index = top end else chunk = arg[index](chunk or "") if chunk == "" then index = index - 1 chunk = retry elseif chunk then if index == n then return chunk else index = index + 1 end else base.error("filter returned inappropriate nil") end end end end end ----------------------------------------------------------------------------- -- Source stuff ----------------------------------------------------------------------------- -- create an empty source local function empty() return nil end function source.empty() return empty end function source.error(err) return function() return nil, err end end function source.file(handle, io_err) if handle then return function() local chunk = handle:read(BLOCKSIZE) if chunk and chunk:len() == 0 then chunk = nil end if not chunk then handle:close() end return chunk end else return source.error(io_err or "unable to open file") end end function source.simplify(src) base.assert(src) return function() local chunk, err_or_new = src() src = err_or_new or src if not chunk then return nil, err_or_new else return chunk end end end function source.string(s) if s then local i = 1 return function() local chunk = string.sub(s, i, i+BLOCKSIZE-1) i = i + BLOCKSIZE if chunk ~= "" then return chunk else return nil end end else return source.empty() end end function source.rewind(src) base.assert(src) local t = {} return function(chunk) if not chunk then chunk = table.remove(t) if not chunk then return src() else return chunk end else t[#t+1] = chunk end end end function source.chain(src, f) base.assert(src and f) local last_in, last_out = "", "" local state = "feeding" local err return function() if not last_out then base.error('source is empty!', 2) end while true do if state == "feeding" then last_in, err = src() if err then return nil, err end last_out = f(last_in) if not last_out then if last_in then base.error('filter returned inappropriate nil') else return nil end elseif last_out ~= "" then state = "eating" if last_in then last_in = "" end return last_out end else last_out = f(last_in) if last_out == "" then if last_in == "" then state = "feeding" else base.error('filter returned ""') end elseif not last_out then if last_in then base.error('filter returned inappropriate nil') else return nil end else return last_out end end end end end -- Sources will be used one after the other, as if they were concatenated -- (thanks to Wim Couwenberg) function source.cat(...) local src = table.remove(arg, 1) return function() while src do local chunk, err = src() if chunk then return chunk end if err then return nil, err end src = table.remove(arg, 1) end end end ----------------------------------------------------------------------------- -- Sink stuff ----------------------------------------------------------------------------- function sink.table(t) t = t or {} local f = function(chunk, err) if chunk then t[#t+1] = chunk end return 1 end return f, t end function sink.simplify(snk) base.assert(snk) return function(chunk, err) local ret, err_or_new = snk(chunk, err) if not ret then return nil, err_or_new end snk = err_or_new or snk return 1 end end function sink.file(handle, io_err) if handle then return function(chunk, err) if not chunk then handle:close() return 1 else return handle:write(chunk) end end else return sink.error(io_err or "unable to open file") end end -- creates a sink that discards data local function null() return 1 end function sink.null() return null end function sink.error(err) return function() return nil, err end end function sink.chain(f, snk) base.assert(f and snk) return function(chunk, err) if chunk ~= "" then local filtered = f(chunk) local done = chunk and "" while true do local ret, snkerr = snk(filtered, err) if not ret then return nil, snkerr end if filtered == done then return 1 end filtered = f(done) end else return 1 end end end ----------------------------------------------------------------------------- -- Pump stuff ----------------------------------------------------------------------------- function pump.step(src, snk) local chunk, src_err = src() local ret, snk_err = snk(chunk, src_err) if chunk and ret then return 1 else return nil, src_err or snk_err end end function pump.all(src, snk, step) base.assert(src and snk) step = step or pump.step while true do local ret, err = step(src, snk) if not ret then if err then return nil, err else return 1 end end end end
apache-2.0
hsmaniee/narsisbaby
plugins/rules.lua
43
2283
-------------------------------------------------- -- ____ ____ _____ -- -- | \| _ )_ _|___ ____ __ __ -- -- | |_ ) _ \ | |/ ·__| _ \_| \/ | -- -- |____/|____/ |_|\____/\_____|_/\/\_| -- -- -- -------------------------------------------------- -- -- -- Developers: @Josepdal & @MaSkAoS -- -- Support: @Skneos, @iicc1 & @serx666 -- -- -- -- Created by @Josepdal & @A7F -- -- -- -------------------------------------------------- local function set_rules_channel(msg, text) local rules = text local hash = 'channel:id:'..msg.to.id..':rules' redis:set(hash, rules) end local function del_rules_channel(chat_id) local hash = 'channel:id:'..chat_id..':rules' redis:del(hash) end local function init_def_rules(chat_id) local rules = 'ℹ️ Rules:\n' ..'1⃣ No Flood.\n' ..'2⃣ No Spam.\n' ..'3⃣ Try to stay on topic.\n' ..'4⃣ Forbidden any racist, sexual, homophobic or gore content.\n' ..'➡️ Repeated failure to comply with these rules will cause ban.' local hash='channel:id:'..chat_id..':rules' redis:set(hash, rules) end local function ret_rules_channel(msg) local chat_id = msg.to.id local hash = 'channel:id:'..msg.to.id..':rules' if redis:get(hash) then return redis:get(hash) else init_def_rules(chat_id) return redis:get(hash) end end local function run(msg, matches) if matches[1] == 'rules' then return ret_rules_channel(msg) elseif matches[1] == 'setrules' then if permissions(msg.from.id, msg.to.id, 'rules') then set_rules_channel(msg, matches[2]) return 'ℹ️ '..lang_text(msg.to.id, 'setRules') end elseif matches[1] == 'remrules' then if permissions(msg.from.id, msg.to.id, 'rules') then del_rules_channel(msg.to.id) return 'ℹ️ '..lang_text(msg.to.id, 'remRules') end end end return { patterns = { '^[!/#](rules)$', '^[!/#](setrules) (.+)$', '^[!/#](remrules)$' }, run = run }
gpl-2.0
RunAwayDSP/darkstar
scripts/globals/spells/phalanx.lua
12
1147
----------------------------------------- -- Spell: PHALANX ----------------------------------------- require("scripts/globals/magic") require("scripts/globals/msg") require("scripts/globals/status") ----------------------------------------- function onMagicCastingCheck(caster, target, spell) return 0 end function onSpellCast(caster, target, spell) local enhskill = caster:getSkillLevel(dsp.skill.ENHANCING_MAGIC) local final = 0 local duration = calculateDuration(180, spell:getSkillType(), spell:getSpellGroup(), caster, target) duration = calculateDurationForLvl(duration, 33, target:getMainLvl()) if enhskill <= 300 then final = math.max(enhskill / 10 - 2, 0) elseif enhskill > 300 then final = (enhskill - 300) / 29 + 28 else print("Warning: Unknown enhancing magic skill for phalanx.") end -- Cap at 35 final = math.min(final, 35) if target:addStatusEffect(dsp.effect.PHALANX, final, 0, duration) then spell:setMsg(dsp.msg.basic.MAGIC_GAIN_EFFECT) else spell:setMsg(dsp.msg.basic.MAGIC_NO_EFFECT) end return dsp.effect.PHALANX end
gpl-3.0
sirinsidiator/ESO-LibAddonMenu
LibAddonMenu-2.0/controls/custom.lua
1
1881
--[[customData = { type = "custom", reference = "MyAddonCustomControl", -- unique name for your control to use as reference (optional) createFunc = function(customControl) end, -- function to call when this custom control was created (optional) refreshFunc = function(customControl) end, -- function to call when panel/controls refresh (optional) width = "full", -- or "half" (optional) minHeight = function() return db.minHeightNumber end, --or number for the minimum height of this control. Default: 26 (optional) maxHeight = function() return db.maxHeightNumber end, --or number for the maximum height of this control. Default: 4 * minHeight (optional) } ]] local widgetVersion = 8 local LAM = LibAddonMenu2 if not LAM:RegisterWidget("custom", widgetVersion) then return end local function UpdateValue(control) if control.data.refreshFunc then control.data.refreshFunc(control) end end local MIN_HEIGHT = 26 function LAMCreateControl.custom(parent, customData, controlName) local control = LAM.util.CreateBaseControl(parent, customData, controlName) local width = control:GetWidth() control:SetResizeToFitDescendents(true) local minHeight = (control.data.minHeight and LAM.util.GetDefaultValue(control.data.minHeight)) or MIN_HEIGHT local maxHeight = (control.data.maxHeight and LAM.util.GetDefaultValue(control.data.maxHeight)) or (minHeight * 4) if control.isHalfWidth then --note these restrictions control:SetDimensionConstraints(width / 2, minHeight, width / 2, maxHeight) else control:SetDimensionConstraints(width, minHeight, width, maxHeight) end control.UpdateValue = UpdateValue LAM.util.RegisterForRefreshIfNeeded(control) if customData.createFunc then customData.createFunc(control) end return control end
artistic-2.0
lichtl/darkstar
scripts/zones/Northern_San_dOria/npcs/Matildie.lua
17
1749
----------------------------------- -- Area: Northern San d'Oria -- NPC: Matildie -- Adventurer's Assistant ------------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Northern_San_dOria/TextIDs"); require("scripts/globals/settings"); require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (trade:getItemCount() == 1 and trade:hasItemQty(0x218,1) == true) then player:startEvent(0x277); player:addGil(GIL_RATE*50); player:tradeComplete(); end -- "Flyers for Regine" conditional script local FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then local count = trade:getItemCount(); local MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x24B); 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 == 0x277) then player:messageSpecial(GIL_OBTAINED,GIL_RATE*50); end end;
gpl-3.0
lichtl/darkstar
scripts/zones/Phomiuna_Aqueducts/npcs/_ir9.lua
14
1790
----------------------------------- -- Area: Phomiuna_Aqueducts -- NPC: _ir9 (Iron Gate) -- @pos 70 -1.5 140 27 ----------------------------------- package.loaded["scripts/zones/Phomiuna_Aqueducts/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/missions"); require("scripts/zones/Phomiuna_Aqueducts/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getXPos() < 70 and npc:getAnimation() == 9) then if (trade:hasItemQty(1660,1) and trade:getItemCount() == 1) then -- Bronze Key player:tradeComplete(); npc:openDoor(15); elseif ((trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1 and player:getMainJob() == JOBS.THF) then -- thief's tool/living key/skeleton key as THF main player:tradeComplete(); npc:openDoor(15); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getXPos() >= 70) then npc:openDoor(15); -- Retail timed elseif (npc:getAnimation() == 9) then player:messageSpecial(DOOR_LOCKED,1660); 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); end;
gpl-3.0
RunAwayDSP/darkstar
scripts/zones/Abyssea-Tahrongi/IDs.lua
12
5067
----------------------------------- -- Area: Abyssea-Tahrongi ----------------------------------- require("scripts/globals/keyitems") require("scripts/globals/zone") ----------------------------------- zones = zones or {} zones[dsp.zone.ABYSSEA_TAHRONGI] = { text = { ITEM_CANNOT_BE_OBTAINED = 6382, -- You cannot obtain the <item>. Come back after sorting your inventory. ITEM_OBTAINED = 6388, -- Obtained: <item>. GIL_OBTAINED = 6389, -- Obtained <number> gil. KEYITEM_OBTAINED = 6391, -- Obtained key item: <keyitem>. CRUOR_TOTAL = 6986, -- Obtained <number> cruor. (Total: <number>) CRUOR_OBTAINED = 7495, -- <name> obtained <number> cruor. }, mob = { }, npc = { QM_POPS = { -- [16961954] = { 'qm1', {2915}, {}, 16961917}, -- Halimede -- [16961955] = { 'qm2', {2916}, {}, 16961918}, -- Vetehinen -- [16961956] = { 'qm3', {2917,2945,2946}, {}, 16961919}, -- Ophanim -- [16961957] = { 'qm4', {2918}, {}, 16961920}, -- Cannered Noz -- [16961958] = { 'qm5', {2919,2947}, {}, 16961921}, -- Treble Noctules -- [16961959] = { 'qm6', {2920}, {}, 16961922}, -- Gancanagh -- [16961960] = { 'qm7', {2921,2948}, {}, 16961923}, -- Hedetet -- [16961961] = { 'qm8', {2922}, {}, 16961924}, -- Abas -- [16961962] = { 'qm9', {2923,2949}, {}, 16961925}, -- Alectryon -- [16961963] = {'qm10', {2924}, {}, 16961926}, -- Tefnet -- [16961964] = {'qm11', {2925,2950}, {}, 16961927}, -- Muscaliet -- [16961965] = {'qm12', {2926}, {}, 16961928}, -- Lachrymater -- [16961966] = {'qm13', {}, {dsp.ki.VEINOUS_HECTEYES_EYELID,dsp.ki.TORN_BAT_WING,dsp.ki.GORY_SCORPION_CLAW,dsp.ki.MOSSY_ADAMANTOISE_SHELL}, 16961929}, -- Chloris -- [16961967] = {'qm14', {}, {dsp.ki.FAT_LINED_COCKATRICE_SKIN,dsp.ki.SODDEN_SANDWORM_HUSK,dsp.ki.LUXURIANT_MANTICORE_MANE,dsp.ki.STICKY_GNAT_WING}, 16961930}, -- Glavoid -- [16961968] = {'qm15', {}, {dsp.ki.OVERGROWN_MANDRAGORA_FLOWER,dsp.ki.CHIPPED_SANDWORM_TOOTH}, 16961931}, -- Lacovie -- [16961969] = {'qm16', {}, {dsp.ki.VEINOUS_HECTEYES_EYELID,dsp.ki.TORN_BAT_WING,dsp.ki.GORY_SCORPION_CLAW,dsp.ki.MOSSY_ADAMANTOISE_SHELL}, 16961946}, -- Chloris -- [16961970] = {'qm17', {}, {dsp.ki.FAT_LINED_COCKATRICE_SKIN,dsp.ki.SODDEN_SANDWORM_HUSK,dsp.ki.LUXURIANT_MANTICORE_MANE,dsp.ki.STICKY_GNAT_WING}, 16961947}, -- Glavoid -- [16961971] = {'qm18', {}, {dsp.ki.OVERGROWN_MANDRAGORA_FLOWER,dsp.ki.CHIPPED_SANDWORM_TOOTH}, 16961948}, -- Lacovie -- [16961972] = {'qm19', {}, {dsp.ki.VEINOUS_HECTEYES_EYELID,dsp.ki.TORN_BAT_WING,dsp.ki.GORY_SCORPION_CLAW,dsp.ki.MOSSY_ADAMANTOISE_SHELL}, 16961949}, -- Chloris -- [16961973] = {'qm20', {}, {dsp.ki.FAT_LINED_COCKATRICE_SKIN,dsp.ki.SODDEN_SANDWORM_HUSK,dsp.ki.LUXURIANT_MANTICORE_MANE,dsp.ki.STICKY_GNAT_WING}, 16961950}, -- Glavoid -- [16961974] = {'qm21', {}, {dsp.ki.OVERGROWN_MANDRAGORA_FLOWER,dsp.ki.CHIPPED_SANDWORM_TOOTH}, 16961951}, -- Lacovie }, }, } return zones[dsp.zone.ABYSSEA_TAHRONGI]
gpl-3.0
bijanbina/Bijoux
Awesome/awesome/b_focus.lua
1
1645
local awful = require("awful") local naughty = require('naughty') -- debug local client = client local aclient = require("awful.client") local timer = require("gears.timer") local function filter_sticky(c) return not c.sticky and aclient.focus.filter(c) end --- Give focus when clients appear/disappear. -- -- @param obj An object that should have a .screen property. local function check_focus(obj) if (not obj.screen) or not obj.screen.valid then return end -- When no visible client has the focus... if not client.focus or not client.focus:isvisible() then local c = aclient.focus.history.get(screen[obj.screen], 0, filter_sticky) if not c then c = aclient.focus.history.get(screen[obj.screen], 0, aclient.focus.filter) end if c then c:emit_signal("request::activate", "autofocus.check_focus", {raise=false}) end end end --- Check client focus (delayed). -- @param obj An object that should have a .screen property. local function check_focus_delayed(obj) timer.delayed_call(check_focus, {screen = obj.screen}) end --tag.connect_signal("property::selected", function (t) -- timer.delayed_call(check_focus_tag, t) --end) client.connect_signal("unmanage", check_focus_delayed) --client.connect_signal("tagged", check_focus_delayed) --client.connect_signal("untagged", check_focus_delayed) client.connect_signal("property::hidden", check_focus_delayed) client.connect_signal("property::minimized", check_focus_delayed) client.connect_signal("property::sticky", check_focus_delayed)
gpl-3.0
punisherbot/he
plugins/minecraft.lua
624
2605
local usage = { "!mine [ip]: Searches Minecraft server on specified ip and sends info. Default port: 25565", "!mine [ip] [port]: Searches Minecraft server on specified ip and port and sends info.", } local ltn12 = require "ltn12" local function mineSearch(ip, port, receiver) --25565 local responseText = "" local api = "https://api.syfaro.net/server/status" local parameters = "?ip="..(URL.escape(ip) or "").."&port="..(URL.escape(port) or "").."&players=true&favicon=true" local http = require("socket.http") local respbody = {} local body, code, headers, status = http.request{ url = api..parameters, method = "GET", redirect = true, sink = ltn12.sink.table(respbody) } local body = table.concat(respbody) if (status == nil) then return "ERROR: status = nil" end if code ~=200 then return "ERROR: "..code..". Status: "..status end local jsonData = json:decode(body) responseText = responseText..ip..":"..port.." ->\n" if (jsonData.motd ~= nil) then local tempMotd = "" tempMotd = jsonData.motd:gsub('%§.', '') if (jsonData.motd ~= nil) then responseText = responseText.." Motd: "..tempMotd.."\n" end end if (jsonData.online ~= nil) then responseText = responseText.." Online: "..tostring(jsonData.online).."\n" end if (jsonData.players ~= nil) then if (jsonData.players.max ~= nil) then responseText = responseText.." Max Players: "..jsonData.players.max.."\n" end if (jsonData.players.now ~= nil) then responseText = responseText.." Players online: "..jsonData.players.now.."\n" end if (jsonData.players.sample ~= nil and jsonData.players.sample ~= false) then responseText = responseText.." Players: "..table.concat(jsonData.players.sample, ", ").."\n" end end if (jsonData.favicon ~= nil and false) then --send_photo(receiver, jsonData.favicon) --(decode base64 and send) end return responseText end local function parseText(chat, text) if (text == nil or text == "!mine") then return usage end ip, port = string.match(text, "^!mine (.-) (.*)$") if (ip ~= nil and port ~= nil) then return mineSearch(ip, port, chat) end local ip = string.match(text, "^!mine (.*)$") if (ip ~= nil) then return mineSearch(ip, "25565", chat) end return "ERROR: no input ip?" end local function run(msg, matches) local chat_id = tostring(msg.to.id) local result = parseText(chat_id, msg.text) return result end return { description = "Searches Minecraft server and sends info", usage = usage, patterns = { "^!mine (.*)$" }, run = run }
gpl-2.0
qenter/vlc-android
vlc/share/lua/playlist/canalplus.lua
113
3501
--[[ $Id: $ Copyright (c) 2007 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.canalplus.fr" ) end -- Parse function. function parse() p = {} --vlc.msg.dbg( vlc.path ) if string.match( vlc.path, "www.canalplus.fr/.*%?pid=.*" ) then -- This is the HTML page's URL local _,_,pid = string.find( vlc.path, "pid(%d-)%-" ) local id, name, description, arturl while true do -- Try to find the video's title local line = vlc.readline() if not line then break end -- vlc.msg.dbg( line ) if string.match( line, "aVideos" ) then if string.match( line, "CONTENT_ID.*=" ) then _,_,id = string.find( line, "\"(.-)\"" ) elseif string.match( line, "CONTENT_VNC_TITRE" ) then _,_,arturl = string.find( line, "src=\"(.-)\"" ) _,_,name = string.find( line, "title=\"(.-)\"" ) elseif string.match( line, "CONTENT_VNC_DESCRIPTION" ) then _,_,description = string.find( line, "\"(.-)\"" ) end if id and string.match( line, "new Array" ) then add_item( p, id, name, description, arturl ) id = nil name = nil arturl = nil description = nil end end end if id then add_item( p, id, name, description, arturl ) end return p elseif string.match( vlc.path, "embed%-video%-player" ) then while true do local line = vlc.readline() if not line then break end --vlc.msg.dbg( line ) if string.match( line, "<hi" ) then local _,_,path = string.find( line, "%[(http.-)%]" ) return { { path = path } } end end end end function get_url_param( url, name ) local _,_,ret = string.find( url, "[&?]"..name.."=([^&]*)" ) return ret end function add_item( p, id, name, description, arturl ) --[[vlc.msg.dbg( "id: " .. tostring(id) ) vlc.msg.dbg( "name: " .. tostring(name) ) vlc.msg.dbg( "arturl: " .. tostring(arturl) ) vlc.msg.dbg( "description: " .. tostring(description) ) --]] --local path = "http://www.canalplus.fr/flash/xml/configuration/configuration-embed-video-player.php?xmlParam="..id.."-"..get_url_param(vlc.path,"pid") local path = "http://www.canalplus.fr/flash/xml/module/embed-video-player/embed-video-player.php?video_id="..id.."&pid="..get_url_param(vlc.path,"pid") table.insert( p, { path = path; name = name; description = description; arturl = arturl } ) end
gpl-2.0
NiLuJe/koreader
frontend/dump.lua
4
2394
--[[-- A simple serialization function which won't do uservalues, functions, or loops. If you need a more full-featured variant, serpent is available in ffi/serpent ;). ]] local insert = table.insert local indent_prefix = " " local function _serialize(what, outt, indent, max_lv, history, pairs_func) if not max_lv then max_lv = math.huge end if indent > max_lv then return end local datatype = type(what) if datatype == "table" then history = history or {} for up, item in ipairs(history) do if item == what then insert(outt, "nil --[[ LOOP:\n") insert(outt, string.rep(indent_prefix, indent - up)) insert(outt, "^------- ]]") return end end local new_history = { what, unpack(history) } local didrun = false insert(outt, "{") for k, v in pairs_func(what) do insert(outt, "\n") insert(outt, string.rep(indent_prefix, indent+1)) insert(outt, "[") _serialize(k, outt, indent+1, max_lv, new_history, pairs_func) insert(outt, "] = ") _serialize(v, outt, indent+1, max_lv, new_history, pairs_func) insert(outt, ",") didrun = true end if didrun then insert(outt, "\n") insert(outt, string.rep(indent_prefix, indent)) end insert(outt, "}") elseif datatype == "string" then insert(outt, string.format("%q", what)) elseif datatype == "number" then insert(outt, tostring(what)) elseif datatype == "boolean" then insert(outt, tostring(what)) elseif datatype == "function" then insert(outt, tostring(what)) elseif datatype == "nil" then insert(outt, "nil") end end --[[--Serializes whatever is in `data` to a string that is parseable by Lua. You can optionally specify a maximum recursion depth in `max_lv`. @function dump @param data the object you want serialized (table, string, number, boolean, nil) @param max_lv optional maximum recursion depth --]] local function dump(data, max_lv, ordered) local out = {} local pairs_func = ordered and require("ffi/util").orderedPairs or pairs _serialize(data, out, 0, max_lv, nil, pairs_func) return table.concat(out) end return dump
agpl-3.0
lichtl/darkstar
scripts/zones/Giddeus/npcs/HomePoint#1.lua
27
1248
----------------------------------- -- Area: Giddeus -- NPC: HomePoint#1 -- @pos -132 -3 -303 145 ----------------------------------- package.loaded["scripts/zones/Giddeus/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/Giddeus/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x21fc, 54); 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 == 0x21fc) then if (option == 1) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); else hpTeleport( player, option); end end end;
gpl-3.0
Levak/Anim-It
src/timer.lua
1
1439
----------------------------- -- Levak ©2014 -------------- -- http://levak.free.fr/ ---- -- levak92@gmail.com -------- ----------------------------- ---------- AnimIt : Timer extension -- Bootstrap of timer.start local _tstart = timer.start function timer.start(ms) if not timer.isRunning then _tstart(ms) end timer.isRunning = true end -- Bootstrap of timer.stop local _tstop = timer.stop function timer.stop() timer.isRunning = false _tstop() end -- Function to call in on.timer function timer.update(no_stop) local j = 1 while j <= #timer.tasks do -- for each task if timer.tasks[j][2]() then -- delete it if has ended table.remove(timer.tasks, j) else j = j + 1 end end if not no_stop and #timer.tasks <= 0 then timer.stop() end end --------------------- ----- Internals ----- --------------------- if platform.hw then timer.multiplier = platform.hw() < 4 and 4 or 1 else timer.multiplier = 4 end timer.tasks = {} function timer.addTask(object, queueID, task) table.insert(timer.tasks, {object, task, queueID}) end function timer.purgeTasks(object, queueID, complete) local j = 1 while j <= #timer.tasks do if timer.tasks[j][1] == object and (not queueID or timer.tasks[j][3] == queueID) then timer.tasks[j][2](complete) table.remove(timer.tasks, j) else j = j + 1 end end end
cc0-1.0
lichtl/darkstar
scripts/zones/Garlaige_Citadel/npcs/Mashira.lua
14
2139
----------------------------------- -- Area: Garlaige Citadel -- NPC: Mashira -- Involved in Quests: Rubbish day, Making Amens! -- @pos 141 -6 138 200 ----------------------------------- package.loaded["scripts/zones/Garlaige_Citadel/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Garlaige_Citadel/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getQuestStatus(JEUNO,RUBBISH_DAY) == QUEST_ACCEPTED and player:getVar("RubbishDayVar") == 0) then player:startEvent(0x000b,1); -- For the quest "Rubbish day" elseif (player:getQuestStatus(WINDURST,MAKING_AMENS) == QUEST_ACCEPTED) then if (player:hasKeyItem(128) == true) then player:startEvent(0x000b,3); else player:startEvent(0x000b,0); -- Making Amens dialogue end else player:startEvent(0x000b,3); -- Standard dialog and menu 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); RubbishDay = player:getQuestStatus(JEUNO,RUBBISH_DAY); MakingAmens = player:getQuestStatus(WINDURST,MAKING_AMENS); if (csid == 0x000b and option == 1 and RubbishDay == QUEST_ACCEPTED) then player:delKeyItem(MAGIC_TRASH); player:setVar("RubbishDayVar",1); elseif (csid == 0x000b and option == 0 and MakingAmens == QUEST_ACCEPTED) then player:addKeyItem(128); --Broken Wand player:messageSpecial(KEYITEM_OBTAINED,128); player:tradeComplete(); end end;
gpl-3.0
lichtl/darkstar
scripts/zones/Kazham/npcs/Pahya_Lolohoiv.lua
17
1373
----------------------------------- -- Area: Kazham -- NPC: Pahya Lolohoiv -- Standard Merchant NPC ----------------------------------- require("scripts/globals/shop"); package.loaded["scripts/zones/Kazham/TextIDs"] = nil; require("scripts/zones/Kazham/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) --player:startEvent(Event(0x004B)); player:showText(npc,PAHYALOLOHOIV_SHOP_DIALOG); stock = {0x119d,10, -- Distilled Water 0x1036,2387, -- Eye Drops 0x1034,290, -- Antidote 0x1037,736, -- Echo Drops 0x1010,837, -- Potion 0x1020,4445, -- Ether 0x039c,556, -- Fiend Blood 0x03af,294} -- Poison Dust 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
lichtl/darkstar
scripts/zones/East_Ronfaure/npcs/Croteillard.lua
14
1043
----------------------------------- -- Area: East Ronfaure -- NPC: Croteillard -- Type: Gate Guard -- @pos 87.426 -62.999 266.709 101 ----------------------------------- package.loaded["scripts/zones/East_Ronfaure/TextIDs"] = nil; ----------------------------------- require("scripts/zones/East_Ronfaure/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc, CROTEILLARD_DIALOG); 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
RunAwayDSP/darkstar
scripts/globals/abilities/pets/judgment_bolt.lua
11
1212
--------------------------------------------------- -- Judgment Bolt --------------------------------------------------- require("/scripts/globals/settings") require("/scripts/globals/status") require("/scripts/globals/monstertpmoves") require("/scripts/globals/magic") --------------------------------------------------- function onAbilityCheck(player, target, ability) local level = player:getMainLvl() * 2 if(player:getMP()<level) then return 87,0 end return 0,0 end function onPetAbility(target, pet, skill, master) local dINT = math.floor(pet:getStat(dsp.mod.INT) - target:getStat(dsp.mod.INT)) local level = pet:getMainLvl() local damage = 48 + (level * 8) damage = damage + (dINT * 1.5) damage = MobMagicalMove(pet,target,skill,damage,dsp.magic.ele.LIGHTNING,1,TP_NO_EFFECT,0) damage = mobAddBonuses(pet, nil, target, damage.dmg, dsp.magic.ele.LIGHTNING) damage = AvatarFinalAdjustments(damage,pet,skill,target,dsp.attackType.MAGICAL,dsp.damageType.LIGHTNING,1) master:setMP(0) target:takeDamage(damage, pet, dsp.attackType.MAGICAL, dsp.damageType.LIGHTNING) target:updateEnmityFromDamage(pet,damage) return damage end
gpl-3.0
lichtl/darkstar
scripts/globals/items/coeurl_sub_+1.lua
18
1925
----------------------------------------- -- ID: 5167 -- Item: coeurl_sub_+1 -- Food Effect: 60Min, All Races ----------------------------------------- -- Magic 15 -- Strength 6 -- Agility 1 -- Intelligence -2 -- Health Regen While Healing 1 -- Attack % 22 -- Attack Cap 80 -- Ranged ATT % 22 -- Ranged ATT Cap 80 -- Sleep Resist 5 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,3600,5167); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MP, 15); target:addMod(MOD_STR, 6); target:addMod(MOD_AGI, 1); target:addMod(MOD_INT, -2); target:addMod(MOD_HPHEAL, 1); target:addMod(MOD_FOOD_ATTP, 22); target:addMod(MOD_FOOD_ATT_CAP, 80); target:addMod(MOD_FOOD_RATTP, 22); target:addMod(MOD_FOOD_RATT_CAP, 80); target:addMod(MOD_SLEEPRES, 5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MP, 15); target:delMod(MOD_STR, 6); target:delMod(MOD_AGI, 1); target:delMod(MOD_INT, -2); target:delMod(MOD_HPHEAL, 1); target:delMod(MOD_FOOD_ATTP, 22); target:delMod(MOD_FOOD_ATT_CAP, 80); target:delMod(MOD_FOOD_RATTP, 22); target:delMod(MOD_FOOD_RATT_CAP, 80); target:delMod(MOD_SLEEPRES, 5); end;
gpl-3.0
RunAwayDSP/darkstar
scripts/zones/Waughroon_Shrine/mobs/Fee.lua
9
1964
----------------------------------- -- Area: Waughroon Shrine -- Mob: Fe'e -- BCNM: Up In Arms ----------------------------------- local ID = require("scripts/zones/Waughroon_Shrine/IDs") require("scripts/globals/status") ----------------------------------- function onMobInitialize(mob) mob:setMobMod(dsp.mobMod.MULTI_HIT, 6) mob:setMod(dsp.mod.BINDRES, 20) mob:setMod(dsp.mod.BLINDRES, 20) mob:setMod(dsp.mod.SLEEPRES, 20) mob:setMod(dsp.mod.LULLABYRES, 20) mob:setMod(dsp.mod.GRAVITYRES, 20) end function onMobSpawn(mob) mob:setLocalVar("tentacles", 6) mob:SetMobSkillAttack(0) end -- Remove a tentacle from Fe'e. This happens six times during the fight, with final at about 33% HP. -- Each removal slows attack speed in exchange for TP regain and damage. -- When all tentacles are removed, its normal melee attack is replaced by a special Ink Jet attack that -- ignores shadows and has knockback. function removeTentacle(mob, tentacles) if tentacles > 0 then mob:setMobMod(dsp.mobMod.MULTI_HIT, tentacles) mob:messageText(mob,ID.text.ONE_TENTACLE_WOUNDED, false) else mob:messageText(mob,ID.text.ALL_TENTACLES_WOUNDED, false) mob:SetMobSkillAttack(704) -- replace melee attack with special Ink Jet attack end mob:addMod(dsp.mod.ATT, 50) mob:addMod(dsp.mod.REGAIN, 50) mob:addMod(dsp.mod.BINDRES, 10) mob:addMod(dsp.mod.BLINDRES, 10) mob:addMod(dsp.mod.SLEEPRES, 10) mob:addMod(dsp.mod.LULLABYRES, 10) mob:addMod(dsp.mod.GRAVITYRES, 10) end function onMobFight(mob,target) local tentacles = mob:getLocalVar("tentacles") if tentacles > 0 then local hpp = mob:getHPP() while hpp < (11 * tentacles + 22) and tentacles > 0 do tentacles = tentacles - 1 removeTentacle(mob, tentacles) end mob:setLocalVar("tentacles", tentacles) end end function onMobDeath(mob, player, isKiller) end
gpl-3.0
lichtl/darkstar
scripts/zones/Southern_San_dOria/npcs/Thadiene.lua
17
2118
----------------------------------- -- Area: Southern San d'Oria -- NPC: Thadiene -- Standard Merchant NPC ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Southern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script local FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then local count = trade:getItemCount(); local MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,ASH_THADI_ENE_SHOP_DIALOG); local stock = {0x4380,1575,1, --Boomerang 0x430a,19630,1, --Great Bow --0x43a9,16,1, --Silver Arrow 0x4302,7128,1, --Wrapped Bow 0x43b8,5,2, --Crossbow Bolt 0x43aa,126,2, --Fire Arrow 0x43a8,7,2, --Iron Arrow 0x4301,482,2, --Self Bow 0x4308,442,3, --Longbow 0x4300,38,3, --Shortbow 0x43a6,3,3, --Wooden Arrow 0x13a5,4320,3} --Scroll of Battlefield Elegy showNationShop(player, NATION_SANDORIA, 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
lichtl/darkstar
scripts/globals/items/plate_of_octopus_sushi_+1.lua
18
1324
----------------------------------------- -- ID: 5694 -- Item: plate_of_octopus_sushi_+1 -- Food Effect: 60Min, All Races ----------------------------------------- -- Strength 2 -- Accuracy % 17 (Unknown, assuming 1% more than NQ) ----------------------------------------- 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,5693); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR, 2); target:addMod(MOD_FOOD_ACCP, 17); target:addMod(MOD_FOOD_ACC_CAP, 999); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_STR, 2); target:delMod(MOD_FOOD_ACCP, 17); target:delMod(MOD_FOOD_ACC_CAP, 999); end;
gpl-3.0
RunAwayDSP/darkstar
scripts/globals/mobskills/crosswind.lua
11
1102
--------------------------------------------- -- Crosswind -- -- Description: Deals Wind damage to enemies within a fan-shaped area. Additional effect: Knockback -- Type: Breath -- Utsusemi/Blink absorb: Ignores shadows -- Range: Unknown cone -- Notes: --------------------------------------------- require("scripts/globals/settings") require("scripts/globals/status") require("scripts/globals/monstertpmoves") --------------------------------------------- function onMobSkillCheck(target,mob,skill) if(mob:getFamily() == 91) then local mobSkin = mob:getModelId() if (mobSkin == 1746) then return 0 else return 1 end end return 0 end function onMobWeaponSkill(target, mob, skill) local dmgmod = 1 local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*3,dsp.magic.ele.WIND,dmgmod,TP_NO_EFFECT) local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,dsp.attackType.MAGICAL,dsp.damageType.WIND,MOBPARAM_IGNORE_SHADOWS) target:takeDamage(dmg, mob, dsp.attackType.MAGICAL, dsp.damageType.WIND) return dmg end
gpl-3.0
NiLuJe/koreader
plugins/readtimer.koplugin/main.lua
4
8010
local DateTimeWidget = require("ui/widget/datetimewidget") local InfoMessage = require("ui/widget/infomessage") local UIManager = require("ui/uimanager") local WidgetContainer = require("ui/widget/container/widgetcontainer") local logger = require("logger") local util = require("util") local _ = require("gettext") local T = require("ffi/util").template local ReadTimer = WidgetContainer:extend{ name = "readtimer", time = 0, -- The expected time of alarm if enabled, or 0. } function ReadTimer:init() self.alarm_callback = function() -- Don't do anything if we were unscheduled if self.time == 0 then return end self.time = 0 UIManager:show(InfoMessage:new{ text = T(_("Read timer alarm\nTime's up. It's %1 now."), os.date("%c")), }) end self.ui.menu:registerToMainMenu(self) end function ReadTimer:scheduled() return self.time ~= 0 end function ReadTimer:remaining() if self:scheduled() then local td = os.difftime(self.time, os.time()) if td > 0 then return td else return 0 end else return math.huge end end function ReadTimer:remainingTime() if self:scheduled() then local remainder = self:remaining() local hours = math.floor(remainder * (1/3600)) local minutes = math.floor(remainder % 3600 * (1/60)) local seconds = math.floor(remainder % 60) return hours, minutes, seconds end end function ReadTimer:unschedule() if self:scheduled() then UIManager:unschedule(self.alarm_callback) self.time = 0 end end function ReadTimer:rescheduleIn(seconds) self.time = os.time() + seconds UIManager:scheduleIn(seconds, self.alarm_callback) end function ReadTimer:addToMainMenu(menu_items) menu_items.read_timer = { text_func = function() if self:scheduled() then local user_duration_format = G_reader_settings:readSetting("duration_format") return T(_("Read timer (%1)"), util.secondsToClockDuration(user_duration_format, self:remaining(), false)) else return _("Read timer") end end, checked_func = function() return self:scheduled() end, sub_item_table = { { text = _("Set time"), keep_menu_open = true, callback = function(touchmenu_instance) local now_t = os.date("*t") local curr_hour = now_t.hour local curr_min = now_t.min local time_widget = DateTimeWidget:new{ hour = curr_hour, min = curr_min, ok_text = _("Set alarm"), title_text = _("New alarm"), info_text = _("Enter a time in hours and minutes."), callback = function(time) touchmenu_instance:closeMenu() self:unschedule() local then_t = now_t then_t.hour = time.hour then_t.min = time.min then_t.sec = 0 local seconds = os.difftime(os.time(then_t), os.time()) if seconds > 0 then self:rescheduleIn(seconds) local user_duration_format = G_reader_settings:readSetting("duration_format") UIManager:show(InfoMessage:new{ -- @translators %1:%2 is a clock time (HH:MM), %3 is a duration text = T(_("Timer set for %1:%2.\n\nThat's %3 from now."), string.format("%02d", time.hour), string.format("%02d", time.min), util.secondsToClockDuration(user_duration_format, seconds, false)), timeout = 5, }) else UIManager:show(InfoMessage:new{ text = _("Timer could not be set. The selected time is in the past."), timeout = 5, }) end end } UIManager:show(time_widget) end, }, { text = _("Set interval"), keep_menu_open = true, callback = function(touchmenu_instance) local remain_time = {} local remain_hours, remain_minutes = self:remainingTime() if not remain_hours and not remain_minutes then remain_time = G_reader_settings:readSetting("reader_timer_remain_time") if remain_time then remain_hours = remain_time[1] remain_minutes = remain_time[2] end end local time_widget = DateTimeWidget:new{ hour = remain_hours or 0, min = remain_minutes or 0, hour_max = 17, ok_text = _("Set timer"), title_text = _("Set reader timer"), info_text = _("Enter a time in hours and minutes."), callback = function(time) touchmenu_instance:closeMenu() self:unschedule() local seconds = time.hour * 3600 + time.min * 60 if seconds > 0 then self:rescheduleIn(seconds) local user_duration_format = G_reader_settings:readSetting("duration_format") UIManager:show(InfoMessage:new{ -- @translators This is a duration text = T(_("Timer will expire in %1."), util.secondsToClockDuration(user_duration_format, seconds, true)), timeout = 5, }) remain_time = {time.hour, time.min} G_reader_settings:saveSetting("reader_timer_remain_time", remain_time) end end } UIManager:show(time_widget) end, }, { text = _("Stop timer"), keep_menu_open = true, enabled_func = function() return self:scheduled() end, callback = function(touchmenu_instance) self:unschedule() touchmenu_instance:updateItems() end, }, }, } end -- The UI ticks on a MONOTONIC time domain, while this plugin deals with REAL wall clock time. function ReadTimer:onResume() if self:scheduled() then logger.dbg("ReadTimer: onResume with an active timer") local remainder = self:remaining() if remainder == 0 then -- Make sure we fire the alarm right away if it expired during suspend... self:alarm_callback() self:unschedule() else -- ...and that we re-schedule the timer against the REAL time if it's still ticking. logger.dbg("ReadTimer: Rescheduling in", remainder, "seconds") self:unschedule() self:rescheduleIn(remainder) end end end return ReadTimer
agpl-3.0
RunAwayDSP/darkstar
scripts/zones/Chamber_of_Oracles/IDs.lua
8
2081
----------------------------------- -- Area: Chamber_of_Oracles ----------------------------------- require("scripts/globals/zone") ----------------------------------- zones = zones or {} zones[dsp.zone.CHAMBER_OF_ORACLES] = { text = { ITEM_CANNOT_BE_OBTAINED = 6382, -- You cannot obtain the <item>. Come back after sorting your inventory. ITEM_OBTAINED = 6388, -- Obtained: <item>. GIL_OBTAINED = 6389, -- Obtained <number> gil. KEYITEM_OBTAINED = 6391, -- Obtained key item: <keyitem>. CONQUEST_BASE = 7049, -- Tallying conquest results... YOU_CANNOT_ENTER_THE_BATTLEFIELD = 7210, -- You cannot enter the battlefield at present. Please wait a little longer. PLACED_INTO_THE_PEDESTAL = 7618, -- It appears that something should be placed into this pedestal. YOU_PLACE_THE = 7619, -- You place the <item> into the pedestal. IS_SET_IN_THE_PEDESTAL = 7620, -- The <item> is set in the pedestal. HAS_LOST_ITS_POWER = 7621, -- The <item> has lost its power. YOU_DECIDED_TO_SHOW_UP = 7640, -- So, you decided to show up. Now it's time to see what you're really made of, heh heh heh. LOOKS_LIKE_YOU_WERENT_READY = 7641, -- Looks like you weren't ready for me, were you? Now go home, wash your face, and come back when you think you've got what it takes. YOUVE_COME_A_LONG_WAY = 7642, -- Hm. That was a mighty fine display of skill there, <name>. You've come a long way... TEACH_YOU_TO_RESPECT_ELDERS = 7643, -- I'll teach you to respect your elders! TAKE_THAT_YOU_WHIPPERSNAPPER = 7644, -- Take that, you whippersnapper! NOW_THAT_IM_WARMED_UP = 7645, -- Now that I'm warmed up... THAT_LL_HURT_IN_THE_MORNING = 7646, -- Ungh... That'll hurt in the morning... }, mob = { }, npc = { }, } return zones[dsp.zone.CHAMBER_OF_ORACLES]
gpl-3.0
lichtl/darkstar
scripts/zones/Port_Bastok/npcs/Carmelo.lua
14
4833
----------------------------------- -- Area: Port Bastok -- NPC: Carmelo -- Start & Finishes Quest: Love and Ice, A Test of True Love -- Start Quest: Lovers in the Dusk -- Involved in Quest: The Siren's Tear -- @zone 236 -- @pos -146.476 -7.48 -10.889 ----------------------------------- require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local SirensTear = player:getQuestStatus(BASTOK,THE_SIREN_S_TEAR); local SirensTearProgress = player:getVar("SirensTear"); local TheStarsOfIfrit = player:getQuestStatus(BASTOK,THE_STARS_OF_IFRIT); local LoveAndIce = player:getQuestStatus(BASTOK,LOVE_AND_ICE); local LoveAndIceProgress = player:getVar("LoveAndIceProgress"); local ATestOfTrueLove = player:getQuestStatus(BASTOK,A_TEST_OF_TRUE_LOVE); local ATestOfTrueLoveProgress = player:getVar("ATestOfTrueLoveProgress"); local LoversInTheDusk = player:getQuestStatus(BASTOK,LOVERS_IN_THE_DUSK); if (SirensTear == QUEST_ACCEPTED) then player:startEvent(0x0006); elseif (SirensTear == QUEST_COMPLETED and player:hasItem(576) == false and SirensTearProgress < 2) then player:startEvent(0x0013); elseif (LoveAndIce == QUEST_AVAILABLE and SirensTear == QUEST_COMPLETED and SirensTear == QUEST_COMPLETED) then if (player:getFameLevel(BASTOK) >= 5 and player:seenKeyItem(CARRIER_PIGEON_LETTER) == true) then player:startEvent(0x00b9); else player:startEvent(0x00bb); end elseif (LoveAndIce == QUEST_ACCEPTED and LoveAndIceProgress == 1) then player:startEvent(0x00ba); elseif (player:getFameLevel(BASTOK) >= 7 and ATestOfTrueLove == QUEST_AVAILABLE and LoveAndIce == QUEST_COMPLETED and player:needToZone() == false) then player:startEvent(0x010e); elseif (ATestOfTrueLove == QUEST_ACCEPTED and ATestOfTrueLoveProgress < 3) then player:startEvent(0x010f); elseif (ATestOfTrueLove == QUEST_ACCEPTED and ATestOfTrueLoveProgress == 3) then player:startEvent(0x0110); elseif (ATestOfTrueLove == QUEST_ACCEPTED and ATestOfTrueLoveProgress == 4 and player:needToZone() == true) then player:startEvent(0x0111); elseif (ATestOfTrueLove == QUEST_ACCEPTED and ATestOfTrueLoveProgress == 4 and player:needToZone() == false) then player:startEvent(0x0112); elseif (LoversInTheDusk == QUEST_AVAILABLE and ATestOfTrueLove == QUEST_COMPLETED and player:needToZone() == false) then player:startEvent(0x0113); elseif (LoversInTheDusk == QUEST_ACCEPTED) then player:startEvent(0x0114); elseif (LoversInTheDusk == QUEST_COMPLETED) then player:startEvent(0x0115); else player:startEvent(0x00b6); 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 == 0x0006) then player:setVar("SirensTear",1); elseif (csid == 0x0013) then player:setVar("SirensTear",2); elseif (csid == 0x00b9) then player:addQuest(BASTOK,LOVE_AND_ICE); player:addKeyItem(CARMELOS_SONG_SHEET); player:messageSpecial(KEYITEM_OBTAINED,CARMELOS_SONG_SHEET); elseif (csid == 0x00ba) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,17356); else player:setVar("LoveAndIceProgress",0); player:needToZone(true); player:addTitle(SORROW_DROWNER); player:addItem(17356); player:messageSpecial(ITEM_OBTAINED,17356); -- Lamia Harp player:addFame(BASTOK,120); player:completeQuest(BASTOK,LOVE_AND_ICE); end elseif (csid == 0x010e) then player:addQuest(BASTOK,A_TEST_OF_TRUE_LOVE); elseif (csid == 0x0110) then player:setVar("ATestOfTrueLoveProgress",4); player:needToZone(true); elseif (csid == 0x0112) then player:setVar("ATestOfTrueLoveProgress",0); player:needToZone(true); player:addFame(BASTOK,120); player:completeQuest(BASTOK,A_TEST_OF_TRUE_LOVE); elseif (csid == 0x0113) then player:addQuest(BASTOK,LOVERS_IN_THE_DUSK); player:addKeyItem(CHANSON_DE_LIBERTE); player:messageSpecial(KEYITEM_OBTAINED,CHANSON_DE_LIBERTE); end end;
gpl-3.0
lichtl/darkstar
scripts/zones/The_Garden_of_RuHmet/bcnms/when_angels_fall.lua
30
2268
----------------------------------- -- Area: The_Garden_of_RuHmet -- Name: when_angels_fall ----------------------------------- package.loaded["scripts/zones/The_Garden_of_RuHmet/TextIDs"] = nil; ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/globals/missions"); require("scripts/zones/The_Garden_of_RuHmet/TextIDs"); ----------------------------------- -- EXAMPLE SCRIPT -- -- What should go here: -- giving key items, playing ENDING cutscenes -- -- What should NOT go here: -- Handling of "battlefield" status, spawning of monsters, -- putting loot into treasure pool, -- enforcing ANY rules (SJ/number of people/etc), moving -- chars around, playing entrance CSes (entrance CSes go in bcnm.lua) -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) end; -- Leaving the BCNM by every mean possible, given by the LeaveCode -- 1=Select Exit on circle -- 2=Winning the BC -- 3=Disconnected or warped out -- 4=Losing the BC -- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called -- from the core when a player disconnects or the time limit is up, etc function onBcnmLeave(player,instance,leavecode) if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage if (player:getCurrentMission(COP) == WHEN_ANGELS_FALL and player:getVar("PromathiaStatus")==4) then player:startEvent(0x7d01,0,0,0,instance:getTimeInside(),0,0,0); player:setVar("PromathiaStatus",5); else player:startEvent(0x7d01,0,0,0,instance:getTimeInside(),0,0,1); -- end elseif (leavecode == 4) then player:startEvent(0x7d02); end --printf("leavecode: %u",leavecode); end; function onEventUpdate(player,csid,option) -- print("bc update csid "..csid.." and option "..option); end; function onEventFinish(player,csid,option) -- print("bc finish csid "..csid.." and option "..option); if (csid== 0x7d01) then player:setPos(420,0,445,192); end end;
gpl-3.0
RunAwayDSP/darkstar
scripts/globals/items/bowl_of_oceanfin_soup.lua
11
1615
----------------------------------------- -- ID: 6070 -- Item: Bowl of Oceanfin Soup -- Food Effect: 4 Hrs, All Races ----------------------------------------- -- Accuracy % 15 Cap 95 -- Ranged Accuracy % 15 Cap 95 -- Attack % 19 Cap 85 -- Ranged Attack % 19 Cap 85 -- Amorph Killer 6 ----------------------------------------- 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,14400,6070) end function onEffectGain(target,effect) target:addMod(dsp.mod.FOOD_ACCP, 15) target:addMod(dsp.mod.FOOD_ACC_CAP, 95) target:addMod(dsp.mod.FOOD_RACCP, 15) target:addMod(dsp.mod.FOOD_RACC_CAP, 95) target:addMod(dsp.mod.FOOD_ATTP, 19) target:addMod(dsp.mod.FOOD_ATT_CAP, 85) target:addMod(dsp.mod.FOOD_RATTP, 19) target:addMod(dsp.mod.FOOD_RATT_CAP, 85) target:addMod(dsp.mod.AMORPH_KILLER, 6) end function onEffectLose(target, effect) target:delMod(dsp.mod.FOOD_ACCP, 15) target:delMod(dsp.mod.FOOD_ACC_CAP, 95) target:delMod(dsp.mod.FOOD_RACCP, 15) target:delMod(dsp.mod.FOOD_RACC_CAP, 95) target:delMod(dsp.mod.FOOD_ATTP, 19) target:delMod(dsp.mod.FOOD_ATT_CAP, 85) target:delMod(dsp.mod.FOOD_RATTP, 19) target:delMod(dsp.mod.FOOD_RATT_CAP, 85) target:delMod(dsp.mod.AMORPH_KILLER, 6) end
gpl-3.0
thermofisherlsms/xcalibur-workbench
zPane.lua
1
7466
-- Copyright (c) 2016 Thermo Fisher Scientific -- -- 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. -- zPane.lua -- A generic zedgraph pane -- Load necessary libraries local properties = require("properties") -- Get assemblies luanet.load_assembly ("System.Drawing") luanet.load_assembly ("ZedGraph") -- Get constructors local plotCtor = luanet.import_type("ZedGraph.ZedGraphControl") local pointPairListCtor = luanet.import_type("ZedGraph.PointPairList") local GraphPane = luanet.import_type("ZedGraph.GraphPane") -- Get enumerations local Color = luanet.import_type("System.Drawing.Color") local SymbolType = luanet.import_type("ZedGraph.SymbolType") -- This is an enum local defaultColors = {Color.Black, Color.Red, Color.Blue, Color.Green, Color.Brown, Color.Orange, Color.Violet, Color.Pink, Color.Aqua, Color.Cyan, Color.DarkBlue, Color.DarkGray, Color.DarkGreen, Color.DarkOrange, Color.DarkRed, Color.LightBlue} -- local variables -- forward declarations for local functions -- local functions -- Start of the zPane object local zPane = {} zPane.__index = zPane setmetatable(zPane, { __call = function (cls, ...) local self = setmetatable({}, cls) self:_init(...) return self end,}) ---Create a new object of the class function zPane:_init(args) args = args or {} self.paneControl = GraphPane() self.paneControl.Tag = self -- Initial Margins are 10 all around -- Initial Border.Width is 1 self.paneControl.Border.Width = 3 properties.Inherit(self) -- Inherit methods from properties table end function zPane:AddCurve(args) args = args or {} local points = pointPairListCtor() -- Get a new point list local curveName = args.name or "" -- No name by default local curveCount = self.paneControl.CurveList.Count + 1 -- This will be the count after adding this curve local curveColor = args.color or defaultColors[curveCount + 1] or Color.Black local curveSymbol = args.symbol or SymbolType.None -- No symbol by default local seriesType = args.seriesType or "curve" local newCurve if seriesType == "curve" then newCurve = self.paneControl:AddCurve(curveName, points, curveColor, curveSymbol) elseif seriesType == "bar" then newCurve = self.paneControl:AddBar(curveName, points, curveColor) elseif seriesType == "stick" then newCurve = self.paneControl:AddStick(curveName, points, curveColor) else print ("Series Type Not Known: ", seriesType) return nil end if args.noLine then newCurve.Line.IsVisible = false end -- Show line by default if args.symbolSize then newCurve.Symbol.Size = args.symbolSize end -- default symbol size return newCurve -- return the curve end function zPane:AddPieSlice(args) args = args or {} local value = args.value if not value then print ("Usage: zPane:AddPieSlice({value = x})") return nil end local paneControl = self.paneControl local newIndex = paneControl.CurveList.Count + 1 local color = args.color or defaultColors[newIndex] local displacement = args.displacement or 0 local name = args.name or "" local slice = self.paneControl:AddPieSlice(value, color, displacement, name) -- returns a PieItem -- Refresh the graph local plotControl = self.plotControl if plotControl and not args.skipDraw then --print ("Refreshing Pane") plotControl:AxisChange() plotControl:Invalidate() end end function zPane:AddXYTable(args) args = args or {} if not args.data or not args.xKey or not args.yKey then print ("Usage: zPane:addXYTable({data = x, xKey = y, yKey = z, [index = zz]})") end local data = args.data local xKey = args.xKey local yKey = args.yKey local index = args.index or 1 local pane = self.paneControl -- If there are not enough curves to match the index -- then just add more for user convenience. while pane.CurveList.Count < index do self:AddCurve(args) end -- Add the data local curve = pane.CurveList[index-1] -- Shift back to C base-0 indexing curve:Clear() if args.lineWidth then curve.Line.Width = args.lineWidth end -- I'm going to pcall the section here because -- I've seen some issues with this crashing when -- there's been .NET memory corruption if not pcall(function() for index, point in ipairs(data) do curve:AddPoint(point[xKey], point[yKey]) if point.label then curve.Points[index-1].Tag = tostring(point.label) end end end) then print ("Memory Error When Plotting Graph!!!!") return end -- Set the axes if args.xMin then pane.XAxis.Scale.Min = args.xMin else pane.XAxis.Scale.MinAuto = true end if args.xMax then pane.XAxis.Scale.Max = args.xMax else pane.XAxis.Scale.MaxAuto = true end if args.yMin then pane.YAxis.Scale.Min = args.yMin else pane.YAxis.Scale.MinAuto = true end if args.yMax then pane.YAxis.Scale.Max = args.yMax else pane.YAxis.Scale.MaxAuto = true end -- Refresh the graph local plotControl = self.plotControl if plotControl and not args.skipDraw then --print ("Refreshing Pane") plotControl:AxisChange() plotControl:Invalidate() end end -- Clear all curves function zPane:Clear() local paneControl = self.paneControl for i = 1, paneControl.CurveList.Count do local curve = paneControl.CurveList[i-1] -- Use 0-based indexing curve:Clear() end end -- Dispose of all associated .NET resources -- curves and point lists function zPane:Dispose() print ("Disposing pane") self.paneControl:Dispose() end -- This will most likely be overridden function zPane:GetPropertyTitle() return "Generic Plot" end function zPane:SetActive(setting) -- No argument means to set active if setting == nil then setting = true end local border = self.paneControl.Border border.IsVisible = setting if setting then border.Color = Color.Blue end self:UpdatePropertyForm() return setting end -- Default is not functionality function zPane:ShiftClick(pointF) end return zPane
mit
lichtl/darkstar
scripts/zones/Bastok_Mines/npcs/Eulaphe.lua
27
1981
----------------------------------- -- Area: Bastok Mines -- NPC: Eulaphe -- Type: Chocobo Renter ----------------------------------- require("scripts/globals/chocobo"); require("scripts/globals/keyitems"); require("scripts/globals/settings"); require("scripts/globals/status"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local level = player:getMainLvl(); local gil = player:getGil(); if (player:hasKeyItem(CHOCOBO_LICENSE) and level >= 15) then local price = getChocoboPrice(player); player:setLocalVar("chocoboPriceOffer",price); if (level >= 20) then level = 0; end player:startEvent(0x003E,price,gil,level); else player:startEvent(0x0041); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); local price = player:getLocalVar("chocoboPriceOffer"); if (csid == 0x003E and option == 0) then if (player:delGil(price)) then updateChocoboPrice(player, price); if (player:getMainLvl() >= 20) then local duration = 1800 + (player:getMod(MOD_CHOCOBO_RIDING_TIME) * 60) player:addStatusEffectEx(EFFECT_CHOCOBO,EFFECT_CHOCOBO,1,0,duration,true); else player:addStatusEffectEx(EFFECT_CHOCOBO,EFFECT_CHOCOBO,1,0,900,true); end player:setPos(580,0,-305,0x40,0x6B); end end end;
gpl-3.0
RunAwayDSP/darkstar
scripts/globals/items/dish_of_spaghetti_carbonara.lua
11
1545
----------------------------------------- -- ID: 5190 -- Item: dish_of_spaghetti_carbonara -- Food Effect: 30Min, All Races ----------------------------------------- -- Health % 14 -- Health Cap 175 -- Magic 10 -- Strength 4 -- Vitality 2 -- Intelligence -3 -- Attack % 17 -- Attack Cap 65 -- Store TP 6 ----------------------------------------- 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,1800,5190) end function onEffectGain(target,effect) target:addMod(dsp.mod.FOOD_HPP, 14) target:addMod(dsp.mod.FOOD_HP_CAP, 175) target:addMod(dsp.mod.MP, 10) target:addMod(dsp.mod.STR, 4) target:addMod(dsp.mod.VIT, 2) target:addMod(dsp.mod.INT, -3) target:addMod(dsp.mod.FOOD_ATTP, 17) target:addMod(dsp.mod.FOOD_ATT_CAP, 65) target:addMod(dsp.mod.STORETP, 6) end function onEffectLose(target, effect) target:delMod(dsp.mod.FOOD_HPP, 14) target:delMod(dsp.mod.FOOD_HP_CAP, 175) target:delMod(dsp.mod.MP, 10) target:delMod(dsp.mod.STR, 4) target:delMod(dsp.mod.VIT, 2) target:delMod(dsp.mod.INT, -3) target:delMod(dsp.mod.FOOD_ATTP, 17) target:delMod(dsp.mod.FOOD_ATT_CAP, 65) target:delMod(dsp.mod.STORETP, 6) end
gpl-3.0
RunAwayDSP/darkstar
scripts/zones/Aydeewa_Subterrane/Zone.lua
9
2145
----------------------------------- -- -- Zone: Aydeewa_Subterrane (68) -- ----------------------------------- local ID = require("scripts/zones/Aydeewa_Subterrane/IDs") require("scripts/globals/keyitems") require("scripts/globals/missions") require("scripts/globals/npc_util") require("scripts/globals/quests") require("scripts/globals/status") require("scripts/globals/titles") ----------------------------------- function onInitialize(zone) zone:registerRegion(1,378,-3,338,382,3,342) end function onZoneIn(player,prevZone) local cs = -1 if player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0 then player:setPos(356.503,-0.364,-179.607,122) end if player:getCurrentMission(TOAU) == dsp.mission.id.toau.TEAHOUSE_TUMULT and player:getCharVar("AhtUrganStatus") == 0 then cs = 10 end return cs end function onRegionEnter(player,region) if region:GetRegionID() == 1 then local StoneID = player:getCharVar("EmptyVesselStone") if player:getQuestStatus(AHT_URHGAN,dsp.quest.id.ahtUrhgan.AN_EMPTY_VESSEL) == QUEST_ACCEPTED and player:getCharVar("AnEmptyVesselProgress") == 4 and player:hasItem(StoneID) then player:startEvent(3,StoneID) end end end function onRegionLeave(player,region) end function onEventUpdate(player,csid,option) end function onEventFinish(player,csid,option) if csid == 3 and option == 13 and npcUtil.completeQuest(player, AHT_URHGAN, dsp.quest.id.ahtUrhgan.AN_EMPTY_VESSEL, {title=dsp.title.BEARER_OF_THE_MARK_OF_ZAHAK, ki=dsp.ki.MARK_OF_ZAHAK, var={"AnEmptyVesselProgress", "EmptyVesselStone"}}) then -- Accept and unlock player:unlockJob(dsp.job.BLU) player:setPos(148,-2,0,130,50) elseif csid == 3 and option ~= 13 then -- Make a mistake and get reset player:setCharVar("AnEmptyVesselProgress", 0) player:setCharVar("EmptyVesselStone", 0) player:delQuest(AHT_URHGAN,dsp.quest.id.ahtUrhgan.AN_EMPTY_VESSEL) player:setPos(148,-2,0,130,50) elseif csid == 10 then player:setCharVar("AhtUrganStatus", 1) end end
gpl-3.0
OctoEnigma/shiny-octo-system
addons/Screengrab-master/lua/autorun/sh_screengrab_v2.lua
1
18154
if SERVER then local sg = {} local NWStrings = { "ScreengrabRequest", "StartScreengrab", "ScreengrabInitCallback", "ScreengrabConfirmation", "ScreengrabSendPart", "SendPartBack", "ScreengrabFinished", "rtxappend", "rtxappend2", "Progress", "ScreengrabInterrupted" } for k, v in next, NWStrings do util.AddNetworkString( v ) end umsg.PoolString( "progress" ) sg.white = "color_white" sg.black = "color_black" sg.red = "Color( 255, 0, 0 )" sg.green = "Color( 0, 255, 0 )" sg.orange = "Color( 255, 100, 0 )" sg.yellow = "Color( 255, 255, 0 )" sg.blue = "Color( 0, 200, 255 )" local meta = FindMetaTable( "Player" ) function meta:CanScreengrab() return self:IsAdmin() end function meta:rtxappend( col, str ) self:SendLua( [[rtxappend(]] .. col .. [[,"]] .. str .. [[")]] ) end net.Receive( "ScreengrabRequest", function( _, ply ) local ent = net.ReadEntity() local qual = net.ReadUInt( 32 ) for k, v in next, player.GetAll() do if v.isgrabbing and v ~= ply then ply:rtxappend( sg, red, "Error: " .. v:Name() .. "is screengrabbing " .. v.sg .. ". To reduce server stress, only one screengrab can be performed at once." ) return end end if ply.isgrabbing then ply:rtxappend( sg.red, "Error: You are already screengrabbing someone" ) return end if not IsValid( ent ) then ply:rtxappend( sg.red, "Error: Invalid target" ) return end if ply:CanScreengrab() then ply:rtxappend( sg.green, "Initializing" ) net.Start( "StartScreengrab" ) net.WriteUInt( qual, 32 ) net.WriteEntity( ply ) net.Send( ent ) ent.sg = ply ply.sg = ent else ply:rtxappend( sg.red, "Error: Insufficient permissions" ) end end ) net.Receive( "ScreengrabInitCallback", function( _, ply ) local tosend = net.ReadEntity() local parts = net.ReadUInt( 32 ) local len = net.ReadUInt( 32 ) local time = net.ReadFloat() ply.parts = parts ply.IsSending = true net.Start( "ScreengrabConfirmation" ) net.WriteUInt( parts, 32 ) net.WriteUInt( len, 32 ) net.WriteFloat( time ) net.WriteEntity( ply ) net.Send( tosend ) end ) net.Receive( "ScreengrabSendPart", function( _, ply ) local sendto = ply.sg local len = net.ReadUInt( 32 ) local data = net.ReadData( len ) if not ply.data then ply.data = {} ply.data[ 1 ] = data sendto:rtxappend( sg.blue, "Received 1st part" ) else local num = table.getn( ply.data ) + 1 ply.data[ num ] = data sendto:rtxappend( sg.blue, "Received " .. num .. STNDRD( num ) .. " part" ) end if table.getn( ply.data ) == ply.parts then ply.IsSending = nil sendto:rtxappend( sg.green, "Preparing to send data [" .. ply.parts .. " parts]" ) local i = 1 timer.Create( "SendDataBack", 0.1, ply.parts, function() net.Start( "SendPartBack" ) local x = ply.data[ i ]:len() net.WriteUInt( x, 32 ) net.WriteData( ply.data[ i ], x ) net.Send( sendto ) sendto:rtxappend( sg.yellow, "Sent " .. i .. STNDRD( i ) .. " part" ) i = i + 1 end ) end end ) net.Receive( "ScreengrabFinished", function( _, ply ) local _ply = ply.sg _ply.parts = nil _ply.data = nil ply.parts = nil ply.data = nil _ply.sg = nil ply.sg = nil ply.isgrabbing = nil _ply.isgrabbing = nil ply:rtxappend( sg.green, "Finished" ) end ) net.Receive( "rtxappend2", function( _, ply ) local col = net.ReadColor() local str = net.ReadString() local tosend = net.ReadEntity() net.Start( "rtxappend" ) net.WriteColor( col ) net.WriteString( str ) net.Send( tosend ) end ) net.Receive( "Progress", function( _, ply ) local pl = net.ReadEntity() local num = net.ReadFloat() umsg.Start( "progress", pl ) umsg.Float( num ) umsg.End() end ) hook.Add( "PlayerDisconnected", "ScreengrabInterrupt", function( ply ) if ply.IsSending then local _ply = ply.sg _ply.parts = nil _ply.data = nil ply.parts = nil ply.data = nil _ply.sg = nil ply.sg = nil ply.isgrabbing = nil _ply.isgrabbing = nil _ply:rtxappend( sg.red, "Target disconnected before their data finished sending" ) net.Start( "ScreengrabInterrupted" ) net.Send( _ply ) end end ) end if CLIENT then CreateClientConVar( "sg_auto_open", "0" ) surface.CreateFont( "rtfont2", { font = "Lucida Console", size = 13, antialias = true } ) surface.CreateFont( "asdf2", { font = "Lucida Console", size = 15, antialias = true } ) surface.CreateFont( "topmenu2", { font = "Lucida Console", size = 15, antialias = true } ) local sg = {} sg.white = color_white sg.black = color_black sg.red = Color( 255, 0, 0 ) sg.green = Color( 0, 255, 0 ) sg.orange = Color( 255, 100, 0 ) sg.yellow = Color( 255, 255, 0 ) sg.blue = Color( 0, 200, 255 ) local progress = {} progress.num = 0 progress.screenshot = nil local function cl_rtxappend2( color, text, ply ) net.Start( "rtxappend2" ) net.WriteColor( color ) net.WriteString( text ) net.WriteEntity( ply ) net.SendToServer() end net.Receive( "StartScreengrab", function() local quality = net.ReadUInt( 32 ) local _ply = net.ReadEntity() cl_rtxappend2( sg.green, "Initializing", _ply ) local function capture( q ) local tab = { format = "jpeg", h = ScrH(), w = ScrW(), quality = q, x = 0, y = 0 } local split = 20000 local _data = util.Base64Encode( render.Capture( tab ) ) local data = util.Compress( _data ) local len = string.len( data ) cl_rtxappend2( color_white, "Captured " .. len .. " bytes", _ply ) local parts = math.ceil( len / split ) cl_rtxappend2( color_white, parts .. " parts", _ply ) local partstab = {} for i = 1, parts do local min local max if i == 1 then min = i max = split elseif i > 1 and i ~= parts then min = ( i - 1 ) * split + 1 max = min + split - 1 elseif i > 1 and i == parts then min = ( i - 1 ) * split + 1 max = len end local str = string.sub( data, min, max ) partstab[ i ] = str end local amt = table.getn( partstab ) net.Start( "ScreengrabInitCallback" ) net.WriteEntity( _ply ) net.WriteUInt( amt, 32 ) net.WriteUInt( len, 32 ) net.WriteFloat( CurTime(), 32 ) net.SendToServer() cl_rtxappend2( Color( 0, 255, 0 ), "Preparing to send data", _ply ) local i = 1 timer.Create( "ScreengrabSendParts", 0.1, amt, function() net.Start( "ScreengrabSendPart" ) local l = partstab[ i ]:len() net.WriteUInt( l, 32 ) net.WriteData( partstab[ i ], l ) net.SendToServer() cl_rtxappend2( Color( 255, 255, 0 ), "Sent " .. i .. STNDRD( i ) .. " part", _ply ) net.Start( "Progress" ) net.WriteEntity( _ply ) net.WriteFloat( ( i / amt ) / 2 ) net.SendToServer() i = i + 1 end ) end capture( quality ) end ) local function DisplayData( str, name ) local elapsedtime if not name then elapsedtime = math.Round( LocalPlayer().EndTime - LocalPlayer().StartTime, 3 ) end local main = vgui.Create( "DFrame", vgui.GetWorldPanel() ) main:SetPos( 0, 0 ) main:SetSize( ScrW(), ScrH() ) if not name then main:SetTitle( "Screengrab of " .. LocalPlayer().gfname .. " (" .. string.len( str ) .. " bytes, took " .. elapsedtime .. " seconds)" ) else local str = name:sub( 1, -5 ) main:SetTitle( str ) end main:MakePopup() local html = vgui.Create( "HTML", main ) html:DockMargin( 0, 0, 0, 0 ) html:Dock( FILL ) html:SetHTML( [[ <img width="]] .. ScrW() .. [[" height="]] .. ScrH() .. [[" src="data:image/jpeg;base64, ]] .. str .. [["/> ]] ) end net.Receive( "ScreengrabInterrupted", function() cl_rtxappend( sg.red, "Connection with target interrupted" ) LocalPlayer().InProgress = nil progress.screenshot = nil progress.num = 0 end ) net.Receive( "ScreengrabConfirmation", function() local parts = net.ReadUInt( 32 ) local len = net.ReadUInt( 32 ) local time = net.ReadFloat() local ent = net.ReadEntity() LocalPlayer().parts = parts LocalPlayer().len = len LocalPlayer().StartTime = time LocalPlayer().gfname = ent:Name() end ) net.Receive( "SendPartBack", function() local len = net.ReadUInt( 32 ) local data = net.ReadData( len ) if not LocalPlayer().sgtable then LocalPlayer().sgtable = {} LocalPlayer().sgtable[ 1 ] = data cl_rtxappend( sg.blue, "Received 1st part" ) progress.num = ( ( 1 / LocalPlayer().parts ) / 2 ) + 0.5 else local x = table.getn( LocalPlayer().sgtable ) + 1 LocalPlayer().sgtable[ x ] = data cl_rtxappend( sg.blue, "Received " .. x .. STNDRD( x ) .. " part" ) progress.num = ( ( x / LocalPlayer().parts ) / 2 ) + 0.5 end if table.getn( LocalPlayer().sgtable ) == LocalPlayer().parts then cl_rtxappend( sg.orange, "Constructing data" ) local con = table.concat( LocalPlayer().sgtable ) local d = util.Decompress( con ) LocalPlayer().EndTime = CurTime() if GetConVar( "sg_auto_open" ):GetInt() == 0 then progress.screenshot = d else progress.screenshot = d DisplayData( d ) end cl_rtxappend( sg.green, "Finished" ) net.Start( "ScreengrabFinished" ) net.SendToServer() LocalPlayer().InProgress = nil end end ) local main function OpenSGMenu() if main then return end main = vgui.Create( "DFrame" ) main:SetSize( 635, 300 ) main:SetTitle( "" ) main:SetVisible( true ) main:ShowCloseButton( true ) main:MakePopup() main:Center() main.btnMaxim:Hide() main.btnMinim:Hide() main.btnClose:Hide() main.Paint = function() surface.SetDrawColor( 50, 50, 50, 135 ) surface.DrawOutlinedRect( 0, 0, main:GetWide(), main:GetTall() ) surface.SetDrawColor( 0, 0, 0, 240 ) surface.DrawRect( 1, 1, main:GetWide() - 2, main:GetTall() - 2 ) surface.SetFont( "topmenu2" ) surface.SetTextPos( main:GetWide() / 2 - surface.GetTextSize( "Screengrab Menu" ) / 2, 5 ) surface.SetTextColor( 255, 255, 255, 255 ) surface.DrawText( "Screengrab Menu" ) end local close = vgui.Create( "DButton", main ) close:SetPos( main:GetWide() - 50, 0 ) close:SetSize( 44, 22 ) close:SetText( "" ) local colorv = Color( 150, 150, 150, 250 ) function PaintClose() if not main then return end surface.SetDrawColor( colorv ) surface.DrawRect( 1, 1, close:GetWide() - 2, close:GetTall() - 2 ) surface.SetFont( "asdf2" ) surface.SetTextColor( 255, 255, 255, 255 ) surface.SetTextPos( 19, 3 ) surface.DrawText( "x" ) return true end close.Paint = PaintClose close.OnCursorEntered = function() colorv = Color( 195, 75, 0, 250 ) PaintClose() end close.OnCursorExited = function() colorv = Color( 150, 150, 150, 250 ) PaintClose() end close.OnMousePressed = function() colorv = Color( 170, 0, 0, 250 ) PaintClose() end close.OnMouseReleased = function() if not LocalPlayer().InProgress then main:Close() end end main.OnClose = function() main:Remove() if main then main = nil end end local inside = vgui.Create( "DPanel", main ) inside:SetPos( 7, 27 ) inside:SetSize( main:GetWide() - 14, main:GetTall() - 34 ) inside.Paint = function() surface.SetDrawColor( 255, 255, 255, 255 ) surface.DrawOutlinedRect( 0, 0, inside:GetWide(), inside:GetTall() ) surface.SetDrawColor( 255, 255, 255, 250 ) surface.DrawRect( 1, 1, inside:GetWide() - 2, inside:GetTall() - 2 ) end local plys = vgui.Create( "DComboBox", inside ) plys:SetPos( 5, 5 ) plys:SetSize( 150, 25 ) plys:AddChoice( "Select a Player", nil, true ) plys.curChoice = "Select a Player" for k, v in next, player.GetHumans() do plys:AddChoice( v:Nick(), v ) end plys.OnSelect = function( pnl, index, value ) local ent = plys.Data[ index ] plys.curChoice = ent end local q = vgui.Create( "Slider", inside ) q:SetPos( 5, 55 ) q:SetWide( 180 ) q:SetMin( 1 ) q:SetMax( 90 ) q:SetDecimals( 0 ) q:SetValue( 50 ) local execute = vgui.Create( "DButton", inside ) execute:SetPos( 5, 35 ) execute:SetSize( 150, 25 ) execute:SetText( "Screengrab" ) execute.Think = function() local cur = plys.curChoice if cur and not isstring( cur ) then execute:SetDisabled( false ) else execute:SetDisabled( true ) end end execute.DoClick = function() LocalPlayer().parts = nil LocalPlayer().len = nil LocalPlayer().StartTime = nil LocalPlayer().gfname = nil LocalPlayer().sgtable = nil progress.screenshot = nil progress.num = 0 timer.Simple( 0.1, function() net.Start( "ScreengrabRequest" ) net.WriteEntity( plys.curChoice ) net.WriteUInt( q:GetValue(), 32 ) net.SendToServer() LocalPlayer().InProgress = true end ) end local auto = vgui.Create( "DCheckBoxLabel", inside ) auto:SetPos( 5, 83 ) auto:SetText( "Automatically Open" ) auto:SetDark( true ) auto:SizeToContents() auto:SetConVar( "sg_auto_open" ) local files = vgui.Create( "DListView", inside ) files:SetPos( 5, 100 ) files:SetSize( 150, 110 ) files:AddColumn( "Screenshots" ) files.filetable = {} files:SetHeaderHeight( 15 ) local f = file.Find( "screengrabs/*.txt", "DATA" ) files.filetable = f for k, v in next, f do files:AddLine( v ) end files.Think = function() local f = file.Find( "screengrabs/*.txt", "DATA" ) if table.ToString( files.filetable ) ~= table.ToString( f ) then files.filetable = f files:Clear() for k, v in next, f do files:AddLine( v ) end end end files.OnRowRightClick = function( main, line ) local menu = DermaMenu() menu:AddOption( "Delete file", function() local f = files:GetLine( line ):GetValue( 1 ) file.Delete( "screengrabs/" .. f ) end ):SetIcon( "icon16/delete.png" ) menu:AddOption( "View Screenshot", function() local f = file.Read( "screengrabs/" .. files:GetLine( line ):GetValue( 1 ), "DATA" ) hook.Add( "Think", "wait", function() if f and isstring( f ) and string.len( f ) > 1 then DisplayData( f, files:GetLine( line ):GetValue( 1 ) ) hook.Remove( "Think", "wait" ) end end ) end ):SetIcon( "icon16/zoom.png" ) menu:Open() end local svlogs = vgui.Create( "DFrame", inside ) svlogs:SetSize( 220, 230 ) svlogs:SetPos( 165, 5 ) svlogs:SetTitle( "Server Logs" ) svlogs:SetSizable( false ) svlogs.Paint = function() surface.SetDrawColor( Color( 0, 0, 0, 250 ) ) surface.DrawRect( 0, 0, svlogs:GetSize() ) end svlogs:ShowCloseButton( false ) rtx = vgui.Create( "RichText", svlogs ) rtx:Dock( FILL ) rtx.Paint = function() rtx.m_FontName = "rtfont2" rtx:SetFontInternal( "rtfont2" ) rtx:SetBGColor( Color( 0, 0, 0, 0 ) ) rtx.Paint = nil end rtx:InsertColorChange( 255, 255, 255, 255 ) function rtxappend( color, text ) if rtx:IsValid() and rtx:IsVisible() then if type( color ) == "string" then rtx:AppendText( color .. "\n" ) return end if IsValid( rtx ) then rtx:InsertColorChange( color.r, color.g, color.b, color.a or 255 ) rtx:AppendText( text .. "\n" ) rtx:InsertColorChange( 255, 255, 255, 255 ) end end end local cllogs = vgui.Create( "DFrame", inside ) cllogs:SetSize( 220, 230 ) cllogs:SetPos( 395, 5 ) cllogs:SetTitle( "Client Logs" ) cllogs:SetSizable( false ) cllogs.Paint = function() surface.SetDrawColor( Color( 0, 0, 0, 250 ) ) surface.DrawRect( 0, 0, cllogs:GetSize() ) end cllogs:ShowCloseButton( false ) cl_rtx = vgui.Create( "RichText", cllogs ) cl_rtx:Dock( FILL ) cl_rtx.Paint = function() cl_rtx.m_FontName = "rtfont2" cl_rtx:SetFontInternal( "rtfont2" ) cl_rtx:SetBGColor( Color( 0, 0, 0, 0 ) ) cl_rtx.Paint = nil end cl_rtx:InsertColorChange( 255, 255, 255, 255 ) function cl_rtxappend( color, text ) if cl_rtx:IsValid() and cl_rtx:IsVisible() then cl_rtx:InsertColorChange( color.r, color.g, color.b, color.a or 255 ) cl_rtx:AppendText( text .. "\n" ) cl_rtx:InsertColorChange( 255, 255, 255, 255 ) end end net.Receive( "rtxappend", function() local col = net.ReadColor() local str = net.ReadString() cl_rtxappend( col, str ) end ) local pro = vgui.Create( "DProgress", inside ) pro:SetPos( 165, 241 ) pro:SetSize( 450, 20 ) pro:SetFraction( 0 ) pro.Think = function() pro:SetFraction( progress.num ) end progress.open = vgui.Create( "DButton", inside ) progress.open:SetPos( 4, 241 ) progress.open:SetSize( 150, 20 ) progress.open:SetText( "Open" ) progress.open:SetDisabled( true ) progress.open.screenshot = nil progress.open.DoClick = function() DisplayData( progress.screenshot ) end cl_rtx.Think = function() if type( progress.screenshot ) == "string" then progress.open:SetDisabled( false ) elseif type( progress.screenshot ) == "nil" then progress.open:SetDisabled( true ) end end local save = vgui.Create( "DButton", inside ) save:SetPos( 4, 220 ) save:SetSize( 150, 20 ) save:SetText( "Save Data" ) save:SetDisabled( true ) rtx.Think = function() if type( progress.screenshot ) == "string" then save:SetDisabled( false ) elseif type( progress.screenshot ) == "nil" then save:SetDisabled( true ) end end save.DoClick = function() if not file.Exists( "screengrabs", "DATA" ) then file.CreateDir( "screengrabs" ) end local name = LocalPlayer().gfname .. " - " .. os.date( "%m_%d %H_%M_%S" ) .. ".txt" local text = progress.screenshot cl_rtxappend( Color( 255, 100, 0 ), "Saving to file: " .. name .. " (" .. string.len( text ) .. " bytes)" ) file.Write( "screengrabs/" .. name, text ) timer.Simple( 1, function() if file.Exists( "screengrabs/" .. name, "DATA" ) then cl_rtxappend( Color( 255, 100, 0 ), "Screenshot saved!" ) else cl_rtxappend( Color( 255, 0, 0 ), "Error: Screenshot not saved!" ) end end ) end end concommand.Add( "screengrab", OpenSGMenu ) usermessage.Hook( "progress", function( um ) progress.num = um:ReadFloat() end ) end
mit
lichtl/darkstar
scripts/zones/The_Boyahda_Tree/npcs/HomePoint#1.lua
27
1273
----------------------------------- -- Area: The Boyahda Tree -- NPC: HomePoint#1 -- @pos 88 -15 -217 153 ----------------------------------- package.loaded["scripts/zones/The_Boyahda_Tree/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/The_Boyahda_Tree/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x21fc, 92); 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 == 0x21fc) then if (option == 1) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); else hpTeleport( player, option); end end end;
gpl-3.0
Srynetix/luabind5.2
examples/glut/glut_bindings.lua
38
1543
quit = false function resize_func(w, h) local ratio = w / h print('====== resize') glMatrixMode(gl.PROJECTION) glLoadIdentity() glViewport(0,0,w,h) gluPerspective(45,ratio,1,1000) glMatrixMode(gl.MODELVIEW) glLoadIdentity() end angle = 0 angle2 = 0 previous_time = 0 function display_func() if quit then return end local cur_time = glutGet(glut.ELAPSED_TIME) local delta = (cur_time - previous_time) / 1000 previous_time = cur_time glClear(gl.COLOR_BUFFER_BIT + gl.DEPTH_BUFFER_BIT) glPushMatrix() glTranslate(0,0,-5) glRotate(angle, 0, 1, 0) glRotate(angle2, 0, 0, 1) glColor3(1,0,0) -- glutWireSphere(0.75, 10, 10) glutSolidTeapot(0.75) -- glColor3(1,1,1) -- glutWireTeapot(0.75) glPopMatrix() angle = angle + 200 * delta angle2 = angle2 + 170 * delta frames = frames + 1 if math.mod(frames, 100) == 0 then local fps = frames * 1000 / (glutGet(glut.ELAPSED_TIME) - start_time); print('fps: ' .. fps .. ' time: ' .. glutGet(glut.ELAPSED_TIME) .. ' frames: ' .. frames) end glutSwapBuffers() end function keyboard_func(key,x,y) print('keyboard' .. key) if key == 27 then glutDestroyWindow(window) quit = true end end glutInitWindowSize(600,600) glutInitWindowPosition(0,0) glutInitDisplayMode(glut.RGB + glut.DOUBLE + glut.DEPTH) window = glutCreateWindow("luabind, glut-bindings") glutDisplayFunc(display_func) glutIdleFunc(display_func) glutKeyboardFunc(keyboard_func) glutReshapeFunc(resize_func) resize_func(600,600) start_time = glutGet(glut.ELAPSED_TIME) frames = 0 glutMainLoop()
mit
scscgit/scsc_wildstar_addons
WildStarInstantMessenger/Libs/GeminiColor/GeminiColor.lua
7
26057
--================================================================================================ -- -- GeminiColor -- -- An Apollo Package for producing UI controls for picking colors, picking colors, -- and working with color data in multiple formats. -- --================================================================================================ --[[ The MIT License (MIT) Copyright (c) 2014 2014 Wildstar NASA Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]] local MAJOR, MINOR = "GeminiColor", 6 -- Get a reference to the package information if any local APkg = Apollo.GetPackage(MAJOR) -- If there was an older version loaded we need to see if this is newer if APkg and (APkg.nVersion or 0) >= MINOR then return -- no upgrade needed end require "Window" ----------------------------------------------------------------------------------------------- -- GeminiColor Module Definition ----------------------------------------------------------------------------------------------- local GeminiColor = APkg and APkg.tPackage or {} ----------------------------------------------------------------------------------------------- -- Constants ----------------------------------------------------------------------------------------------- local ktColors = { { colorName = "IndianRed", strColor = "CD5C5C"}, { colorName = "LightCoral", strColor = "F08080"}, { colorName = "Salmon", strColor = "FA8072"}, { colorName = "DarkSalmon", strColor = "E9967A"}, { colorName = "Red", strColor = "FF0000"}, { colorName = "Crimson", strColor = "DC143C"}, { colorName = "FireBrick", strColor = "B22222"}, { colorName = "DarkRed", strColor = "8B0000"}, { colorName = "Pink", strColor = "FFC0CB"}, { colorName = "LightPink", strColor = "FFB6C1"}, { colorName = "HotPink", strColor = "FF69B4"}, { colorName = "DeepPink", strColor = "FF1493"}, { colorName = "MediumVioletRed", strColor = "C71585"}, { colorName = "PaleVioletRed", strColor = "DB7093"}, { colorName = "LightSalmon", strColor = "FFA07A"}, { colorName = "Coral", strColor = "FF7F50"}, { colorName = "Tomato", strColor = "FF6347"}, { colorName = "OrangeRed", strColor = "FF4500"}, { colorName = "DarkOrange", strColor = "FF8C00"}, { colorName = "Orange", strColor = "FFA500"}, { colorName = "Gold", strColor = "FFD700"}, { colorName = "Yellow", strColor = "FFFF00"}, { colorName = "LightYellow", strColor = "FFFFE0"}, { colorName = "LemonChiffon", strColor = "FFFACD"}, { colorName = "LightGoldenrodYellow", strColor = "FAFAD2"}, { colorName = "PapayaWhip", strColor = "FFEFD5"}, { colorName = "Moccasin", strColor = "FFE4B5"}, { colorName = "PeachPuff", strColor = "FFDAB9"}, { colorName = "PaleGoldenrod", strColor = "EEE8AA"}, { colorName = "Khaki", strColor = "F0E68C"}, { colorName = "DarkKhaki", strColor = "BDB76B"}, { colorName = "Lavender", strColor = "E6E6FA"}, { colorName = "Thistle", strColor = "D8BFD8"}, { colorName = "Plum", strColor = "DDA0DD"}, { colorName = "Violet", strColor = "EE82EE"}, { colorName = "Orchid", strColor = "DA70D6"}, { colorName = "Magenta", strColor = "FF00FF"}, { colorName = "MediumOrchid", strColor = "BA55D3"}, { colorName = "MediumPurple", strColor = "9370DB"}, { colorName = "BlueViolet", strColor = "8A2BE2"}, { colorName = "DarkViolet", strColor = "9400D3"}, { colorName = "DarkOrchid", strColor = "9932CC"}, { colorName = "DarkMagenta", strColor = "8B008B"}, { colorName = "Purple", strColor = "800080"}, { colorName = "Indigo", strColor = "4B0082"}, { colorName = "DarkSlateBlue", strColor = "483D8B"}, { colorName = "SlateBlue", strColor = "6A5ACD"}, { colorName = "MediumSlateBlue", strColor = "7B68EE"}, { colorName = "GreenYellow", strColor = "ADFF2F"}, { colorName = "Chartreuse", strColor = "7FFF00"}, { colorName = "LawnGreen", strColor = "7CFC00"}, { colorName = "Lime", strColor = "00FF00"}, { colorName = "LimeGreen", strColor = "32CD32"}, { colorName = "PaleGreen", strColor = "98FB98"}, { colorName = "LightGreen", strColor = "90EE90"}, { colorName = "MediumSpringGreen", strColor = "00FA9A"}, { colorName = "SpringGreen", strColor = "00FF7F"}, { colorName = "MediumSeaGreen", strColor = "3CB371"}, { colorName = "SeaGreen", strColor = "2E8B57"}, { colorName = "ForestGreen", strColor = "228B22"}, { colorName = "Green", strColor = "008000"}, { colorName = "DarkGreen", strColor = "006400"}, { colorName = "YellowGreen", strColor = "9ACD32"}, { colorName = "OliveDrab", strColor = "6B8E23"}, { colorName = "Olive", strColor = "808000"}, { colorName = "DarkOliveGreen", strColor = "556B2F"}, { colorName = "MediumAquamarine", strColor = "66CDAA"}, { colorName = "DarkSeaGreen", strColor = "8FBC8F"}, { colorName = "LightSeaGreen", strColor = "20B2AA"}, { colorName = "DarkCyan", strColor = "008B8B"}, { colorName = "Teal", strColor = "008080"}, { colorName = "Cyan", strColor = "00FFFF"}, { colorName = "LightCyan", strColor = "E0FFFF"}, { colorName = "PaleTurquoise", strColor = "AFEEEE"}, { colorName = "Aquamarine", strColor = "7FFFD4"}, { colorName = "Turquoise", strColor = "40E0D0"}, { colorName = "MediumTurquoise", strColor = "48D1CC"}, { colorName = "DarkTurquoise", strColor = "00CED1"}, { colorName = "CadetBlue", strColor = "5F9EA0"}, { colorName = "SteelBlue", strColor = "4682B4"}, { colorName = "LightSteelBlue", strColor = "B0C4DE"}, { colorName = "PowderBlue", strColor = "B0E0E6"}, { colorName = "LightBlue", strColor = "ADD8E6"}, { colorName = "SkyBlue", strColor = "87CEEB"}, { colorName = "LightSkyBlue", strColor = "87CEFA"}, { colorName = "DeepSkyBlue", strColor = "00BFFF"}, { colorName = "DodgerBlue", strColor = "1E90FF"}, { colorName = "CornflowerBlue", strColor = "6495ED"}, { colorName = "RoyalBlue", strColor = "4169E1"}, { colorName = "Blue", strColor = "0000FF"}, { colorName = "MediumBlue", strColor = "0000CD"}, { colorName = "DarkBlue", strColor = "00008B"}, { colorName = "Navy", strColor = "000080"}, { colorName = "MidnightBlue", strColor = "191970"}, { colorName = "Cornsilk", strColor = "FFF8DC"}, { colorName = "BlanchedAlmond", strColor = "FFEBCD"}, { colorName = "Bisque", strColor = "FFE4C4"}, { colorName = "NavajoWhite", strColor = "FFDEAD"}, { colorName = "Wheat", strColor = "F5DEB3"}, { colorName = "BurlyWood", strColor = "DEB887"}, { colorName = "Tan", strColor = "D2B48C"}, { colorName = "RosyBrown", strColor = "BC8F8F"}, { colorName = "SandyBrown", strColor = "F4A460"}, { colorName = "Goldenrod", strColor = "DAA520"}, { colorName = "DarkGoldenrod", strColor = "B8860B"}, { colorName = "Peru", strColor = "CD853F"}, { colorName = "Chocolate", strColor = "D2691E"}, { colorName = "SaddleBrown", strColor = "8B4513"}, { colorName = "Sienna", strColor = "A0522D"}, { colorName = "Brown", strColor = "A52A2A"}, { colorName = "Maroon", strColor = "800000"}, { colorName = "White", strColor = "FFFFFF"}, { colorName = "Snow", strColor = "FFFAFA"}, { colorName = "Honeydew", strColor = "F0FFF0"}, { colorName = "MintCream", strColor = "F5FFFA"}, { colorName = "Azure", strColor = "F0FFFF"}, { colorName = "AliceBlue", strColor = "F0F8FF"}, { colorName = "GhostWhite", strColor = "F8F8FF"}, { colorName = "WhiteSmoke", strColor = "F5F5F5"}, { colorName = "Seashell", strColor = "FFF5EE"}, { colorName = "Beige", strColor = "F5F5DC"}, { colorName = "OldLace", strColor = "FDF5E6"}, { colorName = "FloralWhite", strColor = "FFFAF0"}, { colorName = "Ivory", strColor = "FFFFF0"}, { colorName = "AntiqueWhite", strColor = "FAEBD7"}, { colorName = "Linen", strColor = "FAF0E6"}, { colorName = "LavenderBlush", strColor = "FFF0F5"}, { colorName = "MistyRose", strColor = "FFE4E1"}, { colorName = "Gainsboro", strColor = "DCDCDC"}, { colorName = "LightGrey", strColor = "D3D3D3"}, { colorName = "Silver", strColor = "C0C0C0"}, { colorName = "DarkGray", strColor = "A9A9A9"}, { colorName = "Gray", strColor = "808080"}, { colorName = "DimGray", strColor = "696969"}, { colorName = "LightSlateGray", strColor = "778899"}, { colorName = "SlateGray", strColor = "708090"}, { colorName = "DarkSlateGray", strColor = "2F4F4F"}, { colorName = "Black", strColor = "000000"}, } ----------------------------------------------------------------------------------------------- -- GeminiColor Upvalues ----------------------------------------------------------------------------------------------- local floor = math.floor ----------------------------------------------------------------------------------------------- -- GeminiColor OnLoad ----------------------------------------------------------------------------------------------- function GeminiColor:OnLoad() local strPrefix = Apollo.GetAssetFolder() local tToc = XmlDoc.CreateFromFile("toc.xml"):ToTable() for k,v in ipairs(tToc) do local strPath = string.match(v.Name, "(.*)[\\/]GeminiColor") if strPath ~= nil and strPath ~= "" then strPrefix = strPrefix .. "\\" .. strPath .. "\\" break end end local tSpritesXML = { __XmlNode = "Sprites", { -- Form __XmlNode="Sprite", Name="Hue", Cycle="1", { __XmlNode="Frame", Texture= strPrefix .."textures\\GCHSL.tga", x0="0", x1="0", x2="0", x3="0", x4="256", x5="256", y0="0", y1="0", y2="0", y3="0", y4="8", y5="8", HotspotX="0", HotspotY="0", Duration="1.000", StartColor="white", EndColor="white", }, }, } local xmlSprites = XmlDoc.CreateFromTable(tSpritesXML) Apollo.LoadSprites(xmlSprites) self.xmlDoc = XmlDoc.CreateFromFile(strPrefix.."GeminiColor.xml") end ---------------------------------------------------------------------------------------------- -- GeminiColor Functions ----------------------------------------------------------------------------------------------- function GeminiColor:CreateColorPicker(taOwner, fnstrCallback, bCustomColor, strInitialColor, ...) local wndChooser = Apollo.LoadForm(self.xmlDoc, "GeminiChooserForm", nil, self) wndChooser:FindChild("wnd_WidgetContainer:wnd_Hue"):SetSprite("GeminiColorSprites:Hue") local wndSwatches = wndChooser:FindChild("wnd_SwatchContainer") for i, v in pairs(ktColors) do local wndCurrColor = Apollo.LoadForm(self.xmlDoc, "SwatchButtonForm", wndSwatches, self) local xmlDocTT = XmlDoc.new() xmlDocTT:AddLine(v.colorName, "ff"..v.strColor, "CRB_InterfaceMediumBBO") wndCurrColor:SetTooltipDoc(xmlDocTT) wndCurrColor:SetBGColor("ff"..v.strColor) end wndSwatches:ArrangeChildrenTiles() local arg = {...} wndChooser:SetData({ owner = taOwner, callback = fnstrCallback, bCustomColor = bCustomColor, strInitialColor = strInitialColor, args = arg, tColorList = {strInitialColor}, }) if type(strInitialColor) == "string" then self:SetHSV(wndChooser, strInitialColor) self:UpdateCurrPrevColors(wndChooser) else wndChooser:FindChild("wnd_ColorSwatch_Current"):SetBGColor("ffffffff") wndChooser:FindChild("wnd_ColorSwatch_Previous"):SetBGColor("ff000000") end return wndChooser end function GeminiColor:OnGCOn() self:ShowColorPicker({Test = function(self, strColor) Print(strColor) end}, "Test", true) end function GeminiColor:ShowColorPicker(taOwner, fnstrCallback, bCustomColor, strInitialColor, ...) local arg = {...} local wndChooser = self:CreateColorPicker(taOwner, fnstrCallback, bCustomColor, strInitialColor, unpack(arg)) wndChooser:AddEventHandler("WindowHide", "OnColorChooserHide", self) wndChooser:Show(true) wndChooser:ToFront() end function GeminiColor:OnColorChooserHide(wndHandler, wndControl) if wndHandler ~= wndControl then return end wndControl:Destroy() end function GeminiColor:GetColorList() -- returns a table containing sub entries for all X11 colors. -- colorName, strColor return ktColors end function GeminiColor:GetColorStringByName(strColorName) -- returns the hexadecimal string for an x11 color based on name. for i, color in pairs(ktColors) do if color.colorName == strColorName then return color.strColor end end end function GeminiColor:RGBAPercToHex(r, g, b, a) -- Returns a hexadecimal string for the RGBA values passed. if not(a) then a = 1 end r = r <= 1 and r >= 0 and r or 0 g = g <= 1 and g >= 0 and g or 0 b = b <= 1 and b >= 0 and b or 0 a = a <= 1 and a >= 0 and a or 1 -- return hex string return string.format("%02x%02x%02x%02x",a*255 ,r*255, g*255, b*255) end function GeminiColor:HexToRGBAPerc(hex) -- Returns RGBA values for the a hexadecimal string passed. if string.len(hex) == 6 then local rhex, ghex, bhex = string.sub(hex, 1,2), string.sub(hex, 3, 4), string.sub(hex, 5, 6) -- return R,G,B number list return tonumber(rhex, 16)/255, tonumber(ghex, 16)/255, tonumber(bhex, 16)/255, 1 else local ahex, rhex, ghex, bhex = string.sub(hex, 1,2), string.sub(hex, 3, 4), string.sub(hex, 5, 6), string.sub(hex, 7, 8) -- return R, G, B, A number list return tonumber(rhex, 16)/255, tonumber(ghex, 16)/255, tonumber(bhex, 16)/255, tonumber(ahex, 16)/255 end end local function HexToRGBA(hex) if string.len(hex) == 6 then local rhex, ghex, bhex = string.sub(hex, 1,2), string.sub(hex, 3, 4), string.sub(hex, 5, 6) -- return R,G,B number list return tonumber(rhex, 16), tonumber(ghex, 16), tonumber(bhex, 16), 255 else local ahex, rhex, ghex, bhex = string.sub(hex, 1,2), string.sub(hex, 3, 4), string.sub(hex, 5, 6), string.sub(hex, 7, 8) -- return R, G, B, A number list return tonumber(rhex, 16), tonumber(ghex, 16), tonumber(bhex, 16), tonumber(ahex, 16) end end local function RGBAToHex(r, g, b, a) a = a or 255 return string.format("%02x%02x%02x%02x", a, r, g, b) end function GeminiColor:RGBpercToRGB(r,g,b,a) --Converts 0 - 1 RGB to 0 - 255 RGB return r * 255, g * 255, b * 255, a * 255 end function GeminiColor:RGBtoRGBperc(r,g,b,a) --Converts 0 - 255 RGB to 0 - 1 RGB return r / 255, g / 255, b / 255, a / 255 end ----------------------------------------------------------------------------------------------- -- Color Utility Functions -- Adapted From https://github.com/EmmanuelOga/columns/blob/master/utils/color.lua ----------------------------------------------------------------------------------------------- function GeminiColor:RGBtoHSV(r, g, b, a) --[[ * Converts an RGB color value to HSV. Conversion formula * adapted from http://en.wikipedia.org/wiki/HSV_color_space. * Assumes r, g, and b are contained in the set [0, 255] and * returns h, s, and v in the set [0, 1]. * * @param Number r The red color value * @param Number g The green color value * @param Number b The blue color value * @return Array The HSV representation ]] a = a or 255 r, g, b, a = r / 255, g / 255, b / 255, a / 255 local max, min = math.max(r, g, b), math.min(r, g, b) local h, s, v v = max local d = max - min if max == 0 then s = 0 else s = d / max end if max == min then h = 0 -- achromatic else if max == r then h = (g - b) / d if g < b then h = h + 6 end elseif max == g then h = (b - r) / d + 2 elseif max == b then h = (r - g) / d + 4 end h = h / 6 end return h, s, v, a end function GeminiColor:HSVtoRGB(h, s, v, a) --[[ * Converts an HSV color value to RGB. Conversion formula * adapted from http://en.wikipedia.org/wiki/HSV_color_space. * Assumes h, s, and v are contained in the set [0, 1] and * returns r, g, and b in the set [0, 255]. * * @param Number h The hue * @param Number s The saturation * @param Number v The value * @return Array The RGB representation ]] local r, g, b a = a or 1 local i = floor(h * 6); local f = h * 6 - i; local p = v * (1 - s); local q = v * (1 - f * s); local t = v * (1 - (1 - f) * s); i = i % 6 if i == 0 then r, g, b = v, t, p elseif i == 1 then r, g, b = q, v, p elseif i == 2 then r, g, b = p, v, t elseif i == 3 then r, g, b = p, q, v elseif i == 4 then r, g, b = t, p, v elseif i == 5 then r, g, b = v, p, q end return floor(r * 255), floor(g * 255), floor(b * 255), floor(a * 255) end --------------------------------------------------------------------------------------------------- -- GeminiChooserForm Functions --------------------------------------------------------------------------------------------------- function GeminiColor:OnOK(wndHandler, wndControl, eMouseButton) local wndChooser = wndControl:GetParent() local data = wndChooser:GetData() local owner = data.owner local callback if type(data.callback) == "function" then callback = data.callback else callback = owner[data.callback] end local strColor = self:GetCurrentColor(wndChooser) if data.args ~= nil then callback(owner, strColor, unpack(data.args)) else callback(owner, strColor) end wndChooser:Show(false) -- hide the window end function GeminiColor:OnCancel(wndHandler, wndControl, eMouseButton ) wndControl:GetParent():Show(false) -- hide the window end function GeminiColor:OnPickerShow(wndHandler, wndControl) local wndChooser = wndControl:GetParent() local clrOld = wndChooser:FindChild("wnd_ColorSwatch_Current"):GetBGColor():ToTable() local strColorCode = self:RGBAPercToHex(clrOld.r, clrOld.g, clrOld.b, 1) self:SetNewColor(wndChooser, strColorCode) end function GeminiColor:SetPrevCustomColor(wndHandler, wndControl) self:OnPickerShow(wndHandler, wndControl) end function GeminiColor:OnColorSwatchClick(wndHandler, wndControl) local crColor = wndControl:GetBGColor():ToTable() local strColorCode = self:RGBAPercToHex(crColor.r, crColor.g, crColor.b, 1) local wndChooser = wndControl:GetParent():GetParent() -- parent path: button -> wnd_SwatchContainer -> GeminiChooserForm self:SetHSV(wndChooser,strColorCode) self:SetNewColor(wndChooser, strColorCode) end function GeminiColor:SetRGB(wndChooser, R,G,B) -- update the RGB boxes in the color picker wndChooser:FindChild("input_Red"):SetText(R) wndChooser:FindChild("input_Green"):SetText(G) wndChooser:FindChild("input_Blue"):SetText(B) end function GeminiColor:UndoColorChange(wndHandler, wndControl, eMouseButton ) local wndChooser = wndControl:GetParent() local data = wndChooser:GetData() table.remove(data.tColorList, 1) self:SetRGB(wndChooser, self:HexToRGBAPerc(data.tColorList[1])) self:SetHSV(wndChooser, data.tColorList[1]) self:UpdateCurrPrevColors(wndChooser) end function GeminiColor:GetCurrentColor(wndChooser) local data = wndChooser:GetData() return data.tColorList[1] end function GeminiColor:SetHSV(wndChooser, strHexColor) local wndSatVal = wndChooser:FindChild("wnd_WidgetContainer:wnd_SatValue") local wndHue = wndChooser:FindChild("wnd_WidgetContainer:wnd_Hue") local h, s, v, a = self:RGBtoHSV(HexToRGBA(strHexColor)) local left, top, right, bottom = wndSatVal:FindChild("wnd_Loc"):GetAnchorOffsets() left = floor((s * 256) - 10) top = floor(((-v + 1) * 256) - 10) wndSatVal:FindChild("wnd_Loc"):SetAnchorOffsets(left, top, left + 20, top + 20) wndHue:FindChild("SliderBar"):SetValue(h * 100) local clrOverlay = RGBAToHex(self:HSVtoRGB(h, 1, 1)) wndSatVal:SetBGColor(clrOverlay) end function GeminiColor:UpdateHSV(wndChooser, bUpdatePrev) local wndSatVal = wndChooser:FindChild("wnd_WidgetContainer:wnd_SatValue") local wndHue = wndChooser:FindChild("wnd_WidgetContainer:wnd_Hue") --Saturation and Lightness local fSaturation, fLightness = wndSatVal:FindChild("wnd_Loc"):GetAnchorOffsets() fLightness = 1 - ((fLightness + 10) / 256) fSaturation = ((fSaturation + 10) / 256) if fLightness > 1 then fLightness = 1 elseif fLightness < 0 then fLightness = 0 end if fSaturation > 1 then fSaturation = 1 elseif fSaturation < 0 then fSaturation = 0 end -- Hue local fHue = floor(wndHue:FindChild("SliderBar"):GetValue()) / 100 local clrOverlay = RGBAToHex(self:HSVtoRGB(fHue, 1,1)) wndSatVal:SetBGColor(clrOverlay) -- Update Colors local clrCode = RGBAToHex(self:HSVtoRGB(fHue, fSaturation, fLightness)) wndChooser:FindChild("wnd_ColorSwatch_Current"):SetBGColor(clrCode) self:SetRGB(wndChooser, self:HexToRGBAPerc(clrCode)) if bUpdatePrev then self:SetNewColor(wndChooser, clrCode) else wndChooser:GetData().tColorList[1] = clrCode end end function GeminiColor:SatLightClick( wndHandler, wndControl, eMouseButton, nLastRelativeMouseX, nLastRelativeMouseY, bDoubleClick, bStopPropagation ) wndControl:FindChild("wnd_Loc"):SetAnchorOffsets(nLastRelativeMouseX - 10, nLastRelativeMouseY - 10, nLastRelativeMouseX + 10, nLastRelativeMouseY + 10) local wndChooser = wndControl:GetParent():GetParent() -- ancestor chain: wnd_SatValue -> wnd_WidgetContainer -> wnd_ColorPicker -> GeminiChooserForm self:UpdateHSV(wndChooser, true) end function GeminiColor:OnSatValueMove(wndHandler, wndControl) -- Constrain to SatValue local left,top,right,bottom = wndControl:GetAnchorOffsets() local rightEdge = wndControl:GetParent():GetWidth() - 10 local bottomEdge = wndControl:GetParent():GetHeight() - 10 if left < -10 then left = -10 elseif left > rightEdge then left = rightEdge end if top < -10 then top = -10 elseif top > bottomEdge then top = bottomEdge end wndControl:SetAnchorOffsets(left,top,left + 20, top + 20) local wndChooser = wndControl:GetParent():GetParent():GetParent() -- ancestor chain: wnd_Loc -> wnd_SatValue -> wnd_WidgetContainer -> wnd_ColorPicker -> GeminiChooserForm self:UpdateHSV(wndChooser, true) end function GeminiColor:OnHueSliderChanged( wndHandler, wndControl, fNewValue, fOldValue) local wndChooser = wndControl:GetParent():GetParent():GetParent() -- ancestor chain: SliderBar -> wnd_Hue -> wnd_WidgetContainer -> GeminiChooserForm self:UpdateHSV(wndChooser, false) end function GeminiColor:UpdateCurrPrevColors(wndChooser) local data = wndChooser:GetData() local tColorList = data.tColorList if #tColorList > 1 then local currColor = tColorList[1] local prevColor = tColorList[2] local wndCurrColor = wndChooser:FindChild("wnd_ColorSwatch_Current") local wndPrevColor = wndChooser:FindChild("wnd_ColorSwatch_Previous") wndCurrColor:SetBGColor(currColor) wndPrevColor:SetBGColor(prevColor) else local currColor = tColorList[1] local prevColor = "ff000000" local wndCurrColor = wndChooser:FindChild("wnd_ColorSwatch_Current") local wndPrevColor = wndChooser:FindChild("wnd_ColorSwatch_Previous") wndCurrColor:SetBGColor(currColor) wndPrevColor:SetBGColor(prevColor) end end function GeminiColor:SetNewColor(wndChooser, strColorCode) local data = wndChooser:GetData() table.insert(data.tColorList, 1, strColorCode) self:UpdateCurrPrevColors(wndChooser) end --------------------------------------------------------------------------------------------------- -- GeminiColor Dropdown Functions --------------------------------------------------------------------------------------------------- function GeminiColor:CreateColorDropdown(wndHost, strSkin) -- wndHost = place holder window, used to get Window Name, Anchors and Offsets, and Parent -- strSkin = "Holo" or "Metal" -- not case sensitive if wndHost == nil then Print("You must supply a valid window for argument #1."); return end local fLeftAnchor, fTopAnchor, fRightAnchor, fBottomAnchor = wndHost:GetAnchorPoints() local fLeftOffset, fTopOffset, fRightOffset, fBottomOffset = wndHost:GetAnchorOffsets() local strName = wndHost:GetName() local wndParent = wndHost:GetParent() wndHost:Destroy() local wndDD = Apollo.LoadForm(self.xmlDoc, "ColorDDForm", wndParent, self) if string.lower(strSkin) == string.lower("metal") then wndDD:ChangeArt("CRB_Basekit:kitBtn_Dropdown_TextBaseHybrid") --CRB_Basekit:kitBtn_List_MetalContextMenu end local wndDDMenu = wndDD:FindChild("wnd_DDList") for i, v in pairs(ktColors) do local wndCurrColor = Apollo.LoadForm(self.xmlDoc,"ColorListItemForm",wndDDMenu,self) wndCurrColor:SetText(v.colorName) wndCurrColor:SetTextColor("ff"..v.strColor) wndCurrColor:FindChild("swatch"):SetBGColor("ff"..v.strColor) if string.lower(strSkin) == string.lower("metal") then wndDD:ChangeArt("CRB_Basekit:kitBtn_List_MetalContextMenu") end end wndDDMenu:ArrangeChildrenVert() wndDDMenu:Show(false) wndDD:SetAnchorPoints(fLeftAnchor, fTopAnchor, fRightAnchor, fBottomAnchor) wndDD:SetAnchorOffsets(fLeftOffset, fTopOffset, fRightOffset, fBottomOffset) wndDD:SetName(strName) return wndDD end function GeminiColor:OnColorDD(wndHandler, wndControl) -- Show DD List local wndDD = wndControl:FindChild("wnd_ColorDD") wndDD:Show(not wndDD:IsShown()) end function GeminiColor:OnColorClick(wndHandler, wndControl) -- choose from DD list local strColorName = wndControl:GetText() local strColorCode = self:GetColorStringByName(strColorName) strColorCode = "FF"..strColorCode local wndChooser = wndControl:GetParent():GetParent() -- parent path: button -> list window -> Dropdown wndChooser:FindChild("wnd_Text"):SetText(strColorName) wndChooser:FindChild("wnd_Text"):SetTextColor(strColorCode) wndChooser:SetData({ strColor = strColorCode, strName = strColorName, }) wndControl:GetParent():Show(false) end function GeminiColor:new(o) o = o or {} setmetatable(o, self) self.__index = self return o end Apollo.RegisterPackage(GeminiColor:new(), MAJOR, MINOR, {})
mit
yariplus/love-demos
love-controller/input/controller.lua
1
1602
local controller = {} local joystick = null local lastbutton = "none" function controller:update(dt) if not joystick then local joysticks = love.joystick.getJoysticks() joystick = joysticks[1] return end if joystick:isGamepadDown("dpleft") then position.x = position.x - speed * dt elseif joystick:isGamepadDown("dpright") then position.x = position.x + speed * dt end if joystick:isGamepadDown("dpup") then position.y = position.y - speed * dt elseif joystick:isGamepadDown("dpdown") then position.y = position.y + speed * dt end end function love.gamepadpressed(joystick, button) lastbutton = button end function controller:draw() love.graphics.circle("fill", position.x, position.y, 50) if not joystick then return end local buttons = "" for a=1,joystick:getButtonCount() do local state = ""; if joystick:isDown(a) then state = "Pressed" else state = "Released" end buttons = buttons.."Button "..a..": "..state.."\n" end local axis = "" for a=1,joystick:getAxisCount() do axis = axis.."Axis "..a..": "..joystick:getAxis(a).."\n" end local hats = "" for a=1,joystick:getHatCount() do hats = hats.."Hat "..a..": "..joystick:getHat(a).."\n" end love.graphics.print("" .."Last gamepad button pressed: "..lastbutton.."\n" .."\n" .."Buttons: "..joystick:getButtonCount().."\n" .."Axis: "..joystick:getAxisCount().."\n" .."Hats: "..joystick:getHatCount().."\n" .."\n" ..buttons ..axis ..hats , 10, 10) end return controller
cc0-1.0
taiha/luci
libs/luci-lib-nixio/root/usr/lib/lua/nixio/util.lua
179
5824
--[[ nixio - Linux I/O library for lua Copyright 2009 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local table = require "table" local nixio = require "nixio" local getmetatable, assert, pairs, type = getmetatable, assert, pairs, type local tostring = tostring module "nixio.util" local BUFFERSIZE = nixio.const.buffersize local ZIOBLKSIZE = 65536 local socket = nixio.meta_socket local tls_socket = nixio.meta_tls_socket local file = nixio.meta_file local uname = nixio.uname() local ZBUG = uname.sysname == "Linux" and uname.release:sub(1, 3) == "2.4" function consume(iter, append) local tbl = append or {} if iter then for obj in iter do tbl[#tbl+1] = obj end end return tbl end local meta = {} function meta.is_socket(self) return (getmetatable(self) == socket) end function meta.is_tls_socket(self) return (getmetatable(self) == tls_socket) end function meta.is_file(self) return (getmetatable(self) == file) end function meta.readall(self, len) local block, code, msg = self:read(len or BUFFERSIZE) if not block then return nil, code, msg, "" elseif #block == 0 then return "", nil, nil, "" end local data, total = {block}, #block while not len or len > total do block, code, msg = self:read(len and (len - total) or BUFFERSIZE) if not block then return nil, code, msg, table.concat(data) elseif #block == 0 then break end data[#data+1], total = block, total + #block end local data = #data > 1 and table.concat(data) or data[1] return data, nil, nil, data end meta.recvall = meta.readall function meta.writeall(self, data) data = tostring(data) local sent, code, msg = self:write(data) if not sent then return nil, code, msg, 0 end local total = sent while total < #data do sent, code, msg = self:write(data, total) if not sent then return nil, code, msg, total end total = total + sent end return total, nil, nil, total end meta.sendall = meta.writeall function meta.linesource(self, limit) limit = limit or BUFFERSIZE local buffer = "" local bpos = 0 return function(flush) local line, endp, _ if flush then line = buffer:sub(bpos + 1) buffer = type(flush) == "string" and flush or "" bpos = 0 return line end while not line do _, endp, line = buffer:find("(.-)\r?\n", bpos + 1) if line then bpos = endp return line elseif #buffer < limit + bpos then local newblock, code, msg = self:read(limit + bpos - #buffer) if not newblock then return nil, code, msg elseif #newblock == 0 then return nil end buffer = buffer:sub(bpos + 1) .. newblock bpos = 0 else return nil, 0 end end end end function meta.blocksource(self, bs, limit) bs = bs or BUFFERSIZE return function() local toread = bs if limit then if limit < 1 then return nil elseif limit < toread then toread = limit end end local block, code, msg = self:read(toread) if not block then return nil, code, msg elseif #block == 0 then return nil else if limit then limit = limit - #block end return block end end end function meta.sink(self, close) return function(chunk, src_err) if not chunk and not src_err and close then if self.shutdown then self:shutdown() end self:close() elseif chunk and #chunk > 0 then return self:writeall(chunk) end return true end end function meta.copy(self, fdout, size) local source = self:blocksource(nil, size) local sink = fdout:sink() local sent, chunk, code, msg = 0 repeat chunk, code, msg = source() sink(chunk, code, msg) sent = chunk and (sent + #chunk) or sent until not chunk return not code and sent or nil, code, msg, sent end function meta.copyz(self, fd, size) local sent, lsent, code, msg = 0 local splicable if not ZBUG and self:is_file() then local ftype = self:stat("type") if nixio.sendfile and fd:is_socket() and ftype == "reg" then repeat lsent, code, msg = nixio.sendfile(fd, self, size or ZIOBLKSIZE) if lsent then sent = sent + lsent size = size and (size - lsent) end until (not lsent or lsent == 0 or (size and size == 0)) if lsent or (not lsent and sent == 0 and code ~= nixio.const.ENOSYS and code ~= nixio.const.EINVAL) then return lsent and sent, code, msg, sent end elseif nixio.splice and not fd:is_tls_socket() and ftype == "fifo" then splicable = true end end if nixio.splice and fd:is_file() and not splicable then splicable = not self:is_tls_socket() and fd:stat("type") == "fifo" end if splicable then repeat lsent, code, msg = nixio.splice(self, fd, size or ZIOBLKSIZE) if lsent then sent = sent + lsent size = size and (size - lsent) end until (not lsent or lsent == 0 or (size and size == 0)) if lsent or (not lsent and sent == 0 and code ~= nixio.const.ENOSYS and code ~= nixio.const.EINVAL) then return lsent and sent, code, msg, sent end end return self:copy(fd, size) end if tls_socket then function tls_socket.close(self) return self.socket:close() end function tls_socket.getsockname(self) return self.socket:getsockname() end function tls_socket.getpeername(self) return self.socket:getpeername() end function tls_socket.getsockopt(self, ...) return self.socket:getsockopt(...) end tls_socket.getopt = tls_socket.getsockopt function tls_socket.setsockopt(self, ...) return self.socket:setsockopt(...) end tls_socket.setopt = tls_socket.setsockopt end for k, v in pairs(meta) do file[k] = v socket[k] = v if tls_socket then tls_socket[k] = v end end
apache-2.0
lichtl/darkstar
scripts/zones/Port_San_dOria/npcs/Artinien.lua
17
1401
----------------------------------- -- Area: Port San d'Oria -- NPC: Artinien -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Port_San_dOria/TextIDs"); require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script local FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then local count = trade:getItemCount(); local MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x24c); 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
RunAwayDSP/darkstar
scripts/zones/Port_San_dOria/npcs/Joulet.lua
9
3572
----------------------------------- -- Area: Port San d'Oria -- NPC: Joulet -- Starts The Competition -- !pos -18 -2 -45 232 ----------------------------------- local ID = require("scripts/zones/Port_San_dOria/IDs"); require("scripts/globals/npc_util"); require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/globals/titles"); require("scripts/globals/status"); ----------------------------------- function onSpawn(npc) npcUtil.fishingAnimation(npc, 2) end; function onTrade(player,npc,trade) local count = trade:getItemCount(); local MoatCarp = trade:getItemQty(4401) local ForestCarp = trade:getItemQty(4289) local fishCountVar = player:getCharVar("theCompetitionFishCountVar"); local totalFish = MoatCarp + ForestCarp + fishCountVar; if (MoatCarp + ForestCarp > 0 and MoatCarp + ForestCarp == count) then if (player:getQuestStatus(SANDORIA,dsp.quest.id.sandoria.THE_COMPETITION) == QUEST_ACCEPTED and totalFish >= 10000) then -- ultimate reward player:tradeComplete(); player:addFame(SANDORIA,30); player:addGil((GIL_RATE*10*MoatCarp) + (GIL_RATE*15*ForestCarp)); player:messageSpecial(ID.text.GIL_OBTAINED,MoatCarp*10 + ForestCarp*15); player:startEvent(307); elseif (player:getQuestStatus(SANDORIA,dsp.quest.id.sandoria.THE_COMPETITION) >= QUEST_ACCEPTED) then -- regular turn-ins. Still allowed after completion of the quest. player:tradeComplete(); player:addFame(SANDORIA,30); player:addGil((GIL_RATE*10*MoatCarp) + (GIL_RATE*15*ForestCarp)); player:setCharVar("theCompetitionFishCountVar",totalFish); player:startEvent(305); player:messageSpecial(ID.text.GIL_OBTAINED,MoatCarp*10 + ForestCarp*15); else player:startEvent(306); end end npc:setAnimation(0) end; function onTrigger(player,npc) if (player:getQuestStatus(SANDORIA,dsp.quest.id.sandoria.THE_COMPETITION) == QUEST_AVAILABLE and player:getQuestStatus(SANDORIA,dsp.quest.id.sandoria.THE_RIVALRY) == QUEST_AVAILABLE) then -- If you haven't started either quest yet player:startEvent(304, 4401, 4289); -- Moat Carp = 4401, 4289 = Forest Carp elseif (player:getQuestStatus(SANDORIA,dsp.quest.id.sandoria.THE_RIVALRY) == QUEST_ACCEPTED) then player:showText(npc, ID.text.JOULET_HELP_OTHER_BROTHER); elseif ((player:getQuestStatus(SANDORIA,dsp.quest.id.sandoria.THE_COMPETITION)) == QUEST_ACCEPTED) then player:showText(npc, ID.text.JOULET_CARP_STATUS, 0, player:getCharVar("theCompetitionFishCountVar")); end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) if (csid == 307) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ID.text.ITEM_CANNOT_BE_OBTAINED,17386); else player:tradeComplete(); player:addItem(17386); player:messageSpecial(ID.text.ITEM_OBTAINED, 17386); player:addTitle(dsp.title.CARP_DIEM); player:addKeyItem(dsp.ki.TESTIMONIAL); player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.TESTIMONIAL); player:setCharVar("theCompetitionFishCountVar",0); player:completeQuest(SANDORIA,dsp.quest.id.sandoria.THE_COMPETITION); end elseif (csid == 304 and option == 700) then player:addQuest(SANDORIA,dsp.quest.id.sandoria.THE_COMPETITION); end end;
gpl-3.0
RunAwayDSP/darkstar
scripts/zones/Bastok_Markets/npcs/Salimah.lua
11
2867
----------------------------------- -- Area: Bastok Markets -- NPC: Salimah -- Notes: Start & Finishes Quest: Gourmet -- !pos -31.687 -6.824 -73.282 235 ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/titles"); local ID = require("scripts/zones/Bastok_Markets/IDs"); require("scripts/globals/settings"); ----------------------------------- function onTrade(player,npc,trade) local Gourmet = player:getQuestStatus(BASTOK,dsp.quest.id.bastok.GOURMET); if (Gourmet ~= QUEST_AVAILABLE and player:needToZone() == false) then local count = trade:getItemCount(); local hasSleepshroom = trade:hasItemQty(4374,1); local hasTreantBulb = trade:hasItemQty(953,1); local hasWildOnion = trade:hasItemQty(4387,1); if (hasSleepshroom or hasTreantBulb or hasWildOnion) then if (count == 1) then local vanatime = VanadielHour(); local item = 0; local event = 203; if (hasSleepshroom) then item = 4374; if (vanatime>=18 or vanatime<6) then event = 201; end elseif (hasTreantBulb) then item = 953; if (vanatime>=6 and vanatime<12) then event = 201; end elseif (hasWildOnion) then item = 4387; if (vanatime>=12 and vanatime<18) then event = 202; end end player:startEvent(event,item); end end end end; function onTrigger(player,npc) if (player:getQuestStatus(BASTOK,dsp.quest.id.bastok.GOURMET) ~= QUEST_AVAILABLE and player:needToZone()) then player:startEvent(121); else player:startEvent(200); end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) local Gourmet = player:getQuestStatus(BASTOK,dsp.quest.id.bastok.GOURMET); if (csid == 200) then if (Gourmet == QUEST_AVAILABLE) then player:addQuest(BASTOK,dsp.quest.id.bastok.GOURMET); end elseif (csid ~= 121) then player:tradeComplete(); if (Gourmet == QUEST_ACCEPTED) then player:completeQuest(BASTOK,dsp.quest.id.bastok.GOURMET); end local gil=350; local fame=120; if (csid == 201) then gil=200; elseif (csid == 203) then gil=100; fame=60; end player:addGil(gil*GIL_RATE); player:messageSpecial(ID.text.GIL_OBTAINED,gil*GIL_RATE); player:addFame(BASTOK,fame); player:addTitle(dsp.title.MOMMYS_HELPER); player:needToZone(true); end end;
gpl-3.0
taiha/luci
modules/luci-mod-admin-full/luasrc/model/cbi/admin_system/leds.lua
4
4050
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Licensed to the public under the Apache License 2.0. m = Map("system", translate("<abbr title=\"Light Emitting Diode\">LED</abbr> Configuration"), translate("Customizes the behaviour of the device <abbr title=\"Light Emitting Diode\">LED</abbr>s if possible.")) local sysfs_path = "/sys/class/leds/" local leds = {} local fs = require "nixio.fs" local nu = require "nixio.util" local util = require "luci.util" if fs.access(sysfs_path) then leds = nu.consume((fs.dir(sysfs_path))) end if #leds == 0 then return m end s = m:section(TypedSection, "led", "") s.anonymous = true s.addremove = true function s.parse(self, ...) TypedSection.parse(self, ...) os.execute("/etc/init.d/led enable") end s:option(Value, "name", translate("Name")) sysfs = s:option(ListValue, "sysfs", translate("<abbr title=\"Light Emitting Diode\">LED</abbr> Name")) for k, v in ipairs(leds) do sysfs:value(v) end s:option(Flag, "default", translate("Default state")).rmempty = false trigger = s:option(ListValue, "trigger", translate("Trigger")) local triggers = fs.readfile(sysfs_path .. leds[1] .. "/trigger") for t in triggers:gmatch("[%w-]+") do trigger:value(t, translate(t:gsub("-", ""))) end delayon = s:option(Value, "delayon", translate ("On-State Delay")) delayon:depends("trigger", "timer") delayoff = s:option(Value, "delayoff", translate ("Off-State Delay")) delayoff:depends("trigger", "timer") dev = s:option(ListValue, "_net_dev", translate("Device")) dev.rmempty = true dev:value("") dev:depends("trigger", "netdev") function dev.cfgvalue(self, section) return m.uci:get("system", section, "dev") end function dev.write(self, section, value) m.uci:set("system", section, "dev", value) end function dev.remove(self, section) local t = trigger:formvalue(section) if t ~= "netdev" and t ~= "usbdev" then m.uci:delete("system", section, "dev") end end for k, v in pairs(luci.sys.net.devices()) do if v ~= "lo" then dev:value(v) end end mode = s:option(MultiValue, "mode", translate("Trigger Mode")) mode.rmempty = true mode:depends("trigger", "netdev") mode:value("link", translate("Link On")) mode:value("tx", translate("Transmit")) mode:value("rx", translate("Receive")) usbdev = s:option(ListValue, "_usb_dev", translate("USB Device")) usbdev:depends("trigger", "usbdev") usbdev.rmempty = true usbdev:value("") function usbdev.cfgvalue(self, section) return m.uci:get("system", section, "dev") end function usbdev.write(self, section, value) m.uci:set("system", section, "dev", value) end function usbdev.remove(self, section) local t = trigger:formvalue(section) if t ~= "netdev" and t ~= "usbdev" then m.uci:delete("system", section, "dev") end end usbport = s:option(MultiValue, "port", translate("USB Ports")) usbport:depends("trigger", "usbport") usbport.rmempty = true usbport.widget = "checkbox" usbport.cast = "table" usbport.size = 1 function usbport.valuelist(self, section) local port, ports = nil, {} for port in util.imatch(m.uci:get("system", section, "port")) do local b, n = port:match("^usb(%d+)-port(%d+)$") if not (b and n) then b, n = port:match("^(%d+)-(%d+)$") end if b and n then ports[#ports+1] = "usb%u-port%u" %{ tonumber(b), tonumber(n) } end end return ports end function usbport.validate(self, value) return type(value) == "string" and { value } or value end for p in nixio.fs.glob("/sys/bus/usb/devices/[0-9]*/manufacturer") do local id = p:match("%d+-%d+") local mf = nixio.fs.readfile("/sys/bus/usb/devices/" .. id .. "/manufacturer") or "?" local pr = nixio.fs.readfile("/sys/bus/usb/devices/" .. id .. "/product") or "?" usbdev:value(id, "%s (%s - %s)" %{ id, mf, pr }) end for p in nixio.fs.glob("/sys/bus/usb/devices/*/usb[0-9]*-port[0-9]*") do local bus, port = p:match("usb(%d+)-port(%d+)") if bus and port then usbport:value("usb%u-port%u" %{ tonumber(bus), tonumber(port) }, "Hub %u, Port %u" %{ tonumber(bus), tonumber(port) }) end end return m
apache-2.0
lichtl/darkstar
scripts/globals/weaponskills/bora_axe.lua
18
1772
----------------------------------- -- Bora Axe -- Axe weapon skill -- Skill level: 290 -- Delivers a single-hit ranged attack at a maximum distance of 15.7'. Chance of binding varies with TP -- Bind doesn't always break from hitting mob. -- This Weapon Skill's first hit params.ftp is duplicated for all additional hits -- Not natively available to RNG -- Aligned with the ?? Gorget. -- Element: Ice -- Modifiers: DEX 60% -- http://wiki.bluegartr.com/bg/Bora_Axe -- 100%TP 200%TP 300%TP -- 1.0 1.0 1.0 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar) local params = {}; params.numHits = 1; params.ftp100 = 1.0; params.ftp200 = 1.0; params.ftp300 = 1.0; params.str_wsc = 0.0; params.dex_wsc = 0.6; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 3.5; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.ftp100 = 4.5; params.ftp200 = 4.5; params.ftp300 = 4.5; params.dex_wsc = 1.0; params.atkmulti = 1.0; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params); if (damage > 0 and target:hasStatusEffect(EFFECT_BIND) == false) then target:addStatusEffect(EFFECT_BIND, 1, 0, 20); end return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
PrimaStudios/ProjectPrima
src/libs/LOVEly-tiles-master/tmxloader.lua
3
11944
local path = (...):match('^.+[%.\\/]') or '' local grid = require(path..'grid') local atlas = require(path..'atlas') local mapdata = require(path..'mapdata') local map = require(path..'map') local isomap = require(path..'isomap') local drawlist = require(path..'drawlist') local xmlparser = require(path..'ext.xml') local unb64 = require ('mime').unb64 local deflate = require(path..'ext.deflate') local imageCache= setmetatable({},{__mode== 'v'}) -- ============================================== -- ADDONS/HACK -- ============================================== -- hack for offset/opacity/align to bottom left local function proxyDraw(self,draw,x,y,...) x,y = x or 0,y or 0 local opacity = self.opacity local lg = love.graphics local r,g,b,a if opacity then r,g,b,a = lg.getColor() lg.setColor(r,g,b,a*opacity) end -- align bottom left y = y+(self.th-self.atlas.qHeight) local offsets = self.atlas.tileoffset if offsets then draw(self, x+offsets.x,y+offsets.y, ...) else draw(self,x,y,...) end if opacity then lg.setColor(r,g,b,a) end end local function applyTmxStyleToDraw(map) local olddraw = map.draw function map:draw(...) proxyDraw(self,olddraw,...) end end -- ============================================== -- XML HANDLER LOGIC -- ============================================== -- ---------------------------------------------- -- PREPARE ELEMENT -- ---------------------------------------------- local prepareElement = {} local p = prepareElement p.map = function() local element = {} element.tilesets= {} element.layers = {} return element end p.tileset = function() local element= {} element.tiles= {} return element end p.objectgroup = function() local element = {} element.objects= {} return element end -- ---------------------------------------------- -- INSERT ELEMENT TO PARENT -- ---------------------------------------------- local insertToParent = {} local i = insertToParent i.tileset = function(object,parent) parent.tilesets = parent.tilesets or {} table.insert(parent.tilesets,object) end i.tile = function(object,tileset) tileset.tiles[object.id] = object end i.property = function(object,properties) properties[object.name] = object.value end i.layer = function(object,map) table.insert(map.layers,object) end i.objectgroup = function(object,map) table.insert(map.layers,object) end i.imagelayer = function(object,map) table.insert(map.layers,object) end i.object = function(object,objectgroup) table.insert(objectgroup.objects,object) end local function convertPoints(object) local newpoints = {} for point in object.points:gmatch '(-?%d+)' do point = tonumber(point) table.insert(newpoints,point) end object.points = newpoints end i.polygon = function(object,parent) convertPoints(object) parent.polygon = object end i.polyline = function(object,parent) convertPoints(object) parent.polyline = object end -- ============================================== -- XML HANDLER -- ============================================== local handler = {} handler.__index = handler handler.starttag = function(self,name,attr) local stack = self.stack local element = prepareElement[name] and prepareElement[name]() or {} if attr then for k,v in pairs(attr) do if not element[k] then v = tonumber(v) or v v = v == 'true' and true or v == 'false' and false or v element[k] = v end end end stack.len = stack.len + 1 table.insert(self.stack,element) end handler.endtag = function(self,name,attr) local stack = self.stack local element = table.remove(stack,stack.len) stack.len = stack.len - 1 local parent = stack[stack.len] if insertToParent[name] then insertToParent[name](element,parent) else parent[name] = element end end handler.text = function(self,text) self.stack[self.stack.len][1] = text end local function newHandler() local h = {root = {},stack = {len = 1}} h.stack[1] = h.root return setmetatable(h,handler) end -- ============================================== -- PATH FUNCTIONS -- ============================================== local function getPathComponents(path) local dir,name,ext = path:match('^(.-)([^\\/]-)%.?([^\\/%.]*)$') if #name == 0 then name = ext; ext = '' end return dir,name,ext end local function removeUpDirectory(path) while path:find('%.%.[\\/]+') do path = path:gsub('[^\\/]*[\\/]*%.%.[\\/]+','') end return path end local stripExcessSlash = function(path) return path:gsub('[\\/]+','/') end -- ============================================== -- HELPER LOAD FUNCTIONS -- ============================================== local function byteToNumber(str) local num = 0 local len = #str for i = 1,len do num = num + string.byte(str,i) * 256^(i-1) end return num end local streamData = function(tmxmap,layer) local data = layer.data local str = data.encoding == 'base64' and unb64(data[1]) or data[1] local bytes = {len = 0} local byteconsume = function(code) bytes.len = bytes.len+1 bytes[bytes.len]= string.char(code) end local handler = { input = str, output = byteconsume, disable_crc = true } if data.compression == 'gzip' then deflate.gunzip( handler ) str = table.concat(bytes) elseif data.compression == 'zlib' then deflate.inflate_zlib( handler ) str = table.concat(bytes) end return coroutine.wrap(function() local divbits = 2^29 local pattern = data.encoding == 'base64' and '(....)' or '(%d+)' local count = 0 local w,h = layer.width or tmxmap.width,layer.height or tmxmap.height for num in str:gmatch(pattern) do count = count + 1 if data.encoding == 'base64' then num = byteToNumber(num) else num = tonumber(num) end -- bit 32: xflip -- bit 31: yflip -- bit 30: antidiagonal flip local gid = num % divbits local flips = math.floor(num / 2^29) local xflip = math.floor(flips / 4) == 1 local yflip = math.floor( (flips % 4) / 2) == 1 local diagflip = flips % 2 --[[ -\- diag flip first! flipx flipy diagflip --> flipx flipy angle -- or --> flipx flipy angle 1 0 1 0 0 90 1 1 -90 1 1 1 1 0 90 0 1 -90 0 1 1 1 1 90 0 0 -90 0 0 1 0 1 90 1 0 -90 --]] local angle = 0 if diagflip == 1 then angle = math.pi/2 xflip,yflip= yflip,not xflip end if xflip and yflip then angle = angle+math.pi; xflip,yflip = false,false end local y = math.ceil(count/w) local x = count - (y-1)*w coroutine.yield(gid,x,y,angle,xflip,yflip) end end) end local function buildImage(tmxmap,parent) local imagetable = parent.image local source = stripExcessSlash( removeUpDirectory(tmxmap.path..imagetable.source) ) local image = imageCache[source] or love.graphics.newImage(source) imageCache[source]= image parent.image = image parent.source = imagetable.source parent.trans = imagetable.trans end local function mergeExternalTSX(tmxmap,tileset) local h = newHandler() local tsxparser= xmlparser(h) local path = stripExcessSlash( removeUpDirectory(tmxmap.path..tileset.source) ) local str = love.filesystem.read(path) tsxparser:parse(str) local tsxtable = h.root.tilesets[1] for i,v in pairs(tsxtable) do tileset[i] = v end end local function buildAtlasesAndImages(tmxmap) local tilesets = tmxmap.tilesets for _,tileset in ipairs(tilesets) do if tileset.source then mergeExternalTSX(tmxmap,tileset) end local offset = tileset.margin or 0 local space = tileset.spacing or 0 buildImage(tmxmap,tileset) local iw,ih = tileset.image:getWidth(),tileset.image:getHeight() local tw,th = tileset.tilewidth,tileset.tileheight local atlasW = math.floor( (iw-offset*2+space)/(tw+space) ) * (tw+space) - space local atlasH = math.floor( (ih-offset*2+space)/(th+space) ) * (th+space) - space local atlas = atlas.new(iw,ih,tw,th,atlasW,atlasH,offset,offset,space,space) atlas.properties= tileset.properties -- hack for tileoffset atlas.tileoffset= tileset.tileoffset atlas:setName(tileset.name) tileset.atlas = atlas for i,tile in pairs(tileset.tiles) do if tile.properties then local properties = {} for key,value in pairs(tile.properties) do properties[key] = value end atlas:setqProperty(tile.id+1,properties) end end end end local function storeAtlasesByName(tmxmap,dl) dl.atlases = {} for i,tileset in pairs(tmxmap.tilesets) do dl.atlases[tileset.name] = tileset.atlas end end local function getTilesetBuildMap(gid,tmxmap,layer) local tilesets = tmxmap.tilesets local mapnew = tmxmap.orientation == 'orthogonal' and map.new or tmxmap.orientation == 'isometric' and isomap.new local chosen for _,tileset in ipairs(tilesets) do if gid >= tileset.firstgid then chosen = tileset end end local tileset = chosen local map = mapnew(tileset.image,tileset.atlas,tmxmap.tilewidth,tmxmap.tileheight) applyTmxStyleToDraw(map) map.imagesource= tileset.source map.properties = layer.properties map.opacity = layer.opacity map:setViewRange(1,1,tmxmap.width,tmxmap.height) return tileset,map end local tmxToTable = function(filename) local h = newHandler() local tmxparser= xmlparser(h) local hasFile = love.filesystem.isFile(filename) if not hasFile then return nil,'TMX map not found: '..filename end local str = love.filesystem.read(filename) tmxparser:parse(str) local tmxmap = h.root.map local dir = getPathComponents(filename) tmxmap.path = dir return tmxmap end -- ============================================== -- TMX LOADER -- ============================================== local DEFAULT_CHUNK_SIZE = 1000 local worker = function(filename,chunkSize) local tmxmap,err = tmxToTable(filename) if err then return nil,err end local dl = drawlist.new() if chunkSize then coroutine.yield(dl) end dl.properties = tmxmap.properties buildAtlasesAndImages(tmxmap) storeAtlasesByName(tmxmap,dl) local chunkCount = 0 for i,layer in ipairs(tmxmap.layers) do local isTileLayer = layer.data local name = layer.name ~= '' and layer.name or 'layer'..i if isTileLayer then local tileset,map,firstgid for gid,x,y,angle,flipx,flipy in streamData(tmxmap,layer) do if gid ~= 0 then if not (tileset and map) then tileset,map = getTilesetBuildMap(gid,tmxmap,layer) firstgid = tileset.firstgid dl:insert(name,map,1,1,layer.visible ~= 0) map:setName(name) end local index = gid-firstgid+1 map:setTile(x,y,index,angle,flipx,flipy) end chunkCount = chunkCount + 1 if chunkSize and chunkCount == chunkSize then chunkCount = 0 coroutine.yield() end end else if layer.image then buildImage(tmxmap,layer) layer.__element = 'imagelayer' else layer.__element = 'objectgroup' end dl:insert(layer.name,layer) chunkCount = chunkCount + 1 end if chunkSize and chunkCount == chunkSize then chunkCount = 0 coroutine.yield() end end if not chunkSize then return dl end end return function(filename,chunkSize) if chunkSize then local co = coroutine.create(worker) local ok,drawlist,err = coroutine.resume(co,filename,chunkSize) err = not ok and drawlist or err if err then return nil,err end local resume,status = coroutine.resume,coroutine.status local load_done local loader = function() if load_done then return true end local ok,err = resume(co) local finished = status(co) == 'dead' load_done = finished and not err return finished,err end return drawlist,loader else return worker(filename) end end
apache-2.0
ld-test/loop
lua/loop/debug/Viewer.lua
11
5744
-------------------------------------------------------------------------------- ---------------------- ## ##### ##### ###### ----------------------- ---------------------- ## ## ## ## ## ## ## ----------------------- ---------------------- ## ## ## ## ## ###### ----------------------- ---------------------- ## ## ## ## ## ## ----------------------- ---------------------- ###### ##### ##### ## ----------------------- ---------------------- ----------------------- ----------------------- Lua Object-Oriented Programming ------------------------ -------------------------------------------------------------------------------- -- Project: LOOP Class Library -- -- Release: 2.3 beta -- -- Title : Visualization of Lua Values -- -- Author : Renato Maia <maia@inf.puc-rio.br> -- -------------------------------------------------------------------------------- local _G = _G local select = select local type = type local next = next local pairs = pairs local rawget = rawget local rawset = rawset local getmetatable = getmetatable local setmetatable = setmetatable local luatostring = tostring local loaded = package and package.loaded local string = require "string" local table = require "table" local io = require "io" local oo = require "loop.base" module("loop.debug.Viewer", oo.class) maxdepth = -1 indentation = " " linebreak = "\n" prefix = "" output = io.output() function writevalue(self, buffer, value, history, prefix, maxdepth) local luatype = type(value) if luatype == "nil" or luatype == "boolean" or luatype == "number" then buffer:write(luatostring(value)) elseif luatype == "string" then buffer:write(string.format("%q", value)) else local label = history[value] if label then buffer:write(label) else label = self.labels[value] or self:label(value) history[value] = label if luatype == "table" then buffer:write("{ --[[",label,"]]") local key, field = next(value) if key then if maxdepth == 0 then buffer:write(" ... ") else maxdepth = maxdepth - 1 local newprefix = prefix..self.indentation for i = 1, #value do buffer:write(self.linebreak, newprefix) self:writevalue(buffer, value[i], history, newprefix, maxdepth) buffer:write(",") end repeat local keytype = type(key) if keytype ~= "number" or key<=0 or key>#value or (key%1)~=0 then buffer:write(self.linebreak, newprefix) if keytype == "string" and key:match("^[%a_][%w_]*$") then buffer:write(key) else buffer:write("[") self:writevalue(buffer, key, history, newprefix, maxdepth) buffer:write("]") end buffer:write(" = ") self:writevalue(buffer, field, history, newprefix, maxdepth) buffer:write(",") end key, field = next(value, key) until not key buffer:write(self.linebreak, prefix) end else buffer:write(" ") end buffer:write("}") else buffer:write(label) end end end end function writeto(self, buffer, ...) local prefix = self.prefix local maxdepth = self.maxdepth local history = {} for i = 1, select("#", ...) do if i ~= 1 then buffer:write(", ") end self:writevalue(buffer, select(i, ...), history, prefix, maxdepth) end end local function add(self, ...) for i = 1, select("#", ...) do self[#self+1] = select(i, ...) end end function tostring(self, ...) local buffer = { write = add } self:writeto(buffer, ...) return table.concat(buffer) end function write(self, ...) self:writeto(self.output, ...) end function print(self, ...) local output = self.output local prefix = self.prefix local maxdepth = self.maxdepth local history = {} local value for i = 1, select("#", ...) do value = select(i, ...) if type(value) == "string" then output:write(value) else self:writevalue(output, value, history, prefix, maxdepth) end end output:write("\n") end function label(self, value) local meta = getmetatable(value) if meta then local custom = rawget(meta, "__tostring") if custom then rawset(meta, "__tostring", nil) local raw = luatostring(value) rawset(meta, "__tostring", custom) custom = luatostring(value) if raw == custom then return raw else return custom.." ("..raw..")" end end end return luatostring(value) end function package(self, name, pack) local labels = self.labels labels[pack] = name for field, member in pairs(pack) do local kind = type(member) if labels[member] == nil and (kind == "function" or kind == "userdata") and field:match("^[%a_]+[%w_]*$") then labels[member] = name.."."..field end end end if loaded then local luapacks = { coroutine = true, package = true, string = true, table = true, math = true, io = true, os = true, } -- create cache for global values labels = { __mode = "k" } setmetatable(labels, labels) -- cache names of global functions for name, func in pairs(_G) do if type(func) == "function" then labels[func] = name end end -- label loaded Lua library packages for name in pairs(luapacks) do local pack = loaded[name] if pack then package(_M, name, pack) end end -- label other loaded packages for name, pack in pairs(loaded) do if not luapacks[name] and type(pack) == "table" then package(_M, name, pack) end end end
mit
lichtl/darkstar
scripts/zones/Apollyon/mobs/Ice_Elemental.lua
119
2740
----------------------------------- -- Area: Apollyon SW -- NPC: elemental ----------------------------------- package.loaded["scripts/zones/Apollyon/TextIDs"] = nil; ----------------------------------- require("scripts/globals/limbus"); require("scripts/zones/Apollyon/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) end; ----------------------------------- -- onMobDespawn ----------------------------------- function onMobDespawn(mob) local mobID = mob:getID(); -- print(mobID); local mobX = mob:getXPos(); local mobY = mob:getYPos(); local mobZ = mob:getZPos(); local elementalday = GetServerVariable("[SW_Apollyon]ElementalTrigger") - 1; local correctelement=false; switch (elementalday): caseof { [0] = function (x) if (mobID==16932913 or mobID==16932921 or mobID==16932929) then correctelement=true; end end , [1] = function (x) if (mobID==16932912 or mobID==16932920 or mobID==16932928 ) then correctelement=true; end end , [2] = function (x) if (mobID==16932916 or mobID==16932924 or mobID==16932932 ) then correctelement=true; end end , [3] = function (x) if (mobID==16932910 or mobID==16932918 or mobID==16932926 ) then correctelement=true; end end , [4] = function (x) if (mobID==16932914 or mobID==16932922 or mobID==16932930 ) then correctelement=true; end end , [5] = function (x) if (mobID==16932917 or mobID==16932925 or mobID==16932933 ) then correctelement=true; end end , [6] = function (x) if (mobID==16932931 or mobID==16932915 or mobID==16932923 ) then correctelement=true; end end , [7] = function (x) if (mobID==16932911 or mobID==16932919 or mobID==16932927 ) then correctelement=true; end end , }; if (correctelement==true and IselementalDayAreDead()==true) then GetNPCByID(16932864+313):setPos(mobX,mobY,mobZ); GetNPCByID(16932864+313):setStatus(STATUS_NORMAL); end end;
gpl-3.0
lichtl/darkstar
scripts/zones/Apollyon/mobs/Fire_Elemental.lua
119
2740
----------------------------------- -- Area: Apollyon SW -- NPC: elemental ----------------------------------- package.loaded["scripts/zones/Apollyon/TextIDs"] = nil; ----------------------------------- require("scripts/globals/limbus"); require("scripts/zones/Apollyon/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) end; ----------------------------------- -- onMobDespawn ----------------------------------- function onMobDespawn(mob) local mobID = mob:getID(); -- print(mobID); local mobX = mob:getXPos(); local mobY = mob:getYPos(); local mobZ = mob:getZPos(); local elementalday = GetServerVariable("[SW_Apollyon]ElementalTrigger") - 1; local correctelement=false; switch (elementalday): caseof { [0] = function (x) if (mobID==16932913 or mobID==16932921 or mobID==16932929) then correctelement=true; end end , [1] = function (x) if (mobID==16932912 or mobID==16932920 or mobID==16932928 ) then correctelement=true; end end , [2] = function (x) if (mobID==16932916 or mobID==16932924 or mobID==16932932 ) then correctelement=true; end end , [3] = function (x) if (mobID==16932910 or mobID==16932918 or mobID==16932926 ) then correctelement=true; end end , [4] = function (x) if (mobID==16932914 or mobID==16932922 or mobID==16932930 ) then correctelement=true; end end , [5] = function (x) if (mobID==16932917 or mobID==16932925 or mobID==16932933 ) then correctelement=true; end end , [6] = function (x) if (mobID==16932931 or mobID==16932915 or mobID==16932923 ) then correctelement=true; end end , [7] = function (x) if (mobID==16932911 or mobID==16932919 or mobID==16932927 ) then correctelement=true; end end , }; if (correctelement==true and IselementalDayAreDead()==true) then GetNPCByID(16932864+313):setPos(mobX,mobY,mobZ); GetNPCByID(16932864+313):setStatus(STATUS_NORMAL); end end;
gpl-3.0
lichtl/darkstar
scripts/zones/Apollyon/mobs/Water_Elemental.lua
119
2740
----------------------------------- -- Area: Apollyon SW -- NPC: elemental ----------------------------------- package.loaded["scripts/zones/Apollyon/TextIDs"] = nil; ----------------------------------- require("scripts/globals/limbus"); require("scripts/zones/Apollyon/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) end; ----------------------------------- -- onMobDespawn ----------------------------------- function onMobDespawn(mob) local mobID = mob:getID(); -- print(mobID); local mobX = mob:getXPos(); local mobY = mob:getYPos(); local mobZ = mob:getZPos(); local elementalday = GetServerVariable("[SW_Apollyon]ElementalTrigger") - 1; local correctelement=false; switch (elementalday): caseof { [0] = function (x) if (mobID==16932913 or mobID==16932921 or mobID==16932929) then correctelement=true; end end , [1] = function (x) if (mobID==16932912 or mobID==16932920 or mobID==16932928 ) then correctelement=true; end end , [2] = function (x) if (mobID==16932916 or mobID==16932924 or mobID==16932932 ) then correctelement=true; end end , [3] = function (x) if (mobID==16932910 or mobID==16932918 or mobID==16932926 ) then correctelement=true; end end , [4] = function (x) if (mobID==16932914 or mobID==16932922 or mobID==16932930 ) then correctelement=true; end end , [5] = function (x) if (mobID==16932917 or mobID==16932925 or mobID==16932933 ) then correctelement=true; end end , [6] = function (x) if (mobID==16932931 or mobID==16932915 or mobID==16932923 ) then correctelement=true; end end , [7] = function (x) if (mobID==16932911 or mobID==16932919 or mobID==16932927 ) then correctelement=true; end end , }; if (correctelement==true and IselementalDayAreDead()==true) then GetNPCByID(16932864+313):setPos(mobX,mobY,mobZ); GetNPCByID(16932864+313):setStatus(STATUS_NORMAL); end end;
gpl-3.0
google-code/bitfighter
exe/scripts/datadumper.lua
1
7448
-- From http://lua-users.org/wiki/DataDumper --[[ DataDumper.lua Copyright (c) 2007 Olivetti-Engineering SA 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 dumplua_closure = [[ local closures = {} local function closure(t) closures[#closures+1] = t t[1] = assert(loadstring(t[1])) return t[1] end for _,t in pairs(closures) do for i = 2,#t do debug.setupvalue(t[1], i-1, t[i]) end end ]] local lua_reserved_keywords = { 'and', 'break', 'do', 'else', 'elseif', 'end', 'false', 'for', 'function', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat', 'return', 'then', 'true', 'until', 'while' } local function keys(t) local res = {} local oktypes = { stringstring = true, numbernumber = true } local function cmpfct(a,b) if oktypes[type(a)..type(b)] then return a < b else return type(a) < type(b) end end for k in pairs(t) do res[#res+1] = k end table.sort(res, cmpfct) return res end local c_functions = {} for _,lib in pairs{'_G', 'string', 'table', 'math', 'io', 'os', 'coroutine', 'package', 'debug'} do local t = _G[lib] or {} lib = lib .. "." if lib == "_G." then lib = "" end for k,v in pairs(t) do if type(v) == 'function' and not pcall(string.dump, v) then c_functions[v] = lib..k end end end function DataDumper(value, varname, fastmode, ident) local defined, dumplua = {} -- Local variables for speed optimization local string_format, type, string_dump, string_rep = string.format, type, string.dump, string.rep local tostring, pairs, table_concat = tostring, pairs, table.concat local keycache, strvalcache, out, closure_cnt = {}, {}, {}, 0 setmetatable(strvalcache, {__index = function(t,value) local res = string_format('%q', value) t[value] = res return res end}) local fcts = { string = function(value) return strvalcache[value] end, number = function(value) return value end, boolean = function(value) return tostring(value) end, ['nil'] = function(value) return 'nil' end, ['function'] = function(value) return string_format("loadstring(%q)", string_dump(value)) end, userdata = function() error("Cannot dump userdata") end, thread = function() error("Cannot dump threads") end, } local function test_defined(value, path) if defined[value] then if path:match("^getmetatable.*%)$") then out[#out+1] = string_format("s%s, %s)\n", path:sub(2,-2), defined[value]) else out[#out+1] = path .. " = " .. defined[value] .. "\n" end return true end defined[value] = path end local function make_key(t, key) local s if type(key) == 'string' and key:match('^[_%a][_%w]*$') then s = key .. "=" else s = "[" .. dumplua(key, 0) .. "]=" end t[key] = s return s end for _,k in ipairs(lua_reserved_keywords) do keycache[k] = '["'..k..'"] = ' end if fastmode then fcts.table = function (value) -- Table value local numidx = 1 out[#out+1] = "{" for key,val in pairs(value) do if key == numidx then numidx = numidx + 1 else out[#out+1] = keycache[key] end local str = dumplua(val) out[#out+1] = str.."," end if string.sub(out[#out], -1) == "," then out[#out] = string.sub(out[#out], 1, -2); end out[#out+1] = "}" return "" end else fcts.table = function (value, ident, path) if test_defined(value, path) then return "nil" end -- Table value local sep, str, numidx, totallen = " ", {}, 1, 0 local meta, metastr = (debug or getfenv()).getmetatable(value) if meta then ident = ident + 1 metastr = dumplua(meta, ident, "getmetatable("..path..")") totallen = totallen + #metastr + 16 end for _,key in pairs(keys(value)) do local val = value[key] local s = "" local subpath = path if key == numidx then subpath = subpath .. "[" .. numidx .. "]" numidx = numidx + 1 else s = keycache[key] if not s:match "^%[" then subpath = subpath .. "." end subpath = subpath .. s:gsub("%s*=%s*$","") end s = s .. dumplua(val, ident+1, subpath) str[#str+1] = s totallen = totallen + #s + 2 end if totallen > 80 then sep = "\n" .. string_rep(" ", ident+1) end str = "{"..sep..table_concat(str, ","..sep).." "..sep:sub(1,-3).."}" if meta then sep = sep:sub(1,-3) return "setmetatable("..sep..str..","..sep..metastr..sep:sub(1,-3)..")" end return str end fcts['function'] = function (value, ident, path) if test_defined(value, path) then return "nil" end if c_functions[value] then return c_functions[value] elseif debug == nil or debug.getupvalue(value, 1) == nil then return string_format("loadstring(%q)", string_dump(value)) end closure_cnt = closure_cnt + 1 local res = {string.dump(value)} for i = 1,math.huge do local name, v = debug.getupvalue(value,i) if name == nil then break end res[i+1] = v end return "closure " .. dumplua(res, ident, "closures["..closure_cnt.."]") end end function dumplua(value, ident, path) return fcts[type(value)](value, ident, path) end if varname == nil then varname = "return " elseif varname:match("^[%a_][%w_]*$") then varname = varname .. " = " end if fastmode then setmetatable(keycache, {__index = make_key }) out[1] = varname table.insert(out,dumplua(value, 0)) return table.concat(out) else setmetatable(keycache, {__index = make_key }) local items = {} for i=1,10 do items[i] = '' end items[3] = dumplua(value, ident or 0, "t") if closure_cnt > 0 then items[1], items[6] = dumplua_closure:match("(.*\n)\n(.*)") out[#out+1] = "" end if #out > 0 then items[2], items[4] = "local t = ", "\n" items[5] = table.concat(out) items[7] = varname .. "t" else items[2] = varname end return table.concat(items) end end
gpl-2.0
lichtl/darkstar
scripts/zones/Metalworks/npcs/Grohm.lua
14
3042
----------------------------------- -- Area: Metalworks -- NPC: Grohm -- Involved In Mission: Journey Abroad -- @pos -18 -11 -27 237 ----------------------------------- package.loaded["scripts/zones/Metalworks/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/zones/Metalworks/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getCurrentMission(SANDORIA) == JOURNEY_TO_BASTOK) then if (player:getVar("notReceivePickaxe") == 1) then player:startEvent(0x01a9); elseif (player:getVar("MissionStatus") == 4) then player:startEvent(0x01a7); elseif (player:getVar("MissionStatus") == 5 and player:hasItem(599) == false) then player:startEvent(0x01a8); else player:startEvent(0x01a6); end elseif (player:getCurrentMission(SANDORIA) == JOURNEY_TO_BASTOK2) then if (player:getVar("MissionStatus") == 9) then player:startEvent(0x01aa); else player:startEvent(0x01ab); end elseif (player:getCurrentMission(WINDURST) == THE_THREE_KINGDOMS_BASTOK) then if (player:getVar("notReceivePickaxe") == 1) then player:startEvent(0x01a9,1); elseif (player:getVar("MissionStatus") == 4) then player:startEvent(0x01a7,1); elseif (player:getVar("MissionStatus") == 5 and player:hasItem(599) == false) then player:startEvent(0x01a8,1); else player:startEvent(0x01a6); end elseif (player:getCurrentMission(WINDURST) == THE_THREE_KINGDOMS_BASTOK2) then if (player:getVar("MissionStatus") == 9) then player:startEvent(0x01aa,1); else player:startEvent(0x01ab,1); end else player:startEvent(0x01ab);--0x01a6 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 == 0x01a7 or csid == 0x01a9) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,605); -- Pickaxes player:setVar("notReceivePickaxe",1); else player:addItem(605,5); player:messageSpecial(ITEM_OBTAINED,605); -- Pickaxes player:setVar("MissionStatus",5); player:setVar("notReceivePickaxe",0); end elseif (csid == 0x01aa) then player:setVar("MissionStatus",10); end end;
gpl-3.0
lichtl/darkstar
scripts/zones/La_Vaule_[S]/mobs/Lobison.lua
17
1812
----------------------------------- -- Area: La Vaule (S) -- NPC: Lobison ----------------------------------- ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) mob:setLocalVar("transformTime", os.time()) end; ----------------------------------- -- onMobRoam Action ----------------------------------- function onMobRoam(mob) local changeTime = mob:getLocalVar("transformTime"); local roamChance = math.random(1,100); local roamMoonPhase = VanadielMoonPhase(); if (roamChance > 100-roamMoonPhase) then if (mob:AnimationSub() == 0 and os.time() - changeTime > 300) then mob:AnimationSub(1); mob:setLocalVar("transformTime", os.time()); elseif (mob:AnimationSub() == 1 and os.time() - changeTime > 300) then mob:AnimationSub(0); mob:setLocalVar("transformTime", os.time()); end end end; ----------------------------------- -- onMobEngaged -- Change forms every 60 seconds ----------------------------------- function onMobEngaged(mob,target) local changeTime = mob:getLocalVar("changeTime"); local chance = math.random(1,100); local moonPhase = VanadielMoonPhase(); if (chance > 100-moonPhase) then if (mob:AnimationSub() == 0 and mob:getBattleTime() - changeTime > 45) then mob:AnimationSub(1); mob:setLocalVar("changeTime", mob:getBattleTime()); elseif (mob:AnimationSub() == 1 and mob:getBattleTime() - changeTime > 45) then mob:AnimationSub(0); mob:setLocalVar("changeTime", mob:getBattleTime()); end end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) end;
gpl-3.0
dufferzafar/ShaR
v0.2.lua
1
2450
function Ravi_Encrypt(string, strength) tbl_RAVI = {"l","y","f","q","o","s","c","b","x","r","d","j","n","e","p","w","a","h","v","k","m","i","u","z","t","g"}; tbl_ALPHA = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"}; local string = String.Lower(string); --We will handle uppercase chars later local strlen = String.Length(string); --The length of string local encText = ""; --The encrypted text currently "Nothing" posInAlpha = 0; --The position of the character in the alphabets posInString = 0; --The position of the character in the clear text for i = 1, strlen do nChar = String.Mid(string, i, 1); --This helps to get the string character by character for j = 1, 26 do if nChar == tbl_ALPHA[j] then posInAlpha = j; --The actual position in alphabets break; end end posInString = i; --The actual position in the passed string if posInAlpha == 0 or posInString == 0 then --Both of them shouldn't be zer0 Dialog.Message("Error Occured", "An internal error occured in the algorithm.\n\nPress OK to abort.", MB_OK, MB_ICONSTOP, MB_DEFBUTTON1); break; end --[[ This is the main feature of this encryption algorithm This idea is of my friend RAVI KUMAR. So, basically he is the father of this algorithm although he knows nothing about algorithms. What we do here is add both the positions so as a result we get different encrypted text which varies with the strings. For e.g. The encrypted complement of 'a' in strings 'Shadab' and 'Ravi' will vary as in the first string 'a' occurs at 3rd & 5th position while in second string it occurs at 2nd position. ]]-- sumOfPos = posInAlpha + posInString; --[[ So that all the characters are handled. If this is ommited you won't be able to encrypt 'z' as sumOfPos will then be 27 and there is no value corresponding to it in tble_RAVI. ]]-- if sumOfPos > 26 then sumOfPos = sumOfPos - 26; end encText = encText..tbl_RAVI[sumOfPos]; end return encText; end --End Of FUNCTION --------------------------------------------------------------------------------------------- local clearText = Input.GetText("clearText") --Encrypt the text and Set it to the textbox Input.SetText("encText", Ravi_Encrypt(clearText, 0));
unlicense
lichtl/darkstar
scripts/zones/Abyssea-Attohwa/npcs/qm10.lua
9
1346
----------------------------------- -- Zone: Abyssea-Attohwa -- NPC: qm10 (???) -- Spawns Nightshade -- @pos ? ? ? 215 ----------------------------------- require("scripts/globals/status"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) --[[ if (trade:hasItemQty(3082,1) and trade:getItemCount() == 1) then -- Player has all the required items. if (GetMobAction(17658271) == ACTION_NONE) then -- Mob not already spawned from this SpawnMob(17658271):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe) player:tradeComplete(); end end ]] end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(1010, 3082); -- Inform player what items they need. end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
RunAwayDSP/darkstar
scripts/zones/Crawlers_Nest/npcs/qm8.lua
9
2229
----------------------------------- -- Area: Crawlers Nest -- NPC: ??? -- Involved in Quest: The Crimson Trial -- !pos 59 0.1 66 197 ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); local ID = require("scripts/zones/Crawlers_Nest/IDs"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) local cprog = player:getCharVar("theCrimsonTrial_prog"); local cdate = player:getCharVar("theCrimsonTrial_date"); local realday = tonumber(os.date("%j")); -- %M for next minute, %j for next day if (player:hasKeyItem(dsp.ki.CRAWLER_BLOOD) == true and player:hasKeyItem(dsp.ki.OLD_BOOTS) == true) then player:startEvent(4); elseif (cprog == 1 and cdate == realday) then player:messageSpecial(ID.text.EQUIPMENT_COMPLETELY_PURIFIED); elseif (cprog == 1 and cdate ~= realday) then player:startEvent(5); else player:messageSpecial(ID.text.SOMEONE_HAS_BEEN_DIGGING_HERE); end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) if (csid == 4 and option == 1) then player:delKeyItem(dsp.ki.CRAWLER_BLOOD); player:delKeyItem(dsp.ki.OLD_BOOTS); player:setCharVar("theCrimsonTrial_date", os.date("%j")); -- %M for next minute, %j for next day player:setCharVar("theCrimsonTrial_prog", 1); player:messageSpecial(ID.text.YOU_BURY_THE,dsp.ki.OLD_BOOTS,dsp.ki.CRAWLER_BLOOD); elseif (csid == 5) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ID.text.ITEM_CANNOT_BE_OBTAINED,14093); -- Warlock's Boots else player:addItem(14093); player:messageSpecial(ID.text.ITEM_OBTAINED, 14093); -- Warlock's Boots player:setCharVar("theCrimsonTrial_date",0); player:setCharVar("theCrimsonTrial_prog",0); player:setCharVar("needs_crawler_blood",2); -- Fixed being unable start next quest player:addFame(SANDORIA,40); player:completeQuest(SANDORIA,dsp.quest.id.sandoria.ENVELOPED_IN_DARKNESS); end end end;
gpl-3.0
sjznxd/lc-20130222
applications/luci-diag-devinfo/luasrc/model/cbi/luci_diag/netdiscover_devinfo_config.lua
80
1153
--[[ LuCI - Lua Configuration Interface (c) 2009 Daniel Dickinson Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.controller.luci_diag.devinfo_common") m = Map("luci_devinfo", translate("Network Device Scanning Configuration"), translate("Configure scanning for devices on specified networks. Decreasing \'Timeout\', \'Repeat Count\', and/or \'Sleep Between Requests\' may speed up scans, but also may fail to find some devices.")) s = m:section(SimpleSection, "", translate("Use Configuration")) b = s:option(DummyValue, "_scans", translate("Perform Scans (this can take a few minutes)")) b.value = "" b.titleref = luci.dispatcher.build_url("admin", "status", "netdiscover_devinfo") scannet = m:section(TypedSection, "netdiscover_scannet", translate("Scanning Configuration"), translate("Networks to scan for devices")) scannet.addremove = true scannet.anonymous = false luci.controller.luci_diag.devinfo_common.config_devinfo_scan(m, scannet) return m
apache-2.0
lichtl/darkstar
scripts/zones/Konschtat_Highlands/npcs/qm1.lua
14
1374
----------------------------------- -- Area: Konschtat Highlands -- NPC: qm1 (???) -- Continues Quests: Past Perfect -- @pos -201 16 80 108 ----------------------------------- package.loaded["scripts/zones/Konschtat_Highlands/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/zones/Konschtat_Highlands/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local PastPerfect = player:getQuestStatus(BASTOK,PAST_PERFECT); if (PastPerfect == QUEST_ACCEPTED) then player:addKeyItem(0x6d); player:messageSpecial(KEYITEM_OBTAINED,0x6d); -- Tattered Mission Orders else player:messageSpecial(FIND_NOTHING); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID2: %u",csid); -- printf("RESULT2: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
lichtl/darkstar
scripts/zones/Gusgen_Mines/npcs/Clay.lua
14
1229
----------------------------------- -- Area: Gusgen Mines -- NPC: Clay -- Involved in Quest: A Potter's Preference -- @pos 117 -21 432 196 ----------------------------------- package.loaded["scripts/zones/Gusgen_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/zones/Gusgen_Mines/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:addItem(569,1); --569 - dish_of_gusgen_clay player:messageSpecial(ITEM_OBTAINED,569); -- dish_of_gusgen_clay end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID2: %u",csid); -- printf("RESULT2: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
lichtl/darkstar
scripts/globals/items/magma_steak_+1.lua
18
1597
----------------------------------------- -- ID: 6072 -- Item: Magma Steak +1 -- Food Effect: 240 Min, All Races ----------------------------------------- -- Strength +9 -- Attack +24% Cap 185 -- Ranged Attack +24% Cap 185 -- Vermin Killer +6 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) 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,6072); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR, 9); target:addMod(MOD_FOOD_ATTP, 24); target:addMod(MOD_FOOD_ATT_CAP, 185); target:addMod(MOD_FOOD_RATTP, 24); target:addMod(MOD_FOOD_RATT_CAP, 185); target:addMod(MOD_VERMIN_KILLER, 6); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_STR, 9); target:delMod(MOD_FOOD_ATTP, 24); target:delMod(MOD_FOOD_ATT_CAP, 185); target:delMod(MOD_FOOD_RATTP, 24); target:delMod(MOD_FOOD_RATT_CAP, 185); target:delMod(MOD_VERMIN_KILLER, 6); end;
gpl-3.0
lichtl/darkstar
scripts/zones/North_Gustaberg/npcs/Cavernous_Maw.lua
29
1442
----------------------------------- -- Area: North Gustaberg -- NPC: Cavernous Maw -- @pos 466 0 479 106 -- Teleports Players to North Gustaberg [S] ----------------------------------- package.loaded["scripts/zones/North_Gustaberg/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/teleports"); require("scripts/globals/campaign"); require("scripts/zones/North_Gustaberg/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (ENABLE_WOTG == 1 and player:hasKeyItem(PURE_WHITE_FEATHER) and hasMawActivated(player,7)) then player:startEvent(0x0387); else player:messageSpecial(NOTHING_HAPPENS); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID:",csid); -- printf("RESULT:",option); if (csid == 0x0387 and option == 1) then toMaw(player,11); end end;
gpl-3.0
lichtl/darkstar
scripts/zones/Abyssea-Tahrongi/npcs/qm2.lua
14
1343
----------------------------------- -- Zone: Abyssea-Tahrongi -- NPC: qm2 (???) -- Spawns Vetehinen -- @pos ? ? ? 45 ----------------------------------- require("scripts/globals/status"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) --[[ if (trade:hasItemQty(2916,1) and trade:getItemCount() == 1) then -- Player has all the required items. if (GetMobAction(16961918) == ACTION_NONE) then -- Mob not already spawned from this SpawnMob(16961918):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe) player:tradeComplete(); end end ]] end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(1010, 2916); -- Inform payer what items they need. end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
lichtl/darkstar
scripts/globals/items/hellsteak.lua
18
1722
----------------------------------------- -- ID: 5609 -- Item: hellsteak -- Food Effect: 180Min, All Races ----------------------------------------- -- Health 20 -- Strength 6 -- Intelligence -2 -- Health Regen While Healing 2 -- Attack % 19 -- Ranged ATT % 19 -- Dragon Killer 5 -- Demon Killer 5 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,5609); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 20); target:addMod(MOD_STR, 6); target:addMod(MOD_INT, -2); target:addMod(MOD_HPHEAL, 2); target:addMod(MOD_ATTP, 19); target:addMod(MOD_RATTP, 19); target:addMod(MOD_DRAGON_KILLER, 5); target:addMod(MOD_DEMON_KILLER, 5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 20); target:delMod(MOD_STR, 6); target:delMod(MOD_INT, -2); target:delMod(MOD_HPHEAL, 2); target:delMod(MOD_ATTP, 19); target:delMod(MOD_RATTP, 19); target:delMod(MOD_DRAGON_KILLER, 5); target:delMod(MOD_DEMON_KILLER, 5); end;
gpl-3.0
lichtl/darkstar
scripts/zones/Windurst_Walls/npcs/Naih_Arihmepp.lua
14
1471
----------------------------------- -- Area: Windurst Walls -- NPC: Naih Arihmepp -- Type: Standard NPC -- @pos -64.578 -13.465 202.147 239 ----------------------------------- package.loaded["scripts/zones/Windurst_Walls/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/zones/Windurst_Walls/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local WildcatWindurst = player:getVar("WildcatWindurst"); if (player:getQuestStatus(WINDURST,LURE_OF_THE_WILDCAT_WINDURST) == QUEST_ACCEPTED and player:getMaskBit(WildcatWindurst,9) == false) then player:startEvent(0x01f4); else player:startEvent(0x0146); 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 == 0x01f4) then player:setMaskBit(player:getVar("WildcatWindurst"),"WildcatWindurst",9,true); end end;
gpl-3.0
sjznxd/lc-20130222
applications/luci-radvd/luasrc/model/cbi/radvd/interface.lua
78
7996
--[[ LuCI - Lua Configuration Interface Copyright 2010 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local sid = arg[1] local utl = require "luci.util" m = Map("radvd", translatef("Radvd - Interface %q", "?"), translate("Radvd is a router advertisement daemon for IPv6. " .. "It listens to router solicitations and sends router advertisements " .. "as described in RFC 4861.")) m.redirect = luci.dispatcher.build_url("admin/network/radvd") if m.uci:get("radvd", sid) ~= "interface" then luci.http.redirect(m.redirect) return end m.uci:foreach("radvd", "interface", function(s) if s['.name'] == sid and s.interface then m.title = translatef("Radvd - Interface %q", s.interface) return false end end) s = m:section(NamedSection, sid, "interface", translate("Interface Configuration")) s.addremove = false s:tab("general", translate("General")) s:tab("timing", translate("Timing")) s:tab("mobile", translate("Mobile IPv6")) -- -- General -- o = s:taboption("general", Flag, "ignore", translate("Enable")) o.rmempty = false function o.cfgvalue(...) local v = Flag.cfgvalue(...) return v == "1" and "0" or "1" end function o.write(self, section, value) Flag.write(self, section, value == "1" and "0" or "1") end o = s:taboption("general", Value, "interface", translate("Interface"), translate("Specifies the logical interface name this section belongs to")) o.template = "cbi/network_netlist" o.nocreate = true o.optional = false function o.formvalue(...) return Value.formvalue(...) or "-" end function o.validate(self, value) if value == "-" then return nil, translate("Interface required") end return value end function o.write(self, section, value) m.uci:set("radvd", section, "ignore", 0) m.uci:set("radvd", section, "interface", value) end o = s:taboption("general", DynamicList, "client", translate("Clients"), translate("Restrict communication to specified clients, leave empty to use multicast")) o.rmempty = true o.datatype = "ip6addr" o.placeholder = "any" function o.cfgvalue(...) local v = Value.cfgvalue(...) local l = { } for v in utl.imatch(v) do l[#l+1] = v end return l end o = s:taboption("general", Flag, "AdvSendAdvert", translate("Enable advertisements"), translate("Enables router advertisements and solicitations")) o.rmempty = false function o.write(self, section, value) if value == "1" then m.uci:set("radvd", section, "ignore", 0) m.uci:set("radvd", section, "IgnoreIfMissing", 1) end m.uci:set("radvd", section, "AdvSendAdvert", value) end o = s:taboption("general", Flag, "UnicastOnly", translate("Unicast only"), translate("Indicates that the underlying link is not broadcast capable, prevents unsolicited advertisements from being sent")) o:depends("AdvSendAdvert", "1") o = s:taboption("general", Flag, "AdvManagedFlag", translate("Managed flag"), translate("Enables the additional stateful administered autoconfiguration protocol (RFC2462)")) o:depends("AdvSendAdvert", "1") o = s:taboption("general", Flag, "AdvOtherConfigFlag", translate("Configuration flag"), translate("Enables the autoconfiguration of additional, non address information (RFC2462)")) o:depends("AdvSendAdvert", "1") o = s:taboption("general", Flag, "AdvSourceLLAddress", translate("Source link-layer address"), translate("Includes the link-layer address of the outgoing interface in the RA")) o.rmempty = false o.default = "1" o:depends("AdvSendAdvert", "1") o = s:taboption("general", Value, "AdvLinkMTU", translate("Link MTU"), translate("Advertises the given link MTU in the RA if specified. 0 disables MTU advertisements")) o.datatype = "uinteger" o.placeholder = 0 o:depends("AdvSendAdvert", "1") o = s:taboption("general", Value, "AdvCurHopLimit", translate("Current hop limit"), translate("Advertises the default Hop Count value for outgoing unicast packets in the RA. 0 disables hopcount advertisements")) o.datatype = "uinteger" o.optional = false o.placeholder = 64 o:depends("AdvSendAdvert", "1") o = s:taboption("general", ListValue, "AdvDefaultPreference", translate("Default preference"), translate("Advertises the default router preference")) o.optional = false o.default = "medium" o:value("low", translate("low")) o:value("medium", translate("medium")) o:value("high", translate("high")) o:depends("AdvSendAdvert", "1") -- -- Timing -- o = s:taboption("timing", Value, "MinRtrAdvInterval", translate("Minimum advertisement interval"), translate("The minimum time allowed between sending unsolicited multicast router advertisements from the interface, in seconds")) o.datatype = "uinteger" o.optional = false o.placeholder = 198 o:depends("AdvSendAdvert", "1") o = s:taboption("timing", Value, "MaxRtrAdvInterval", translate("Maximum advertisement interval"), translate("The maximum time allowed between sending unsolicited multicast router advertisements from the interface, in seconds")) o.datatype = "uinteger" o.optional = false o.placeholder = 600 o:depends("AdvSendAdvert", "1") o = s:taboption("timing", Value, "MinDelayBetweenRAs", translate("Minimum advertisement delay"), translate("The minimum time allowed between sending multicast router advertisements from the interface, in seconds")) o.datatype = "uinteger" o.optional = false o.placeholder = 3 o:depends("AdvSendAdvert", "1") o = s:taboption("timing", Value, "AdvReachableTime", translate("Reachable time"), translate("Advertises assumed reachability time in milliseconds of neighbours in the RA if specified. 0 disables reachability advertisements")) o.datatype = "uinteger" o.optional = false o.placeholder = 0 o:depends("AdvSendAdvert", "1") o = s:taboption("timing", Value, "AdvRetransTimer", translate("Retransmit timer"), translate("Advertises wait time in milliseconds between Neighbor Solicitation messages in the RA if specified. 0 disables retransmit advertisements")) o.datatype = "uinteger" o.optional = false o.placeholder = 0 o:depends("AdvSendAdvert", "1") o = s:taboption("timing", Value, "AdvDefaultLifetime", translate("Default lifetime"), translate("Advertises the lifetime of the default router in seconds. 0 indicates that the node is no default router")) o.datatype = "uinteger" o.optional = false o.placeholder = 1800 o:depends("AdvSendAdvert", "1") -- -- Mobile -- o = s:taboption("mobile", Flag, "AdvHomeAgentFlag", translate("Advertise Home Agent flag"), translate("Advertises Mobile IPv6 Home Agent capability (RFC3775)")) o:depends("AdvSendAdvert", "1") o = s:taboption("mobile", Flag, "AdvIntervalOpt", translate("Mobile IPv6 interval option"), translate("Include Mobile IPv6 Advertisement Interval option to RA")) o:depends({AdvHomeAgentFlag = "1", AdvSendAdvert = "1"}) o = s:taboption("mobile", Flag, "AdvHomeAgentInfo", translate("Home Agent information"), translate("Include Home Agent Information in the RA")) o:depends({AdvHomeAgentFlag = "1", AdvSendAdvert = "1"}) o = s:taboption("mobile", Flag, "AdvMobRtrSupportFlag", translate("Mobile IPv6 router registration"), translate("Advertises Mobile Router registration capability (NEMO Basic)")) o:depends({AdvHomeAgentInfo = "1", AdvSendAdvert = "1"}) o = s:taboption("mobile", Value, "HomeAgentLifetime", translate("Home Agent lifetime"), translate("Advertises the time in seconds the router is offering Mobile IPv6 Home Agent services")) o.datatype = "uinteger" o.optional = false o.placeholder = 1800 o:depends({AdvHomeAgentInfo = "1", AdvSendAdvert = "1"}) o = s:taboption("mobile", Value, "HomeAgentPreference", translate("Home Agent preference"), translate("The preference for the Home Agent sending this RA")) o.datatype = "uinteger" o.optional = false o.placeholder = 0 o:depends({AdvHomeAgentInfo = "1", AdvSendAdvert = "1"}) return m
apache-2.0
lichtl/darkstar
scripts/zones/Giddeus/npcs/Harvesting_Point.lua
17
1079
----------------------------------- -- Area: Giddeus -- NPC: Harvesting Point ----------------------------------- package.loaded["scripts/zones/Giddeus/TextIDs"] = nil; ------------------------------------- require("scripts/globals/harvesting"); require("scripts/zones/Giddeus/TextIDs"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) startHarvesting(player,player:getZoneID(),npc,trade,0x0046); end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) player:messageSpecial(HARVESTING_IS_POSSIBLE_HERE,1020); 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
NiLuJe/koreader
frontend/luasettings.lua
4
8151
--[[-- This module handles generic settings as well as KOReader's global settings system. ]] local dump = require("dump") local ffiutil = require("ffi/util") local lfs = require("libs/libkoreader-lfs") local logger = require("logger") local LuaSettings = {} function LuaSettings:extend(o) o = o or {} setmetatable(o, self) self.__index = self return o end -- NOTE: Instances are created via open, so we do *NOT* implement a new method, to avoid confusion. --- Opens a settings file. function LuaSettings:open(file_path) local new = LuaSettings:extend{ file = file_path, } local ok, stored -- File being absent and returning an empty table is a use case, -- so logger.warn() only if there was an existing file local existing = lfs.attributes(new.file, "mode") == "file" ok, stored = pcall(dofile, new.file) if ok and stored then new.data = stored else if existing then logger.warn("LuaSettings: Failed reading", new.file, "(probably corrupted).") end -- Fallback to .old if it exists ok, stored = pcall(dofile, new.file..".old") if ok and stored then if existing then logger.warn("LuaSettings: read from backup file", new.file..".old") end new.data = stored else if existing then logger.warn("LuaSettings: no usable backup file for", new.file, "to read from") end new.data = {} end end return new end function LuaSettings:wrap(data) return self:extend{ data = type(data) == "table" and data or {}, } end --[[--Reads child settings. @usage Settings:saveSetting("key", { a = "b", c = true, d = false, }) local child = Settings:child("key") child:readSetting("a") -- result "b" ]] function LuaSettings:child(key) return self:wrap(self:readSetting(key)) end --[[-- Reads a setting, optionally initializing it to a default. If default is provided, and the key doesn't exist yet, it is initialized to default first. This ensures both that the defaults are actually set if necessary, and that the returned reference actually belongs to the LuaSettings object straight away, without requiring further interaction (e.g., saveSetting) from the caller. This is mainly useful if the data type you want to retrieve/store is assigned/returned/passed by reference (e.g., a table), and you never actually break that reference by assigning another one to the same variable, (by e.g., assigning it a new object). c.f., <https://www.lua.org/manual/5.1/manual.html#2.2>. @param key The setting's key @param default Initialization data (Optional) ]] function LuaSettings:readSetting(key, default) -- No initialization data: legacy behavior if not default then return self.data[key] end if not self:has(key) then self.data[key] = default end return self.data[key] end --- Saves a setting. function LuaSettings:saveSetting(key, value) self.data[key] = value return self end --- Deletes a setting. function LuaSettings:delSetting(key) self.data[key] = nil return self end --- Checks if setting exists. function LuaSettings:has(key) return self.data[key] ~= nil end --- Checks if setting does not exist. function LuaSettings:hasNot(key) return self.data[key] == nil end --- Checks if setting is `true` (boolean). function LuaSettings:isTrue(key) return self.data[key] == true end --- Checks if setting is `false` (boolean). function LuaSettings:isFalse(key) return self.data[key] == false end --- Checks if setting is `nil` or `true`. function LuaSettings:nilOrTrue(key) return self:hasNot(key) or self:isTrue(key) end --- Checks if setting is `nil` or `false`. function LuaSettings:nilOrFalse(key) return self:hasNot(key) or self:isFalse(key) end --- Flips `nil` or `true` to `false`, and `false` to `nil`. --- e.g., a setting that defaults to true. function LuaSettings:flipNilOrTrue(key) if self:nilOrTrue(key) then self:saveSetting(key, false) else self:delSetting(key) end return self end --- Flips `nil` or `false` to `true`, and `true` to `nil`. --- e.g., a setting that defaults to false. function LuaSettings:flipNilOrFalse(key) if self:nilOrFalse(key) then self:saveSetting(key, true) else self:delSetting(key) end return self end --- Flips a setting between `true` and `nil`. function LuaSettings:flipTrue(key) if self:isTrue(key) then self:delSetting(key) else self:saveSetting(key, true) end return self end --- Flips a setting between `false` and `nil`. function LuaSettings:flipFalse(key) if self:isFalse(key) then self:delSetting(key) else self:saveSetting(key, false) end return self end -- Unconditionally makes a boolean setting `true`. function LuaSettings:makeTrue(key) self:saveSetting(key, true) return self end -- Unconditionally makes a boolean setting `false`. function LuaSettings:makeFalse(key) self:saveSetting(key, false) return self end --- Toggles a boolean setting function LuaSettings:toggle(key) if self:nilOrFalse(key) then self:saveSetting(key, true) else self:saveSetting(key, false) end return self end -- Initializes settings per extension with default values function LuaSettings:initializeExtSettings(key, defaults, force_init) local curr = self:readSetting(key) if not curr or force_init then self:saveSetting(key, defaults) return true end return false end -- Returns saved setting for given extension function LuaSettings:getSettingForExt(key, ext) local saved_settings = self:readSetting(key) or {} return saved_settings[ext] end -- Sets setting for given extension function LuaSettings:saveSettingForExt(key, value, ext) local saved_settings = self:readSetting(key) or {} saved_settings[ext] = value self:saveSetting(key, saved_settings) end --- Adds item to table. function LuaSettings:addTableItem(key, value) local settings_table = self:has(key) and self:readSetting(key) or {} table.insert(settings_table, value) self:saveSetting(key, settings_table) return self end --- Removes index from table. function LuaSettings:removeTableItem(key, index) local settings_table = self:has(key) and self:readSetting(key) or {} table.remove(settings_table, index) self:saveSetting(key, settings_table) return self end --- Replaces existing settings with table. function LuaSettings:reset(table) self.data = table return self end --- Writes settings to disk. function LuaSettings:flush() if not self.file then return end local directory_updated = false if lfs.attributes(self.file, "mode") == "file" then -- As an additional safety measure (to the ffiutil.fsync* calls used below), -- we only backup the file to .old when it has not been modified in the last 60 seconds. -- This should ensure in the case the fsync calls are not supported -- that the OS may have itself sync'ed that file content in the meantime. local mtime = lfs.attributes(self.file, "modification") if mtime < os.time() - 60 then os.rename(self.file, self.file .. ".old") directory_updated = true -- fsync directory content too below end end local f_out = io.open(self.file, "w") if f_out ~= nil then f_out:write("-- we can read Lua syntax here!\nreturn ") f_out:write(dump(self.data, nil, true)) f_out:write("\n") ffiutil.fsyncOpenedFile(f_out) -- force flush to the storage device f_out:close() end if directory_updated then -- Ensure the file renaming is flushed to storage device ffiutil.fsyncDirectory(self.file) end return self end --- Closes settings file. function LuaSettings:close() self:flush() end --- Purges settings file. function LuaSettings:purge() if self.file then os.remove(self.file) end return self end return LuaSettings
agpl-3.0
RunAwayDSP/darkstar
scripts/zones/RuAun_Gardens/Zone.lua
9
2491
----------------------------------- -- -- Zone: RuAun_Gardens (130) -- ----------------------------------- local ID = require("scripts/zones/RuAun_Gardens/IDs"); require("scripts/globals/missions"); require("scripts/globals/conquest"); require("scripts/globals/treasure") require("scripts/globals/status"); require("scripts/globals/titles"); ----------------------------------- function onInitialize(zone) for k, v in pairs(ID.npc.PORTALS) do zone:registerRegion(k,unpack(v["coords"])); end dsp.treasure.initZone(zone) dsp.conq.setRegionalConquestOverseers(zone:getRegionID()) end; function onConquestUpdate(zone, updatetype) dsp.conq.onConquestUpdate(zone, updatetype) end; function onZoneIn(player,prevZone) local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos(333.017,-44.896,-458.35,164); end if (player:getCurrentMission(ZILART) == dsp.mission.id.zilart.THE_GATE_OF_THE_GODS and player:getCharVar("ZilartStatus") == 1) then cs = 51; end return cs; end; function onRegionEnter(player,region) local p = ID.npc.PORTALS[region:GetRegionID()]; if (p["green"] ~= nil) then -- green portal if (player:getCharVar("skyShortcut") == 1) then player:startEvent(42); else title = player:getTitle(); if (title == dsp.title.WARRIOR_OF_THE_CRYSTAL) then player:startEvent(41,title); else player:startEvent(43,title); end end elseif (p["portal"] ~= nil) then -- blue portal if (GetNPCByID(p["portal"]):getAnimation() == dsp.anim.OPEN_DOOR) then player:startEvent(p["event"]); end elseif (type(p["event"]) == "table") then -- portal with random destination local events = p["event"]; player:startEvent(events[math.random(#events)]); else -- portal with static destination player:startEvent(p["event"]); end end; function onRegionLeave(player,region) end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) if (csid == 41 and option ~= 0) then player:setCharVar("skyShortcut",1); elseif (csid == 51) then player:setCharVar("ZilartStatus",0); player:completeMission(ZILART,dsp.mission.id.zilart.THE_GATE_OF_THE_GODS); player:addMission(ZILART,dsp.mission.id.zilart.ARK_ANGELS); end end;
gpl-3.0
sdkbox/sdkbox-facebook-sample-v2
samples/Lua/TestLua/Resources/luaScript/EffectsAdvancedTest/EffectsAdvancedTest.lua
8
8894
local kTagTextLayer = 1 local kTagSprite1 = 1 local kTagSprite2 = 2 local kTagBackground = 1 local kTagLabel = 2 local originCreateLayer = createTestLayer local function createTestLayer(title, subtitle) local ret = originCreateLayer(title, subtitle) local bg = CCSprite:create("Images/background3.png") ret:addChild(bg, 0, kTagBackground) bg:setPosition( VisibleRect:center() ) local grossini = CCSprite:create("Images/grossinis_sister2.png") bg:addChild(grossini, 1, kTagSprite1) grossini:setPosition( ccp(VisibleRect:left().x+VisibleRect:getVisibleRect().size.width/3.0, VisibleRect:bottom().y+ 200) ) local sc = CCScaleBy:create(2, 5) local sc_back = sc:reverse() local arr = CCArray:create() arr:addObject(sc) arr:addObject(sc_back) grossini:runAction( CCRepeatForever:create(CCSequence:create(arr))) local tamara = CCSprite:create("Images/grossinis_sister1.png") bg:addChild(tamara, 1, kTagSprite2) tamara:setPosition( ccp(VisibleRect:left().x+2*VisibleRect:getVisibleRect().size.width/3.0,VisibleRect:bottom().y+200) ) local sc2 = CCScaleBy:create(2, 5) local sc2_back = sc2:reverse() arr = CCArray:create() arr:addObject(sc2) arr:addObject(sc2_back) tamara:runAction( CCRepeatForever:create(CCSequence:create(arr))) return ret end -------------------------------------------------------------------- -- -- Effect1 -- -------------------------------------------------------------------- local function Effect1() local ret = createTestLayer("Lens + Waves3d and OrbitCamera") local target = ret:getChildByTag(kTagBackground) -- To reuse a grid the grid size and the grid type must be the same. -- in this case: -- Lens3D is Grid3D and it's size is (15,10) -- Waves3D is Grid3D and it's size is (15,10) local size = CCDirector:sharedDirector():getWinSize() local lens = CCLens3D:create(0.0, CCSizeMake(15,10), ccp(size.width/2,size.height/2), 240) local waves = CCWaves3D:create(10, CCSizeMake(15,10), 18, 15) local reuse = CCReuseGrid:create(1) local delay = CCDelayTime:create(8) local orbit = CCOrbitCamera:create(5, 1, 2, 0, 180, 0, -90) local orbit_back = orbit:reverse() local arr = CCArray:create() arr:addObject(orbit) arr:addObject(orbit_back) target:runAction( CCRepeatForever:create( CCSequence:create(arr))) arr = CCArray:create() arr:addObject(lens) arr:addObject(delay) arr:addObject(reuse) arr:addObject(waves) target:runAction( CCSequence:create(arr)) return ret end -------------------------------------------------------------------- -- -- Effect2 -- -------------------------------------------------------------------- local function Effect2() local ret = createTestLayer("ShakyTiles + ShuffleTiles + TurnOffTiles") local target = ret:getChildByTag(kTagBackground) -- To reuse a grid the grid size and the grid type must be the same. -- in this case: -- ShakyTiles is TiledGrid3D and it's size is (15,10) -- Shuffletiles is TiledGrid3D and it's size is (15,10) -- TurnOfftiles is TiledGrid3D and it's size is (15,10) local shaky = CCShakyTiles3D:create(5, CCSizeMake(15,10), 4, false) local shuffle = CCShuffleTiles:create(0, CCSizeMake(15,10), 3) local turnoff = CCTurnOffTiles:create(0, CCSizeMake(15,10), 3) local turnon = turnoff:reverse() -- reuse 2 times: -- 1 for shuffle -- 2 for turn off -- turnon tiles will use a new grid local reuse = CCReuseGrid:create(2) local delay = CCDelayTime:create(1) local arr = CCArray:create() arr:addObject(shaky) arr:addObject(delay) arr:addObject(reuse) arr:addObject(shuffle) arr:addObject(tolua.cast(delay:copy():autorelease(), "CCAction")) arr:addObject(turnoff) arr:addObject(turnon) target:runAction(CCSequence:create(arr)) return ret end -------------------------------------------------------------------- -- -- Effect3 -- -------------------------------------------------------------------- local function Effect3() local ret = createTestLayer("Effects on 2 sprites") local bg = ret:getChildByTag(kTagBackground) local target1 = bg:getChildByTag(kTagSprite1) local target2 = bg:getChildByTag(kTagSprite2) local waves = CCWaves:create(5, CCSizeMake(15,10), 5, 20, true, false) local shaky = CCShaky3D:create(5, CCSizeMake(15,10), 4, false) target1:runAction( CCRepeatForever:create( waves ) ) target2:runAction( CCRepeatForever:create( shaky ) ) -- moving background. Testing issue #244 local move = CCMoveBy:create(3, ccp(200,0) ) local arr = CCArray:create() arr:addObject(move) arr:addObject(move:reverse()) bg:runAction(CCRepeatForever:create( CCSequence:create(arr))) return ret end -------------------------------------------------------------------- -- -- Effect4 -- -------------------------------------------------------------------- -- class Lens3DTarget : public CCNode -- public: -- virtual void setPosition(const CCPoint& var) -- m_pLens3D:setPosition(var) -- end -- virtual const CCPoint& getPosition() -- return m_pLens3D:getPosition() -- end -- static Lens3DTarget* create(CCLens3D* pAction) -- Lens3DTarget* pRet = new Lens3DTarget() -- pRet:m_pLens3D = pAction -- pRet:autorelease() -- return pRet -- end -- private: -- Lens3DTarget() -- : m_pLens3D(NULL) -- {} -- CCLens3D* m_pLens3D -- end local function Effect4() local ret = createTestLayer("Jumpy Lens3D") local lens = CCLens3D:create(10, CCSizeMake(32,24), ccp(100,180), 150) local move = CCJumpBy:create(5, ccp(380,0), 100, 4) local move_back = move:reverse() local arr = CCArray:create() arr:addObject(move) arr:addObject(move_back) local seq = CCSequence:create( arr) -- /* In cocos2d-iphone, the type of action's target is 'id', so it supports using the instance of 'CCLens3D' as its target. -- While in cocos2d-x, the target of action only supports CCNode or its subclass, -- so we make an encapsulation for CCLens3D to achieve that. -- */ local director = CCDirector:sharedDirector() -- local pTarget = Lens3DTarget:create(lens) -- -- Please make sure the target been added to its parent. -- ret:addChild(pTarget) -- director:getActionManager():addAction(seq, pTarget, false) ret:runAction( lens ) return ret end -------------------------------------------------------------------- -- -- Effect5 -- -------------------------------------------------------------------- local function Effect5() local ret = createTestLayer("Test Stop-Copy-Restar") local effect = CCLiquid:create(2, CCSizeMake(32,24), 1, 20) local arr = CCArray:create() arr:addObject(effect) arr:addObject(CCDelayTime:create(2)) arr:addObject(CCStopGrid:create()) local stopEffect = CCSequence:create(arr) local bg = ret:getChildByTag(kTagBackground) bg:runAction(stopEffect) local function onNodeEvent(event) if event == "exit" then CCDirector:sharedDirector():setProjection(kCCDirectorProjection3D) end end ret:registerScriptHandler(onNodeEvent) return ret end -------------------------------------------------------------------- -- -- Issue631 -- -------------------------------------------------------------------- local function Issue631() local ret = createTestLayer("Testing Opacity", "Effect image should be 100% opaque. Testing issue #631") local arr = CCArray:create() arr:addObject(CCDelayTime:create(2.0)) arr:addObject(CCShaky3D:create(5.0, CCSizeMake(5, 5), 16, false)) local effect = CCSequence:create(arr) -- cleanup local bg = ret:getChildByTag(kTagBackground) ret:removeChild(bg, true) -- background local layer = CCLayerColor:create( ccc4(255,0,0,255) ) ret:addChild(layer, -10) local sprite = CCSprite:create("Images/grossini.png") sprite:setPosition( ccp(50,80) ) layer:addChild(sprite, 10) -- foreground local layer2 = CCLayerColor:create(ccc4( 0, 255,0,255 ) ) local fog = CCSprite:create("Images/Fog.png") local bf = ccBlendFunc() bf.src = GL_SRC_ALPHA bf.dst = GL_ONE_MINUS_SRC_ALPHA fog:setBlendFunc(bf) layer2:addChild(fog, 1) ret:addChild(layer2, 1) layer2:runAction( CCRepeatForever:create(effect) ) return ret end function EffectAdvancedTestMain() cclog("EffectAdvancedTestMain") Helper.index = 1 local scene = CCScene:create() Helper.createFunctionTable = { Effect3, Effect2, Effect1, Effect4, Effect5, Issue631 } scene:addChild(Effect3()) scene:addChild(CreateBackMenuItem()) return scene end
mit
conupefox/openwrt-d2o
package/my_package/mwan/mwan3-luci/files/usr/lib/lua/luci/model/cbi/mwan3/mwan3_interface.lua
9
9177
-- ------ extra functions ------ -- function iface_check() -- find issues with too many interfaces, reliability and metric uci.cursor():foreach("mwan3", "interface", function (section) local ifname = section[".name"] ifnum = ifnum+1 -- count number of mwan3 interfaces configured -- create list of metrics for none and duplicate checking local metlkp = ut.trim(sys.exec("uci get -p /var/state network." .. ifname .. ".metric")) if metlkp == "" then err_found = 1 err_nomet_list = err_nomet_list .. ifname .. " " else metric_list = metric_list .. ifname .. " " .. metlkp .. "\n" end -- check if any interfaces have a higher reliability requirement than tracking IPs configured local tipnum = tonumber(ut.trim(sys.exec("echo $(uci get -p /var/state mwan3." .. ifname .. ".track_ip) | wc -w"))) if tipnum > 0 then local relnum = tonumber(ut.trim(sys.exec("uci get -p /var/state mwan3." .. ifname .. ".reliability"))) if relnum and relnum > tipnum then err_found = 1 err_rel_list = err_rel_list .. ifname .. " " end end -- check if any interfaces are not properly configured in /etc/config/network or have no default route in main routing table if ut.trim(sys.exec("uci get -p /var/state network." .. ifname)) == "interface" then local ifdev = ut.trim(sys.exec("uci get -p /var/state network." .. ifname .. ".ifname")) if ifdev == "uci: Entry not found" or ifdev == "" then err_found = 1 err_netcfg_list = err_netcfg_list .. ifname .. " " err_route_list = err_route_list .. ifname .. " " else local rtcheck = ut.trim(sys.exec("route -n | awk -F' ' '{ if ($8 == \"" .. ifdev .. "\" && $1 == \"0.0.0.0\") print $1 }'")) if rtcheck == "" then err_found = 1 err_route_list = err_route_list .. ifname .. " " end end else err_found = 1 err_netcfg_list = err_netcfg_list .. ifname .. " " err_route_list = err_route_list .. ifname .. " " end end ) -- check if any interfaces have duplicate metrics local metric_dupnums = sys.exec("echo '" .. metric_list .. "' | awk -F' ' '{ print $2 }' | uniq -d") if metric_dupnums ~= "" then err_found = 1 local metric_dupes = "" for line in metric_dupnums:gmatch("[^\r\n]+") do metric_dupes = sys.exec("echo '" .. metric_list .. "' | grep '" .. line .. "' | awk -F' ' '{ print $1 }'") err_dupmet_list = err_dupmet_list .. metric_dupes end err_dupmet_list = sys.exec("echo '" .. err_dupmet_list .. "' | tr '\n' ' '") end end function iface_warn() -- display status and warning messages at the top of the page local warns = "" if ifnum <= 250 then warns = "<strong>There are currently " .. ifnum .. " of 250 supported interfaces configured</strong>" else warns = "<font color=\"ff0000\"><strong>WARNING: " .. ifnum .. " interfaces are configured exceeding the maximum of 250!</strong></font>" end if err_rel_list ~= " " then warns = warns .. "<br /><br /><font color=\"ff0000\"><strong>WARNING: some interfaces have a higher reliability requirement than there are tracking IP addresses!</strong></font>" end if err_route_list ~= " " then warns = warns .. "<br /><br /><font color=\"ff0000\"><strong>WARNING: some interfaces have no default route in the main routing table!</strong></font>" end if err_netcfg_list ~= " " then warns = warns .. "<br /><br /><font color=\"ff0000\"><strong>WARNING: some interfaces are configured incorrectly or not at all in /etc/config/network!</strong></font>" end if err_nomet_list ~= " " then warns = warns .. "<br /><br /><font color=\"ff0000\"><strong>WARNING: some interfaces have no metric configured in /etc/config/network!</strong></font>" end if err_dupmet_list ~= " " then warns = warns .. "<br /><br /><font color=\"ff0000\"><strong>WARNING: some interfaces have duplicate metrics configured in /etc/config/network!</strong></font>" end return warns end -- ------ interface configuration ------ -- dsp = require "luci.dispatcher" sys = require "luci.sys" ut = require "luci.util" ifnum = 0 metric_list = "" err_found = 0 err_dupmet_list = " " err_netcfg_list = " " err_nomet_list = " " err_rel_list = " " err_route_list = " " iface_check() m5 = Map("mwan3", translate("MWAN3 Multi-WAN Interface Configuration"), translate(iface_warn())) m5:append(Template("mwan3/mwan3_config_css")) mwan_interface = m5:section(TypedSection, "interface", translate("Interfaces"), translate("MWAN3 supports up to 250 physical and/or logical interfaces<br />" .. "MWAN3 requires that all interfaces have a unique metric configured in /etc/config/network<br />" .. "Names must match the interface name found in /etc/config/network (see advanced tab)<br />" .. "Names may contain characters A-Z, a-z, 0-9, _ and no spaces<br />" .. "Interfaces may not share the same name as configured members, policies or rules")) mwan_interface.addremove = true mwan_interface.dynamic = false mwan_interface.sectionhead = "Interface" mwan_interface.sortable = true mwan_interface.template = "cbi/tblsection" mwan_interface.extedit = dsp.build_url("admin", "network", "mwan3", "configuration", "interface", "%s") function mwan_interface.create(self, section) TypedSection.create(self, section) m5.uci:save("mwan3") luci.http.redirect(dsp.build_url("admin", "network", "mwan3", "configuration", "interface", section)) end enabled = mwan_interface:option(DummyValue, "enabled", translate("Enabled")) enabled.rawhtml = true function enabled.cfgvalue(self, s) if self.map:get(s, "enabled") == "1" then return "Yes" else return "No" end end track_ip = mwan_interface:option(DummyValue, "track_ip", translate("Tracking IP")) track_ip.rawhtml = true function track_ip.cfgvalue(self, s) local str = "" tracked = self.map:get(s, "track_ip") if tracked then for k,v in pairs(tracked) do str = str .. v .. "<br />" end return str else return "&#8212;" end end reliability = mwan_interface:option(DummyValue, "reliability", translate("Tracking reliability")) reliability.rawhtml = true function reliability.cfgvalue(self, s) if tracked then return self.map:get(s, "reliability") or "&#8212;" else return "&#8212;" end end count = mwan_interface:option(DummyValue, "count", translate("Ping count")) count.rawhtml = true function count.cfgvalue(self, s) if tracked then return self.map:get(s, "count") or "&#8212;" else return "&#8212;" end end timeout = mwan_interface:option(DummyValue, "timeout", translate("Ping timeout")) timeout.rawhtml = true function timeout.cfgvalue(self, s) if tracked then local tcheck = self.map:get(s, "timeout") if tcheck then return tcheck .. "s" else return "&#8212;" end else return "&#8212;" end end interval = mwan_interface:option(DummyValue, "interval", translate("Ping interval")) interval.rawhtml = true function interval.cfgvalue(self, s) if tracked then local icheck = self.map:get(s, "interval") if icheck then return icheck .. "s" else return "&#8212;" end else return "&#8212;" end end down = mwan_interface:option(DummyValue, "down", translate("Interface down")) down.rawhtml = true function down.cfgvalue(self, s) if tracked then return self.map:get(s, "down") or "&#8212;" else return "&#8212;" end end up = mwan_interface:option(DummyValue, "up", translate("Interface up")) up.rawhtml = true function up.cfgvalue(self, s) if tracked then return self.map:get(s, "up") or "&#8212;" else return "&#8212;" end end metric = mwan_interface:option(DummyValue, "metric", translate("Metric")) metric.rawhtml = true function metric.cfgvalue(self, s) local metcheck = sys.exec("uci get -p /var/state network." .. s .. ".metric") if metcheck ~= "" then return metcheck else return "&#8212;" end end errors = mwan_interface:option(DummyValue, "errors", translate("Errors")) errors.rawhtml = true function errors.cfgvalue(self, s) if err_found == 1 then local mouseover, linebrk = "", "" if string.find(err_rel_list, " " .. s .. " ") then mouseover = "Higher reliability requirement than there are tracking IP addresses" linebrk = "&#10;&#10;" end if string.find(err_route_list, " " .. s .. " ") then mouseover = mouseover .. linebrk .. "No default route in the main routing table" linebrk = "&#10;&#10;" end if string.find(err_netcfg_list, " " .. s .. " ") then mouseover = mouseover .. linebrk .. "Configured incorrectly or not at all in /etc/config/network" linebrk = "&#10;&#10;" end if string.find(err_nomet_list, " " .. s .. " ") then mouseover = mouseover .. linebrk .. "No metric configured in /etc/config/network" linebrk = "&#10;&#10;" end if string.find(err_dupmet_list, " " .. s .. " ") then mouseover = mouseover .. linebrk .. "Duplicate metric configured in /etc/config/network" end if mouseover == "" then return "" else return "<span title=\"" .. mouseover .. "\"><img src=\"/luci-static/resources/cbi/reset.gif\" alt=\"error\"></img></span>" end else return "" end end return m5
gpl-2.0
lichtl/darkstar
scripts/zones/North_Gustaberg/npcs/Stone_Monument.lua
14
1295
----------------------------------- -- Area: North Gustaberg -- NPC: Stone Monument -- Involved in quest "An Explorer's Footsteps" -- @pos -199.635 96.106 505.624 106 ----------------------------------- package.loaded["scripts/zones/North_Gustaberg/TextIDs"] = nil; ----------------------------------- require("scripts/zones/North_Gustaberg/TextIDs"); ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0384); end; ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) if (trade:getItemCount() == 1 and trade:hasItemQty(571,1)) then player:tradeComplete(); player:addItem(570); player:messageSpecial(ITEM_OBTAINED,570); player:setVar("anExplorer-CurrentTablet",0x00020); 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
qenter/vlc-android
vlc/share/lua/playlist/mpora.lua
97
2565
--[[ $Id$ Copyright © 2009 the VideoLAN team Authors: Konstantin Pavlov (thresh@videolan.org) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. --]] -- Probe function. function probe() return vlc.access == "http" and string.match( vlc.path, "video%.mpora%.com/watch/" ) end -- Parse function. function parse() p = {} while true do -- Try to find the video's title line = vlc.readline() if not line then break end if string.match( line, "meta name=\"title\"" ) then _,_,name = string.find( line, "content=\"(.*)\" />" ) end if string.match( line, "image_src" ) then _,_,arturl = string.find( line, "image_src\" href=\"(.*)\" />" ) end if string.match( line, "video_src" ) then _,_,video = string.find( line, 'href="http://video%.mpora%.com/ep/(.*)%.swf" />' ) end end if not name or not arturl or not video then return nil end -- Try and get URL for SD video. sd = vlc.stream("http://api.mpora.com/tv/player/playlist/vid/"..video.."/") if not sd then return nil end page = sd:read( 65653 ) sdurl = string.match( page, "url=\"(.*)\" />") page = nil table.insert( p, { path = sdurl; name = name; arturl = arturl; } ) -- Try and check if HD video is available. checkhd = vlc.stream("http://api.mpora.com/tv/player/load/vid/"..video.."/platform/video/domain/video.mpora.com/" ) if not checkhd then return nil end page = checkhd:read( 65653 ) hashd = tonumber( string.match( page, "<has_hd>(%d)</has_hd>" ) ) page = nil if hashd then hd = vlc.stream("http://api.mpora.com/tv/player/playlist/vid/"..video.."/hd/true/") page = hd:read( 65653 ) hdurl = string.match( page, "url=\"(.*)\" />") table.insert( p, { path = hdurl; name = name.." (HD)"; arturl = arturl; } ) end return p end
gpl-2.0
lichtl/darkstar
scripts/zones/Cloister_of_Tides/bcnms/trial-size_trial_by_water.lua
29
2207
----------------------------------- -- Area: Cloister of Tides -- BCNM: Trial by Water ----------------------------------- package.loaded["scripts/zones/Cloister_of_Tides/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Cloister_of_Tides/TextIDs"); ----------------------------------- -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) end; -- Leaving the BCNM by every mean possible, given by the LeaveCode -- 1=Select Exit on circle -- 2=Winning the BC -- 3=Disconnected or warped out -- 4=Losing the BC -- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called -- from the core when a player disconnects or the time limit is up, etc function onBcnmLeave(player,instance,leavecode) -- print("leave code "..leavecode); trialLightning = player:getQuestStatus(OUTLANDS,TRIAL_SIZE_TRIAL_BY_WATER) if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,0); elseif (leavecode == 4) then player:setVar("TrialSizeWater_date",tonumber(os.date("%j"))); -- If you loose, you need to wait 1 real day player:startEvent(0x7d02); end end; function onEventUpdate(player,csid,option) -- print("bc update csid "..csid.." and option "..option); end; function onEventFinish(player,csid,option) -- print("bc finish csid "..csid.." and option "..option); if (csid == 0x7d01) then if (player:hasSpell(300) == false) then player:addSpell(300); -- Leviathan player:messageSpecial(LEVIATHAN_UNLOCKED,0,0,2); end if (player:hasItem(4181) == false) then player:addItem(4181); player:messageSpecial(ITEM_OBTAINED,4181); -- Scroll of instant warp end player:setVar("TrialSizeWater_date", 0); player:addFame(NORG,30); player:completeQuest(OUTLANDS,TRIAL_SIZE_TRIAL_BY_WATER); end end;
gpl-3.0
RunAwayDSP/darkstar
scripts/globals/items/vongola_clam.lua
11
1432
----------------------------------------- -- ID: 5131 -- Item: Vongola Clam -- Food Effect: 5Min, Mithra only ----------------------------------------- -- Dexterity -5 -- Vitality 4 -- Defense +17% - 50 Cap -- HP 5% - 50 Cap ----------------------------------------- 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,5131) end function onEffectGain(target, effect) target:addMod(dsp.mod.DEX, -5) target:addMod(dsp.mod.VIT, 4) target:addMod(dsp.mod.FOOD_DEFP, 17) target:addMod(dsp.mod.FOOD_DEF_CAP, 50) target:addMod(dsp.mod.FOOD_HPP, 5) target:addMod(dsp.mod.FOOD_HP_CAP, 50) end function onEffectLose(target, effect) target:delMod(dsp.mod.DEX, -5) target:delMod(dsp.mod.VIT, 4) target:delMod(dsp.mod.FOOD_DEFP, 17) target:delMod(dsp.mod.FOOD_DEF_CAP, 50) target:delMod(dsp.mod.FOOD_HPP, 5) target:delMod(dsp.mod.FOOD_HP_CAP, 50) end
gpl-3.0
RunAwayDSP/darkstar
scripts/globals/weaponskills/blade_ei.lua
10
1231
----------------------------------- -- Blade Ei -- Katana weapon skill -- Skill Level: 175 -- Delivers a dark elemental attack. Damage varies with TP. -- Aligned with the Shadow Gorget. -- Aligned with the Shadow Belt. -- Element: Dark -- Modifiers: STR:30% INT:30% -- 100%TP 200%TP 300%TP -- 1.00 1.50 2.00 ----------------------------------- require("scripts/globals/magic") require("scripts/globals/status") require("scripts/globals/settings") require("scripts/globals/weaponskills") ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar) local params = {} params.ftp100 = 1 params.ftp200 = 1.5 params.ftp300 = 2 params.str_wsc = 0.3 params.dex_wsc = 0.0 params.vit_wsc = 0.0 params.agi_wsc = 0.0 params.int_wsc = 0.3 params.mnd_wsc = 0.0 params.chr_wsc = 0.0 params.ele = dsp.magic.ele.DARK params.skill = dsp.skill.KATANA params.includemab = true if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.str_wsc = 0.4 params.int_wsc = 0.4 end local damage, tpHits, extraHits = doMagicWeaponskill(player, target, wsID, params, tp, action, primary) return tpHits, extraHits, criticalHit, damage end
gpl-3.0