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
raymondtfr/forgottenserver
data/global.lua
1
6641
dofile('data/lib/lib.lua') STORAGEVALUE_PROMOTION = 30018 ropeSpots = {384, 418, 8278, 8592, 13189, 14435, 14436, 15635, 19518} doors = {[1209] = 1211, [1210] = 1211, [1212] = 1214, [1213] = 1214, [1219] = 1220, [1221] = 1222, [1231] = 1233, [1232] = 1233, [1234] = 1236, [1235] = 1236, [1237] = 1238, [1239] = 1240, [1249] = 1251, [1250] = 1251, [1252] = 1254, [1253] = 1254, [1539] = 1540, [1541] = 1542, [3535] = 3537, [3536] = 3537, [3538] = 3539, [3544] = 3546, [3545] = 3546, [3547] = 3548, [4913] = 4915, [4914] = 4915, [4916] = 4918, [4917] = 4918, [5082] = 5083, [5084] = 5085, [5098] = 5100, [5099] = 5100, [5101] = 5102, [5107] = 5109, [5108] = 5109, [5110] = 5111, [5116] = 5118, [5117] = 5118, [5119] = 5120, [5125] = 5127, [5126] = 5127, [5128] = 5129, [5134] = 5136, [5135] = 5136, [5137] = 5139, [5138] = 5139, [5140] = 5142, [5141] = 5142, [5143] = 5145, [5144] = 5145, [5278] = 5280, [5279] = 5280, [5281] = 5283, [5282] = 5283, [5284] = 5285, [5286] = 5287, [5515] = 5516, [5517] = 5518, [5732] = 5734, [5733] = 5734, [5735] = 5737, [5736] = 5737, [6192] = 6194, [6193] = 6194, [6195] = 6197, [6196] = 6197, [6198] = 6199, [6200] = 6201, [6249] = 6251, [6250] = 6251, [6252] = 6254, [6253] = 6254, [6255] = 6256, [6257] = 6258, [6795] = 6796, [6797] = 6798, [6799] = 6800, [6801] = 6802, [6891] = 6893, [6892] = 6893, [6894] = 6895, [6900] = 6902, [6901] = 6902, [6903] = 6904, [7033] = 7035, [7034] = 7035, [7036] = 7037, [7042] = 7044, [7043] = 7044, [7045] = 7046, [7054] = 7055, [7056] = 7057, [8541] = 8543, [8542] = 8543, [8544] = 8546, [8545] = 8546, [8547] = 8548, [8549] = 8550, [9165] = 9167, [9166] = 9167, [9168] = 9170, [9169] = 9170, [9171] = 9172, [9173] = 9174, [9267] = 9269, [9268] = 9269, [9270] = 9272, [9271] = 9272, [9273] = 9274, [9275] = 9276, [10276] = 10277, [10274] = 10275, [10268] = 10270, [10269] = 10270, [10271] = 10273, [10272] = 10273, [10471] = 10472, [10480] = 10481, [10477] = 10479, [10478] = 10479, [10468] = 10470, [10469] = 10470, [10775] = 10777, [10776] = 10777, [12092] = 12094, [12093] = 12094, [12188] = 12190, [12189] = 12190, [19840] = 19842, [19841] = 19842, [19843] = 19844, [19980] = 19982, [19981] = 19982, [19983] = 19984, [20273] = 20275, [20274] = 20275, [20276] = 20277, [17235] = 17236, [18208] = 18209, [13022] = 13023, [10784] = 10786, [10785] = 10786, [12099] = 12101, [12100] = 12101, [12197] = 12199, [12198] = 12199, [19849] = 19851, [19850] = 19851, [19852] = 19853, [19989] = 19991, [19990] = 19991, [19992] = 19993, [20282] = 20284, [20283] = 20284, [20285] = 20286, [17237] = 17238, [13020] = 13021, [10780] = 10781, [12095] = 12096, [12195] = 12196, [19845] = 19846, [19985] = 19986, [20278] = 20279, [10789] = 10790, [12102] = 12103, [12204] = 12205, [19854] = 19855, [19994] = 19995, [20287] = 20288, [10782] = 10783, [12097] = 12098, [12193] = 12194, [19847] = 19848, [19987] = 19988, [20280] = 20281, [10791] = 10792, [12104] = 12105, [12202] = 12203, [19856] = 19857, [19996] = 19997, [20289] = 20290} verticalOpenDoors = {1211, 1220, 1224, 1228, 1233, 1238, 1242, 1246, 1251, 1256, 1260, 1540, 3546, 3548, 3550, 3552, 4915, 5083, 5109, 5111, 5113, 5115, 5127, 5129, 5131, 5133, 5142, 5145, 5283, 5285, 5289, 5293, 5516, 5737, 5749, 6194, 6199, 6203, 6207, 6251, 6256, 6260, 6264, 6798, 6802, 6902, 6904, 6906, 6908, 7044, 7046, 7048, 7050, 7055, 8543, 8548, 8552, 8556, 9167, 9172, 9269, 9274, 9274, 9269, 9278, 9282, 10270, 10275, 10279, 10283, 10479, 10481, 10485, 10483, 10786, 12101, 12199, 19851, 19853, 19991, 19993, 20284, 20286, 17238, 13021, 10790, 12103, 12205, 19855, 19995, 20288, 10792, 12105, 12203, 19857, 19997, 20290} horizontalOpenDoors = {1214, 1222, 1226, 1230, 1236, 1240, 1244, 1248, 1254, 1258, 1262, 1542, 3537, 3539, 3541, 3543, 4918, 5085, 5100, 5102, 5104, 5106, 5118, 5120, 5122, 5124, 5136, 5139, 5280, 5287, 5291, 5295, 5518, 5734, 5746, 6197, 6201, 6205, 6209, 6254, 6258, 6262, 6266, 6796, 6800, 6893, 6895, 6897, 6899, 7035, 7037, 7039, 7041, 7057, 8546, 8550, 8554, 8558, 9170, 9174, 9272, 9276, 9280, 9284, 10273, 10277, 10281, 10285, 10470, 10472, 10476, 10474, 10777, 12094, 12190, 19842, 19844, 19982, 19984, 20275, 20277, 17236, 18209, 13023, 10781, 12096, 12196, 19846, 19986, 20279, 10783, 12098, 12194, 19848, 19988, 20281} openSpecialDoors = {1224, 1226, 1228, 1230, 1242, 1244, 1246, 1248, 1256, 1258, 1260, 1262, 3541, 3543, 3550, 3552, 5104, 5106, 5113, 5115, 5122, 5124, 5131, 5133, 5289, 5291, 5293, 5295, 6203, 6205, 6207, 6209, 6260, 6262, 6264, 6266, 6897, 6899, 6906, 6908, 7039, 7041, 7048, 7050, 8552, 8554, 8556, 8558, 9176, 9178, 9180, 9182, 9278, 9280, 9282, 9284, 10279, 10281, 10283, 10285, 10474, 10476, 10483, 10485, 10781, 12096, 12196, 19846, 19986, 20279, 10783, 12098, 12194, 19848, 19988, 20281, 10790, 12103, 12205, 19855, 19995, 20288, 10792, 12105, 12203, 19857, 19997, 20290} questDoors = {1223, 1225, 1241, 1243, 1255, 1257, 3542, 3551, 5105, 5114, 5123, 5132, 5288, 5290, 5745, 5748, 6202, 6204, 6259, 6261, 6898, 6907, 7040, 7049, 8551, 8553, 9175, 9177, 9277, 9279, 10278, 10280, 10475, 10484, 10782, 10791, 12097, 12104, 12193, 12202, 19847, 19856, 19987, 19996, 20280, 20289} levelDoors = {1227, 1229, 1245, 1247, 1259, 1261, 3540, 3549, 5103, 5112, 5121, 5130, 5292, 5294, 6206, 6208, 6263, 6265, 6896, 6905, 7038, 7047, 8555, 8557, 9179, 9181, 9281, 9283, 10282, 10284, 10473, 10482, 10780, 10789, 10780, 12095, 12102, 12204, 12195, 19845, 19854, 19985, 19994, 20278, 20287} keys = {2086, 2087, 2088, 2089, 2090, 2091, 2092, 10032} function getDistanceBetween(firstPosition, secondPosition) local xDif = math.abs(firstPosition.x - secondPosition.x) local yDif = math.abs(firstPosition.y - secondPosition.y) local posDif = math.max(xDif, yDif) if firstPosition.z ~= secondPosition.z then posDif = posDif + 15 end return posDif end function getFormattedWorldTime() local worldTime = getWorldTime() local hours = math.floor(worldTime / 60) local minutes = worldTime % 60 if minutes < 10 then minutes = '0' .. minutes end return hours .. ':' .. minutes end function getLootRandom() math.randomseed(os.mtime()) return math.random(0, MAX_LOOTCHANCE) / configManager.getNumber(configKeys.RATE_LOOT) end table.contains = function(array, value) for _, targetColumn in pairs(array) do if targetColumn == value then return true end end return false end string.split = function(str, sep) local res = {} for v in str:gmatch("([^" .. sep .. "]+)") do res[#res + 1] = v end return res end string.trim = function(str) return str:match'^()%s*$' and '' or str:match'^%s*(.*%S)' end if not nextUseStaminaTime then nextUseStaminaTime = {} end
gpl-2.0
rezaar/Tele-Sorena
plugins/settings.s.lua
13
33964
-------------------------------------------------- -- ____ ____ _____ -- -- | \| _ )_ _|___ ____ __ __ -- -- | |_ ) _ \ | |/ ·__| _ \_| \/ | -- -- |____/|____/ |_|\____/\_____|_/\/\_| -- -- -- -------------------------------------------------- -- -- -- Developers: @Josepdal & @MaSkAoS -- -- Support: @Skneos, @iicc1 & @serx666 -- -- -- -- #creategroup by @lamjavid & @Josepdal -- -- -- -------------------------------------------------- do local function create_group(msg, group_name) local group_creator = msg.from.print_name create_group_chat(group_creator, group_name, ok_cb, false) return 'ℹ️ '..lang_text(msg.to.id, 'createGroup:1')..' "'..string.gsub(group_name, '_', ' ')..'" '..lang_text(msg.to.id, 'createGroup:2') end local function remove_message(extra, success, result) msg = backward_msg_format(result) delete_msg(msg.id, ok_cb, false) end local function set_group_photo(msg, success, result) local receiver = get_receiver(msg) if success then local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) if msg.to.type == 'channel' then channel_set_photo (receiver, file, ok_cb, false) elseif msg.to.type == 'chat' then chat_set_photo(receiver, file, ok_cb, false) end return 'ℹ️ '..lang_text(msg.to.id, 'photoSaved') else print('Error downloading: '..msg.id) return 'ℹ️ '..lang_text(msg.to.id, 'photoSaved') end end local function pre_process(msg) local hash = 'flood:max:'..msg.to.id if not redis:get(hash) then floodMax = 5 else floodMax = tonumber(redis:get(hash)) end local hash = 'flood:time:'..msg.to.id if not redis:get(hash) then floodTime = 3 else floodTime = tonumber(redis:get(hash)) end if not permissions(msg.from.id, msg.to.id, "pre_process") then --Checking flood local hashse = 'anti-flood:'..msg.to.id print(1) if not redis:get(hashse) then print('anti-flood enabled') -- Check flood if msg.from.type == 'user' then if not permissions(msg.from.id, msg.to.id, "no_flood_ban") then -- Increase the number of messages from the user on the chat local hash = 'flood:'..msg.from.id..':'..msg.to.id..':msg-num' local msgs = tonumber(redis:get(hash) or 0) if msgs > floodMax then local receiver = get_receiver(msg) local user = msg.from.id local chat = msg.to.id local channel = msg.to.id local bhash = 'banned:'..msg.to.id..':'..msg.from.id redis:set(bhash, true) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, lang_text(chat, 'user')..' @'..msg.from.username..' ('..msg.from.id..') '..lang_text(chat, 'isFlooding'), ok_cb, true) chat_del_user('chat#id'..msg.to.id, 'user#id'..msg.from.id, ok_cb, true) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, lang_text(chat, 'user')..' @'..msg.from.username..' ('..msg.from.id..') '..lang_text(chat, 'isFlooding'), ok_cb, true) channel_kick_user('channel#id'..msg.to.id, 'user#id'..msg.from.id, ok_cb, true) end end redis:setex(hash, floodTime, msgs+1) end end end --Checking stickers if not msg.media then webp = 'nothing' else webp = msg.media.caption end if webp == 'sticker.webp' then hash = 'stickers:'..msg.to.id if redis:get(hash) then delete_msg(msg.id, ok_cb, false) end end if not msg.media then mp4 = 'nothing' else if msg.media.type == 'document' then mp4 = msg.media.caption or 'audio' end end --Checking GIFs and MP4 files if mp4 == 'giphy.mp4' then hash = 'gifs:'..msg.to.id if redis:get(hash) then delete_msg(msg.id, ok_cb, false) end else if msg.media then if msg.media.type == 'document' then gifytpe = string.find(mp4, 'gif.mp4') or 'audio' if gifytpe == 'audio' then hash = 'audio:'..msg.to.id if redis:get(hash) then delete_msg(msg.id, ok_cb, false) end else hash = 'gifs:'..msg.to.id if redis:get(hash) then delete_msg(msg.id, ok_cb, false) end end end end end --Checking photos if msg.media then if msg.media.type == 'photo' then local hash = 'setphoto:'..msg.to.id..':'..msg.from.id if redis:get(hash) then redis:del(hash) load_photo(msg.id, set_group_photo, msg) delete_msg(msg.id, ok_cb, false) end local hash = 'photo:'..msg.to.id if redis:get(hash) then delete_msg(msg.id, ok_cb, false) end end end --Checking muteall local hash = 'muteall:'..msg.to.id if redis:get(hash) then delete_msg(msg.id, ok_cb, false) end end return msg end local function run(msg, matches) if matches[1] == 'settings' then if permissions(msg.from.id, msg.to.id, "settings") then if matches[2] ~= nil then if matches[2] == 'stickers' then if matches[3] == 'enable' then hash = 'stickers:'..msg.to.id redis:del(hash) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'stickersT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'stickersL'), ok_cb, false) end elseif matches[3] == 'disable' then hash = 'stickers:'..msg.to.id redis:set(hash, true) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noStickersT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noStickersL'), ok_cb, false) end end return elseif matches[2] == 'gifs' then if matches[3] == 'enable' then hash = 'gifs:'..msg.to.id redis:del(hash) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'gifsT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'gifsL'), ok_cb, false) end elseif matches[3] == 'disable' then hash = 'gifs:'..msg.to.id redis:set(hash, true) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noGifsT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noGifsL'), ok_cb, false) end end return elseif matches[2] == 'photos' then if matches[3] == 'enable' then hash = 'photo:'..msg.to.id redis:del(hash) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'photosT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'photosL'), ok_cb, false) end elseif matches[3] == 'disable' then hash = 'photo:'..msg.to.id redis:set(hash, true) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noPhotosT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noPhotosL'), ok_cb, false) end end return elseif matches[2] == 'arabic' then if matches[3] == 'enable' then hash = 'arabic:'..msg.to.id redis:del(hash) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'arabicT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'arabicL'), ok_cb, false) end elseif matches[3] == 'disable' then hash = 'arabic:'..msg.to.id redis:set(hash, true) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noArabicT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noArabicL'), ok_cb, false) end end return elseif matches[2] == 'audios' then if matches[3] == 'enable' then hash = 'audio:'..msg.to.id redis:del(hash) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'audiosT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'audiosL'), ok_cb, false) end elseif matches[3] == 'disable' then hash = 'audio:'..msg.to.id redis:set(hash, true) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noAudiosT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noAudiosL'), ok_cb, false) end end return elseif matches[2] == 'kickme' then if matches[3] == 'enable' then hash = 'kickme:'..msg.to.id redis:set(hash, true) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'kickmeT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'kickmeL'), ok_cb, false) end elseif matches[3] == 'disable' then hash = 'kickme:'..msg.to.id redis:del(hash) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noKickmeT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noKickmeL'), ok_cb, false) end end return elseif matches[2] == 'flood' then if matches[3] == 'enable' then hash = 'anti-flood:'..msg.to.id redis:set(hash, true) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'floodT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'floodL'), ok_cb, false) end elseif matches[3] == 'disable' then hash = 'anti-flood:'..msg.to.id redis:del(hash) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noFloodT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noFloodL'), ok_cb, false) end end return elseif matches[2] == 'spam' then if matches[3] == 'enable' then local hash = 'spam:'..msg.to.id redis:del(hash) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'allowedSpamT'), ok_cb, true) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'allowedSpamL'), ok_cb, true) end elseif matches[3] == 'disable' then local hash = 'spam:'..msg.to.id redis:set(hash, true) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'notAllowedSpamT'), ok_cb, true) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'notAllowedSpamL'), ok_cb, true) end end elseif matches[2] == 'lockmember' then hash = 'lockmember:'..msg.to.id if matches[3] == 'enable' then redis:set(hash, true) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'lockMembersT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'lockMembersL'), ok_cb, false) end elseif matches[3] == 'disable' then redis:del(hash) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'notLockMembersT'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'notLockMembersT'), ok_cb, false) end end return elseif matches[2] == 'floodtime' then if not matches[3] then else hash = 'flood:time:'..msg.to.id redis:set(hash, matches[3]) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'floodTime')..matches[3], ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'floodTime')..matches[3], ok_cb, false) end end return elseif matches[2] == 'maxflood' then if not matches[3] then else hash = 'flood:max:'..msg.to.id redis:set(hash, matches[3]) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'floodMax')..matches[3], ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'floodMax')..matches[3], ok_cb, false) end end return elseif matches[2] == 'setname' then if matches[3] == 'enable' then local hash = 'name:enabled:'..msg.to.id redis:del(hash) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'chatRename'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'channelRename'), ok_cb, false) end elseif matches[3] == 'disable' then local hash = 'name:enabled:'..msg.to.id redis:set(hash, true) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'notChatRename'), ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'notChannelRename'), ok_cb, false) end end end else if msg.to.type == 'chat' then text = '⚙ '..lang_text(msg.to.id, 'gSettings')..':\n' elseif msg.to.type == 'channel' then text = '⚙ '..lang_text(msg.to.id, 'sSettings')..':\n' end local allowed = lang_text(msg.to.id, 'allowed') local noAllowed = lang_text(msg.to.id, 'noAllowed') --Enable/disable Stickers local hash = 'stickers:'..msg.to.id if redis:get(hash) then sStickers = noAllowed sStickersD = '🔹' else sStickers = allowed sStickersD = '🔸' end text = text..sStickersD..' '..lang_text(msg.to.id, 'stickers')..': '..sStickers..'\n' --Enable/disable Links local hash = 'antilink:'..msg.to.id if redis:get(hash) then sLink = noAllowed sLinkD = '🔹' else sLink = allowed sLinkD = '🔸' end text = text..sLinkD..' '..lang_text(msg.to.id, 'links')..': '..sLink..'\n' --Enable/disable arabic messages local hash = 'arabic:'..msg.to.id if not redis:get(hash) then sArabe = allowed sArabeD = '🔸' else sArabe = noAllowed sArabeD = '🔹' end text = text..sArabeD..' '..lang_text(msg.to.id, 'arabic')..': '..sArabe..'\n' --Enable/disable bots local hash = 'antibot:'..msg.to.id if redis:get(hash) then sBots = allowed sBotsD = '🔸' else sBots = noAllowed sBotsD = '🔹' end text = text..sBotsD..' '..lang_text(msg.to.id, 'bots')..': '..sBots..'\n' --Enable/disable gifs local hash = 'gifs:'..msg.to.id if redis:get(hash) then sGif = noAllowed sGifD = '🔹' else sGif = allowed sGifD = '🔸' end text = text..sGifD..' '..lang_text(msg.to.id, 'gifs')..': '..sGif..'\n' --Enable/disable send photos local hash = 'photo:'..msg.to.id if redis:get(hash) then sPhoto = noAllowed sPhotoD = '🔹' else sPhoto = allowed sPhotoD = '🔸' end text = text..sPhotoD..' '..lang_text(msg.to.id, 'photos')..': '..sPhoto..'\n' --Enable/disable send audios local hash = 'audio:'..msg.to.id if redis:get(hash) then sAudio = noAllowed sAudioD = '🔹' else sAudio = allowed sAudioD = '🔸' end text = text..sAudioD..' '..lang_text(msg.to.id, 'audios')..': '..sAudio..'\n' --Enable/disable kickme local hash = 'kickme:'..msg.to.id if redis:get(hash) then sKickme = allowed sKickmeD = '🔸' else sKickme = noAllowed sKickmeD = '🔹' end text = text..sKickmeD..' '..lang_text(msg.to.id, 'kickme')..': '..sKickme..'\n' --Enable/disable spam local hash = 'spam:'..msg.to.id if redis:get(hash) then sSpam = noAllowed sSpamD = '🔹' else sSpam = allowed sSpamD = '🔸' end text = text..sSpamD..' '..lang_text(msg.to.id, 'spam')..': '..sSpam..'\n' --Enable/disable setphoto local hash = 'setphoto:'..msg.to.id..':'..msg.from.id if redis:get(hash) then sSPhoto = allowed sSPhotoD = '🔸' else sSPhoto = noAllowed sSPhotoD = '🔹' end text = text..sSPhotoD..' '..lang_text(msg.to.id, 'setphoto')..': '..sSPhoto..'\n' --Enable/disable changing group name local hash = 'name:enabled:'..msg.to.id if redis:get(hash) then sName = noAllowed sNameD = '🔹' else sName = allowed sNameD = '🔸' end text = text..sNameD..' '..lang_text(msg.to.id, 'gName')..': '..sName..'\n' --Lock/unlock numbers of channel members local hash = 'lockmember:'..msg.to.id if redis:get(hash) then sLock = noAllowed sLockD = '🔹' else sLock = allowed sLockD = '🔸' end text = text..sLockD..' lockmembers: '..sLock..'\n' --Enable/disable Flood local hash = 'anti-flood:'..msg.to.id if redis:get(hash) then sFlood = allowed sFloodD = '🔸' else sFlood = noAllowed sFloodD = '🔹' end text = text..sFloodD..' '..lang_text(msg.to.id, 'flood')..': '..sFlood..'\n' local hash = 'langset:'..msg.to.id if redis:get(hash) then sLang = redis:get(hash) sLangD = '🔸' else sLang = lang_text(msg.to.id, 'noSet') sLangD = '🔹' end text = text..sLangD..' '..lang_text(msg.to.id, 'language')..': '..string.upper(sLang)..'\n' local hash = 'flood:max:'..msg.to.id if not redis:get(hash) then floodMax = 5 else floodMax = redis:get(hash) end local hash = 'flood:time:'..msg.to.id if not redis:get(hash) then floodTime = 3 else floodTime = redis:get(hash) end text = text..'🔺 '..lang_text(msg.to.id, 'mFlood')..': '..floodMax..'\n🔺 '..lang_text(msg.to.id, 'tFlood')..': '..floodTime..'\n' --Send settings to group or supergroup if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, text, ok_cb, false) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, text, ok_cb, false) end return end else return '🚫 '..lang_text(msg.to.id, 'require_mod') end elseif matches[1] == 'rem' then if permissions(msg.from.id, msg.to.id, "settings") then if msg.reply_id then get_message(msg.reply_id, remove_message, false) get_message(msg.id, remove_message, false) end return else return '🚫 '..lang_text(msg.to.id, 'require_mod') end elseif matches[1] == 'lang' then if permissions(msg.from.id, msg.to.id, "set_lang") then hash = 'langset:'..msg.to.id redis:set(hash, matches[2]) return lang_text(msg.to.id, 'langUpdated')..string.upper(matches[2]) else return '🚫 '..lang_text(msg.to.id, 'require_sudo') end elseif matches[1] == 'setname' then if permissions(msg.from.id, msg.to.id, "settings") then local hash = 'name:enabled:'..msg.to.id if not redis:get(hash) then if msg.to.type == 'chat' then rename_chat(msg.to.peer_id, matches[2], ok_cb, false) elseif msg.to.type == 'channel' then rename_channel(msg.to.peer_id, matches[2], ok_cb, false) end end return else return '🚫 '..lang_text(msg.to.id, 'require_mod') end elseif matches[1] == 'setlink' then if permissions(msg.from.id, msg.to.id, "setlink") then hash = 'link:'..msg.to.id redis:set(hash, matches[2]) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'linkSaved'), ok_cb, true) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'linkSaved'), ok_cb, true) end return else return '🚫 '..lang_text(msg.to.id, 'require_admin') end elseif matches[1] == 'link' then if permissions(msg.from.id, msg.to.id, "link") then hash = 'link:'..msg.to.id local linktext = redis:get(hash) if linktext then if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, '🌐 '..lang_text(msg.to.id, 'groupLink')..': '..linktext, ok_cb, true) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, '🌐 '..lang_text(msg.to.id, 'sGroupLink')..': '..linktext, ok_cb, true) end else if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noLinkSet'), ok_cb, true) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'noLinkSet'), ok_cb, true) end end return else return '🚫 '..lang_text(msg.to.id, 'require_mod') end elseif matches[1] == 'setphoto' then if permissions(msg.from.id, msg.to.id, "settings") then if matches[2] == 'stop' then hash = 'setphoto:'..msg.to.id..':'..msg.from.id redis:del(hash) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'setPhotoAborted'), ok_cb, true) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'setPhotoAborted'), ok_cb, true) end else hash = 'setphoto:'..msg.to.id..':'..msg.from.id redis:set(hash, true) if msg.to.type == 'chat' then send_msg('chat#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'sendPhoto'), ok_cb, true) elseif msg.to.type == 'channel' then send_msg('channel#id'..msg.to.id, 'ℹ️ '..lang_text(msg.to.id, 'sendPhoto'), ok_cb, true) end end return else return '🚫 '..lang_text(msg.to.id, 'require_mod') end elseif matches[1] == 'tosupergroup' then if msg.to.type == 'chat' then if permissions(msg.from.id, msg.to.id, "tosupergroup") then chat_upgrade('chat#id'..msg.to.id, ok_cb, false) return 'ℹ️ '..lang_text(msg.to.id, 'chatUpgrade') else return '🚫 '..lang_text(msg.to.id, 'require_sudo') end else return 'ℹ️ '..lang_text(msg.to.id, 'notInChann') end elseif matches[1] == 'setdescription' then if permissions(msg.from.id, msg.to.id, "description") then local text = matches[2] local chat = 'channel#id'..msg.to.id if msg.to.type == 'channel' then channel_set_about(chat, text, ok_cb, false) return 'ℹ️ '..lang_text(msg.to.id, 'desChanged') else return 'ℹ️ '..lang_text(msg.to.id, 'desOnlyChannels') end else return '🚫 '..lang_text(msg.to.id, 'require_admin') end elseif matches[1] == 'muteall' and matches[2] then if permissions(msg.from.id, msg.to.id, "muteall") then print(1) local hash = 'muteall:'..msg.to.id redis:setex(hash, tonumber(matches[2]), true) print(2) return 'ℹ️ '..lang_text(msg.to.id, 'muteAllX:1')..' '..matches[2]..' '..lang_text(msg.to.id, 'muteAllX:2') else return '🚫 '..lang_text(msg.to.id, 'require_admin') end elseif matches[1] == 'muteall' then if permissions(msg.from.id, msg.to.id, "muteall") then local hash = 'muteall:'..msg.to.id redis:set(hash, true) return 'ℹ️ '..lang_text(msg.to.id, 'muteAll') else return '🚫 '..lang_text(msg.to.id, 'require_admin') end elseif matches[1] == 'unmuteall' then if permissions(msg.from.id, msg.to.id, "muteall") then local hash = 'muteall:'..msg.to.id redis:del(hash) return 'ℹ️ '..lang_text(msg.to.id, 'unmuteAll') else return '🚫 '..lang_text(msg.to.id, 'require_admin') end elseif matches[1] == 'creategroup' and matches[2] then if permissions(msg.from.id, msg.to.id, "creategroup") then group_name = matches[2] return create_group(msg, group_name) end elseif matches[1] == 'chat_created' and msg.from.id == 0 then return '🆕 '..lang_text(msg.to.id, 'newGroupWelcome') end end return { patterns = { '^#(settings)$', '^#(settings) (.*) (.*)$', '^#(rem)$', '^#(setname) (.*)$', '^#(setphoto)$', '^#(setphoto) (.*)$', '^#(muteall)$', '^#(muteall) (.*)$', '^#(unmuteall)$', '^#(link)$', "^#(tosupergroup)$", "^#(setdescription) (.*)$", '^#(setlink) (.*)$', '^#(lang) (.*)$', '^#(creategroup) (.*)$', '^!!tgservice (.+)$' }, pre_process = pre_process, run = run } end
gpl-2.0
alihbs/S_NAKE
plugins/owners.lua
284
12473
local function lock_group_namemod(msg, data, target) local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_namemod(msg, data, target) local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end local function lock_group_floodmod(msg, data, target) local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_floodmod(msg, data, target) local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end local function lock_group_membermod(msg, data, target) local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_membermod(msg, data, target) local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end local function unlock_group_photomod(msg, data, target) local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function show_group_settingsmod(msg, data, target) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX return text end local function set_rules(target, rules) local data = load_data(_config.moderation.data) local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end local function set_description(target, about) local data = load_data(_config.moderation.data) local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function run(msg, matches) if msg.to.type ~= 'chat' then local chat_id = matches[1] local receiver = get_receiver(msg) local data = load_data(_config.moderation.data) if matches[2] == 'ban' then local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) == tonumber(our_id) then return false end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't ban yourself" end ban_user(matches[3], matches[1]) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] banned user ".. matches[3]) return 'User '..user_id..' banned' end if matches[2] == 'unban' then if tonumber(matches[3]) == tonumber(our_id) then return false end local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't unban yourself" end local hash = 'banned:'..matches[1] redis:srem(hash, user_id) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unbanned user ".. matches[3]) return 'User '..user_id..' unbanned' end if matches[2] == 'kick' then local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) == tonumber(our_id) then return false end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't kick yourself" end kick_user(matches[3], matches[1]) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] kicked user ".. matches[3]) return 'User '..user_id..' kicked' end if matches[2] == 'clean' then if matches[3] == 'modlist' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end for k,v in pairs(data[tostring(matches[1])]['moderators']) do data[tostring(matches[1])]['moderators'][tostring(k)] = nil save_data(_config.moderation.data, data) end local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned modlist") end if matches[3] == 'rules' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local data_cat = 'rules' data[tostring(matches[1])][data_cat] = nil save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned rules") end if matches[3] == 'about' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local data_cat = 'description' data[tostring(matches[1])][data_cat] = nil save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned about") end end if matches[2] == "setflood" then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) < 5 or tonumber(matches[3]) > 20 then return "Wrong number,range is [5-20]" end local flood_max = matches[3] data[tostring(matches[1])]['settings']['flood_msg_max'] = flood_max save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] set flood to ["..matches[3].."]") return 'Group flood has been set to '..matches[3] end if matches[2] == 'lock' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local target = matches[1] if matches[3] == 'name' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] locked name ") return lock_group_namemod(msg, data, target) end if matches[3] == 'member' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end end if matches[2] == 'unlock' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local target = matches[1] if matches[3] == 'name' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unlocked name ") return unlock_group_namemod(msg, data, target) end if matches[3] == 'member' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end end if matches[2] == 'new' then if matches[3] == 'link' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local function callback (extra , success, result) local receiver = 'chat#'..matches[1] vardump(result) data[tostring(matches[1])]['settings']['set_link'] = result save_data(_config.moderation.data, data) return end local receiver = 'chat#'..matches[1] local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] revoked group link ") export_chat_link(receiver, callback, true) return "Created a new new link ! \n owner can get it by /owners "..matches[1].." get link" end end if matches[2] == 'get' then if matches[3] == 'link' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local group_link = data[tostring(matches[1])]['settings']['set_link'] if not group_link then return "Create a link using /newlink first !" end local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] requested group link ["..group_link.."]") return "Group link:\n"..group_link end end if matches[1] == 'changeabout' and matches[2] and is_owner2(msg.from.id, matches[2]) then local target = matches[2] local about = matches[3] local name = user_print_name(msg.from) savelog(matches[2], name.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]") return set_description(target, about) end if matches[1] == 'changerules' and is_owner2(msg.from.id, matches[2]) then local rules = matches[3] local target = matches[2] local name = user_print_name(msg.from) savelog(matches[2], name.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]") return set_rules(target, rules) end if matches[1] == 'changename' and is_owner2(msg.from.id, matches[2]) then local new_name = string.gsub(matches[3], '_', ' ') data[tostring(matches[2])]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(matches[2])]['settings']['set_name'] local to_rename = 'chat#id'..matches[2] local name = user_print_name(msg.from) savelog(matches[2], "Group {} name changed to [ "..new_name.." ] by "..name.." ["..msg.from.id.."]") rename_chat(to_rename, group_name_set, ok_cb, false) end if matches[1] == 'loggroup' and matches[2] and is_owner2(msg.from.id, matches[2]) then savelog(matches[2], "------") send_document("user#id".. msg.from.id,"./groups/"..matches[2].."log.txt", ok_cb, false) end end end return { patterns = { "^[!/]owners (%d+) ([^%s]+) (.*)$", "^[!/]owners (%d+) ([^%s]+)$", "^[!/](changeabout) (%d+) (.*)$", "^[!/](changerules) (%d+) (.*)$", "^[!/](changename) (%d+) (.*)$", "^[!/](loggroup) (%d+)$" }, run = run }
gpl-2.0
Godfather021/lion
plugins/rss.lua
731
1601
do -- Recursive function local function getRandomButts(attempt) attempt = attempt or 0 attempt = attempt + 1 local res,status = http.request("http://api.obutts.ru/noise/1") if status ~= 200 then return nil end local data = json:decode(res)[1] -- The OpenBoobs API sometimes returns an empty array if not data and attempt <= 3 then print('Cannot get that butts, trying another one...') return getRandomButts(attempt) end return 'http://media.obutts.ru/' .. data.preview end local function getRandomBoobs(attempt) attempt = attempt or 0 attempt = attempt + 1 local res,status = http.request("http://api.oboobs.ru/noise/1") if status ~= 200 then return nil end local data = json:decode(res)[1] -- The OpenBoobs API sometimes returns an empty array if not data and attempt < 10 then print('Cannot get that boobs, trying another one...') return getRandomBoobs(attempt) end return 'http://media.oboobs.ru/' .. data.preview end local function run(msg, matches) local url = nil if matches[1] == "!boobs" then url = getRandomBoobs() end if matches[1] == "!butts" then url = getRandomButts() end if url ~= nil then local receiver = get_receiver(msg) send_photo_from_url(receiver, url) else return 'Error getting boobs/butts for you, please try again later.' end end return { description = "Gets a random boobs or butts pic", usage = { "!boobs: Get a boobs NSFW image. 🔞", "!butts: Get a butts NSFW image. 🔞" }, patterns = { "^!boobs$", "^!butts$" }, run = run } end
gpl-2.0
dani-sj/mahandany
plugins/boobs.lua
731
1601
do -- Recursive function local function getRandomButts(attempt) attempt = attempt or 0 attempt = attempt + 1 local res,status = http.request("http://api.obutts.ru/noise/1") if status ~= 200 then return nil end local data = json:decode(res)[1] -- The OpenBoobs API sometimes returns an empty array if not data and attempt <= 3 then print('Cannot get that butts, trying another one...') return getRandomButts(attempt) end return 'http://media.obutts.ru/' .. data.preview end local function getRandomBoobs(attempt) attempt = attempt or 0 attempt = attempt + 1 local res,status = http.request("http://api.oboobs.ru/noise/1") if status ~= 200 then return nil end local data = json:decode(res)[1] -- The OpenBoobs API sometimes returns an empty array if not data and attempt < 10 then print('Cannot get that boobs, trying another one...') return getRandomBoobs(attempt) end return 'http://media.oboobs.ru/' .. data.preview end local function run(msg, matches) local url = nil if matches[1] == "!boobs" then url = getRandomBoobs() end if matches[1] == "!butts" then url = getRandomButts() end if url ~= nil then local receiver = get_receiver(msg) send_photo_from_url(receiver, url) else return 'Error getting boobs/butts for you, please try again later.' end end return { description = "Gets a random boobs or butts pic", usage = { "!boobs: Get a boobs NSFW image. 🔞", "!butts: Get a butts NSFW image. 🔞" }, patterns = { "^!boobs$", "^!butts$" }, run = run } end
gpl-2.0
disslove85/NOVA1-BOT
plugins/boobs.lua
731
1601
do -- Recursive function local function getRandomButts(attempt) attempt = attempt or 0 attempt = attempt + 1 local res,status = http.request("http://api.obutts.ru/noise/1") if status ~= 200 then return nil end local data = json:decode(res)[1] -- The OpenBoobs API sometimes returns an empty array if not data and attempt <= 3 then print('Cannot get that butts, trying another one...') return getRandomButts(attempt) end return 'http://media.obutts.ru/' .. data.preview end local function getRandomBoobs(attempt) attempt = attempt or 0 attempt = attempt + 1 local res,status = http.request("http://api.oboobs.ru/noise/1") if status ~= 200 then return nil end local data = json:decode(res)[1] -- The OpenBoobs API sometimes returns an empty array if not data and attempt < 10 then print('Cannot get that boobs, trying another one...') return getRandomBoobs(attempt) end return 'http://media.oboobs.ru/' .. data.preview end local function run(msg, matches) local url = nil if matches[1] == "!boobs" then url = getRandomBoobs() end if matches[1] == "!butts" then url = getRandomButts() end if url ~= nil then local receiver = get_receiver(msg) send_photo_from_url(receiver, url) else return 'Error getting boobs/butts for you, please try again later.' end end return { description = "Gets a random boobs or butts pic", usage = { "!boobs: Get a boobs NSFW image. 🔞", "!butts: Get a butts NSFW image. 🔞" }, patterns = { "^!boobs$", "^!butts$" }, run = run } end
gpl-2.0
taschemann/kq-lives
scripts/tower.lua
2
32325
-- tower - "Oracle's tower, southwest of mountain fort" -- /* -- { -- -- P_ORACLE: Spoke to Oracle in the Tower -- (0) Haven't spoken to her yet -- (1) She told you your quest, requested help from monsters -- (2) You helped with monsters (stopped them from getting to the portal) (not done) -- -- P_ORACLEMONSTERS: Status of the monsters in the caves below -- (0) You haven't even seen the monsters take the Statue thru the portal -- (1) Monsters thru portal: Haven't told Oracle about it -- (2) Monsters thru portal: Told Oracle about it -- (3) Followed monsters thru portal: monsters still in cave -- (4) Oracle asks you to take care of monsters; they're still there -- (5) Monsters are gone (not done) -- -- P_FTOTAL: Total number of floor switches activated -- P_FLOOR1..P_FLOOR4: Status of this floor switch -- Hint: press bottom left and top right. -- -- SI_BSTONES: # of Black stones in your inventory -- SI_WSTONES: # of White stones in your inventory -- P_STONE1..P_STONE4: Whether this stone is in your inventory -- P_WALL1..P_WALL4: Which stone (if any) is in this wall slot -- Hint: Stones should be placed in the holes in this order -- from left to right: black, white, white, black. -- -- P_DOOROPEN: (4: Single treasure, left floor switch) -- P_DOOROPEN2: (3: Treasure room, bottom) -- P_TREASUREROOM: (3: Treasure room, top) -- -- P_TOWEROPEN: Whether you can return and talk to the Oracle -- (0) Never spoke to Oracle, cannot enter Tower -- (1) Never spoke to Oracle, can enter Tower -- (2) Spoke to Oracle, cannot enter Tower -- (3) Spoke to Oracle, can enter Tower (not done) -- -- P_DRAGONDOWN: Whether the stone dragon is alive or not -- -- P_DENORIAN: Status of the Denorian statue -- (0) You have not spoken to the Dville town council -- (1) If you refused to help the Denorians -- (2) You've agreed to help: haven't found Demnas -- (3) You found Demnas: haven't found the troll -- (4) You found the troll -- (5) Broken statue returned to the Denorians -- (6) 2nd half of broken statue returned to Denorians (not done) -- -- still need to complete P_ORACLE and P_ORACLEMONSTERS -- } -- */ function autoexec() refresh() end function entity_handler(en) local x, y -- Oracle if (en == 0) then -- /* -- { -- When you talk to the Oracle, she will discuss the following situations with you: -- 1: Civil war in the goblin lands from the missing OracleStatue -- 2: Monsters are trying to get into the TravelPoint -- These are actually all related, but she does not know that; she suspects as much, though -- -- P_ORACLE: Spoke to Oracle in the Tower -- (0) Have not spoken to her yet -- (1) Spoke to her; she requested help from monsters -- (2) You helped with monsters (stopped them from getting to the portal) -- -- P_ORACLEMONSTERS: Status of the monsters in the caves below -- (0) You haven't seen the monsters take the Statue thru the portal -- (1) Monsters thru portal: Have not told Oracle about it yet -- (2) Monsters thru portal: Told Oracle about it -- (3) Followed monsters thru portal: monsters still in cave -- (4) Oracle asks you to take care of monsters; they're still there -- (5) Monsters are gone -- -- P_DENORIAN: Status of the stolen statue -- (0) You have not spoken to the Dville town council -- (1) If you refused to help the Denorians -- (2) You've agreed to help: haven't found Demnas -- (3) You found Demnas: haven't found the troll -- (4) You found the troll -- (5) Broken statue returned to the Denorians -- (6) 2nd half of broken statue returned to Denorians -- } -- */ if (get_progress(P_ORACLEMONSTERS) == 0) then -- 0: // You haven't seen the monsters take the Statue thru the portal if (get_progress(P_ORACLE) == 0) then bubble(en, _"$0, thank you for coming.") if (get_numchrs() == 1) then bubble(HERO1, _"Hello, um... Oracle. How did you know I was coming?") else bubble(HERO1, _"Hello, um... Oracle. How did you know we were coming?") end bubble(en, _"Tsorin sent a messenger here, of course.") bubble(en, _"I'm surprised that you came up to see me, seeing as how the TravelPoint is back in the caves from whence you came.") if (get_progress(P_DENORIAN) == 0) then -- 0: // Haven't spoken to Denorian Council, so know nothing about -- // where to look. bubble(en, _"I am glad you stopped by, though. There is civil unrest in the goblin lands to the south.") bubble(en, _"The Statue, which I gave to the Denorians as a gift, has been stolen. Because of that, there is much unrest.") if (get_numchrs() == 1) then bubble(HERO1, _"I am a bit hurried in my quest to find... well, something of importance.") else bubble(HERO1, _"We are a bit hurried in our quest to find... well...") bubble(HERO2, _"To find, um... something of importance.") end bubble(en, _"Yes, but would you consider helping my people find their missing Statue?") if (prompt(en, 2, 1, "Anything you can do would", "help.", " yes", " no") == 0) then bubble(en, _"Thank you so much. Please talk to the head of the Denorian Council to find out more information.") else bubble(en, _"That is too bad. But if you would like to help in the future, please talk to the head of the Denorian Council.") end bubble(en, _"The Denorian village is south of here, by the mountain stream.") elseif (get_progress(P_DENORIAN) == 1) then -- 1: // You refused the Denorian's plea and were kicked out of town bubble(en, _"I am glad you stopped by, though. There is civil unrest in the goblin lands to the south.") if (get_numchrs() == 1) then bubble(HERO1, _"Yes, I know. The Denorian Council told me about the missing statue.") else bubble(HERO1, _"Yes, we know. The Denorian Council told us about the missing statue.") end bubble(en, _"Oh! So you've agreed to help?") bubble(HERO1, _"Well ...mumble... no...") if (get_numchrs() == 1) then bubble(HERO1, _"I am a bit hurried in my quest to find... well, something of importance.") else bubble(HERO2, _"Not exactly...") bubble(HERO1, _"We are a bit hurried in our quest to find... well, something of importance.") end bubble(en, _"Oh, I see. Your quest must be very important, then. Very well, I shall ask someone else.") elseif (get_progress(P_DENORIAN) == 2) then -- 2: // You told the Denorian Council you would help (haven't found -- // anything yet) bubble(en, _"I am glad you stopped by, though. There is civil unrest in the goblin lands to the south.") if (get_numchrs() == 1) then bubble(HERO1, _"Yes, I know. The Denorian Council told me about the missing statue but I haven't found anything yet.") else bubble(HERO1, _"Yes, we know. The Denorian Council told us about the missing statue.") bubble(HERO2, _"We haven't found anything yet, however.") end bubble(en, _"Don't worry; I'm sure you'll find something. Good luck to you!") elseif (get_progress(P_DENORIAN) == 3) then -- 3: // You found Demnas (but not the troll), but didn't report it -- // to the Denorians; you still have the the broken statue with -- // you. bubble(en, _"I am glad you stopped by, though. I hear some of the civil unrest in the goblin lands has let up somewhat.") bubble(HERO1, _"Yes, a Narakian named Demnas supposedly stole the missing statue.") bubble(en, _"And did you get the statue back?") bubble(HERO1, _"Well, only half of it. It seems it was broken in half before we ever got to it.") if (get_numchrs() == 1) then bubble(en, _"Which means someone may still have it.") else bubble(HERO2, _"Which means someone probably still has it.") end bubble(en, _"Could you do me a favor?") if (prompt(en, 2, 0, "Could you find out who has", "the other half of the statue?", " yes", " no") == 0) then bubble(en, _"Thank you so very much.") else bubble(en, _"Well, that's alright. You've done enough already. Thank you so very much.") end elseif (get_progress(P_DENORIAN) == 4) then -- 4: You found the troll, too, but you did not return the broken -- statue to the Denorians. You still have it with you. bubble(en, _"I am glad you stopped by, though. I hear...") bubble(en, _"...wait!", "What is that statue you have there?") if (get_numchrs() == 1) then bubble(HERO1, _"This is the Denorian Statue. I rescued it from a guy named Demnas and his troll.") else bubble(HERO1, _"This is the Denorian Statue. We rescued it from a guy named Demnas and his troll.") end bubble(en, _"So you did... What happened to it? Part of it is missing.") if (get_progress(P_TALK_CORIN) == 0) then -- // You fought the troll but didn't talk to Corin, so still -- // don't know about Malkaron. Which was stupid, since he was -- // standing RIGHT THERE. if (get_numchrs() == 1) then bubble(HERO1, _"I'm not too sure. He accused me of trying to steal the second half of it from him.") else bubble(HERO2, _"We're not too sure. He accused us of trying to steal the second half of it from him.") end bubble(en, _"Second half? It sounds as if someone else may have gotten to him first.") if (get_numchrs() == 1) then bubble(HERO1, _"That's what I think as well.") else bubble(HERO2, _"That's what we think as well.") end bubble(en, _"Well, either way, if you could return that half back to the Denorian village, it will help with the unrest.") else -- // You fought the troll and Corin told you about Malkaron's -- // army stealing the statue. bubble(HERO1, _"It was Malkaron's armies. They had a spat with Demnas and when the statue broke, they stole half of it.") if (get_pidx(0) == CORIN) then bubble(HERO1, _"Demnas thought I was with them and locked me in with a troll.") else bubble(HERO1, _"Demnas thought CORIN was with them and locked him in with a troll.") end bubble(en, _"Oh, how awful!") bubble(HERO1, _"It's alright. Everything worked out. But now we have to consider Malkaron's involvement in this.") bubble(en, _"Yes, I certainly hope you get to the bottom of this.") bubble(en, _"Would you return the statue to the Denorian village? It is a very important treasure.") end elseif (get_progress(P_DENORIAN) == 5) then -- 5: The broken statue was returned to the village bubble(en, _"I am glad you stopped by. The Denorians sent word that you returned part of their statue.") bubble(HERO1, _"Yea, well, someone had to do something about that whole mess...") if (get_progress(P_TALK_CORIN) == 0) then bubble(en, _"An important question is, who has the other half?") if (get_numchrs() == 1) then bubble(HERO1, _"That's a good question. I'm searching for the same person... or persons, for that matter.") else bubble(HERO1, _"That's a good question. We're searching for the same person.") bubble(HERO2, _"Or persons, for that matter.") end bubble(en, _"Be careful. Whoever is out there may do rash and unpredictable things if he thinks you are following him.") else bubble(en, _"An important question is, what will we do about Malkaron's followers?") if (get_numchrs() == 1) then bubble(HERO1, _"That's actually what I'm trying to find out.") else bubble(HERO1, _"That's actually what we're trying to find out.") end bubble(en, _"If Malkaron is responsible for all this upheaval, you must be careful.") bubble(en, _"One as strong as he may do rash and unpredictable things if he thinks you are following him.") end if (get_numchrs() == 1) then bubble(HERO1, _"Yes, I was warned to keep my party small.") else bubble(HERO1, _"Yes, we were warned to keep our numbers small. That's why we're traveling in a party of only two.") end bubble(en, _"Well, I wish you luck. Thank you for all you've done already.") elseif (get_progress(P_DENORIAN) == 6) then -- 6: // We can't get here with P_ORACLEMONSTERS == 0, as the player -- // would have seen Malkaron's men take the statue thru the -- // portal already. end set_autoparty(1) move_entity(HERO1, "oracle", 0) if (get_numchrs() == 1) then wait_for_entity(HERO1, HERO1) bubble(HERO1, _"This whole thing sure seems fishy. I hope I can figure out what's going on.") bubble(HERO1, _"I wonder if this statue has anything to do with this missing staff Nostik wants everyone to find?") set_ent_facing(HERO1, FACE_DOWN) drawmap() screen_dump() bubble(HERO1, _"...I should probably stop talking to myself too.") elseif (get_numchrs() == 2) then x, y = marker("oracle") move_entity(HERO2, x, y + 1, 0) wait_for_entity(HERO1, HERO2) orient_heroes() bubble(HERO2, _"Hey $0.") set_ent_facing(HERO1, FACE_DOWN) bubble(HERO1, _"Yeah?") bubble(HERO2, _"Do you think that this statue could have something to with this missing staff Nostik wants us to find?") bubble(HERO1, _"Whoa, $1. Keep your voice down!") bubble(HERO2, _"Oh, right. Sorry.") bubble(HERO2, _"So... do you?") bubble(HERO1, _"I never thought of that. Let's hope that it doesn't. We have no choice but to go on anyways.") bubble(HERO2, _"Yeah, I guess you're right. Let's go.") end bubble(en, _"Oh, one last thing. I have a request of you before you go.") if (get_numchrs() == 2) then set_ent_facing(HERO2, FACE_DOWN) end bubble(en, _"If you can, please get rid of the monsters in the caves below. You can also use my TravelPoint in the caves as well.") bubble(en, _"Good luck. I hope to meet with you again.") set_autoparty(0) set_progress(P_ORACLE, 1) elseif (get_progress(P_ORACLE) == 1) then bubble(en, _"The monsters in the caves below appeared out of nowhere. Please get rid of them so travelers who wish to use my TravelPoint may do so.") else -- We will never get P_ORACLE > 1 here since P_ORACLEMONSTERS will -- modify that separately. end elseif (get_progress(P_ORACLEMONSTERS) == 1) then -- 1: // Regardless of the status of P_ORACLE, you will tell her of -- // Malkaron's monsters with the statue. if (get_progress(P_DENORIAN) == 0) then -- // You don't know what's going on with the Oracle's statue if (get_numchrs() == 1) then bubble(HERO1, _"Oracle! I saw Malkaron's monsters take some statue that looked like you through the portal below!") bubble(HERO1, _"At least, it looked like part of a statue, anyway.") else bubble(HERO2, _"Oracle! We saw Malkaron's monsters take some statue that looked like you through the portal below!") bubble(HERO1, _"At least, it looked like part of a statue, anyway.") end bubble(en, _"That must have been the Denorian's statue; that has been stolen from the village to the south.") else -- // You know that the Oracle's statue had been stolen so you know to -- // tell the Oracle if (get_numchrs() == 1) then bubble(HERO1, _"Oracle! I saw Malkaron's monsters take the stolen statue through the portal below!") else bubble(HERO1, _"Oracle! We saw Malkaron's monsters take your statue through the portal below!") end end bubble(en, _"You must go after it! That statue is very important to my people.") set_progress(P_ORACLEMONSTERS, 2) elseif (get_progress(P_ORACLEMONSTERS) == 2) then -- 2: // You told the Oracle about the monsters going thru the portal bubble(en, _"Please hurry and get that statue back!") elseif (get_progress(P_ORACLEMONSTERS) == 3) then -- 3: // Followed Malkaron's men thru portal; monsters still in cave bubble(en, _"Welcome back.") bubble(HERO1, _"Oracle! The monsters went through the portal below with your statue!") if (get_numchrs() == 1) then bubble(HERO1, _"I went through the portal, but was sent to Maldea somehow.") else bubble(HERO1, _"We went through the portal, but were was sent to Maldea somehow.") end bubble(en, _"Yes, the statue probably disrupted the portal somehow. I'm glad to see you made it back safely.") if (get_progress(P_ORACLE) == 0) then bubble(en, _"I ask you to find the missing statue, if you possibly can.") else bubble(en, _"Please continue your search for the statue. It is very important to my people.") end bubble(en, _"And would you be able to take care of the monsters in the caves below?") set_progress(P_ORACLEMONSTERS, 4) elseif (get_progress(P_ORACLEMONSTERS) == 4) then -- 4: // Oracle asked you to take care of monsters; they're still there bubble(en, _"I thank you for looking into the missing statue situation.") bubble(en, _"There are still monsters lurking around in the caves below. Please get rid of them.") elseif (get_progress(P_ORACLEMONSTERS) == 5) then -- 5: // Monsters are gone bubble(en, _"The monsters are gone! Thank you so much!") end end end function postexec() return end function refresh() local x, y showch("treasure1", 33) showch("treasure2", 34) showch("treasure3", 35) showch("treasure4", 36) showch("treasure5", 37) showch("treasure6", 38) showch("treasure7", 39) showch("treasure8", 40) showch("treasure9", 41) showch("treasure10", 42) showch("treasure11", 43) showch("treasure12", 44) -- Dragon guard (1: Main entrance) LOC_draw_dragon() -- Floor switches (2: Floor switches) LOC_set_floor("floor1", P_FLOOR1, "floor1a", "floor1b") LOC_set_floor("floor2", P_FLOOR2, "floor2a", "floor2b") LOC_set_floor("floor3", P_FLOOR3, "floor3a", "floor3b") LOC_set_floor("floor4", P_FLOOR4, "floor4a", "floor4b") -- Wall holes (3: Treasure room, top left) LOC_set_wall("wall1", P_WALL1) LOC_set_wall("wall2", P_WALL2) LOC_set_wall("wall3", P_WALL3) LOC_set_wall("wall4", P_WALL4) -- Door (3: Treasure room, top) LOC_set_door("door3_1", P_TREASUREROOM, 40) -- Door (3: Treasure room, bottom) LOC_set_door("door3_2", P_DOOROPEN2, 10) -- Door (4: Single treasure, left floor switch) if (get_progress(P_DOOROPEN) == 1) then x, y = marker("switch") set_btile(x, y, 190) set_btile(x + 1, y, 189) else x, y = marker("switch") set_btile(x, y, 189) set_btile(x + 1, y, 190) end LOC_set_door("door4", P_DOOROPEN, 10) -- Black stone (1: Main entrance, right) -- LOC_get_stone("stone1", P_STONE1, 20, 222) -- White stone (2: Floor switches, bottom left) -- LOC_get_stone("stone2", P_STONE2, 21, 221) -- White stone (3: Treasure room, top right) -- LOC_get_stone("stone3", P_STONE3, 22, 221) -- Black stone (4: Single treasure, treasure chest) if (get_progress(P_STONE4) == 1) then showch("stone4", -1) end end -- Show the status of a chest function showch(which_marker, which_chest) -- Set tiles if -1 passed in as 'which_chest' or if chest already opened if (which_chest < 0 or get_treasure(which_chest) == 1) then set_mtile(which_marker, 65) set_zone(which_marker, 0) end end function zone_handler(zn) -- Combat can be anywhere that other zones do not populate if (zn == 0) then combat(54) -- Front doors (1: Main entrance) elseif (zn == 1) then if (get_progress(P_ORACLE) > 0) then set_progress(P_TOWEROPEN, 2) end LOC_reset_progress() change_map("main", "tower") -- Stairs up (1: Main entrance -> 2: Floor switches) elseif (zn == 2) then warp("dstairs2", 8) -- Stairs down (2: Floor switches -> 1: Main Entrance) elseif (zn == 3) then warp("ustairs1", 8) -- Stairs up (2: Floor switches -> 3: Treasure room) elseif (zn == 4) then warp("dstairs3", 8) -- Stairs down (3: Treasure room -> 2: Floor switches) elseif (zn == 5) then warp("ustairs2", 8) -- Stairs up (3: Treasure room -> 4: Single treasure) elseif (zn == 6) then warp("dstairs4", 8) -- Stairs down (4: Single treasure -> 3: Treasure room) elseif (zn == 7) then warp("ustairs3", 8) -- Stairs up (4: Single treasure -> 5: Oracle room) elseif (zn == 8) then warp("dstairs5", 8) -- Stairs down (5: Oracle room -> 4: Single treasure) elseif (zn == 9) then warp("ustairs4", 8) -- Locked doors (3: Treasure room) or (4: Single treasure) elseif (zn == 10) then bubble(HERO1, _"Locked.") -- Oracle bookshelves (5: Oracle room) elseif (zn == 11) then bubble(HERO1, _"Wow! There are a lot of strange books here.") -- Floor switch (2: Floor switches, top left) elseif (zn == 12) then LOC_floor_switch(P_FLOOR1) -- Floor switch (2: Floor switches, top right) elseif (zn == 13) then LOC_floor_switch(P_FLOOR3) -- Floor switch (2: Floor switches, bottom left) elseif (zn == 14) then LOC_floor_switch(P_FLOOR2) -- Floor switch (2: Floor switches, bottom right) elseif (zn == 15) then LOC_floor_switch(P_FLOOR4) -- Wall switch (3: Treasure room, top left) elseif (zn == 16) then LOC_stoner("wall1", P_WALL1) -- Wall switch (3: Treasure room, top right) elseif (zn == 17) then LOC_stoner("wall2", P_WALL2) -- Wall switch (3: Treasure room, bottom left) elseif (zn == 18) then LOC_stoner("wall3", P_WALL3) -- Wall switch (3: Treasure room, bottom right) elseif (zn == 19) then LOC_stoner("wall4", P_WALL4) -- Black stone (1: Main entrance, right) elseif (zn == 20) then if (get_progress(P_STONE1) == 0) then set_progress(P_STONE1, 1) add_special_item(SI_BLACKSTONE) sfx(5) msg(_"Black Stone procured!", 15, 0) LOC_get_stone("stone1", P_STONE1, 20, 222) end -- White stone (2: Floor switches, bottom left) elseif (zn == 21) then if (get_progress(P_STONE2) == 0) then set_progress(P_STONE2, 1) add_special_item(SI_WHITESTONE) sfx(5) msg(_"White Stone procured!", 15, 0) LOC_get_stone("stone2", P_STONE2, 21, 221) end -- White stone (3: Treasure room) elseif (zn == 22) then if (get_progress(P_STONE3) == 0) then set_progress(P_STONE3, 1) add_special_item(SI_WHITESTONE) sfx(5) msg(_"White Stone procured!", 15, 0) LOC_get_stone("stone3", P_STONE3, 22, 221) end -- Treasure chest (4: Single treasure) elseif (zn == 23) then if (get_progress(P_STONE4) == 0) then set_progress(P_STONE4, 1) add_special_item(SI_BLACKSTONE) sfx(5) msg(_"Black Stone procured!", 15, 0) refresh() end -- Floor switch (4: Single treasure, left) elseif (zn == 24) then if (get_progress(P_DOOROPEN) == 0) then set_progress(P_DOOROPEN, 1) LOC_set_door("door4", P_DOOROPEN, 10) refresh() end -- Floor switch (4: Single treasure, right) elseif (zn == 25) then if (get_progress(P_DOOROPEN) == 1) then set_progress(P_DOOROPEN, 0) sfx(26) refresh() end -- Floor switch (5: Oracle room, left) elseif (zn == 26) then if (get_progress(P_DOOROPEN2) == 0) then bubble(HERO1, _"Oh! I think I stepped on a switch!") set_progress(P_DOOROPEN2, 1) LOC_set_door("door3_2", P_DOOROPEN2, 10) refresh() end -- Treasure chest (3: Treasure room) elseif (zn == 27) then chest(33, I_PCURING, 1) refresh() -- Treasure chest (3: Treasure room) elseif (zn == 28) then chest(34, I_LTONIC, 1) refresh() -- Treasure chest (3: Treasure room) elseif (zn == 29) then chest(35, I_SPEEDBOOTS, 1) refresh() -- Treasure chest (3: Treasure room) elseif (zn == 30) then chest(36, I_SWORD3, 1) refresh() -- Treasure chest (3: Treasure room) elseif (zn == 31) then chest(37, I_ROBE3, 1) refresh() -- Treasure chest (3: Treasure room) elseif (zn == 32) then chest(38, 0, 400) refresh() -- Treasure chest (3: Treasure room) elseif (zn == 33) then chest(39, I_B_WHIRLWIND, 1) refresh() -- Treasure chest (3: Treasure room) elseif (zn == 34) then chest(40, I_EDAENRA, 1) refresh() -- Treasure chest (3: Treasure room) elseif (zn == 35) then chest(41, I_SSTONE, 1) refresh() -- Treasure chest (3: Treasure room) elseif (zn == 36) then chest(42, I_MESRA, 1) refresh() -- Treasure chest (3: Treasure room) elseif (zn == 37) then chest(43, I_STAFF2, 1) refresh() -- Treasure chest (3: Treasure room) elseif (zn == 38) then chest(44, I_GAUNTLET2, 1) refresh() -- Fire (5: Oracle room) elseif (zn == 39) then touch_fire(party[0]) -- Locked door (3: Treasure room) elseif (zn == 40) then if (get_progress(P_WALL1) == 1 and get_progress(P_WALL2) == 2 and get_progress(P_WALL3) == 2 and get_progress(P_WALL4) == 1) then set_progress(P_TREASUREROOM, 1) LOC_set_door("door3_1", P_TREASUREROOM, 40) refresh() end -- zn == 41: no enemies attack (3: Treasure room, 5: Oracle room) -- Guardian Dragon (1: Main entrance) elseif (zn == 42) then if (get_progress(P_DRAGONDOWN) == 0) then bubble(255, _"The Oracle is not to be disturbed!") drawmap() screen_dump() set_run(0) combat(55) set_run(1) if (get_alldead() == 0) then set_progress(P_DRAGONDOWN, 1) LOC_draw_dragon() else return end end -- Save spot (5: Oracle room) elseif (zn == 43) then set_save(1) set_sstone(1) sfx(7) -- Off of Save spot (5: Oracle room) elseif (zn == 44) then set_save(0) set_sstone(0) end end function LOC_draw_dragon() local a local x, y = marker("dragon") if (get_progress(P_DRAGONDOWN) == 0) then -- Dragon icon tile (223..228) in the for..loop below: local b = 223 for a = x, x + 2, 1 do set_ftile(a, y - 2, b) set_ftile(a, y - 1, b + 3) b = b + 1 end -- Dragon icon tile (229..230) in the for..loop below: b = 229 for a = x, x + 1, 1 do set_btile(a, y, b) set_obs(a, y, 1) set_zone(a, y, 42) b = b + 1 end elseif (get_progress(P_DRAGONDOWN) == 1) then for a = x, x + 2, 1 do set_ftile(a, y - 2, 0) set_ftile(a, y - 1, 0) end for a = x, x + 1, 1 do set_btile(a, y, 160) set_obs(a, y, 0) set_zone(a, y, 0) end end end function LOC_floor_switch(p_floor) if (get_progress(p_floor) == 0) then if (get_progress(P_FTOTAL) < 2) then set_progress(p_floor, 1) set_progress(P_FTOTAL, get_progress(P_FTOTAL) + 1) end else set_progress(p_floor, 0) set_progress(P_FTOTAL, get_progress(P_FTOTAL) - 1) end refresh() end function LOC_get_stone(stone, p_stone, zone, color) local x, y = marker(stone) if (get_progress(p_stone) == 0) then set_ftile(x, y, color) set_zone(x, y, zone) set_obs(x, y, 1) return elseif (get_progress(p_stone) == 1) then set_ftile(x, y, 0) set_zone(x, y, 0) set_obs(x, y, 0) return end end function LOC_reset_progress() -- Reset the Black and White stones on the ground set_progress(P_STONE1, 0) set_progress(P_STONE2, 0) set_progress(P_STONE3, 0) set_progress(P_STONE4, 0) remove_special_item(SI_BLACKSTONE) remove_special_item(SI_WHITESTONE) -- Reset the stones located in the walls set_progress(P_WALL1, 0) set_progress(P_WALL2, 0) set_progress(P_WALL3, 0) set_progress(P_WALL4, 0) -- Close the open-by-switch doors set_progress(P_DOOROPEN, 0) set_progress(P_DOOROPEN2, 0) set_progress(P_TREASUREROOM, 0) -- Reset the holes on the 2nd floor set_progress(P_FTOTAL, 0) set_progress(P_FLOOR1, 0) set_progress(P_FLOOR2, 0) set_progress(P_FLOOR3, 0) set_progress(P_FLOOR4, 0) end function LOC_set_door(door, p_door, zone) local x, y = marker(door) if (get_progress(p_door) == 0) then set_ftile(x, y - 1, 169) set_btile(x, y - 1, 178) set_btile(x, y, 170) set_obs(x, y - 1, 1) set_zone(x, y - 1, zone) else set_ftile(x, y - 1, 175) set_btile(x, y, 176) set_obs(x, y - 1, 0) set_zone(x, y - 1, 0) end sfx(26) end function LOC_set_floor(floor, p_floor, floor_a, floor_b) local x, y = marker(floor) local x1, y1 = marker(floor_a) local x2, y2 = marker(floor_b) if (get_progress(p_floor) == 0) then set_btile(x, y, 189) set_btile(x1, y1, 0) set_obs(x1, y1, 1) set_btile(x2, y2, 0) set_obs(x2, y2, 1) else set_btile(x, y, 190) set_btile(x1, y1, 160) set_obs(x1, y1, 0) set_btile(x2, y2, 160) set_obs(x2, y2, 0) end sfx(26) end function LOC_set_wall(wall, p_wall) local x, y = marker(wall) if (get_progress(p_wall) == 0) then set_ftile(x, y, 220) -- No stone elseif (get_progress(p_wall) == 1) then set_ftile(x, y, 222) -- White stone elseif (get_progress(p_wall) == 2) then set_ftile(x, y, 221) -- Black stone end end function LOC_stoner(wall, p_wall) if (get_progress(p_wall) == 0) then -- No stones picked up if (not has_special_item(SI_BLACKSTONE) and not has_special_item(SI_WHITESTONE)) then return end -- Black stones picked up but no White stones if (has_special_item(SI_BLACKSTONE) and not has_special_item(SI_WHITESTONE)) then set_progress(p_wall, 1) add_special_item(SI_BLACKSTONE, -1) sfx(5) LOC_set_wall(wall, p_wall) return end -- White stones picked up but no Black stones if (not has_special_item(SI_BLACKSTONE) and has_special_item(SI_WHITESTONE)) then set_progress(p_wall, 2) add_special_item(SI_WHITESTONE, -1) -- remove 1 white stone sfx(5) LOC_set_wall(wall, p_wall) return end -- At least one of each color stone picked up if (prompt(255, 2, 0, _"What stone will you place?", _" black", _" white") == 0) then set_progress(p_wall, 1) add_special_item(SI_BLACKSTONE, -1) sfx(5) LOC_set_wall(wall, p_wall) return else set_progress(p_wall, 2) add_special_item(SI_WHITESTONE, -1) sfx(5) LOC_set_wall(wall, p_wall) return end else -- Actually, this is already implicitly true if ((get_progress(p_wall) ~= 0) and (get_progress(P_TREASUREROOM) == 0)) then if (get_progress(p_wall) == 1) then -- Remove a White stone set_progress(p_wall, 0) add_special_item(SI_BLACKSTONE) sfx(4) LOC_set_wall(wall, p_wall) elseif (get_progress(p_wall) == 2) then -- Remove a Black stone set_progress(p_wall, 0) add_special_item(SI_WHITESTONE) LOC_set_wall(wall, p_wall) return end end end end
gpl-2.0
gedads/Neodynamis
scripts/globals/items/cup_of_choco-delight.lua
12
1151
----------------------------------------- -- ID: 4283 -- Item: cup_of_choco-delight -- Food Effect: 240Min, All Races ----------------------------------------- -- Magic Regen While Healing 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,14400,4283); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MPHEAL, 5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MPHEAL, 5); end;
gpl-3.0
starlightknight/darkstar
scripts/zones/Windurst_Woods/npcs/Umumu.lua
9
2411
----------------------------------- -- Area: Windurst Woods -- NPC: Umumu -- Involved In Quest: Making Headlines -- !pos 32.575 -5.250 141.372 241 ----------------------------------- local ID = require("scripts/zones/Windurst_Woods/IDs") require("scripts/globals/quests") require("scripts/globals/titles") ----------------------------------- function onTrade(player,npc,trade) end function onTrigger(player,npc) function testflag(set,flag) return (set % (2*flag) >= flag) end local MakingHeadlines = player:getQuestStatus(WINDURST,dsp.quest.id.windurst.MAKING_HEADLINES) local WildcatWindurst = player:getCharVar("WildcatWindurst") if player:getQuestStatus(WINDURST,dsp.quest.id.windurst.LURE_OF_THE_WILDCAT) == QUEST_ACCEPTED and not player:getMaskBit(WildcatWindurst,3) then player:startEvent(731) elseif MakingHeadlines == 1 then local prog = player:getCharVar("QuestMakingHeadlines_var") -- Variable to track if player has talked to 4 NPCs and a door -- 1 = Kyume -- 2 = Yujuju -- 4 = Hiwom -- 8 = Umumu -- 16 = Mahogany Door if testflag(tonumber(prog),16) then player:startEvent(383) -- Advised to go to Naiko elseif not testflag(tonumber(prog),8) then player:startEvent(381) -- Get scoop and asked to validate else player:startEvent(382) -- Reminded to validate end elseif MakingHeadlines == 2 then local rand = math.random(1,3) if rand == 1 then player:startEvent(385) -- Conversation after quest completed elseif rand == 2 then player:startEvent(386) -- Conversation after quest completed elseif rand == 3 then player:startEvent(414) -- Standard Conversation end else player:startEvent(414) -- Standard Conversation end end function onEventUpdate(player,csid,option) end function onEventFinish(player,csid,option) if csid == 381 then local prog = player:getCharVar("QuestMakingHeadlines_var") player:addKeyItem(dsp.ki.WINDURST_WOODS_SCOOP) player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.WINDURST_WOODS_SCOOP) player:setCharVar("QuestMakingHeadlines_var",prog+8) elseif csid == 731 then player:setMaskBit(player:getCharVar("WildcatWindurst"),"WildcatWindurst",3,true) end end
gpl-3.0
gedads/Neodynamis
scripts/zones/Caedarva_Mire/npcs/qm12.lua
3
2027
----------------------------------- -- Area: Caedarva Mire -- NPC: ??? -- !pos 456.993 -7.000 -270.815 79 ----------------------------------- package.loaded["scripts/zones/Caedarva_Mire/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/zones/Caedarva_Mire/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local notMeantToBeProg = player:getVar("notmeanttobeCS"); if (notMeantToBeProg == 1) then player:startEvent(0x0010); elseif (player:getQuestStatus(AHT_URHGAN,NOT_MEANT_TO_BE) == QUEST_ACCEPTED and notMeantToBeProg == 3) then player:startEvent(0x0011); elseif (player:getVar("notmeanttobeMoshdahnKilled") == 1 and player:getVar("notmeanttobeLamia27Killed") == 1) then player:startEvent(0x0012); else player:messageSpecial(NOTHING_HAPPENS); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0010) then player:setVar("notmeanttobeCS",2); elseif (csid == 0x0011) then if (GetMobAction(17101149) == 0 and GetMobAction(17101148) == 0) then SpawnMob(17101149):updateClaim(player); SpawnMob(17101148):updateClaim(player); end elseif (csid == 0x0012) then player:setVar("notmeanttobeMoshdahnKilled",0); player:setVar("notmeanttobeLamia27Killed",0); player:setVar("notmeanttobeCS",5); end end;
gpl-3.0
RememberTheAir/GroupButler
lua/groupbutler/plugins/setlang.lua
1
2272
local config = require "groupbutler.config" local _M = {} function _M:new(update_obj) local plugin_obj = {} setmetatable(plugin_obj, {__index = self}) for k, v in pairs(update_obj) do plugin_obj[k] = v end return plugin_obj end local function doKeyboard_lang() local keyboard = { inline_keyboard = {} } for lang, flag in pairs(config.available_languages) do local line = {{text = flag, callback_data = 'langselected:'..lang}} table.insert(keyboard.inline_keyboard, line) end return keyboard end function _M:onTextMessage() local api = self.api local msg = self.message local i18n = self.i18n if msg.from.chat.type == "private" or msg.from:can("can_change_info") then local keyboard = doKeyboard_lang() api:sendMessage(msg.from.chat.id, i18n("*List of available languages*:"), "Markdown", nil, nil, nil, keyboard) end end function _M:onCallbackQuery(blocks) local api = self.api local msg = self.message local red = self.red local i18n = self.i18n if msg.from.chat.type ~= "private" and not msg.from:isAdmin() then api:answerCallbackQuery(msg.cb_id, i18n("Sorry, you don't have permission to change settings")) return end if blocks[1] == "selectlang" then local keyboard = doKeyboard_lang() api:editMessageText(msg.from.chat.id, msg.message_id, nil, i18n("*List of available languages*:"), "Markdown", nil, keyboard) return end i18n:setLanguage(blocks[1]) red:set("lang:"..msg.from.chat.id, i18n:getLanguage()) if msg.from.chat.type ~= "private" and (blocks[1] == "ar_SA" or blocks[1] == "fa_IR") then red:hset("chat:"..msg.from.chat.id..":char", "Arab", "allowed") red:hset("chat:"..msg.from.chat.id..":char", "Rtl", "allowed") end -- TRANSLATORS: replace 'English' with the name of your language api:editMessageText(msg.from.chat.id, msg.message_id, nil, i18n("English language is *set*")..i18n([[. Please note that translators are volunteers, and this localization _may be incomplete_. You can help improve translations on our [Crowdin Project](https://crowdin.com/project/group-butler). ]]), "Markdown") end _M.triggers = { onTextMessage = {config.cmd..'(lang)$'}, onCallbackQuery = { '^###cb:(selectlang)', '^###cb:langselected:(%l%l)$', '^###cb:langselected:(%l%l_%u%u)$' } } return _M
gpl-2.0
gedads/Neodynamis
scripts/globals/items/choco-ligar.lua
12
1197
----------------------------------------- -- ID: 5919 -- Item: Choco-ligar -- Food Effect: 3 Min, All Races ----------------------------------------- -- Vitality 1 -- Speed 12.5% ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,180,5919); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_VIT, 1); target:addMod(MOD_MOVE, 13); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_VIT, 1); target:delMod(MOD_MOVE, 13); end;
gpl-3.0
starlightknight/darkstar
scripts/zones/Windurst_Waters/npcs/Chomoro-Kyotoro.lua
9
1200
----------------------------------- -- Area: Windurst Waters -- NPC: Chomoro-Kyotoro -- Involved in Quest: Making the Grade -- !pos 133 -5 167 238 ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/globals/settings"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) -- needs check for dsp.ki.TATTERED_TEST_SHEET then sets to var 3 if (player:getQuestStatus(WINDURST,dsp.quest.id.windurst.MAKING_THE_GRADE) == QUEST_ACCEPTED) then local prog = player:getCharVar("QuestMakingTheGrade_prog"); if (prog == 0) then player:startEvent(454); elseif (prog == 1) then player:startEvent(457); elseif (prog == 2) then player:startEvent(460); else player:startEvent(461); end else player:startEvent(432); end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) if (csid == 460) then player:setCharVar("QuestMakingTheGrade_prog",3); player:delKeyItem(dsp.ki.TATTERED_TEST_SHEET); end end;
gpl-3.0
CAAP/Lua
carlos/ferre/miss.lua
1
1240
-- Import Section -- local fd = require'carlos.fold' local format = require'string'.format local print = print -- No more external access after this point _ENV = nil -- or M -- Local Variables for module-only access -- local DATA = {} -------------------------------- -- Local function definitions -- -------------------------------- -- -- cmds: tabs, delete, msgs local function update(pid, cmd, msg) if not PIDS[pid] then PIDS[pid] = {} end local p = PIDS[pid] if cmd == 'delete' and p.tabs then p.tabs = nil else p[cmd] = '%s ' .. msg end -- add fruit end local function switch( msg, msgr ) local cmd = msg:match'%a+' if cmd == 'pins' then PINS.store(pid, msg) msgr:send_msg( msg ) elseif cmd == 'login' then local fruit = msg:match'fruit=(%a+)' local ft = FRUITS[pid] if ft and ft ~= fruit then msgr:send_msg(format('%s logout pid=%d', ft, pid)) end FRUITS[pid] = fruit if PIDS[pid] then fd.reduce(fd.keys(PIDS[pid]), function(m) msgr:send_msg(format(m, fruit)) end) end else -- tabs, delete, msgs update(pid, cmd, msg) local ft = FRUITS[pid] if cmd == 'msgs' and ft then msgr:send_msg(format('%s %s', ft, msg)) end end print(msg, '\n') ::FIN:: end return switch
gpl-2.0
gedads/Neodynamis
scripts/globals/abilities/pets/attachments/smoke_screen.lua
4
1095
----------------------------------- -- Attachment: Smoke Screen ----------------------------------- require("scripts/globals/status"); ----------------------------------- -- onUseAbility ----------------------------------- function onEquip(pet) pet:addMod(MOD_EVA, 20); pet:addMod(MOD_ACC, -20); end function onUnequip(pet) pet:delMod(MOD_EVA, 20); pet:delMod(MOD_ACC, -20); end function onManeuverGain(pet,maneuvers) if (maneuvers == 1) then pet:addMod(MOD_EVA, 20); pet:addMod(MOD_ACC, -20); elseif (maneuvers == 2) then pet:addMod(MOD_EVA, 40); pet:addMod(MOD_ACC, -40); elseif (maneuvers == 3) then pet:addMod(MOD_EVA, 80); pet:addMod(MOD_ACC, -80); end end function onManeuverLose(pet,maneuvers) if (maneuvers == 1) then pet:delMod(MOD_EVA, 20); pet:delMod(MOD_ACC, -20); elseif (maneuvers == 2) then pet:delMod(MOD_EVA, 40); pet:delMod(MOD_ACC, -40); elseif (maneuvers == 3) then pet:delMod(MOD_EVA, 80); pet:delMod(MOD_ACC, -80); end end
gpl-3.0
starlightknight/darkstar
scripts/mixins/families/qutrub.lua
12
1861
require("scripts/globals/mixins") g_mixins = g_mixins or {} g_mixins.families = g_mixins.families or {} -- AnimationSub for Qutrub -- 0 = main weapon out, sub weapon sheathed -- 1 = main weapon broken, sub weapon sheathed -- 2 = main weapon broken, sub weapon out -- 3 = both weapons broken g_mixins.families.qutrub = function(mob) -- set default 10% chance to break weapon on critical hit taken -- this can be overridden in onMobSpawn mob:addListener("SPAWN", "QUTRUB_SPAWN", function(mob) mob:setLocalVar("qutrubBreakChance", 10) end) -- when a qutrub's weapon has been broken it will switch between using its second mob:addListener("COMBAT_TICK", "QUTRUB_COMBAT_TICK", function(mob) local swapTime = mob:getLocalVar("swapTime") if swapTime > 0 and os.time() > swapTime then local animationSub = mob:AnimationSub() if animationSub == 1 then mob:AnimationSub(2) mob:setLocalVar("swapTime", os.time() + 60) elseif animationSub == 2 then mob:AnimationSub(1) mob:setLocalVar("swapTime", os.time() + 60) end end end) -- chance to break weapon when taking a critical hit mob:addListener("CRITICAL_TAKE", "QUTRUB_CRITICAL_TAKE", function(mob) if math.random(100) <= mob:getLocalVar("qutrubBreakChance") then local animationSub = mob:AnimationSub() -- break first weapon if animationSub == 0 then mob:AnimationSub(1) mob:setLocalVar("swapTime", os.time() + 60) -- break second weapon elseif animationSub == 2 then mob:AnimationSub(3) mob:setLocalVar("swapTime", 0) end end end) end return g_mixins.families.qutrub
gpl-3.0
Craige/prosody-modules
mod_auth_custom_http/mod_auth_custom_http.lua
32
1346
-- Prosody IM -- Copyright (C) 2008-2010 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local new_sasl = require "util.sasl".new; local json_encode = require "util.json"; local http = require "socket.http"; local options = module:get_option("auth_custom_http"); local post_url = options and options.post_url; assert(post_url, "No HTTP POST URL provided"); local provider = {}; function provider.test_password(username, password) return nil, "Not supported" end function provider.get_password(username) return nil, "Not supported" end function provider.set_password(username, password) return nil, "Not supported" end function provider.user_exists(username) return true; end function provider.create_user(username, password) return nil, "Not supported" end function provider.delete_user(username) return nil, "Not supported" end function provider.get_sasl_handler() local getpass_authentication_profile = { plain_test = function(sasl, username, password, realm) local postdata = json_encode({ username = username, password = password }); local result = http.request(post_url, postdata); return result == "true", true; end, }; return new_sasl(module.host, getpass_authentication_profile); end module:provides("auth", provider);
mit
gedads/Neodynamis
scripts/globals/items/windurst_taco.lua
12
1644
----------------------------------------- -- ID: 5172 -- Item: windurst_taco -- Food Effect: 30Min, All Races ----------------------------------------- -- MP 20 -- Vitality -1 -- Agility 5 -- MP Recovered While Healing 1 -- Ranged Accuracy % 8 (cap 10) -- Ranged Attack +1 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,5172); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MP, 20); target:addMod(MOD_VIT, -1); target:addMod(MOD_AGI, 5); target:addMod(MOD_MPHEAL, 1); target:addMod(MOD_RATT, 1); target:addMod(MOD_FOOD_RACCP, 8); target:addMod(MOD_FOOD_RACC_CAP, 10); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MP, 20); target:delMod(MOD_VIT, -1); target:delMod(MOD_AGI, 5); target:delMod(MOD_MPHEAL, 1); target:delMod(MOD_RATT, 1); target:delMod(MOD_FOOD_RACCP, 8); target:delMod(MOD_FOOD_RACC_CAP, 10); end;
gpl-3.0
hades2013/openwrt-mtk
package/ralink/ui/luci-mtk/src/libs/nixio/axTLS/www/lua/download.lua
180
1550
#!/usr/local/bin/lua require"luasocket" function receive (connection) connection:settimeout(0) local s, status = connection:receive (2^10) if status == "timeout" then coroutine.yield (connection) end return s, status end function download (host, file, outfile) --local f = assert (io.open (outfile, "w")) local c = assert (socket.connect (host, 80)) c:send ("GET "..file.." HTTP/1.0\r\n\r\n") while true do local s, status = receive (c) --f:write (s) if status == "closed" then break end end c:close() --f:close() end local threads = {} function get (host, file, outfile) print (string.format ("Downloading %s from %s to %s", file, host, outfile)) local co = coroutine.create (function () return download (host, file, outfile) end) table.insert (threads, co) end function dispatcher () while true do local n = table.getn (threads) if n == 0 then break end local connections = {} for i = 1, n do local status, res = coroutine.resume (threads[i]) if not res then table.remove (threads, i) break else table.insert (connections, res) end end if table.getn (connections) == n then socket.select (connections) end end end local url = arg[1] if not url then print (string.format ("usage: %s url [times]", arg[0])) os.exit() end local times = arg[2] or 5 url = string.gsub (url, "^http.?://", "") local _, _, host, file = string.find (url, "^([^/]+)(/.*)") local _, _, fn = string.find (file, "([^/]+)$") for i = 1, times do get (host, file, fn..i) end dispatcher ()
gpl-2.0
mynameiscraziu/sickout21
plugins/invite.lua
63
1107
do local function callbackres(extra, success, result) -- Callback for res_user in line 27 local user = 'user#id'..result.id local chat = 'chat#id'..extra.chatid if is_banned(result.id, extra.chatid) or is_gbanned(result.id) then -- Ignore bans and globall bans send_large_msg(chat, 'User is banned.') else chat_add_user(chat, user, ok_cb, false) -- Add user on chat end end function run(msg, matches) local data = load_data(_config.moderation.data) if not is_realm(msg) then if data[tostring(msg.to.id)]['settings']['lock_member'] == 'yes' and not is_admin(msg) then return 'Group is private.' end end if msg.to.type ~= 'chat' then return end if not is_momod(msg) then return end --if not is_admin(msg) then -- For admins only ! --return 'Only admins can invite.' --end local cbres_extra = {chatid = msg.to.id} local username = matches[1] local username = username:gsub("@","") res_user(username, callbackres, cbres_extra) end return { patterns = { "^/invite (.*)$" }, run = run } end
gpl-2.0
gedads/Neodynamis
scripts/zones/Aht_Urhgan_Whitegate/npcs/Mushayra.lua
3
1048
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Mushayra -- Type: Standard NPC -- !pos -111.551 -6.999 -61.720 50 ----------------------------------- package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0207); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
gedads/Neodynamis
scripts/zones/The_Sanctuary_of_ZiTah/npcs/Kasim.lua
3
1876
----------------------------------- -- Area: The Sanctuary of Zitah -- NPC: Kasim -- !pos -46 0 -148 121 ----------------------------------- package.loaded["scripts/zones/The_Sanctuary_of_Zitah/TextIDs"] = nil; ----------------------------------- require("scripts/globals/shop"); require("scripts/globals/conquest"); require("scripts/zones/The_Sanctuary_of_ZiTah/TextIDs"); local region = LITELOR; local csid = 0x7ff4; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local owner = GetRegionOwner(region); local arg1 = getArg1(owner,player); if (owner == player:getNation()) then nation = 1; elseif (arg1 < 1792) then nation = 2; else nation = 0; end player:startEvent(csid,nation,OP_TeleFee(player,region),0,OP_TeleFee(player,region),player:getCP(),0,0,0); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); player:updateEvent(player:getGil(),OP_TeleFee(player,region),0,OP_TeleFee(player,region),player:getCP()); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); if (option == 1) then ShowOPVendorShop(player); elseif (option == 2) then if (player:delGil(OP_TeleFee(player,region))) then toHomeNation(player); end elseif (option == 6) then player:delCP(OP_TeleFee(player,region)); toHomeNation(player); end end;
gpl-3.0
starlightknight/darkstar
scripts/zones/Open_sea_route_to_Al_Zahbi/IDs.lua
12
1193
----------------------------------- -- Area: Open_sea_route_to_Al_Zahbi ----------------------------------- require("scripts/globals/zone") ----------------------------------- zones = zones or {} zones[dsp.zone.OPEN_SEA_ROUTE_TO_AL_ZAHBI] = { 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>. FISHING_MESSAGE_OFFSET = 7049, -- You can't fish here. ON_WAY_TO_AL_ZAHBI = 7308, -- We are on our way to Al Zahbi. We should arrive in [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] (# [minute/minutes] in Earth time). DOCKING_IN_AL_ZAHBI = 7309, -- We are now docking in Al Zahbi. CEHN_TEYOHNGO_SHOP_DIALOG = 7312, -- If you're looking for fishing gear, you've come to the right place! }, mob = { }, npc = { }, } return zones[dsp.zone.OPEN_SEA_ROUTE_TO_AL_ZAHBI]
gpl-3.0
starlightknight/darkstar
scripts/globals/abilities/pets/attachments/eraser.lua
11
1703
----------------------------------- -- Attachment: Eraser ----------------------------------- require("scripts/globals/status") ----------------------------------- local removable = { dsp.effect.PETRIFICATION, dsp.effect.SILENCE, dsp.effect.BANE, dsp.effect.CURSE_II, dsp.effect.CURSE, dsp.effect.PARALYSIS, dsp.effect.PLAGUE, dsp.effect.POISON, dsp.effect.DISEASE, dsp.effect.BLINDNESS } function onEquip(pet) pet:addListener("AUTOMATON_ATTACHMENT_CHECK", "ATTACHMENT_ERASER", function(automaton, target) local master = automaton:getMaster() if not automaton:hasRecast(dsp.recast.ABILITY, 2021) and master and master:countEffect(dsp.effect.LIGHT_MANEUVER) > 0 then local erasetarget = false local function checkEffects(entity) for _, status in pairs(removable) do if entity:hasStatusEffect(status) then return true end end return false end if automaton:hasStatusEffectByFlag(dsp.effectFlag.ERASABLE) or checkEffects(automaton) then erasetarget = automaton elseif (automaton:checkDistance(master) - master:getModelSize()) < 7 and (master:hasStatusEffectByFlag(dsp.effectFlag.ERASABLE) or checkEffects(master)) then erasetarget = master end if not erasetarget then return 0 end automaton:useMobAbility(2021, erasetarget) else return 0 end end) end function onUnequip(pet) pet:removeListener("ATTACHMENT_ERASER") end function onManeuverGain(pet, maneuvers) end function onManeuverLose(pet, maneuvers) end
gpl-3.0
disslove85/NOVA1-BOT
plugins/get.lua
613
1067
local function get_variables_hash(msg) if msg.to.type == 'chat' then return 'chat:'..msg.to.id..':variables' end if msg.to.type == 'user' then return 'user:'..msg.from.id..':variables' end end local function list_variables(msg) local hash = get_variables_hash(msg) if hash then local names = redis:hkeys(hash) local text = '' for i=1, #names do text = text..names[i]..'\n' end return text end end local function get_value(msg, var_name) local hash = get_variables_hash(msg) if hash then local value = redis:hget(hash, var_name) if not value then return'Not found, use "!get" to list variables' else return var_name..' => '..value end end end local function run(msg, matches) if matches[2] then return get_value(msg, matches[2]) else return list_variables(msg) end end return { description = "Retrieves variables saved with !set", usage = "!get (value_name): Returns the value_name value.", patterns = { "^(!get) (.+)$", "^!get$" }, run = run }
gpl-2.0
gedads/Neodynamis
scripts/zones/The_Eldieme_Necropolis/npcs/_5fn.lua
3
2646
----------------------------------- -- Area: The Eldieme Necropolis -- NPC: North Plate -- !pos 180 -34 71 195 ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local state0 = 8; local state1 = 9; local DoorOffset = npc:getID() - 22; -- _5f1 if (npc:getAnimation() == 8) then state0 = 9; state1 = 8; end -- Gates -- Shiva's Gate GetNPCByID(DoorOffset):setAnimation(state0); GetNPCByID(DoorOffset+1):setAnimation(state0); GetNPCByID(DoorOffset+2):setAnimation(state0); GetNPCByID(DoorOffset+3):setAnimation(state0); GetNPCByID(DoorOffset+4):setAnimation(state0); -- Odin's Gate GetNPCByID(DoorOffset+5):setAnimation(state1); GetNPCByID(DoorOffset+6):setAnimation(state1); GetNPCByID(DoorOffset+7):setAnimation(state1); GetNPCByID(DoorOffset+8):setAnimation(state1); GetNPCByID(DoorOffset+9):setAnimation(state1); -- Leviathan's Gate GetNPCByID(DoorOffset+10):setAnimation(state0); GetNPCByID(DoorOffset+11):setAnimation(state0); GetNPCByID(DoorOffset+12):setAnimation(state0); GetNPCByID(DoorOffset+13):setAnimation(state0); GetNPCByID(DoorOffset+14):setAnimation(state0); -- Titan's Gate GetNPCByID(DoorOffset+15):setAnimation(state1); GetNPCByID(DoorOffset+16):setAnimation(state1); GetNPCByID(DoorOffset+17):setAnimation(state1); GetNPCByID(DoorOffset+18):setAnimation(state1); GetNPCByID(DoorOffset+19):setAnimation(state1); -- Plates -- East Plate GetNPCByID(DoorOffset+20):setAnimation(state0); GetNPCByID(DoorOffset+21):setAnimation(state0); -- North Plate GetNPCByID(DoorOffset+22):setAnimation(state0); GetNPCByID(DoorOffset+23):setAnimation(state0); -- West Plate GetNPCByID(DoorOffset+24):setAnimation(state0); GetNPCByID(DoorOffset+25):setAnimation(state0); -- South Plate GetNPCByID(DoorOffset+26):setAnimation(state0); GetNPCByID(DoorOffset+27):setAnimation(state0); return 0; 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
pravsingh/Algorithm-Implementations
Knuth_Morris_Pratt/Lua/Yonaba/kmp.lua
26
1219
-- Knuth-Morris-Pratt string searching algorithm implementation -- See: http://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm local function kmp_table(pattern) local result = {} for i = 1, #pattern+1,1 do local j = i while true do if j == 1 then result[#result + 1] = 1 break end j = j-1 if pattern:sub(result[j], result[j]) == pattern:sub(i, i) then result[#result + 1] = result[j] + 1 break end j = result[j] end end return result end -- Knuth-Morris-Pratt string searching function -- needle : the pattern to search -- haystack : the string in which the pattern will be searched -- returns : the position of the match, otherwise nil return function(needle, haystack) local fail = kmp_table(needle) local index, match = 0,1 while index + match < #haystack do if haystack:sub(index + match, index + match) == needle:sub(match, match) then match = match + 1 if match-1 == #needle then return index end else if match == 1 then index = index + 1 else index = index + match - (fail[match-1]) match = fail[match-1] end end end end
mit
teleowner/TELEOWNER
plugins/src.lua
1
1049
local function googlethat(query) local api = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&" local parameters = "q=".. (URL.escape(query) or "") -- Do the request local res, code = https.request(api..parameters) if code ~=200 then return nil end local data = json:decode(res) local results = {} for key,result in ipairs(data.responseData.results) do table.insert(results, { result.titleNoFormatting, result.unescapedUrl or result.url }) end return results end local function stringlinks(results) local stringresults="Search in Google:\n______________________________\n" for key,val in ipairs(results) do stringresults=stringresults..val[1].." - "..val[2].."\n" end return stringresults end local function run(msg, matches) local results = googlethat(matches[1]) return stringlinks(results) end return { description = "Searche in Google", usage = "/src (item) : google search", patterns = { "^[#!/]src (.*)$", "^%.[s|S]rc (.*)$" }, run = run }
gpl-2.0
ahupowerdns/pdns
pdns/recursordist/contrib/powerdns-example-script.lua
14
3915
pdnslog("pdns-recursor Lua script starting!", pdns.loglevels.Warning) blockset = newDS() blockset:add{"powerdns.org", "xxx"} dropset = newDS(); dropset:add("123.cn") malwareset = newDS() malwareset:add("nl") magic2 = newDN("www.magic2.com") magicMetric = getMetric("magic") -- shows the various ways of blocking, dropping, changing questions -- return false to say you did not take over the question, but we'll still listen to 'variable' -- to selectively disable the cache function preresolve(dq) print("Got question for "..dq.qname:toString().." from "..dq.remoteaddr:toString().." to "..dq.localaddr:toString()) local ednssubnet=dq:getEDNSSubnet() if(ednssubnet) then print("Packet EDNS subnet source: "..ednssubnet:toString()..", "..ednssubnet:getNetwork():toString()) end local a=dq:getEDNSOption(3) if(a) then print("There is an EDNS option 3 present: "..a) end loc = newCA("127.0.0.1") if(dq.remoteaddr:equal(loc)) then print("Query from loopback") end -- note that the comparisons below are CaSe InSensiTivE and you don't have to worry about trailing dots if(dq.qname:equal("magic.com")) then magicMetric:inc() print("Magic!") else print("not magic..") end if(dq.qname:__eq(magic2)) -- we hope to improve this syntax then print("Faster magic") -- compares against existing DNSName end -- sadly, dq.qname == magic2 won't work yet if blockset:check(dq.qname) then dq.variable = true -- disable packet cache in any case if dq.qtype == pdns.A then dq:addAnswer(pdns.A, "1.2.3.4") dq:addAnswer(pdns.TXT, "\"Hello!\"", 3601) -- ttl return true; end end if dropset:check(dq.qname) then dq.rcode = pdns.DROP return true; end if malwareset:check(dq.qname) then dq:addAnswer(pdns.CNAME, "xs.powerdns.com.") dq.rcode = 0 dq.followupFunction="followCNAMERecords" -- this makes PowerDNS lookup your CNAME return true; end return false; end -- this implements DNS64 function nodata(dq) if dq.qtype == pdns.AAAA then dq.followupFunction="getFakeAAAARecords" dq.followupName=dq.qname dq.followupPrefix="fe80::" return true end if dq.qtype == pdns.PTR then dq.followupFunction="getFakePTRRecords" dq.followupName=dq.qname dq.followupPrefix="fe80::" return true end return false end badips = newNMG() badips:addMask("127.1.0.0/16") -- this check is applied before any packet parsing is done function ipfilter(rem, loc, dh) print("ipfilter called, rem: ", rem:toStringWithPort(), "loc: ",loc:toStringWithPort(),"match:", badips:match(rem)) print("id: ",dh:getID(), "aa: ", dh:getAA(), "ad: ", dh:getAD(), "arcount: ", dh:getARCOUNT()) print("ports: ",rem:getPort(),loc:getPort()) return badips:match(rem) end -- postresolve runs after the packet has been answered, and can be used to change things -- or still drop function postresolve(dq) print("postresolve called for ",dq.qname:toString()) local records = dq:getRecords() for k,v in pairs(records) do print(k, v.name:toString(), v:getContent()) if v.type == pdns.A and v:getContent() == "185.31.17.73" then print("Changing content!") v:changeContent("130.161.252.29") v.ttl=1 end end dq:setRecords(records) return true end nxdomainsuffix=newDN("com") function nxdomain(dq) print("Hooking: ",dq.qname:toString()) if dq.qname:isPartOf(nxdomainsuffix) then dq.rcode=0 -- make it a normal answer dq:addAnswer(pdns.CNAME, "ourhelpfulservice.com") dq:addAnswer(pdns.A, "1.2.3.4", 60, "ourhelpfulservice.com") return true end return false end
gpl-2.0
gedads/Neodynamis
scripts/zones/Apollyon/Zone.lua
31
11702
----------------------------------- -- -- Zone: Apollyon -- ----------------------------------- require("scripts/globals/settings"); package.loaded["scripts/zones/Apollyon/TextIDs"] = nil; require("scripts/zones/Apollyon/TextIDs"); require("scripts/globals/limbus"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) SetServerVariable("[NW_Apollyon]UniqueID",0); SetServerVariable("[SW_Apollyon]UniqueID",0); SetServerVariable("[NE_Apollyon]UniqueID",0) ; SetServerVariable("[SE_Apollyon]UniqueID",0); SetServerVariable("[CS_Apollyon]UniqueID",0); SetServerVariable("[CS_Apollyon_II]UniqueID",0); SetServerVariable("[Central_Apollyon]UniqueID",0); SetServerVariable("[Central_Apollyon_II]UniqueID",0); zone:registerRegion(1, 637,-4,-642,642,4,-637); -- APPOLLYON_SE_NE exit zone:registerRegion(2, -642,-4,-642,-637,4,-637); -- APPOLLYON_NW_SW exit zone:registerRegion(3, 468,-4,-637, 478,4,-622); -- appolyon SE register zone:registerRegion(4, 421,-4,-98, 455,4,-78); -- appolyon NE register zone:registerRegion(5, -470,-4,-629, -459,4,-620); -- appolyon SW register zone:registerRegion(6, -455,-4,-95, -425,4,-67); -- appolyon NW register zone:registerRegion(7, -3,-4,-214, 3,4,-210); -- appolyon CS register zone:registerRegion(8, -3,-4, 207, 3,4, 215); -- appolyon Center register zone:registerRegion(20, 396,-4,-522, 403,4,-516); -- appolyon SE telporter floor1 to floor2 zone:registerRegion(21, 116,-4,-443, 123,4,-436); -- appolyon SE telporter floor2 to floor3 zone:registerRegion(22, 276,-4,-283, 283,4,-276); -- appolyon SE telporter floor3 to floor4 zone:registerRegion(23, 517,-4,-323, 523,4,-316); -- appolyon SE telporter floor4 to entrance zone:registerRegion(24, 396,-4,76, 403,4,83); -- appolyon NE telporter floor1 to floor2 zone:registerRegion(25, 276,-4,356, 283,4,363); -- appolyon NE telporter floor2 to floor3 zone:registerRegion(26, 236,-4,517, 243,4,523); -- appolyon NE telporter floor3 to floor4 zone:registerRegion(27, 517,-4,637, 523,4,643); -- appolyon NE telporter floor4 to floor5 zone:registerRegion(28, 557,-4,356, 563,4,363); -- appolyon NE telporter floor5 to entrance zone:registerRegion(29, -403,-4,-523, -396,4,-516); -- appolyon SW telporter floor1 to floor2 zone:registerRegion(30, -123,-4,-443, -116,4,-436); -- appolyon SW telporter floor2 to floor3 zone:registerRegion(31, -283,-4,-283, -276,4,-276); -- appolyon SW telporter floor3 to floor4 zone:registerRegion(32, -523,-4,-323, -517,4,-316); -- appolyon SW telporter floor4 to entrance zone:registerRegion(33, -403,-4,76, -396,4,83); -- appolyon NW telporter floor1 to floor2 zone:registerRegion(34, -283,-4,356, -276,4,363); -- appolyon NW telporter floor2 to floor3 zone:registerRegion(35, -243,-4,516, -236,4,523); -- appolyon NW telporter floor3 to floor4 zone:registerRegion(36, -523,-4,636, -516,4,643); -- appolyon NW telporter floor4 to floor5 zone:registerRegion(37, -563,-4,356, -556,4,363); -- appolyon NW telporter floor5 to entrance end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) cs = -1; if (prevZone~=33) then local playerLimbusID = player:getVar("LimbusID"); if (playerLimbusID== 1290 or playerLimbusID== 1291 or playerLimbusID== 1294 or playerLimbusID== 1295 or playerLimbusID== 1296 or playerLimbusID== 1297) then player:setPos(-668,0.1,-666); else player:setPos(643,0.1,-600); end elseif ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then player:setPos(643,0.1,-600); end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) local regionID = region:GetRegionID(); switch (regionID): caseof { [1] = function (x) player:startEvent(0x0064); -- APPOLLYON_SE_NE exit end, [2] = function (x) player:startEvent(0x0065); -- APPOLLYON_NW_SW exit -- print("APPOLLYON_NW_SW"); end, [3] = function (x) if (player:hasStatusEffect(EFFECT_BATTLEFIELD) == false) then RegisterLimbusInstance(player,1293); end --create instance appolyon SE end, [4] = function (x) if (player:hasStatusEffect(EFFECT_BATTLEFIELD) == false) then RegisterLimbusInstance(player,1292); end --create instance appolyon NE end, [5] = function (x) if (player:hasStatusEffect(EFFECT_BATTLEFIELD) == false) then RegisterLimbusInstance(player,1291); end --create instance appolyon SW end, [6] = function (x) if (player:hasStatusEffect(EFFECT_BATTLEFIELD) == false) then RegisterLimbusInstance(player,1290); end --create instance appolyon NW end, [7] = function (x) if (player:hasStatusEffect(EFFECT_BATTLEFIELD) == false) then RegisterLimbusInstance(player,1294); end --create instance appolyon CS end, [8] = function (x) if (player:hasStatusEffect(EFFECT_BATTLEFIELD) == false) then RegisterLimbusInstance(player,1296); end --create instance appolyon CENTER end, -- ///////////////////////APPOLLYON SE TELEPORTER/////////////////////////////////////////// [20] = function (x) -- print("SE_telporter_f1_to_f2"); if (IsMobDead(16932992)==true and player:getAnimation()==0) then player:startEvent(0x00DB);end end, [21] = function (x) -- print("SE_telporter_f2_to_f3"); if (IsMobDead(16933006)==true and player:getAnimation()==0) then player:startEvent(0x00DA);end end, [22] = function (x) -- print("SE_telporter_f3_to_f4"); if (IsMobDead(16933020)==true and player:getAnimation()==0) then player:startEvent(0x00D8);end end, [23] = function (x) -- print("SE_telporter_f3_to_entrance"); if (IsMobDead(16933032)==true and player:getAnimation()==0) then player:startEvent(0x00D9);end end, -- /////////////////////////////////////////////////////////////////////////////////////////// -- ///////////////////// APPOLLYON NE TELEPORTER //////////////////////////////// [24] = function (x) -- print("NE_telporter_f1_to_f2"); if (IsMobDead(16933044)==true and player:getAnimation()==0) then player:startEvent(0x00D6);end end, [25] = function (x) -- print("NE_telporter_f2_to_f3"); if (IsMobDead(16933064)==true and player:getAnimation()==0) then player:startEvent(0x00D4);end --212 end, [26] = function (x) -- print("NE_telporter_f3_to_f4"); if (IsMobDead(16933086)==true and player:getAnimation()==0) then player:startEvent(0x00D2);end --210 end, [27] = function (x) -- print("NE_telporter_f4_to_f5"); if (IsMobDead(16933101)==true and player:getAnimation()==0) then player:startEvent(0x00D7);end --215 end, [28] = function (x) -- print("NE_telporter_f5_to_entrance"); if ( (IsMobDead(16933114)==true or IsMobDead(16933113)==true) and player:getAnimation()==0) then player:startEvent(0x00D5);end --213 end, -- ////////////////////////////////////////////////////////////////////////////////////////////////// -- ///////////////////// APPOLLYON SW TELEPORTER //////////////////////////////// [29] = function (x) if (IsMobDead(16932873)==true and player:getAnimation()==0) then player:startEvent(0x00D0);end --208 end, [30] = function (x) if (IsMobDead(16932885)==true and player:getAnimation()==0) then player:startEvent(0x00D1);end --209 --printf("Mimics should be 0: %u",GetServerVariable("[SW_Apollyon]MimicTrigger")); end, [31] = function (x) if (( IsMobDead(16932896)==true or IsMobDead(16932897)==true or IsMobDead(16932898)==true or IsMobDead(16932899)==true )and player:getAnimation()==0) then player:startEvent(0x00CF);end -- 207 end, [32] = function (x) if (IselementalDayAreDead()==true and player:getAnimation()==0) then player:startEvent(0x00CE);end -- 206 end, -- ////////////////////////////////////////////////////////////////////////////////////////////////// -- ///////////////////// APPOLLYON NW TELEPORTER //////////////////////////////// [33] = function (x) if (IsMobDead(16932937)==true and player:getAnimation()==0) then player:startEvent(0x00CD);end --205 end, [34] = function (x) if (IsMobDead(16932950)==true and player:getAnimation()==0) then player:startEvent(0x00CB);end --203 end, [35] = function (x) if (IsMobDead(16932963)==true and player:getAnimation()==0) then player:startEvent(0x00C9);end --201 end, [36] = function (x) if (IsMobDead(16932976)==true and player:getAnimation()==0) then player:startEvent(0x00C8);end --200 end, [37] = function (x) if (IsMobDead(16932985)==true and player:getAnimation()==0) then player:startEvent(0x00CA);end --202 end, } end; ----------------------------------- -- onRegionLeave ----------------------------------- function onRegionLeave(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x00D1 and option == 0 and GetServerVariable("[SW_Apollyon]MimicTrigger")==0) then SpawnCofferSWfloor3(); --printf("Mimics should be 1: %u",GetServerVariable("[SW_Apollyon]MimicTrigger")); elseif (csid == 0x00CF and option == 0 and GetServerVariable("[SW_Apollyon]ElementalTrigger")==0) then SetServerVariable("[SW_Apollyon]ElementalTrigger",VanadielDayElement()+1); -- printf("Elementals should be 1: %u",GetServerVariable("[SW_Apollyon]ElementalTrigger")); end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0064 and option == 1) then player:setPos(557,-1,441,128,0x21); -- APPOLLYON_SE_NE exit elseif (csid == 0x0065 and option == 1) then player:setPos(-561,0,443,242,0x21); -- APPOLLYON_NW_SW exit end end;
gpl-3.0
gedads/Neodynamis
scripts/zones/RuLude_Gardens/npcs/Magian_Moogle_Green.lua
3
2441
----------------------------------- -- Area: Ru'Lude Gardens -- NPC: Magian Moogle (Green Bobble) -- Type: Magian Trials NPC (Job Emotes) -- !pos -4.558 2.451 111.305 64 ----------------------------------- package.loaded["scripts/zones/RuLude_Gardens/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/zones/RuLude_Gardens/TextIDs"); require("scripts/globals/magiantrials"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (trade:getItemCount() == 1) then local ItemID = trade:getItemId(); local TrialInfo = getEmoteTrialInfo(ItemID); local invalid = 0; if (TrialInfo.t1 == 0 and TrialInfo.t2 == 0 and TrialInfo.t3 == 0 and TrialInfo.t4 == 0) then invalid = 1; end player:startEvent(10153, TrialInfo.t1, TrialInfo.t2, TrialInfo.t3, TrialInfo.t4, 0, ItemID, 0, invalid); else -- placeholder for torque+other required item trade. end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local LearnerLog = player:hasKeyItem(MAGIAN_LEARNERS_LOG); local TrialLog = player:hasKeyItem(MAGIAN_TRIAL_LOG); if (player:getMainLvl() < 30) then player:startEvent(10151); elseif (player:getVar("MetGreenMagianMog") == 0 and LearnerLog == false) then if (TrialLog == false) then player:startEvent(10160, 0); else player:startEvent(10160, 1); end else player:startEvent(10152); -- parameters unknown 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 == 10160 and option == 1) then if (player:hasKeyItem(MAGIAN_TRIAL_LOG) == false) then player:messageSpecial(KEYITEM_OBTAINED,MAGIAN_LEARNERS_LOG); player:addKeyItem(MAGIAN_LEARNERS_LOG); end player:setVar("MetGreenMagianMog",1); --elseif -- end end;
gpl-3.0
starlightknight/darkstar
scripts/commands/setplayervar.lua
9
1288
--------------------------------------------------------------------------------------------------- -- func: setplayervar -- desc: Sets a variable on the target player. --------------------------------------------------------------------------------------------------- cmdprops = { permission = 1, parameters = "ssi" }; function error(player, msg) player:PrintToPlayer(msg); player:PrintToPlayer("!setplayervar <player> <variable> <value>"); end; function onTrigger(player, target, variable, value) -- validate target local targ; if (target == nil) then error(player, "You must provide a player name."); return; else targ = GetPlayerByName( target ); if (targ == nil) then error(player, string.format( "Player named '%s' not found!", target ) ); return; end end -- validate var if (variable == nil) then error(player, "You must provide a variable name."); return; end -- validate value if (value == nil) then error(player, "You must provide a value."); return; end targ:setCharVar(variable, value); player:PrintToPlayer( string.format( "Set %s's variable '%s' to %i.", targ:getName(), variable, value ) ); end
gpl-3.0
gedads/Neodynamis
scripts/globals/magicburst.lua
33
3436
require("scripts/globals/status") SC_NONE = 0 -- Lv0 None SC_TRANSFIXION = 1 -- Lv1 Light SC_COMPRESSION = 2 -- Lv1 Dark SC_LIQUEFACTION = 3 -- Lv1 Fire SC_SCISSION = 4 -- Lv1 Earth SC_REVERBERATION = 5 -- Lv1 Water SC_DETONATION = 6 -- Lv1 Wind SC_INDURATION = 7 -- Lv1 Ice SC_IMPACTION = 8 -- Lv1 Thunder SC_GRAVITATION = 9 -- Lv2 Dark & Earth SC_DISTORTION = 10 -- Lv2 Water & Ice SC_FUSION = 11 -- Lv2 Fire & Light SC_FRAGMENTATION = 12 -- Lv2 Wind & Thunder SC_LIGHT = 13 -- Lv3 Fire, Light, Wind, Thunder SC_DARKNESS = 14 -- Lv3 Dark, Earth, Water, Ice SC_LIGHT_II = 15 -- Lv4 Light SC_DARKNESS_II = 16 -- Lv4 Darkness local matches = -- [element id][resonance id] { -- 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 -- N T C L S R D I I G D F F L D L D {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, -- ( 1) NONE {0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0}, -- ( 2) FIRE {0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1}, -- ( 3) EARTH {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1}, -- ( 4) WATER {0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0}, -- ( 5) WIND {0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1}, -- ( 6) ICE {0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0}, -- ( 7) THUNDER {0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0}, -- ( 8) LIGHT {0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1}, -- ( 9) DARK -- Blue mage spells. Included for the sake of completeness {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, -- (10) BLU - Physical Blunt {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, -- (11) BLU - Physical Hand-to-Hand {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, -- (12) BLU - Physical Piercing {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, -- (13) BLU - Physical Slashing } -- Returns a boolean if the spell's element matches the resonace given function doesSpellElementMatchResonance(ele, resonance) isMatch = matches[ele + 1][resonance:getPower() + 1]; return (isMatch ~= nil and isMatch > 0); end -- Returns the burst level for a spell / target combination function FormMagicBurst(ele, target) local resonance = target:getStatusEffect(EFFECT_SKILLCHAIN); if (resonance ~= nil and resonance:getTier() > 0) then -- Resonance exists, ignore it if its tier 0 if (doesSpellElementMatchResonance(ele, resonance) == true) then return resonance:getTier(), resonance:getSubPower(); end end -- if resonance return 0, 0; end function MobFormMagicBurst(element, target) local resonance = target:getStatusEffect(EFFECT_SKILLCHAIN); if (resonance ~= nil and resonance:getTier() > 0) then -- Resonance exists, ignore it if its tier 0 if (doesMobSpellElementMatchResonance(element, resonance) == true) then return resonance:getTier(), resonance:getSubPower(); end end -- if resonance return 0, 0; end function doesMobSpellElementMatchResonance(element, resonance) isMatch = matches[element + 1][resonance:getPower() + 1]; return (isMatch ~= nil and isMatch > 0); end -- Returns a boolean if the element matches the skillchain property given function doesElementMatchWeaponskill(ele, SCProp) isMatch = matches[ele + 1][SCProp + 1]; return (isMatch ~= nil and isMatch > 0); end
gpl-3.0
gedads/Neodynamis
scripts/zones/Tavnazian_Safehold/npcs/_0qa.lua
3
2029
----------------------------------- -- Area: Tavnazian Safehold -- NPC: walnut door -- Involved in mission 2-4 -- !pos 111 -41 41 26 ----------------------------------- package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/zones/Tavnazian_Safehold/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getCurrentMission(COP) == AN_ETERNAL_MELODY and player:getVar("PromathiaStatus") == 0) then player:startEvent(0x0068); elseif (player:getCurrentMission(COP) == THE_SECRETS_OF_WORSHIP and player:getVar("PromathiaStatus") == 0) then player:startEvent(0x006F); elseif (player:getCurrentMission(COP) == CHAINS_AND_BONDS and player:getVar("PromathiaStatus")==4) then player:startEvent(0x0073); elseif (player:getCurrentMission(COP) == DAWN and player:getVar("PromathiaStatus")==5) then player:startEvent(0x021F); end return 1; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0068 or csid == 0x006F) then player:setVar("PromathiaStatus",1); elseif (csid == 0x0073) then player:setVar("PromathiaStatus",0); player:completeMission(COP,CHAINS_AND_BONDS); player:addMission(COP,FLAMES_IN_THE_DARKNESS); elseif (csid == 0x021F) then player:setVar("PromathiaStatus",6); end end;
gpl-3.0
starlightknight/darkstar
scripts/globals/weaponskills/shell_crusher.lua
10
1698
----------------------------------- -- Shell Crusher -- Staff weapon skill -- Skill Level: 175 -- Lowers target's defense. Duration of effect varies with TP. -- If unresisted, lowers target defense by 25%. -- Will stack with Sneak Attack. -- Aligned with the Breeze Gorget. -- Aligned with the Breeze Belt. -- Element: None -- Modifiers: STR:100% -- 100%TP 200%TP 300%TP -- 1.00 1.00 1.00 ----------------------------------- require("scripts/globals/status") require("scripts/globals/settings") require("scripts/globals/weaponskills") ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar) local params = {} params.numHits = 1 params.ftp100 = 1 params.ftp200 = 1 params.ftp300 = 1 params.str_wsc = 0.35 params.dex_wsc = 0.0 params.vit_wsc = 0.0 params.agi_wsc = 0.0 params.int_wsc = 0.0 params.mnd_wsc = 0.0 params.chr_wsc = 0.0 params.crit100 = 0.0 params.crit200 = 0.0 params.crit300 = 0.0 params.canCrit = false params.acc100 = 0.0 params.acc200= 0.0 params.acc300= 0.0 params.atk100 = 1; params.atk200 = 1; params.atk300 = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.str_wsc = 1.0 end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, params, tp, action, primary, taChar) if (damage > 0 and target:hasStatusEffect(dsp.effect.DEFENSE_DOWN) == false) then local duration = (120 + (tp/1000 * 60)) * applyResistanceAddEffect(player,target,dsp.magic.ele.WIND,0) target:addStatusEffect(dsp.effect.DEFENSE_DOWN, 25, 0, duration) end return tpHits, extraHits, criticalHit, damage end
gpl-3.0
Craige/prosody-modules
mod_manifesto/mod_manifesto.lua
32
6828
-- mod_manifesto local timer = require "util.timer"; local jid_split = require "util.jid".split; local st = require "util.stanza"; local dm = require "util.datamanager"; local dataforms_new = require "util.dataforms".new; local adhoc_initial = require "util.adhoc".new_initial_data_form; local mm_reload = require "modulemanager".reload; local s2s_destroy_session = require "core.s2smanager".destroy_session; local config = require "core.configmanager"; local config_get = config.get; local config_set = config.set; local t_concat = table.concat; local adhoc_new = module:require "adhoc".new; local time = os.time; local hosts = prosody.hosts; local host = module.host; local host_session = hosts[host]; local incoming_s2s = prosody.incoming_s2s; local s2s_sessions = module:shared"/*/s2s/sessions"; local default_tpl = [[ Hello there. This is a brief system message to let you know about some upcoming changes to the $HOST service. Some of your contacts are on other Jabber/XMPP services that do not support encryption. As part of an initiative to increase the security of the Jabber/XMPP network, this service ($HOST) will be participating in a series of tests to discover the impact of our planned changes, and you may lose the ability to communicate with some of your contacts. The test days will be on the following dates: January 4, February 22, March 22 and April 19. On these days we will require that all client and server connections are encrypted. Unless they enable encryption before that, you will be unable to communicate with your contacts that use these services: $SERVICES Your affected contacts are: $CONTACTS What can you do? You may tell your contacts to inform their service administrator about their lack of encryption. Your contacts may also switch to a more secure service. A list of public services can be found at https://xmpp.net/directory.php For more information about the Jabber/XMPP security initiative that we are participating in, please read the announcement at https://stpeter.im/journal/1496.html If you have any questions or concerns, you may contact us via $CONTACTVIA at $CONTACT ]]; local message = module:get_option_string("manifesto_contact_encryption_warning", default_tpl); local contact = module:get_option_string("admin_contact_address", module:get_option_array("admins", {})[1]); if not contact then error("mod_manifesto needs you to set 'admin_contact_address' in your config file.", 0); end local contact_method = "Jabber/XMPP"; if select(2, contact:gsub("^mailto:", "")) > 0 then contact_method = "email"; end local notified; module:hook("resource-bind", function (event) local session = event.session; local now = time(); local last_notify = notified[session.username] or 0; if last_notify > ( now - 86400 * 7 ) then return end timer.add_task(15, function () if session.type ~= "c2s" then return end -- user quit already local bad_contacts, bad_hosts = {}, {}; for contact_jid, item in pairs(session.roster or {}) do local _, contact_host = jid_split(contact_jid); local bad = false; local remote_host_session = host_session.s2sout[contact_host]; if remote_host_session and remote_host_session.type == "s2sout" then -- Only check remote hosts we have completed s2s connections to if not remote_host_session.secure then bad = true; end end for session in pairs(incoming_s2s) do if session.to_host == host and session.from_host == contact_host and session.type == "s2sin" then if not session.secure then bad = true; end end end if bad then local contact_name = item.name; if contact_name then table.insert(bad_contacts, contact_name.." <"..contact_jid..">"); else table.insert(bad_contacts, contact_jid); end if not bad_hosts[contact_host] then bad_hosts[contact_host] = true; table.insert(bad_hosts, contact_host); end end end if #bad_contacts > 0 then local vars = { HOST = host; CONTACTS = " "..table.concat(bad_contacts, "\n "); SERVICES = " "..table.concat(bad_hosts, "\n "); CONTACTVIA = contact_method, CONTACT = contact; }; session.send(st.message({ type = "headline", from = host }):tag("body"):text(message:gsub("$(%w+)", vars))); notified[session.username] = now; end end); end); function module.load() notified = dm.load(nil, host, module.name) or {}; end function module.save() dm.store(nil, host, module.name, notified); return { notified = notified }; end function module.restore(data) notified = data.notified; end function module.unload() dm.store(nil, host, module.name, notified); end function module.uninstall() dm.store(nil, host, module.name, nil); end -- Ad-hoc command for switching to/from "manifesto mode" local layout = dataforms_new { title = "Configure manifesto mode"; { name = "FORM_TYPE", type = "hidden", value = "http://prosody.im/protocol/manifesto" }; { name = "state", type = "list-single", required = true, label = "Manifesto mode:"}; }; local adhoc_handler = adhoc_initial(layout, function() local enabled = config_get(host, "c2s_require_encryption") and config_get(host, "s2s_require_encryption"); return { state = { { label = "Enabled", value = "enabled", default = enabled }, { label = "Configuration settings", value = "config", default = not enabled }, }}; end, function(fields, err) if err then local errmsg = {}; for name, err in pairs(errors) do errmsg[#errmsg + 1] = name .. ": " .. err; end return { status = "completed", error = { message = t_concat(errmsg, "\n") } }; end local info; if fields.state == "enabled" then config_set(host, "c2s_require_encryption", true); config_set(host, "s2s_require_encryption", true); for _, session in pairs(s2s_sessions) do if not session.secure then (session.close or s2s_destroy_session)(session); end end info = "Manifesto mode enabled"; else local ok, err = prosody.reload_config(); if not ok then return { status = "completed", error = { message = "Failed to reload config: " .. tostring(err) } }; end info = "Reset to configuration settings"; end local ok, err = mm_reload(host, "tls"); if not ok then return { status = "completed", error = { message = "Failed to reload mod_tls: " .. tostring(err) } }; end ok, err = mm_reload(host, "s2s"); if not ok then return { status = "completed", error = { message = "Failed to reload mod_s2s: " .. tostring(err) } }; end ok, err = mm_reload(host, "saslauth"); if not ok then return { status = "completed", error = { message = "Failed to reload mod_saslauth: " .. tostring(err) } }; end return { status = "completed", info = info }; end); module:provides("adhoc", adhoc_new("Configure manifesto mode", "http://prosody.im/protocol/manifesto", adhoc_handler, "admin"));
mit
gedads/Neodynamis
scripts/zones/Mhaura/npcs/Celestina.lua
3
2688
----------------------------------- -- Area: Mhaura -- NPC: Celestina -- Finish Quest: The Sand Charm -- Involved in Quest: Riding on the Clouds -- Guild Merchant NPC: Goldsmithing Guild -- !pos -37.624 -16.050 75.681 249 ----------------------------------- package.loaded["scripts/zones/Mhaura/TextIDs"] = nil; package.loaded["scripts/globals/settings"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Mhaura/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(OTHER_AREAS,THE_SAND_CHARM) == QUEST_ACCEPTED) then if (trade:hasItemQty(13095,1) and trade:getItemCount() == 1) then player:startEvent(0x007f); -- Finish quest "The Sand Charm" end end if (player:getQuestStatus(JEUNO,RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getVar("ridingOnTheClouds_3") == 5) then if (trade:hasItemQty(1127,1) and trade:getItemCount() == 1) then -- Trade Kindred seal player:setVar("ridingOnTheClouds_3",0); player:tradeComplete(); player:addKeyItem(SOMBER_STONE); player:messageSpecial(KEYITEM_OBTAINED,SOMBER_STONE); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getVar("theSandCharmVar") == 3) then player:startEvent(0x007e,13095); -- During quest "The Sand Charm" - 3rd dialog elseif (player:sendGuild(528,8,23,4)) then player:showText(npc,GOLDSMITHING_GUILD); 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 == 0x007e and option == 70) then player:setVar("theSandCharmVar",4); elseif (csid == 0x007f) then player:tradeComplete(); player:setVar("theSandCharmVar",0); player:setVar("SmallDialogByBlandine",1); player:addKeyItem(MAP_OF_BOSTAUNIEUX_OUBLIETTE); player:messageSpecial(KEYITEM_OBTAINED,MAP_OF_BOSTAUNIEUX_OUBLIETTE); player:addFame(OTHER_AREAS,30); player:completeQuest(OTHER_AREAS,THE_SAND_CHARM); end end;
gpl-3.0
gedads/Neodynamis
scripts/globals/mobskills/final_retribution.lua
31
1048
--------------------------------------------- -- Final Retribution -- Family: Corse -- Description: Damages enemies in an area of effect. Additional effect: Stun -- Type: Physical -- Utsusemi/Blink absorb: 1-3 shadows -- Range: Radial -- Notes: Only used by some notorious monsters like Xolotl. --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0; end; function onMobWeaponSkill(target, mob, skill) local numhits = 1; local accmod = 1; local dmgmod = 3.2; local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,MOBPARAM_3_SHADOW); local typeEffect = EFFECT_STUN; MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, 1, 0, 4); target:delHP(dmg); return dmg; end;
gpl-3.0
Jamanno/Zero-K-Infrastructure
Benchmarker/Benchmarks/Configs/ZKL_default/LuaUI/Config/ZK_order.lua
12
4858
-- Widget Order List (0 disables a widget) return { ["AA Command Helper"] = 14, AdvPlayersList = 0, ["Ally Resource Bars"] = 0, AllyCursors = 59, AnimatorGUI = 0, ["Attack AoE"] = 50, ["Attack Warning"] = 55, ["Auto First Build Facing"] = 15, ["Auto Group"] = 53, ["Auto Patrol Nanos"] = 16, ["Auto Reclaim/Heal/Assist"] = 0, ["Auto Repair"] = 0, ["Auto Set Retreat @60"] = 0, ["Automatic Tip Dispenser"] = 0, Autoquit = 17, ["Ballistic Calculator"] = 0, ["Blast Radius"] = 18, BlobShadow = 0, ["BloomShader (v0.31) (unstable)"] = 0, BlurApi = 0, ["Bounty & Marketplace Icons (experimental)"] = 0, BuildETA = 12, ["Building Starter"] = 74, CALayout = 0, ["CEG Spawner"] = 0, CameraRecorder = 0, CameraShake = 19, ["Central Build AI"] = 0, ["Chat Shortcut"] = 0, ["Chili Chat 2.1"] = 68, ["Chili Chat Bubbles"] = 20, ["Chili Core Selector"] = 75, ["Chili Crude Player List"] = 69, ["Chili Deluxe Player List - Alpha 2.02"] = 0, ["Chili Docking"] = 70, ["Chili FactoryBar"] = 0, ["Chili Framework"] = 71, ["Chili Gesture Menu"] = 78, ["Chili Integral Menu"] = 80, ["Chili Keyboard Menu"] = 0, ["Chili Minimap"] = 3, ["Chili Radial Build Menu"] = 0, ["Chili Rejoining Progress Bar"] = 21, ["Chili Resource Bars"] = 22, ["Chili Selections & CursorTip"] = 23, ["Chili Vote Display"] = 11, ["Chili Widget Selector"] = 4, ChiliInspector = 0, ChiliProfiler = 0, ["Clippy Comments"] = 52, ["Cloak Fire State"] = 13, ["Cloaker Guard"] = 75, ComCounter = 24, ["Combo Overhead/Free Camera (experimental)"] = 0, ["Comm Marker"] = 0, ["Comm-n-Elo Startpos. Info"] = 0, CommandInsert = 60, ["Commander Name Tags "] = 0, ["Constructor Auto Assist"] = 25, ["Context Menu"] = 26, ["Custom Cursor Sets"] = 5, CustomFormations2 = 79, DCIcon = 0, Darkening = 27, ["Decoration Handler"] = 28, ["Defense Range Zero-K"] = 12345, ["Dev Commands"] = 0, ["Disable Mouse Toggle"] = 0, ["Display DPS"] = 0, ["Double-Click Fight"] = 0, ["Dynamic Avoidance System"] = 0, ["EPIC Menu"] = 2, ["Easy Facing"] = 0, ["External VR Grid"] = 0, ["FPS Log"] = 0, ["FPS Log direct"] = 49, ["Ferry Points"] = 29, ["Gadget Icons"] = 61, ["Ghost Site"] = 53, Halo = 0, HealthBars = 9, ["Hide map marks and cursor"] = 7, ["Highlight Geos"] = 30, IdleBuildersNEW = 0, ["Image Preloader"] = 74, ["Jumpjet GUI"] = 77, ["Keep Target"] = 31, ["Keybind Updater v0.9.4"] = 0, ["Lag (AFK) monitor"] = 72, ["Lasso Terraform GUI"] = 81, ["Local Team Colors"] = 6, ["Local Widgets Config"] = 32, LockCamera = 0, ["LogFlush Disabler"] = 12345, Lups = 73, LupsManager = 66, LupsStats = 0, ["Map Draw Blocker"] = 0, ["Map Edge Barrier"] = 0, ["Map Edge Extension"] = 33, MessageBoxes = 51, MetalFeatures = 34, ["Mex Placement Handler"] = 35, ["Mexspot Fetcher"] = 6, ["MiniMap Start Boxes"] = 12345, MinimapEvents = 36, ["Missile Silo Range"] = 37, ["Modular Comm Info"] = 13, ["Music Player"] = 38, ["News Ticker"] = 0, Night = 0, ["Nightvision Shader"] = 0, NoDuplicateOrders = 54, Noises = 8, Nubtron = 56, ["Nuke Button Zero-K"] = 0, Objectives = 52, Outline = 0, ["Pause Screen"] = 39, ["Persistent Build Spacing"] = 40, ["PlanetWars Info"] = 12345, ["Point Tracker"] = 41, ["Rank Icons 2"] = 62, ["Receive Units Indicator"] = 82, ReclaimInfo = 42, ["Replace Cloak Con Orders"] = 0, ["Replay control buttons"] = 12345, ["Resource Stat Writer"] = 0, ["Restricted Zones"] = 76, Retreat = 43, ["Select Keys"] = 53, ["Selection Send"] = 63, ["Selection Squares"] = 0, SelectionCircle = 0, ["Shared Functions"] = 1, ["Shield Guard"] = 64, ["Show All Commands"] = 0, ["Smart Nanos"] = 0, ["Smoke Signal"] = 0, SmoothScroll = 54, SpecRun = 0, ["Specialmap Hide Decals"] = 0, ["Specific Unit Reclaimer"] = 0, ["Spectate Selected Team"] = 44, Spotter = 0, ["Starlight Drawer"] = 0, ["Start Point Remover & Comm Selector"] = 58, ["Startup Info and Selector"] = 55, ["State Icons"] = 65, ["State Reverse Toggle"] = 45, Stereo3D = 46, Stockpiler = 56, ["Stuck Keys"] = 0, ["TeamCommEnds & Lavarise indicator"] = 13, TeamPlatter = 0, ["Test Version Warning"] = 0, ["Text To Speech Control"] = 47, ["Transport AI"] = 57, Transporting = 0, ["Unit Icons"] = 10, ["Unit Marker Zero-K"] = 12345, ["Unit Mover"] = 0, ["Unit Start State"] = 57, UnitGroups = 0, UnitNoStuckInFactory = 55, UnitShapes = 58, ["Units on Fire"] = 67, ["Vertical Line on Radar Dots"] = 0, ["Voice Assistant"] = 48, Voices = 0, WidgetProfiler = 0, Widget_Fps_Log = 49, XrayHaloSelections = 0, XrayShader = 0, chiliGUIDemo = 0, lastWidgetDetailLevel = 2, unit_waypoint_dragger = 0, version = 8, }
gpl-3.0
laino/luakit
lib/quickmarks.lua
6
8888
---------------------------------------------------------------- -- Vimperator style quickmarking -- -- @author Piotr Husiatyński &lt;phusiatynski@gmail.com&gt; -- -- @author Mason Larobina &lt;mason.larobina@gmail.com&gt; -- ---------------------------------------------------------------- -- Get lua environment local os = os local io = io local assert = assert local string = string local ipairs = ipairs local pairs = pairs local tostring = tostring local type = type local table = table -- Get luakit environment local lousy = require "lousy" local window = window local add_binds, add_cmds = add_binds, add_cmds local new_mode, menu_binds = new_mode, menu_binds local capi = { luakit = luakit } module("quickmarks") local qmarks local quickmarks_file = capi.luakit.data_dir .. '/quickmarks' local function check_token(token) assert(string.match(tostring(token), "^(%w)$"), "invalid token: " .. tostring(token)) return token end --- Load quick bookmarks from storage file into memory -- @param fd_name bookmarks storage file path of nil to use default one function load(fd_name) if not qmarks then qmarks = {} end local fd_name = fd_name or quickmarks_file if not os.exists(fd_name) then return end for line in io.lines(fd_name) do local token, uris = string.match(lousy.util.string.strip(line), "^(%w)%s+(.+)$") if token then qmarks [token] = lousy.util.string.split(uris, ",%s+") end end end --- Save quick bookmarks to file -- @param fd_name bookmarks storage file path of nil to use default one function save(fd_name) -- Quickmarks init check if not qmarks then load() end local fd = io.open(fd_name or quickmarks_file, "w") for _, token in ipairs(lousy.util.table.keys(qmarks )) do local uris = table.concat(qmarks [token], ", ") fd:write(string.format("%s %s\n", token, uris)) end io.close(fd) end --- Return url related to given key or nil if does not exist -- @param token quick bookmarks mapping token -- @param load_file Call quickmark.load() before get function get(token, load_file) -- Load quickmarks from other sessions if not qmarks or load_file ~= false then load() end return qmarks[check_token(token)] end --- Return a list of all the tokens in the quickmarks table function get_tokens() if not qmarks then load() end return lousy.util.table.keys(qmarks ) end --- Set new quick bookmarks mapping -- @param token The token under which given uris will be available -- @param uris List of locations to quickmark -- @param load_file Call quickmark.load() before set -- @param save_file Call quickmark.save() after set function set(token, uris, load_file, save_file) -- Load quickmarks from other sessions if not qmarks or load_file ~= false then load() end -- Parse uris: "http://forum1.com, google.com, imdb some artist" if uris and type(uris) == "string" then uris = lousy.util.string.split(uris, ",%s+") elseif uris and type(uris) ~= "table" then error("invalid locations type: ", type(uris)) end qmarks[check_token(token)] = uris -- By default, setting new quickmark saves them to if save_file ~= false then save() end end --- Delete a quickmark -- @param token The quickmark token -- @param load_file Call quickmark.load() before deletion -- @param save_file Call quickmark.save() after deletion function del(token, load_file, save_file) -- Load quickmarks from other sessions if not qmarks or load_file ~= false then load() end qmarks[check_token(token)] = nil if save_file ~= false then save() end end --- Delete all quickmarks -- @param save_file Call quickmark.save() function. function delall(save_file) qmarks = {} if save_file ~= false then save() end end -- Add quickmarking binds to normal mode local buf = lousy.bind.buf add_binds("normal", { buf("^g[onw][a-zA-Z0-9]$", [[Jump to quickmark in current tab with `go{a-zA-Z0-9}`, `gn{a-zA-Z0-9}` to open in new tab and or `gw{a-zA-Z0-9}` to open a quickmark in a new window.]], function (w, b, m) local mode, token = string.match(b, "^g(.)(.)$") local uris = lousy.util.table.clone(get(token) or {}) for i, uri in ipairs(uris) do uris[i] = w:search_open(uri) end for c=1,m.count do if mode == "w" then window.new(uris) else for i, uri in ipairs(uris or {}) do if mode == "o" and c == 1 and i == 1 then w:navigate(uri) else w:new_tab(uri, i == 1) end end end end end, {count=1}), buf("^M[a-zA-Z0-9]$", [[Add quickmark for current URL.]], function (w, b) local token = string.match(b, "^M(.)$") local uri = w.view.uri set(token, {uri}) w:notify(string.format("Quickmarked %q: %s", token, uri)) end), }) -- Add quickmarking commands local cmd = lousy.bind.cmd add_cmds({ -- Quickmark add (`:qmark f http://forum1.com, forum2.com, imdb some artist`) cmd("qma[rk]", "Add a quickmark.", function (w, a) local token, uris = string.match(lousy.util.string.strip(a), "^(%w)%s+(.+)$") assert(token, "invalid token") uris = lousy.util.string.split(uris, ",%s+") set(token, uris) w:notify(string.format("Quickmarked %q: %s", token, table.concat(uris, ", "))) end), -- Quickmark edit (`:qmarkedit f` -> `:qmark f furi1, furi2, ..`) cmd({"qmarkedit", "qme"}, "Edit a quickmark.", function (w, a) token = lousy.util.string.strip(a) assert(#token == 1, "invalid token length: " .. token) local uris = get(token) w:enter_cmd(string.format(":qmark %s %s", token, table.concat(uris or {}, ", "))) end), -- Quickmark del (`:delqmarks b-p Aa z 4-9`) cmd("delqm[arks]", "Delete a quickmark.", function (w, a) -- Find and del all range specifiers string.gsub(a, "(%w%-%w)", function (range) range = "["..range.."]" for _, token in ipairs(get_tokens()) do if string.match(token, range) then del(token, false) end end end) -- Delete lone tokens string.gsub(a, "(%w)", function (token) del(token, false) end) save() end), -- View all quickmarks in an interactive menu cmd("qmarks", "List all quickmarks.", function (w) w:set_mode("qmarklist") end), -- Delete all quickmarks cmd({"delqmarks!", "delqm!"}, "Delete all quickmarks.", function (w) delall() end), }) -- Add mode to display all quickmarks in an interactive menu new_mode("qmarklist", { enter = function (w) local rows = {{ "Quickmarks", " URI(s)", title = true }} for _, qmark in ipairs(get_tokens()) do local uris = lousy.util.escape(table.concat(get(qmark, false), ", ")) table.insert(rows, { " " .. qmark, " " .. uris, qmark = qmark }) end w.menu:build(rows) w:notify("Use j/k to move, d delete, e edit, t tabopen, w winopen.", false) end, leave = function (w) w.menu:hide() end, }) -- Add additional binds to quickmarks menu mode local key = lousy.bind.key add_binds("qmarklist", lousy.util.table.join({ -- Delete quickmark key({}, "d", function (w) local row = w.menu:get() if row and row.qmark then del(row.qmark) w.menu:del() end end), -- Edit quickmark key({}, "e", function (w) local row = w.menu:get() if row and row.qmark then local uris = get(row.qmark) w:enter_cmd(string.format(":qmark %s %s", row.qmark, table.concat(uris or {}, ", "))) end end), -- Open quickmark key({}, "Return", function (w) local row = w.menu:get() if row and row.qmark then for i, uri in ipairs(get(row.qmark) or {}) do uri = w:search_open(uri) if i == 1 then w:navigate(uri) else w:new_tab(uri, false) end end end end), -- Open quickmark in new tab key({}, "t", function (w) local row = w.menu:get() if row and row.qmark then for _, uri in ipairs(get(row.qmark) or {}) do w:new_tab(w:search_open(uri), false) end end end), -- Open quickmark in new window key({}, "w", function (w) local row = w.menu:get() w:set_mode() if row and row.qmark then window.new(get(row.qmark) or {}) end end), -- Exit menu key({}, "q", function (w) w:set_mode() end), }, menu_binds)) -- vim: et:sw=4:ts=8:sts=4:tw=80
gpl-3.0
pedro-andrade-inpe/terrame
packages/base/tests/functional/alternative/SocialNetwork.lua
3
4695
------------------------------------------------------------------------------------------- -- TerraME - a software platform for multiple scale spatially-explicit dynamic modeling. -- Copyright (C) 2001-2017 INPE and TerraLAB/UFOP -- www.terrame.org -- This code is part of the TerraME framework. -- This framework is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public -- License as published by the Free Software Foundation; either -- version 2.1 of the License, or (at your option) any later version. -- You should have received a copy of the GNU Lesser General Public -- License along with this library. -- The authors reassure the license terms regarding the warranties. -- They specifically disclaim any warranties, including, but not limited to, -- the implied warranties of merchantability and fitness for a particular purpose. -- The framework provided hereunder is on an "as is" basis, and the authors have no -- obligation to provide maintenance, support, updates, enhancements, or modifications. -- In no event shall INPE and TerraLAB / UFOP be held liable to any party for direct, -- indirect, special, incidental, or consequential damages arising out of the use -- of this software and its documentation. -- ------------------------------------------------------------------------------------------- return{ add = function(unitTest) local sn = SocialNetwork() local ag1 = Agent{} local error_func = function() sn:add() end unitTest:assertError(error_func, mandatoryArgumentMsg(1)) error_func = function() sn:add(112) end unitTest:assertError(error_func, incompatibleTypeMsg(1, "Agent", 112)) error_func = function() sn:add(ag1, "not_number") end unitTest:assertError(error_func, incompatibleTypeMsg(2, "number", "not_number")) error_func = function() sn:add(ag1) end unitTest:assertError(error_func, "Agent should have an id in order to be added to a SocialNetwork.") ag1 = Agent{id = "1"} sn:add(ag1) error_func = function() sn:add(ag1) end unitTest:assertError(error_func, "Agent '1' already belongs to the SocialNetwork.") end, getWeight = function(unitTest) local ag1 = Agent{id = "1"} local ag2 = Agent{} local sn = SocialNetwork() local cell = Cell{} local error_func = function() sn:getWeight() end unitTest:assertError(error_func, mandatoryArgumentMsg(1)) error_func = function() sn:getWeight(cell) end unitTest:assertError(error_func, incompatibleTypeMsg(1, "Agent", cell)) error_func = function() sn:getWeight(ag2) end unitTest:assertError(error_func, "Agent does not belong to the SocialNetwork because it does not have an id.") error_func = function() sn:getWeight(ag1) end unitTest:assertError(error_func, "Agent '1' does not belong to the SocialNetwork.") end, isConnection = function(unitTest) local sn = SocialNetwork() local error_func = function() sn:isConnection() end unitTest:assertError(error_func, mandatoryArgumentMsg(1)) error_func = function() sn:isConnection(123) end unitTest:assertError(error_func, incompatibleTypeMsg(1, "Agent", 123)) end, remove = function(unitTest) local sn = SocialNetwork() local error_func = function() sn:remove() end unitTest:assertError(error_func, mandatoryArgumentMsg(1)) error_func = function() sn:remove(123) end unitTest:assertError(error_func, incompatibleTypeMsg(1, "Agent", 123)) end, sample = function(unitTest) local sn = SocialNetwork() local error_func = function() sn:sample() end unitTest:assertError(error_func, "It is not possible to sample the SocialNetwork because it is empty.") end, setWeight = function(unitTest) local ag1 = Agent{id = "1"} local ag2 = Agent{} local sn = SocialNetwork() local cell = Cell{} local error_func = function() sn:setWeight() end unitTest:assertError(error_func, mandatoryArgumentMsg(1)) error_func = function() sn:setWeight(cell) end unitTest:assertError(error_func, incompatibleTypeMsg(1, "Agent", cell)) error_func = function() sn:setWeight(ag1) end unitTest:assertError(error_func, mandatoryArgumentMsg(2)) error_func = function() sn:setWeight(ag1, "notnumber") end unitTest:assertError(error_func, incompatibleTypeMsg(2, "number", "notnumber")) error_func = function() sn:setWeight(ag2, 0.5) end unitTest:assertError(error_func, "Agent does not belong to the SocialNetwork because it does not have an id.") error_func = function() sn:setWeight(ag1, 0.5) end unitTest:assertError(error_func, "Agent '1' does not belong to the SocialNetwork.") end }
lgpl-3.0
gedads/Neodynamis
scripts/zones/Port_Bastok/npcs/Alib-Mufalib.lua
2
4065
----------------------------------- -- Area: Port Bastok -- NPC: Alib-Mufalib -- Type: Warp NPC -- !pos 116.080 7.372 -31.820 236 ----------------------------------- package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/globals/missions"); require("scripts/globals/teleports"); require("scripts/globals/keyitems"); require("scripts/zones/Port_Bastok/TextIDs"); --[[ Bitmask Designations: Port Bastok (East to West) 00001 (J-5) Kaede (northernmost house) 00002 (F-5) Patient Wheel (north of Warehouse 2) 00004 (F-6) Paujean (bottom floor of Warehouse 2) 00008 (E-6) Hilda (Steaming Sheep Restaurant, walks on the top floor and occasionally down. However, she can still be talked to when on second floor. Unable to get if you have Cid's Secret flagged.) 00010 (F-8) Tilian (end of a pier west of Air Travel Agency) Metalworks (all found on top floor) 00020 (G-8) Raibaht (Cid's lab) 00040 (G-8) Invincible Shield (outside Cid's Lab) 00080 (G-7) Manilam (on top of Cermet Refinery) 00100 (I-8) Kaela (between Consulate of Windurst & Consulate of Bastok) 00200 (K-7) Ayame (Inside north Cannonry) Bastok Markets (East to West) 00400 (K-10) Harmodios (Harmodios's Music Shop) 00800 (J-10) Arawn (west of music store) 01000 (I-9) Horatius (Inside Trader's Home) 02000 (E-10) Ken (outside Mjoll's General Goods) 04000 (E-11) Pavel (West Gate to South Gustaberg) Bastok Mines (Clockwise, starting at Ore Street, upper floor to lower floor) 08000 (H-5) Griselda (upper floor, Bat's Lair Inn) 10000 (I-6) Goraow (upper floor, in stairwell of Ore Street) 20000 (I-7) Echo Hawk (lower floor, Ore Street) 40000 (H-6) Deidogg (lower floor, Ore Street) 80000 (H-9) Vaghron (southwest of South Auction House) ]]-- function onTrade(player,npc,trade) if (trade:getGil() == 300 and trade:getItemCount() == 1 and player:getQuestStatus(BASTOK,LURE_OF_THE_WILDCAT_BASTOK) == QUEST_COMPLETED and player:getCurrentMission(TOAU) > IMMORTAL_SENTRIES) then -- Needs a check for at least traded an invitation card to Naja Salaheem player:startEvent(0x017b); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local LureBastok = player:getQuestStatus(BASTOK,LURE_OF_THE_WILDCAT_BASTOK); local WildcatBastok = player:getVar("WildcatBastok"); if (LureBastok ~= 2 and ENABLE_TOAU == 1) then if (LureBastok == 0) then player:startEvent(0x0165); else if (WildcatBastok == 0) then player:startEvent(0x0166); elseif (player:isMaskFull(WildcatBastok,20) == true) then player:startEvent(0x0168); else player:startEvent(0x0167); end end elseif (player:getCurrentMission(TOAU) >= 2) then player:startEvent(0x017a); else player:startEvent(0x0169); end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0165) then player:addQuest(BASTOK,LURE_OF_THE_WILDCAT_BASTOK); player:setVar("WildcatBastok",0); player:addKeyItem(BLUE_SENTINEL_BADGE); player:messageSpecial(KEYITEM_OBTAINED,BLUE_SENTINEL_BADGE); elseif (csid == 0x0168) then player:completeQuest(BASTOK,LURE_OF_THE_WILDCAT_BASTOK); player:addFame(BASTOK,150); player:setVar("WildcatBastok",0); player:delKeyItem(BLUE_SENTINEL_BADGE); player:addKeyItem(BLUE_INVITATION_CARD); player:messageSpecial(KEYITEM_LOST,BLUE_SENTINEL_BADGE); player:messageSpecial(KEYITEM_OBTAINED,BLUE_INVITATION_CARD); elseif (csid == 0x017b) then player:tradeComplete(); toAhtUrhganWhitegate(player); end end;
gpl-3.0
O-P-E-N/CC-ROUTER
feeds/luci/applications/luci-app-meshwizard/luasrc/model/cbi/freifunk/meshwizard.lua
92
6917
-- wizard rewrite wip local uci = require "luci.model.uci".cursor() local sys = require "luci.sys" local util = require "luci.util" local ip = require "luci.ip" local community = "profile_" .. (uci:get("freifunk", "community", "name") or "Freifunk") local mesh_network = ip.IPv4(uci:get_first(community, "community", "mesh_network") or "10.0.0.0/8") local community_ipv6 = uci:get_first(community, "community", "ipv6") or 0 local community_ipv6mode = uci:get_first(community, "community", "ipv6_config") or "static" local meshkit_ipv6 = uci:get("meshwizard", "ipv6", "enabled") or 0 local community_vap = uci:get_first(community, "community", "vap") or 0 m = Map("meshwizard", translate("Wizard"), translate("This wizard will assist you in setting up your router for Freifunk " .. "or another similar wireless community network.")) n = m:section(NamedSection, "netconfig", nil, translate("Interfaces")) n.anonymous = true -- common functions function cbi_configure(device) local configure = n:taboption(device, Flag, device .. "_config", translate("Configure this interface"), translate("Note: this will set up this interface for mesh operation, i.e. add it to zone 'freifunk' and enable olsr.")) end function cbi_ip4addr(device) local ip4addr = n:taboption(device, Value, device .. "_ip4addr", translate("Mesh IP address"), translate("This is a unique address in the mesh (e.g. 10.1.1.1) and has to be registered at your local community.")) ip4addr:depends(device .. "_config", 1) ip4addr.datatype = "ip4addr" function ip4addr.validate(self, value) local x = ip.IPv4(value) if mesh_network:contains(x) then return value else return nil, translate("The given IP address is not inside the mesh network range ") .. "(" .. mesh_network:string() .. ")." end end end function cbi_ip6addr(device) local ip6addr = n:taboption(device, Value, device .. "_ip6addr", translate("Mesh IPv6 address"), translate("This is a unique IPv6 address in CIDR notation (e.g. 2001:1:2:3::1/64) and has to be registered at your local community.")) ip6addr:depends(device .. "_config", 1) ip6addr.datatype = "ip6addr" end function cbi_dhcp(device) local dhcp = n:taboption(device, Flag, device .. "_dhcp", translate("Enable DHCP"), translate("DHCP will automatically assign ip addresses to clients")) dhcp:depends(device .. "_config", 1) dhcp.rmempty = true end function cbi_ra(device) local ra = n:taboption(device, Flag, device .. "_ipv6ra", translate("Enable RA"), translate("Send router advertisements on this device.")) ra:depends(device .. "_config", 1) ra.rmempty = true end function cbi_dhcprange(device) local dhcprange = n:taboption(device, Value, device .. "_dhcprange", translate("DHCP IP range"), translate("The IP range from which clients are assigned ip addresses (e.g. 10.1.2.1/28). " .. "If this is a range inside your mesh network range, then it will be announced as HNA. Any other range will use NAT. " .. "If left empty then the defaults from the community profile will be used.")) dhcprange:depends(device .. "_dhcp", "1") dhcprange.rmempty = true dhcprange.datatype = "ip4addr" end -- create tabs and config for wireless local nets={} uci:foreach("wireless", "wifi-device", function(section) local device = section[".name"] table.insert(nets, device) end) local wired_nets = {} uci:foreach("network", "interface", function(section) local device = section[".name"] if not util.contains(nets, device) and device ~= "loopback" and not device:find("wireless") then table.insert(nets, device) table.insert(wired_nets, device) end end) for _, net in util.spairs(nets, function(a,b) return (nets[a] < nets[b]) end) do n:tab(net, net) end -- create cbi config for wireless uci:foreach("wireless", "wifi-device", function(section) local device = section[".name"] local hwtype = section.type local syscc = section.country or uci:get(community, "wifi_device", "country") or uci:get("freifunk", "wifi_device", "country") cbi_configure(device) -- Channel selection if hwtype == "atheros" then local cc = util.trim(sys.exec("grep -i '" .. syscc .. "' /lib/wifi/cc_translate.txt |cut -d ' ' -f 2")) or 0 sys.exec('"echo " .. cc .. " > /proc/sys/dev/" .. device .. "/countrycode"') elseif hwtype == "mac80211" then sys.exec("iw reg set " .. syscc) elseif hwtype == "broadcom" then sys.exec ("wlc country " .. syscc) end local chan = n:taboption(device, ListValue, device .. "_channel", translate("Channel"), translate("Your device and neighbouring nodes have to use the same channel.")) chan:depends(device .. "_config", 1) chan:value('default') local iwinfo = sys.wifi.getiwinfo(device) if iwinfo and iwinfo.freqlist then for _, f in ipairs(iwinfo.freqlist) do if not f.restricted then chan:value(f.channel) end end end -- IPv4 address cbi_ip4addr(device) -- DHCP enable cbi_dhcp(device) -- DHCP range cbi_dhcprange(device) -- IPv6 addr and RA if community_ipv6 == "1" then if community_ipv6mode == "static" then cbi_ip6addr(device) end cbi_ra(device) end -- Enable VAP local supports_vap = 0 if sys.call("/usr/bin/meshwizard/helpers/supports_vap.sh " .. device .. " " .. hwtype) == 0 then supports_vap = 1 end if supports_vap == 1 then local vap = n:taboption(device, Flag, device .. "_vap", translate("Virtual Access Point (VAP)"), translate("This will setup a new virtual wireless interface in Access Point mode.")) vap:depends(device .. "_dhcp", "1") vap.rmempty = true if community_vap == "1" then vap.default = "1" end end end) for _, device in pairs(wired_nets) do cbi_configure(device) cbi_ip4addr(device) cbi_dhcp(device) cbi_dhcprange(device) -- IPv6 addr and RA if community_ipv6 == "1" then if community_ipv6mode == "static" then cbi_ip6addr(device) end cbi_ra(device) end end -- General settings g = m:section(TypedSection, "general", translate("General Settings")) g.anonymous = true local cleanup = g:option(Flag, "cleanup", translate("Cleanup config"), translate("If this is selected then config is cleaned before setting new config options.")) cleanup.default = "1" local restrict = g:option(Flag, "local_restrict", translate("Protect LAN"), translate("Check this to protect your LAN from other nodes or clients") .. " (" .. translate("recommended") .. ").") local share = g:option(Flag, "sharenet", translate("Share your internet connection"), translate("Select this to allow others to use your connection to access the internet.")) share.rmempty = true -- IPv6 config if community_ipv6 == "1" then v6 = m:section(NamedSection, "ipv6", nil, translate("IPv6 Settings")) local enabled = v6:option(Flag, "enabled", translate("Enabled"), translate("Activate or deactivate IPv6 config globally.")) enabled.default = meshkit_ipv6 enabled.rmempty = false end return m
gpl-2.0
pedro-andrade-inpe/terrame
packages/luadoc/lua/main/util.lua
1
7822
------------------------------------------------------------------------------- -- General utilities. -- @release $Id: util.lua,v 1.16 2008/02/17 06:42:51 jasonsantos Exp $ ------------------------------------------------------------------------------- -- local lfs = require "lfs" local table, io, assert, setmetatable = table, io, assert, setmetatable local string, ipairs, mkDir, printError = string, ipairs, lfs.mkdir, _Gtme.printError ------------------------------------------------------------------------------- -- Module with several utilities that could not fit in a specific module -- module "luadoc.util" ------------------------------------------------------------------------------- -- Removes spaces from the begining and end of a given string -- @arg s string to be trimmed -- @return trimmed string function trim(s) return (string.gsub(s, "^%s*(.-)%s*$", "%1")) end ------------------------------------------------------------------------------- -- Removes spaces from the begining and end of a given string, considering the -- string is inside a lua comment. -- @arg s string to be trimmed -- @return trimmed string -- @see trim -- @see string.gsub function trim_comment(s) s = string.gsub(s, "%-%-+(.*)$", "%1") return trim(s) end ------------------------------------------------------------------------------- -- Checks if a given line is empty -- @arg line string with a line -- @return true if line is empty, false otherwise function line_empty(line) return (string.len(trim(line)) == 0) end ------------------------------------------------------------------------------- -- Appends two string, but if the first one is nil, use to second one -- @arg str1 first string, can be nil -- @arg str2 second string -- @return str1 .. " " .. str2, or str2 if str1 is nil function concat(str1, str2) if str1 == nil or string.len(str1) == 0 then return str2 else return str1 .. " " .. str2 end end ------------------------------------------------------------------------------- -- Split text into a list consisting of the strings in text, -- separated by strings matching delim (which may be a pattern). -- @arg delim if delim is "" then action is the same as %s+ except that -- field 1 may be preceeded by leading whitespace -- @usage split(",%s*", "Anna, Bob, Charlie,Dolores") -- @usage split(""," x y") gives {"x","y"} -- @usage split("%s+"," x y") gives {"", "x","y"} -- @return array with strings -- @see table.concat function split(delim, text) local list = {} --if string.len(text) > 0 then if text and #text > 0 then delim = delim or "" local pos = 1 -- if delim matches empty string then it would give an endless loop if string.find("", delim, 1) and delim ~= "" then error("delim matches empty string!") end local first, last while 1 do if delim ~= "" then first, last = string.find(text, delim, pos) else first, last = string.find(text, "%s+", pos) if first == 1 then pos = last+1 first, last = string.find(text, "%s+", pos) end end if first then -- found? table.insert(list, string.sub(text, pos, first-1)) pos = last+1 else table.insert(list, string.sub(text, pos)) break end end end return list end ------------------------------------------------------------------------------- -- Comments a paragraph. -- @arg text text to comment with "--", may contain several lines -- @return commented text function comment(text) text = string.gsub(text, "\n", "\n-- ") return "-- " .. text end ------------------------------------------------------------------------------- -- Wrap a string into a paragraph. -- @arg s string to wrap -- @arg w width to wrap to [80] -- @arg i1 indent of first line [0] -- @arg i2 indent of subsequent lines [0] -- @return wrapped paragraph function wrap(s, w, i1, i2) w = w or 80 i1 = i1 or 0 i2 = i2 or 0 assert(i1 < w and i2 < w, "the indents must be less than the line width") s = string.rep(" ", i1) .. s local lstart, len = 1, string.len(s) while len - lstart > w do local i = lstart + w while i > lstart and string.sub(s, i, i) ~= " " do i = i - 1 end local j = i while j > lstart and string.sub(s, j, j) == " " do j = j - 1 end s = string.sub(s, 1, j) .. "\n" .. string.rep(" ", i2) .. string.sub(s, i + 1, -1) local change = i2 + 1 - (i - j) lstart = j + change len = len + change end return s end ------------------------------------------------------------------------------- -- Opens a file, creating the directories if necessary -- @arg filename full path of the file to open (or create) -- @arg mode mode of opening -- @return file handle function openFile (filename, mode) local f = io.open(filename, mode) if f == nil then filename = string.gsub(filename, "\\", "/") local dir = "" for d in string.gmatch(filename, ".-/") do dir = dir .. d mkDir(dir) end f = io.open(filename, mode) end return f end ---------------------------------------------------------------------------------- -- Creates a Logger with LuaLogging, if present. Otherwise, creates a mock logger. -- @arg options a table with options for the logging mechanism -- @return logger object that will implement log methods function loadlogengine(options) -- TODO: Verify this block -- local logenabled = pcall(function() -- require "logging" -- require "logging.console" -- end) local logging = logenabled and logging if logenabled then if options.filelog then logger = logging.file("luadoc.log") -- use this to get a file log else logger = logging.console("[%level] %message\n") end if options.verbose then logger:setLevel(logging.INFO) else logger:setLevel(logging.WARN) end else noop = {__index=function() return function() -- noop end end} logger = {} setmetatable(logger, noop) end return logger end local check_arguments -- Sort a tab descriptor and check for declared arguments function parse_tab(tab, func, filename, doc_report) local arguments = {} local header = tab[1] local is_strategy_table for k, title in ipairs(header) do local mtitle = title:lower() if mtitle:match("arguments") then is_strategy_table = true local line = 2 while (line <= #tab) do local arg_list = tab[line][k] local arg_tab = split(",%s*", arg_list) table.sort(arg_tab) if arg_tab[1] == "..." then table.remove(arg_tab, 1) table.insert(arg_tab, "...") end arg_list = table.concat(arg_tab, ", ") tab[line][k] = arg_list line = line + 1 for _, v in ipairs(arg_tab) do v = v:match("%S+") if not arguments[v] then arguments[v] = v table.insert(arguments, v) end end end end end if is_strategy_table then check_arguments(arguments, func, filename, header[1], doc_report) end end function check_arguments(parsed_args, func, _, header, doc_report) local unknown = {} local unused = {} for _, arg in ipairs(parsed_args) do if not func.arg[arg] and not unknown[arg] then unknown[arg] = arg table.insert(unknown, arg) end end for _, arg in ipairs(func.arg) do if not parsed_args[arg] and not func.tabular[arg] and not unused[arg] then unused[arg] = arg table.insert(unused, arg) end end for _, arg in ipairs(unknown) do local warning = "Unknown argument '%s' for '%s' used in the @tabular" if header then warning = warning.." for '"..header.."'" end printError(warning:format(arg, func.name)) doc_report.unknown_arg = doc_report.unknown_arg + 1 end for _, arg in ipairs(unused) do local warning = "Argument '%s' for '%s' is not used in the @tabular" if header then warning = warning.." for '"..header.."'" end printError(warning:format(arg, func.name)) doc_report.unused_arg = doc_report.unused_arg + 1 end end
lgpl-3.0
Amorph/premake-stable
src/actions/vstudio/vs200x_vcproj_user.lua
26
1489
-- -- vs200x_vcproj_user.lua -- Generate a Visual Studio 2002-2008 C/C++ project .user file -- Copyright (c) 2011 Jason Perkins and the Premake project -- -- -- Set up namespaces -- local vc200x = premake.vstudio.vc200x -- -- Generate the .vcproj.user file -- function vc200x.generate_user(prj) vc200x.header('VisualStudioUserFile') _p(1,'ShowAllFiles="false"') _p(1,'>') _p(1,'<Configurations>') for _, cfginfo in ipairs(prj.solution.vstudio_configs) do if cfginfo.isreal then local cfg = premake.getconfig(prj, cfginfo.src_buildcfg, cfginfo.src_platform) _p(2,'<Configuration') _p(3,'Name="%s"', premake.esc(cfginfo.name)) _p(3,'>') vc200x.debugdir(cfg) _p(2,'</Configuration>') end end _p(1,'</Configurations>') _p('</VisualStudioUserFile>') end -- -- Output the debug settings element -- function vc200x.environmentargs(cfg) if cfg.environmentargs and #cfg.environmentargs > 0 then _p(4,'Environment="%s"', string.gsub(table.concat(cfg.environmentargs, "&#x0A;"),'"','&quot;')) if cfg.flags.EnvironmentArgsDontMerge then _p(4,'EnvironmentMerge="false"') end end end function vc200x.debugdir(cfg) _p(3,'<DebugSettings') if cfg.debugdir then _p(4,'WorkingDirectory="%s"', path.translate(cfg.debugdir, '\\')) end if #cfg.debugargs > 0 then _p(4,'CommandArguments="%s"', table.concat(cfg.debugargs, " ")) end vc200x.environmentargs(cfg) _p(3,'/>') end
bsd-3-clause
gedads/Neodynamis
scripts/zones/Northern_San_dOria/npcs/Taulenne.lua
16
5134
----------------------------------- -- Area: Northern San d'Oria -- NPC: Taulenne -- Armor Storage NPC ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; package.loaded["scripts/globals/armorstorage"] = nil; ----------------------------------- require("scripts/zones/Northern_San_dOria/TextIDs"); require("scripts/globals/armorstorage"); require("scripts/globals/settings"); require("scripts/globals/quests"); local Deposit = 0x0304; local Withdrawl = 0x0305; local ArraySize = #StorageArray; local G1 = 0; local G2 = 0; local G3 = 0; local G4 = 0; local G5 = 0; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) 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 for SetId = 1,ArraySize,11 do local TradeCount = trade:getItemCount(); local T1 = trade:hasItemQty(StorageArray[SetId + 5],1); if (T1 == true) then if (player:hasKeyItem(StorageArray[SetId + 10]) == false) then if (TradeCount == StorageArray[SetId + 3]) then local T2 = trade:hasItemQty(StorageArray[SetId + 4],1); local T3 = trade:hasItemQty(StorageArray[SetId + 6],1); local T4 = trade:hasItemQty(StorageArray[SetId + 7],1); local T5 = trade:hasItemQty(StorageArray[SetId + 8],1); if (StorageArray[SetId + 4] == 0) then T2 = true; end if (StorageArray[SetId + 6] == 0) then T3 = true; end if (StorageArray[SetId + 7] == 0) then T4 = true; end if (StorageArray[SetId + 8] == 0) then T5 = true; end if (T2 == true and T3 == true and T4 == true and T5 == true) then player:startEvent(Deposit,0,0,0,0,0,StorageArray[SetId + 9]); player:addKeyItem(StorageArray[SetId + 10]); player:messageSpecial(KEYITEM_OBTAINED,StorageArray[SetId + 10]); break; end end end end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local CurrGil = player:getGil(); for KeyItem = 11,ArraySize,11 do if player:hasKeyItem(StorageArray[KeyItem]) then if StorageArray[KeyItem - 9] == 1 then G1 = G1 + StorageArray[KeyItem - 8]; elseif StorageArray[KeyItem - 9] == 2 then G2 = G2 + StorageArray[KeyItem - 8]; elseif StorageArray[KeyItem - 9] == 3 then G3 = G3 + StorageArray[KeyItem - 8]; elseif StorageArray[KeyItem - 9] == 4 then G4 = G4 + StorageArray[KeyItem - 8]; elseif StorageArray[KeyItem - 9] == 6 then G5 = G5 + StorageArray[KeyItem - 8]; end end end player:startEvent(Withdrawl,G1,G2,G3,G4,CurrGil,G5); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) if (csid == Withdrawl) then player:updateEvent( StorageArray[option * 11 - 6], StorageArray[option * 11 - 5], StorageArray[option * 11 - 4], StorageArray[option * 11 - 3], StorageArray[option * 11 - 2], StorageArray[option * 11 - 1]); end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) if (csid == Withdrawl) then if (option > 0 and option <= StorageArray[ArraySize] - 10) then if (player:getFreeSlotsCount() >= StorageArray[option * 11 - 7]) then for Item = 2,6,1 do if (StorageArray[option * 11 - Item] > 0) then player:addItem(StorageArray[option * 11 - Item],1); player:messageSpecial(ITEM_OBTAINED,StorageArray[option * 11 - Item]); end end player:delKeyItem(StorageArray[option * 11]); player:setGil(player:getGil() - StorageArray[option * 11 - 1]); else for Item = 2,6,1 do if (StorageArray[option * 11 - Item] > 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,StorageArray[option * 11 - Item]); end end end end end if (csid == Deposit) then player:tradeComplete(); end end;
gpl-3.0
Erns/Erns-Suicide-Kings
Ern_SKTab_Options.lua
1
11185
--[[ Ern's Suicide Kings <Ern_SKTab_Options.lua> Original Creation Date: 7/18/2012 Updated Date: 2/16/2014 Contact: Ern.Warcraft@gmail.com Refer to LICENSE.txt for the Apache License, Version 2.0. Copyright 2012-2014 Aaron Sayles. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]] btnOptionsTabList = {} fntOptionsTabList = {} btnOptionsTabPlayer = {} fntOptionsTabPlayer = {} function optionsOnShow() --Activate Sync option as appropriate local _, partyID = GetLootMethod() btnOptionsTab_AltSync:Disable() if (IsInGroup() and partyID == 0) then btnOptionsTab_AltSync:Enable() end end --Create new list entry and button function createListButton(index, offset) ---> Main Tab if (btnMainTabList[index] == "" or btnMainTabList[index] == nil) then btnMainTabList[index] = CreateFrame("Button","btnMainTabList"..index, scrMainTab_ListsChild, "scrMainTab_List_Template") btnMainTabList[index]:SetPoint("TOPLEFT", 7, offset) btnMainTabList[index]:SetWidth(140) btnMainTabList[index]:SetHeight(12) fntMainTabList[index] = btnMainTabList[index]:CreateFontString("fntMainTabList"..index) fntMainTabList[index]:SetFont("Fonts\\FRIZQT__.TTF", 11, "OUTLINE") fntMainTabList[index]:SetText("") fntMainTabList[index]:SetPoint("LEFT", btnMainTabList[index], "LEFT", 5, 0) end ---> Options Tab if (btnOptionsTabList[index] == "" or btnOptionsTabList[index] == nil) then btnOptionsTabList[index] = CreateFrame("Button","btnOptionsTabList"..index, scrOptionsTab_ListsChild, "scrOptionsTab_List_Template") btnOptionsTabList[index]:SetPoint("TOPLEFT", 7, offset) btnOptionsTabList[index]:SetWidth(140) btnOptionsTabList[index]:SetHeight(12) fntOptionsTabList[index] = btnOptionsTabList[index]:CreateFontString("fntOptionsTabList"..index) fntOptionsTabList[index]:SetFont("Fonts\\FRIZQT__.TTF", 11, "OUTLINE") fntOptionsTabList[index]:SetText("") fntOptionsTabList[index]:SetPoint("LEFT", btnOptionsTabList[index], "LEFT", 5, 0) end end --Modify existing List Button function modifyListButton(index) ---> Main Tab btnMainTabList[index]:Show() btnMainTabList[index]:SetHighlightTexture(sButtonHighlight) fntMainTabList[index]:SetText(listAdded[index]) ---> Options Tab btnOptionsTabList[index]:Show() btnOptionsTabList[index]:SetHighlightTexture(sButtonHighlight) fntOptionsTabList[index]:SetText(listAdded[index]) end --Create blank Player buttons function createPlayerButton(index, offset) ---> Main Tab if (btnMainTabPlayer[index] == "" or btnMainTabPlayer[index] == nil) then btnMainTabPlayer[index] = CreateFrame("Button","btnMainTabPlayer"..index, scrMainTab_PlayersChild, "scrMainTab_Player_Template") btnMainTabPlayer[index]:SetPoint("TOPLEFT", 0, offset) btnMainTabPlayer[index]:SetWidth(140) btnMainTabPlayer[index]:SetHeight(12) fntMainTabPlayer[index] = btnMainTabPlayer[index]:CreateFontString("fntMainTabPlayer"..index) fntMainTabPlayer[index]:SetFont("Fonts\\FRIZQT__.TTF", 11, "OUTLINE") fntMainTabPlayer[index]:SetText("") fntMainTabPlayer[index]:SetPoint("LEFT", btnMainTabPlayer[index], "LEFT", 5, 0) end ---> Options Tab if (btnOptionsTabPlayer[index] == "" or btnOptionsTabPlayer[index] == nil) then btnOptionsTabPlayer[index] = CreateFrame("Button","btnOptionsTabPlayer"..index, scrOptionsTab_PlayersChild, "scrOptionsTab_Player_Template") btnOptionsTabPlayer[index]:SetPoint("TOPLEFT", 0, offset) btnOptionsTabPlayer[index]:SetWidth(140) btnOptionsTabPlayer[index]:SetHeight(12) fntOptionsTabPlayer[index] = btnOptionsTabPlayer[index]:CreateFontString("fntOptionsTabPlayer"..index) fntOptionsTabPlayer[index]:SetFont("Fonts\\FRIZQT__.TTF", 11, "OUTLINE") fntOptionsTabPlayer[index]:SetText("") fntOptionsTabPlayer[index]:SetPoint("LEFT", btnOptionsTabPlayer[index], "LEFT", 5, 0) end end --Collect and send sync data function performAltSync() local playerOrder = {} SendAddonMessage("ESK_ALTS_START", "", "RAID") for key, value in pairs(ErnSK_Alts) do SendAddonMessage("ESK_ALTS_KEY", key, "RAID") --Get clean table of alt data clearTable(playerOrder) local playersListed = Split(ErnSK_Alts[key], ";;") for _, value2 in pairs(playersListed) do if (value2 ~= nil and value2 ~= "") then table.insert(playerOrder, value2) end end --Setup alts to send, sending multiple sets if string gets too long local sendPlayers = "" for i = 1, #playerOrder do sendPlayers = sendPlayers .. playerOrder[i] .. ";;" --If the string length is starting to get too long and there's more to send if (strlen(sendPlayers) > 200 and i < #playerOrder) then SendAddonMessage("ESK_ALTS_VALUES", sendPlayers, "RAID") sendPlayers = "" end end SendAddonMessage("ESK_ALTS_VALUES", sendPlayers, "RAID") SendAddonMessage("ESK_ALTS_DATA", sendPlayers, "RAID") end SendAddonMessage("ESK_ALTS_FINISH", "", "RAID") end ------------------- -- BUTTONS ------------------- function btnOptionsTab_ListAdd_OnClick() StaticPopup_Show("OptionsTab_AddList") end function btnOptionsTab_ListCopy_OnClick() StaticPopup_Show("OptionsTab_CopyList") end function btnOptionsTab_ListRemove_OnClick() StaticPopup_Show("OptionsTab_RemoveList") end function btnOptionsTab_PlayerAdd_OnClick() frmOptions_SKTab_AddPlayer:Show() fntOptionsTab_AddPlayer_ListName:SetText(selectedList) end function btnOptionsTab_PlayerRemove_OnClick() StaticPopup_Show("OptionsTab_RemovePlayer") end function btnOptionsTab_AltJoiner_OnClick() frmOptions_SKTab_AltJoiner:Show() end function btnOptionsTab_AltSync_OnClick() StaticPopup_Show("OptionTab_SyncConfirm") end -- Player Tooltips --->Tooltip enter local function PlayerAltTooltip_OnEnter(self) local index for key, value in pairs(btnOptionsTabPlayer) do if (btnOptionsTabPlayer[key] == self) then index = key break end end local sPlayer = fntOptionsTabPlayer[index]:GetText() if (ErnSK_Alts[sPlayer] ~= nil and ErnSK_Alts[sPlayer] ~= "") then GameTooltip:SetOwner(self, "ANCHOR_CURSOR") local playerFirstName = Split(sPlayer, "-") GameTooltip:SetText(playerFirstName[1].."'s Alts:") local playersListed = Split(ErnSK_Alts[sPlayer], ";;") table.sort(playersListed) for key, value in pairs(playersListed) do if (value ~= nil and value ~= "") then local sAlt = nameOnly(value) GameTooltip:AddLine("- " .. value, 1, 1, 1) end end GameTooltip:Show() end end --->Tooltip leave local function PlayerAltTooltip_OnLeave() GameTooltip:Hide() end --Sync Tooltip --->Tooltip enter function btnOptionsTab_AltSync_OnEnter(self) if btnOptionsTab_AltSync:GetButtonState() == "DISABLED" then GameTooltip:SetOwner(self, "ANCHOR_CURSOR") GameTooltip:SetText("Activation Requirements:") if not IsInGroup() then GameTooltip:AddLine("- You must be in a raid/party.", 1, 1, 1) end GameTooltip:AddLine("- You must be the Loot Master in said raid/party.", 1, 1, 1) GameTooltip:Show() end end --->Tooltip leave function btnOptionsTab_AltSync_OnLeave() GameTooltip:Hide() end ------------------- -- POP UPs ------------------- --Add List StaticPopupDialogs["OptionsTab_AddList"] = { text = "Please enter new list's name:", button1 = "Add List", button2 = "Cancel", hasEditBox = 1, whileDead = 1, hideOnEscape = 1, timeout = 0, OnShow = function(self) getglobal(self:GetName().."EditBox"):SetText("") end, OnAccept = function(self) variable = getglobal(self:GetName().."EditBox"):GetText() --Ensure list doesn't exist already for key, value in pairs(listAdded) do if (value == variable) then StaticPopup_Show("OptionsTab_AddListDUPLICATE") return false end end --Add new key to Master List if (variable ~= "") then ErnSK_Lists[variable] = "" end loadMasterList() end }; --Add List StaticPopupDialogs["OptionsTab_CopyList"] = { text = "Please enter new list's name:", button1 = "Copy List", button2 = "Cancel", hasEditBox = 1, whileDead = 1, hideOnEscape = 1, timeout = 0, OnShow = function(self) getglobal(self:GetName().."EditBox"):SetText("") end, OnAccept = function(self) variable = getglobal(self:GetName().."EditBox"):GetText() --Ensure list doesn't exist already for key, value in pairs(listAdded) do if (value == variable) then StaticPopup_Show("OptionsTab_AddListDUPLICATE") return false end end --Add new key to Master List ErnSK_Lists[variable] = ErnSK_Lists[selectedList] loadMasterList() end }; --List duplicate warning StaticPopupDialogs["OptionsTab_AddListDUPLICATE"] = { text = "List already exists!", button1 = "OK", whileDead = 1, hideOnEscape = 1, timeout = 0, OnAccept = function(self) --StaticPopup_Show("OptionsTab_AddList") end }; --List removal warning StaticPopupDialogs["OptionsTab_RemoveList"] = { text = "Please confirm that you intend to DELETE this List.", button1 = "Yes", button2 = "No", whileDead = 1, hideOnEscape = 1, timeout = 0, OnAccept = function(self) --Remove entry from Master List and clear selected if currentSelectedLootList == selectedList then currentSelectedLootList = "" end ErnSK_Lists[selectedList] = nil loadMasterList() btnOptionsTab_ListRemove:Disable() btnOptionsTab_ListCopy:Disable() end }; --Player duplicate warning StaticPopupDialogs["OptionsTab_AddPlayerDUPLICATE"] = { text = "Player already exists on this list!", button1 = "OK", whileDead = 1, hideOnEscape = 1, timeout = 0, OnAccept = function(self) end }; --Player removal warning StaticPopupDialogs["OptionsTab_RemovePlayer"] = { text = "Please confirm that you intend to REMOVE the selected player from the selected list.", button1 = "Yes", button2 = "No", whileDead = 1, hideOnEscape = 1, timeout = 0, OnAccept = function(self) --Remove player info from Master List for selected list local playersListed = Split(ErnSK_Lists[selectedList], ";;") for key, value in pairs(playersListed) do if (value ~= nil and value ~= "") then if (selectedPlayer == nameOnly(value)) then table.remove(playersListed, key) end end end local sPlayers = "" for _, value in pairs(playersListed) do if (value ~= nil and value ~= "") then sPlayers = sPlayers .. value .. ";;" end end ErnSK_Lists[selectedList] = sPlayers --Repopulate player listing selectedPlayer = "" btnOptionsTab_PlayerRemove:Disable() populatePlayerList() end }; --Alt Sync confirm StaticPopupDialogs["OptionTab_SyncConfirm"] = { text = "Do you want to sync all of your current set Alts with your raid/party members?", button1 = "Yes", button2 = "No", whileDead = 1, hideOnEscape = 1, timeout = 0, OnAccept = function(self) performAltSync() end };
apache-2.0
deathshadow85/max
bot/utils.lua
473
24167
URL = require "socket.url" http = require "socket.http" https = require "ssl.https" ltn12 = require "ltn12" serpent = require "serpent" feedparser = require "feedparser" json = (loadfile "./libs/JSON.lua")() mimetype = (loadfile "./libs/mimetype.lua")() redis = (loadfile "./libs/redis.lua")() JSON = (loadfile "./libs/dkjson.lua")() http.TIMEOUT = 10 function get_receiver(msg) if msg.to.type == 'user' then return 'user#id'..msg.from.id end if msg.to.type == 'chat' then return 'chat#id'..msg.to.id end if msg.to.type == 'encr_chat' then return msg.to.print_name end end function is_chat_msg( msg ) if msg.to.type == 'chat' then return true end return false end function string.random(length) local str = ""; for i = 1, length do math.random(97, 122) str = str..string.char(math.random(97, 122)); end return str; end function string:split(sep) local sep, fields = sep or ":", {} local pattern = string.format("([^%s]+)", sep) self:gsub(pattern, function(c) fields[#fields+1] = c end) return fields end -- DEPRECATED function string.trim(s) print("string.trim(s) is DEPRECATED use string:trim() instead") return s:gsub("^%s*(.-)%s*$", "%1") end -- Removes spaces function string:trim() return self:gsub("^%s*(.-)%s*$", "%1") end function get_http_file_name(url, headers) -- Eg: foo.var local file_name = url:match("[^%w]+([%.%w]+)$") -- Any delimited alphanumeric on the url file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$") -- Random name, hope content-type works file_name = file_name or str:random(5) local content_type = headers["content-type"] local extension = nil if content_type then extension = mimetype.get_mime_extension(content_type) end if extension then file_name = file_name.."."..extension end local disposition = headers["content-disposition"] if disposition then -- attachment; filename=CodeCogsEqn.png file_name = disposition:match('filename=([^;]+)') or file_name end return file_name end -- Saves file to /tmp/. If file_name isn't provided, -- will get the text after the last "/" for filename -- and content-type for extension function download_to_file(url, file_name) print("url to download: "..url) local respbody = {} local options = { url = url, sink = ltn12.sink.table(respbody), redirect = true } -- nil, code, headers, status local response = nil if url:starts('https') then options.redirect = false response = {https.request(options)} else response = {http.request(options)} end local code = response[2] local headers = response[3] local status = response[4] if code ~= 200 then return nil end file_name = file_name or get_http_file_name(url, headers) local file_path = "/tmp/"..file_name print("Saved to: "..file_path) file = io.open(file_path, "w+") file:write(table.concat(respbody)) file:close() return file_path end function vardump(value) print(serpent.block(value, {comment=false})) end -- taken from http://stackoverflow.com/a/11130774/3163199 function scandir(directory) local i, t, popen = 0, {}, io.popen for filename in popen('ls -a "'..directory..'"'):lines() do i = i + 1 t[i] = filename end return t end -- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen function run_command(str) local cmd = io.popen(str) local result = cmd:read('*all') cmd:close() return result end -- User has privileges function is_sudo(msg) local var = false -- Check users id in config for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end -- Returns the name of the sender function get_name(msg) local name = msg.from.first_name if name == nil then name = msg.from.id end return name end -- Returns at table of lua files inside plugins function plugins_names( ) local files = {} for k, v in pairs(scandir("plugins")) do -- Ends with .lua if (v:match(".lua$")) then table.insert(files, v) end end return files end -- Function name explains what it does. function file_exists(name) local f = io.open(name,"r") if f ~= nil then io.close(f) return true else return false end end -- Save into file the data serialized for lua. -- Set uglify true to minify the file. function serialize_to_file(data, file, uglify) file = io.open(file, 'w+') local serialized if not uglify then serialized = serpent.block(data, { comment = false, name = '_' }) else serialized = serpent.dump(data) end file:write(serialized) file:close() end -- Returns true if the string is empty function string:isempty() return self == nil or self == '' end -- Returns true if the string is blank function string:isblank() self = self:trim() return self:isempty() end -- DEPRECATED!!!!! function string.starts(String, Start) print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead") return Start == string.sub(String,1,string.len(Start)) end -- Returns true if String starts with Start function string:starts(text) return text == string.sub(self,1,string.len(text)) end -- Send image to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_photo(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function, cb_extra = cb_extra } -- Call to remove with optional callback send_photo(receiver, file_path, cb_function, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_photo_from_url(receiver, url, cb_function, cb_extra) -- If callback not provided cb_function = cb_function or ok_cb cb_extra = cb_extra or false local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, cb_function, cb_extra) else print("File path: "..file_path) _send_photo(receiver, file_path, cb_function, cb_extra) end end -- Same as send_photo_from_url but as callback function function send_photo_from_url_callback(cb_extra, success, result) local receiver = cb_extra.receiver local url = cb_extra.url local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, ok_cb, false) else print("File path: "..file_path) _send_photo(receiver, file_path, ok_cb, false) end end -- Send multiple images asynchronous. -- param urls must be a table. function send_photos_from_url(receiver, urls) local cb_extra = { receiver = receiver, urls = urls, remove_path = nil } send_photos_from_url_callback(cb_extra) end -- Use send_photos_from_url. -- This function might be difficult to understand. function send_photos_from_url_callback(cb_extra, success, result) -- cb_extra is a table containing receiver, urls and remove_path local receiver = cb_extra.receiver local urls = cb_extra.urls local remove_path = cb_extra.remove_path -- The previously image to remove if remove_path ~= nil then os.remove(remove_path) print("Deleted: "..remove_path) end -- Nil or empty, exit case (no more urls) if urls == nil or #urls == 0 then return false end -- Take the head and remove from urls table local head = table.remove(urls, 1) local file_path = download_to_file(head, false) local cb_extra = { receiver = receiver, urls = urls, remove_path = file_path } -- Send first and postpone the others as callback send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra) end -- Callback to remove a file function rmtmp_cb(cb_extra, success, result) local file_path = cb_extra.file_path local cb_function = cb_extra.cb_function or ok_cb local cb_extra = cb_extra.cb_extra if file_path ~= nil then os.remove(file_path) print("Deleted: "..file_path) end -- Finally call the callback cb_function(cb_extra, success, result) end -- Send document to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_document(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function or ok_cb, cb_extra = cb_extra or false } -- Call to remove with optional callback send_document(receiver, file_path, rmtmp_cb, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_document_from_url(receiver, url, cb_function, cb_extra) local file_path = download_to_file(url, false) print("File path: "..file_path) _send_document(receiver, file_path, cb_function, cb_extra) end -- Parameters in ?a=1&b=2 style function format_http_params(params, is_get) local str = '' -- If is get add ? to the beginning if is_get then str = '?' end local first = true -- Frist param for k,v in pairs (params) do if v then -- nil value if first then first = false str = str..k.. "="..v else str = str.."&"..k.. "="..v end end end return str end -- Check if user can use the plugin and warns user -- Returns true if user was warned and false if not warned (is allowed) function warns_user_not_allowed(plugin, msg) if not user_allowed(plugin, msg) then local text = 'This plugin requires privileged user' local receiver = get_receiver(msg) send_msg(receiver, text, ok_cb, false) return true else return false end end -- Check if user can use the plugin function user_allowed(plugin, msg) if plugin.privileged and not is_sudo(msg) then return false end return true end function send_order_msg(destination, msgs) local cb_extra = { destination = destination, msgs = msgs } send_order_msg_callback(cb_extra, true) end function send_order_msg_callback(cb_extra, success, result) local destination = cb_extra.destination local msgs = cb_extra.msgs local file_path = cb_extra.file_path if file_path ~= nil then os.remove(file_path) print("Deleted: " .. file_path) end if type(msgs) == 'string' then send_large_msg(destination, msgs) elseif type(msgs) ~= 'table' then return end if #msgs < 1 then return end local msg = table.remove(msgs, 1) local new_cb_extra = { destination = destination, msgs = msgs } if type(msg) == 'string' then send_msg(destination, msg, send_order_msg_callback, new_cb_extra) elseif type(msg) == 'table' then local typ = msg[1] local nmsg = msg[2] new_cb_extra.file_path = nmsg if typ == 'document' then send_document(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'image' or typ == 'photo' then send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'audio' then send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'video' then send_video(destination, nmsg, send_order_msg_callback, new_cb_extra) else send_file(destination, nmsg, send_order_msg_callback, new_cb_extra) end end end -- Same as send_large_msg_callback but friendly params function send_large_msg(destination, text) local cb_extra = { destination = destination, text = text } send_large_msg_callback(cb_extra, true) end -- If text is longer than 4096 chars, send multiple msg. -- https://core.telegram.org/method/messages.sendMessage function send_large_msg_callback(cb_extra, success, result) local text_max = 4096 local destination = cb_extra.destination local text = cb_extra.text local text_len = string.len(text) local num_msg = math.ceil(text_len / text_max) if num_msg <= 1 then send_msg(destination, text, ok_cb, false) else local my_text = string.sub(text, 1, 4096) local rest = string.sub(text, 4096, text_len) local cb_extra = { destination = destination, text = rest } send_msg(destination, my_text, send_large_msg_callback, cb_extra) end end -- Returns a table with matches or nil function match_pattern(pattern, text, lower_case) if text then local matches = {} if lower_case then matches = { string.match(text:lower(), pattern) } else matches = { string.match(text, pattern) } end if next(matches) then return matches end end -- nil end -- Function to read data from files function load_from_file(file, default_data) local f = io.open(file, "r+") -- If file doesn't exists if f == nil then -- Create a new empty table default_data = default_data or {} serialize_to_file(default_data, file) print ('Created file', file) else print ('Data loaded from file', file) f:close() end return loadfile (file)() end -- See http://stackoverflow.com/a/14899740 function unescape_html(str) local map = { ["lt"] = "<", ["gt"] = ">", ["amp"] = "&", ["quot"] = '"', ["apos"] = "'" } new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s) var = map[s] or n == "#" and string.char(s) var = var or n == "#x" and string.char(tonumber(s,16)) var = var or orig return var end) return new end --Check if this chat is realm or not function is_realm(msg) local var = false local realms = 'realms' local data = load_data(_config.moderation.data) local chat = msg.to.id if data[tostring(realms)] then if data[tostring(realms)][tostring(msg.to.id)] then var = true end return var end end --Check if this chat is a group or not function is_group(msg) local var = false local groups = 'groups' local data = load_data(_config.moderation.data) local chat = msg.to.id if data[tostring(groups)] then if data[tostring(groups)][tostring(msg.to.id)] then var = true end return var end end function savelog(group, logtxt) local text = (os.date("[ %c ]=> "..logtxt.."\n \n")) local file = io.open("./groups/logs/"..group.."log.txt", "a") file:write(text) file:close() end function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end --Check if user is the owner of that group or not function is_owner(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['set_owner'] then if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then var = true end end end if data['admins'] then if data['admins'][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_owner2(user_id, group_id) local var = false local data = load_data(_config.moderation.data) if data[tostring(group_id)] then if data[tostring(group_id)]['set_owner'] then if data[tostring(group_id)]['set_owner'] == tostring(user_id) then var = true end end end if data['admins'] then if data['admins'][tostring(user_id)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end --Check if user is admin or not function is_admin(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id local admins = 'admins' if data[tostring(admins)] then if data[tostring(admins)][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_admin2(user_id) local var = false local data = load_data(_config.moderation.data) local user = user_id local admins = 'admins' if data[tostring(admins)] then if data[tostring(admins)][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end --Check if user is the mod of that group or not function is_momod(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['moderators'] then if data[tostring(msg.to.id)]['moderators'][tostring(user)] then var = true end end end if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['set_owner'] then if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then var = true end end end if data['admins'] then if data['admins'][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_momod2(user_id, group_id) local var = false local data = load_data(_config.moderation.data) local usert = user_id if data[tostring(group_id)] then if data[tostring(group_id)]['moderators'] then if data[tostring(group_id)]['moderators'][tostring(usert)] then var = true end end end if data[tostring(group_id)] then if data[tostring(group_id)]['set_owner'] then if data[tostring(group_id)]['set_owner'] == tostring(user_id) then var = true end end end if data['admins'] then if data['admins'][tostring(user_id)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == usert then var = true end end return var end -- Returns the name of the sender function kick_user(user_id, chat_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_owner2(user_id, chat_id) then -- Ignore admins return end local chat = 'chat#id'..chat_id local user = 'user#id'..user_id chat_del_user(chat, user, ok_cb, true) end -- Ban function ban_user(user_id, chat_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_admin2(user_id) then -- Ignore admins return end -- Save to redis local hash = 'banned:'..chat_id redis:sadd(hash, user_id) -- Kick from chat kick_user(user_id, chat_id) end -- Global ban function banall_user(user_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_admin2(user_id) then -- Ignore admins return end -- Save to redis local hash = 'gbanned' redis:sadd(hash, user_id) end -- Global unban function unbanall_user(user_id) --Save on redis local hash = 'gbanned' redis:srem(hash, user_id) end -- Check if user_id is banned in chat_id or not function is_banned(user_id, chat_id) --Save on redis local hash = 'banned:'..chat_id local banned = redis:sismember(hash, user_id) return banned or false end -- Check if user_id is globally banned or not function is_gbanned(user_id) --Save on redis local hash = 'gbanned' local banned = redis:sismember(hash, user_id) return banned or false end -- Returns chat_id ban list function ban_list(chat_id) local hash = 'banned:'..chat_id local list = redis:smembers(hash) local text = "Ban list !\n\n" for k,v in pairs(list) do local user_info = redis:hgetall('user:'..v) -- vardump(user_info) if user_info then if user_info.username then user = '@'..user_info.username elseif user_info.print_name and not user_info.username then user = string.gsub(user_info.print_name, "_", " ") else user = '' end text = text..k.." - "..user.." ["..v.."]\n" end end return text end -- Returns globally ban list function banall_list() local hash = 'gbanned' local list = redis:smembers(hash) local text = "global bans !\n\n" for k,v in pairs(list) do local user_info = redis:hgetall('user:'..v) -- vardump(user_info) if user_info then if user_info.username then user = '@'..user_info.username elseif user_info.print_name and not user_info.username then user = string.gsub(user_info.print_name, "_", " ") else user = '' end text = text..k.." - "..user.." ["..v.."]\n" end end return text end -- /id by reply function get_message_callback_id(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id send_large_msg(chat, result.from.id) else return 'Use This in Your Groups' end end -- kick by reply for mods and owner function Kick_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't kick myself" end if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin return "you can't kick mods,owner and admins" end chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) else return 'Use This in Your Groups' end end -- Kick by reply for admins function Kick_by_reply_admins(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't kick myself" end if is_admin2(result.from.id) then -- Ignore admins return end chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) else return 'Use This in Your Groups' end end --Ban by reply for admins function ban_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't ban myself" end if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin return "you can't kick mods,owner and admins" end ban_user(result.from.id, result.to.id) send_large_msg(chat, "User "..result.from.id.." Banned") else return 'Use This in Your Groups' end end -- Ban by reply for admins function ban_by_reply_admins(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't ban myself" end if is_admin2(result.from.id) then -- Ignore admins return end ban_user(result.from.id, result.to.id) send_large_msg(chat, "User "..result.from.id.." Banned") else return 'Use This in Your Groups' end end -- Unban by reply function unban_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't unban myself" end send_large_msg(chat, "User "..result.from.id.." Unbanned") -- Save on redis local hash = 'banned:'..result.to.id redis:srem(hash, result.from.id) else return 'Use This in Your Groups' end end function banall_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't banall myself" end if is_admin2(result.from.id) then -- Ignore admins return end local name = user_print_name(result.from) banall_user(result.from.id) chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) send_large_msg(chat, "User "..name.."["..result.from.id.."] hammered") else return 'Use This in Your Groups' end end
gpl-2.0
rezaar/Tele-Sorena
bot/utils.lua
473
24167
URL = require "socket.url" http = require "socket.http" https = require "ssl.https" ltn12 = require "ltn12" serpent = require "serpent" feedparser = require "feedparser" json = (loadfile "./libs/JSON.lua")() mimetype = (loadfile "./libs/mimetype.lua")() redis = (loadfile "./libs/redis.lua")() JSON = (loadfile "./libs/dkjson.lua")() http.TIMEOUT = 10 function get_receiver(msg) if msg.to.type == 'user' then return 'user#id'..msg.from.id end if msg.to.type == 'chat' then return 'chat#id'..msg.to.id end if msg.to.type == 'encr_chat' then return msg.to.print_name end end function is_chat_msg( msg ) if msg.to.type == 'chat' then return true end return false end function string.random(length) local str = ""; for i = 1, length do math.random(97, 122) str = str..string.char(math.random(97, 122)); end return str; end function string:split(sep) local sep, fields = sep or ":", {} local pattern = string.format("([^%s]+)", sep) self:gsub(pattern, function(c) fields[#fields+1] = c end) return fields end -- DEPRECATED function string.trim(s) print("string.trim(s) is DEPRECATED use string:trim() instead") return s:gsub("^%s*(.-)%s*$", "%1") end -- Removes spaces function string:trim() return self:gsub("^%s*(.-)%s*$", "%1") end function get_http_file_name(url, headers) -- Eg: foo.var local file_name = url:match("[^%w]+([%.%w]+)$") -- Any delimited alphanumeric on the url file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$") -- Random name, hope content-type works file_name = file_name or str:random(5) local content_type = headers["content-type"] local extension = nil if content_type then extension = mimetype.get_mime_extension(content_type) end if extension then file_name = file_name.."."..extension end local disposition = headers["content-disposition"] if disposition then -- attachment; filename=CodeCogsEqn.png file_name = disposition:match('filename=([^;]+)') or file_name end return file_name end -- Saves file to /tmp/. If file_name isn't provided, -- will get the text after the last "/" for filename -- and content-type for extension function download_to_file(url, file_name) print("url to download: "..url) local respbody = {} local options = { url = url, sink = ltn12.sink.table(respbody), redirect = true } -- nil, code, headers, status local response = nil if url:starts('https') then options.redirect = false response = {https.request(options)} else response = {http.request(options)} end local code = response[2] local headers = response[3] local status = response[4] if code ~= 200 then return nil end file_name = file_name or get_http_file_name(url, headers) local file_path = "/tmp/"..file_name print("Saved to: "..file_path) file = io.open(file_path, "w+") file:write(table.concat(respbody)) file:close() return file_path end function vardump(value) print(serpent.block(value, {comment=false})) end -- taken from http://stackoverflow.com/a/11130774/3163199 function scandir(directory) local i, t, popen = 0, {}, io.popen for filename in popen('ls -a "'..directory..'"'):lines() do i = i + 1 t[i] = filename end return t end -- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen function run_command(str) local cmd = io.popen(str) local result = cmd:read('*all') cmd:close() return result end -- User has privileges function is_sudo(msg) local var = false -- Check users id in config for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end -- Returns the name of the sender function get_name(msg) local name = msg.from.first_name if name == nil then name = msg.from.id end return name end -- Returns at table of lua files inside plugins function plugins_names( ) local files = {} for k, v in pairs(scandir("plugins")) do -- Ends with .lua if (v:match(".lua$")) then table.insert(files, v) end end return files end -- Function name explains what it does. function file_exists(name) local f = io.open(name,"r") if f ~= nil then io.close(f) return true else return false end end -- Save into file the data serialized for lua. -- Set uglify true to minify the file. function serialize_to_file(data, file, uglify) file = io.open(file, 'w+') local serialized if not uglify then serialized = serpent.block(data, { comment = false, name = '_' }) else serialized = serpent.dump(data) end file:write(serialized) file:close() end -- Returns true if the string is empty function string:isempty() return self == nil or self == '' end -- Returns true if the string is blank function string:isblank() self = self:trim() return self:isempty() end -- DEPRECATED!!!!! function string.starts(String, Start) print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead") return Start == string.sub(String,1,string.len(Start)) end -- Returns true if String starts with Start function string:starts(text) return text == string.sub(self,1,string.len(text)) end -- Send image to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_photo(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function, cb_extra = cb_extra } -- Call to remove with optional callback send_photo(receiver, file_path, cb_function, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_photo_from_url(receiver, url, cb_function, cb_extra) -- If callback not provided cb_function = cb_function or ok_cb cb_extra = cb_extra or false local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, cb_function, cb_extra) else print("File path: "..file_path) _send_photo(receiver, file_path, cb_function, cb_extra) end end -- Same as send_photo_from_url but as callback function function send_photo_from_url_callback(cb_extra, success, result) local receiver = cb_extra.receiver local url = cb_extra.url local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, ok_cb, false) else print("File path: "..file_path) _send_photo(receiver, file_path, ok_cb, false) end end -- Send multiple images asynchronous. -- param urls must be a table. function send_photos_from_url(receiver, urls) local cb_extra = { receiver = receiver, urls = urls, remove_path = nil } send_photos_from_url_callback(cb_extra) end -- Use send_photos_from_url. -- This function might be difficult to understand. function send_photos_from_url_callback(cb_extra, success, result) -- cb_extra is a table containing receiver, urls and remove_path local receiver = cb_extra.receiver local urls = cb_extra.urls local remove_path = cb_extra.remove_path -- The previously image to remove if remove_path ~= nil then os.remove(remove_path) print("Deleted: "..remove_path) end -- Nil or empty, exit case (no more urls) if urls == nil or #urls == 0 then return false end -- Take the head and remove from urls table local head = table.remove(urls, 1) local file_path = download_to_file(head, false) local cb_extra = { receiver = receiver, urls = urls, remove_path = file_path } -- Send first and postpone the others as callback send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra) end -- Callback to remove a file function rmtmp_cb(cb_extra, success, result) local file_path = cb_extra.file_path local cb_function = cb_extra.cb_function or ok_cb local cb_extra = cb_extra.cb_extra if file_path ~= nil then os.remove(file_path) print("Deleted: "..file_path) end -- Finally call the callback cb_function(cb_extra, success, result) end -- Send document to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_document(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function or ok_cb, cb_extra = cb_extra or false } -- Call to remove with optional callback send_document(receiver, file_path, rmtmp_cb, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_document_from_url(receiver, url, cb_function, cb_extra) local file_path = download_to_file(url, false) print("File path: "..file_path) _send_document(receiver, file_path, cb_function, cb_extra) end -- Parameters in ?a=1&b=2 style function format_http_params(params, is_get) local str = '' -- If is get add ? to the beginning if is_get then str = '?' end local first = true -- Frist param for k,v in pairs (params) do if v then -- nil value if first then first = false str = str..k.. "="..v else str = str.."&"..k.. "="..v end end end return str end -- Check if user can use the plugin and warns user -- Returns true if user was warned and false if not warned (is allowed) function warns_user_not_allowed(plugin, msg) if not user_allowed(plugin, msg) then local text = 'This plugin requires privileged user' local receiver = get_receiver(msg) send_msg(receiver, text, ok_cb, false) return true else return false end end -- Check if user can use the plugin function user_allowed(plugin, msg) if plugin.privileged and not is_sudo(msg) then return false end return true end function send_order_msg(destination, msgs) local cb_extra = { destination = destination, msgs = msgs } send_order_msg_callback(cb_extra, true) end function send_order_msg_callback(cb_extra, success, result) local destination = cb_extra.destination local msgs = cb_extra.msgs local file_path = cb_extra.file_path if file_path ~= nil then os.remove(file_path) print("Deleted: " .. file_path) end if type(msgs) == 'string' then send_large_msg(destination, msgs) elseif type(msgs) ~= 'table' then return end if #msgs < 1 then return end local msg = table.remove(msgs, 1) local new_cb_extra = { destination = destination, msgs = msgs } if type(msg) == 'string' then send_msg(destination, msg, send_order_msg_callback, new_cb_extra) elseif type(msg) == 'table' then local typ = msg[1] local nmsg = msg[2] new_cb_extra.file_path = nmsg if typ == 'document' then send_document(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'image' or typ == 'photo' then send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'audio' then send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'video' then send_video(destination, nmsg, send_order_msg_callback, new_cb_extra) else send_file(destination, nmsg, send_order_msg_callback, new_cb_extra) end end end -- Same as send_large_msg_callback but friendly params function send_large_msg(destination, text) local cb_extra = { destination = destination, text = text } send_large_msg_callback(cb_extra, true) end -- If text is longer than 4096 chars, send multiple msg. -- https://core.telegram.org/method/messages.sendMessage function send_large_msg_callback(cb_extra, success, result) local text_max = 4096 local destination = cb_extra.destination local text = cb_extra.text local text_len = string.len(text) local num_msg = math.ceil(text_len / text_max) if num_msg <= 1 then send_msg(destination, text, ok_cb, false) else local my_text = string.sub(text, 1, 4096) local rest = string.sub(text, 4096, text_len) local cb_extra = { destination = destination, text = rest } send_msg(destination, my_text, send_large_msg_callback, cb_extra) end end -- Returns a table with matches or nil function match_pattern(pattern, text, lower_case) if text then local matches = {} if lower_case then matches = { string.match(text:lower(), pattern) } else matches = { string.match(text, pattern) } end if next(matches) then return matches end end -- nil end -- Function to read data from files function load_from_file(file, default_data) local f = io.open(file, "r+") -- If file doesn't exists if f == nil then -- Create a new empty table default_data = default_data or {} serialize_to_file(default_data, file) print ('Created file', file) else print ('Data loaded from file', file) f:close() end return loadfile (file)() end -- See http://stackoverflow.com/a/14899740 function unescape_html(str) local map = { ["lt"] = "<", ["gt"] = ">", ["amp"] = "&", ["quot"] = '"', ["apos"] = "'" } new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s) var = map[s] or n == "#" and string.char(s) var = var or n == "#x" and string.char(tonumber(s,16)) var = var or orig return var end) return new end --Check if this chat is realm or not function is_realm(msg) local var = false local realms = 'realms' local data = load_data(_config.moderation.data) local chat = msg.to.id if data[tostring(realms)] then if data[tostring(realms)][tostring(msg.to.id)] then var = true end return var end end --Check if this chat is a group or not function is_group(msg) local var = false local groups = 'groups' local data = load_data(_config.moderation.data) local chat = msg.to.id if data[tostring(groups)] then if data[tostring(groups)][tostring(msg.to.id)] then var = true end return var end end function savelog(group, logtxt) local text = (os.date("[ %c ]=> "..logtxt.."\n \n")) local file = io.open("./groups/logs/"..group.."log.txt", "a") file:write(text) file:close() end function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end --Check if user is the owner of that group or not function is_owner(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['set_owner'] then if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then var = true end end end if data['admins'] then if data['admins'][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_owner2(user_id, group_id) local var = false local data = load_data(_config.moderation.data) if data[tostring(group_id)] then if data[tostring(group_id)]['set_owner'] then if data[tostring(group_id)]['set_owner'] == tostring(user_id) then var = true end end end if data['admins'] then if data['admins'][tostring(user_id)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end --Check if user is admin or not function is_admin(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id local admins = 'admins' if data[tostring(admins)] then if data[tostring(admins)][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_admin2(user_id) local var = false local data = load_data(_config.moderation.data) local user = user_id local admins = 'admins' if data[tostring(admins)] then if data[tostring(admins)][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end --Check if user is the mod of that group or not function is_momod(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['moderators'] then if data[tostring(msg.to.id)]['moderators'][tostring(user)] then var = true end end end if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['set_owner'] then if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then var = true end end end if data['admins'] then if data['admins'][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_momod2(user_id, group_id) local var = false local data = load_data(_config.moderation.data) local usert = user_id if data[tostring(group_id)] then if data[tostring(group_id)]['moderators'] then if data[tostring(group_id)]['moderators'][tostring(usert)] then var = true end end end if data[tostring(group_id)] then if data[tostring(group_id)]['set_owner'] then if data[tostring(group_id)]['set_owner'] == tostring(user_id) then var = true end end end if data['admins'] then if data['admins'][tostring(user_id)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == usert then var = true end end return var end -- Returns the name of the sender function kick_user(user_id, chat_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_owner2(user_id, chat_id) then -- Ignore admins return end local chat = 'chat#id'..chat_id local user = 'user#id'..user_id chat_del_user(chat, user, ok_cb, true) end -- Ban function ban_user(user_id, chat_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_admin2(user_id) then -- Ignore admins return end -- Save to redis local hash = 'banned:'..chat_id redis:sadd(hash, user_id) -- Kick from chat kick_user(user_id, chat_id) end -- Global ban function banall_user(user_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_admin2(user_id) then -- Ignore admins return end -- Save to redis local hash = 'gbanned' redis:sadd(hash, user_id) end -- Global unban function unbanall_user(user_id) --Save on redis local hash = 'gbanned' redis:srem(hash, user_id) end -- Check if user_id is banned in chat_id or not function is_banned(user_id, chat_id) --Save on redis local hash = 'banned:'..chat_id local banned = redis:sismember(hash, user_id) return banned or false end -- Check if user_id is globally banned or not function is_gbanned(user_id) --Save on redis local hash = 'gbanned' local banned = redis:sismember(hash, user_id) return banned or false end -- Returns chat_id ban list function ban_list(chat_id) local hash = 'banned:'..chat_id local list = redis:smembers(hash) local text = "Ban list !\n\n" for k,v in pairs(list) do local user_info = redis:hgetall('user:'..v) -- vardump(user_info) if user_info then if user_info.username then user = '@'..user_info.username elseif user_info.print_name and not user_info.username then user = string.gsub(user_info.print_name, "_", " ") else user = '' end text = text..k.." - "..user.." ["..v.."]\n" end end return text end -- Returns globally ban list function banall_list() local hash = 'gbanned' local list = redis:smembers(hash) local text = "global bans !\n\n" for k,v in pairs(list) do local user_info = redis:hgetall('user:'..v) -- vardump(user_info) if user_info then if user_info.username then user = '@'..user_info.username elseif user_info.print_name and not user_info.username then user = string.gsub(user_info.print_name, "_", " ") else user = '' end text = text..k.." - "..user.." ["..v.."]\n" end end return text end -- /id by reply function get_message_callback_id(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id send_large_msg(chat, result.from.id) else return 'Use This in Your Groups' end end -- kick by reply for mods and owner function Kick_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't kick myself" end if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin return "you can't kick mods,owner and admins" end chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) else return 'Use This in Your Groups' end end -- Kick by reply for admins function Kick_by_reply_admins(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't kick myself" end if is_admin2(result.from.id) then -- Ignore admins return end chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) else return 'Use This in Your Groups' end end --Ban by reply for admins function ban_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't ban myself" end if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin return "you can't kick mods,owner and admins" end ban_user(result.from.id, result.to.id) send_large_msg(chat, "User "..result.from.id.." Banned") else return 'Use This in Your Groups' end end -- Ban by reply for admins function ban_by_reply_admins(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't ban myself" end if is_admin2(result.from.id) then -- Ignore admins return end ban_user(result.from.id, result.to.id) send_large_msg(chat, "User "..result.from.id.." Banned") else return 'Use This in Your Groups' end end -- Unban by reply function unban_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't unban myself" end send_large_msg(chat, "User "..result.from.id.." Unbanned") -- Save on redis local hash = 'banned:'..result.to.id redis:srem(hash, result.from.id) else return 'Use This in Your Groups' end end function banall_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't banall myself" end if is_admin2(result.from.id) then -- Ignore admins return end local name = user_print_name(result.from) banall_user(result.from.id) chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) send_large_msg(chat, "User "..name.."["..result.from.id.."] hammered") else return 'Use This in Your Groups' end end
gpl-2.0
gedads/Neodynamis
scripts/globals/items/plate_of_salmon_sushi_+1.lua
12
1583
----------------------------------------- -- ID: 5664 -- Item: plate_of_salmon_sushi_+1 -- Food Effect: 60Min, All Races ----------------------------------------- -- Strength 2 -- Accuracy % 15 (cap 72) -- Ranged ACC % 15 (cap 72) -- Resist Sleep +2 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,3600,5664); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR, 2); target:addMod(MOD_FOOD_ACCP, 15); target:addMod(MOD_FOOD_ACC_CAP, 72); target:addMod(MOD_FOOD_RACCP, 15); target:addMod(MOD_FOOD_RACC_CAP, 72); target:addMod(MOD_SLEEPRES, 2); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_STR, 2); target:delMod(MOD_FOOD_ACCP, 15); target:delMod(MOD_FOOD_ACC_CAP, 72); target:delMod(MOD_FOOD_RACCP, 15); target:delMod(MOD_FOOD_RACC_CAP, 72); target:delMod(MOD_SLEEPRES, 2); end;
gpl-3.0
mmaxs/pull_requests--ettercap
src/lua/share/core/base64.lua
12
2550
-- Base64-encoding -- Sourced from http://en.wikipedia.org/wiki/Base64 require('math') local __author__ = 'Daniel Lindsley' local __version__ = 'scm-1' local __license__ = 'BSD' local index_table = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' function to_binary(integer) local remaining = tonumber(integer) local bin_bits = '' for i = 7, 0, -1 do local current_power = math.pow(2, i) if remaining >= current_power then bin_bits = bin_bits .. '1' remaining = remaining - current_power else bin_bits = bin_bits .. '0' end end return bin_bits end function from_binary(bin_bits) return tonumber(bin_bits, 2) end function to_base64(to_encode) local bit_pattern = '' local encoded = '' local trailing = '' for i = 1, string.len(to_encode) do bit_pattern = bit_pattern .. to_binary(string.byte(string.sub(to_encode, i, i))) end -- Check the number of bytes. If it's not evenly divisible by three, -- zero-pad the ending & append on the correct number of ``=``s. if math.mod(string.len(bit_pattern), 3) == 2 then trailing = '==' bit_pattern = bit_pattern .. '0000000000000000' elseif math.mod(string.len(bit_pattern), 3) == 1 then trailing = '=' bit_pattern = bit_pattern .. '00000000' end for i = 1, string.len(bit_pattern), 6 do local byte = string.sub(bit_pattern, i, i+5) local offset = tonumber(from_binary(byte)) encoded = encoded .. string.sub(index_table, offset+1, offset+1) end return string.sub(encoded, 1, -1 - string.len(trailing)) .. trailing end function from_base64(to_decode) local padded = to_decode:gsub("%s", "") local unpadded = padded:gsub("=", "") local bit_pattern = '' local decoded = '' for i = 1, string.len(unpadded) do local char = string.sub(to_decode, i, i) local offset, _ = string.find(index_table, char) if offset == nil then error("Invalid character '" .. char .. "' found.") end bit_pattern = bit_pattern .. string.sub(to_binary(offset-1), 3) end for i = 1, string.len(bit_pattern), 8 do local byte = string.sub(bit_pattern, i, i+7) decoded = decoded .. string.char(from_binary(byte)) end local padding_length = padded:len()-unpadded:len() if (padding_length == 1 or padding_length == 2) then decoded = decoded:sub(1,-2) end return decoded end
gpl-2.0
gedads/Neodynamis
scripts/globals/items/plate_of_bream_sushi.lua
12
1667
----------------------------------------- -- ID: 5176 -- Item: plate_of_bream_sushi -- Food Effect: 30Min, All Races ----------------------------------------- -- Dexterity 6 -- Vitality 5 -- Accuracy % 16 (cap 76) -- Ranged ACC % 16 (cap 76) -- Sleep Resist 1 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,5176); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 6); target:addMod(MOD_VIT, 5); target:addMod(MOD_FOOD_ACCP, 16); target:addMod(MOD_FOOD_ACC_CAP, 76); target:addMod(MOD_FOOD_RACCP, 16); target:addMod(MOD_FOOD_RACC_CAP, 76); target:addMod(MOD_SLEEPRES, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 6); target:delMod(MOD_VIT, 5); target:delMod(MOD_FOOD_ACCP, 16); target:delMod(MOD_FOOD_ACC_CAP, 76); target:delMod(MOD_FOOD_RACCP, 16); target:delMod(MOD_FOOD_RACC_CAP, 76); target:delMod(MOD_SLEEPRES, 1); end;
gpl-3.0
gedads/Neodynamis
scripts/zones/Crawlers_Nest/npcs/qm12.lua
3
2120
----------------------------------- -- Area: Crawlers' Nest -- NPC: qm12 (??? - Exoray Mold Crumbs) -- Involved in Quest: In Defiant Challenge -- !pos 99.326 -0.126 -188.869 197 ----------------------------------- package.loaded["scripts/zones/Crawlers_Nest/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/globals/settings"); require("scripts/zones/Crawlers_Nest/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (OldSchoolG1 == false) then if (player:hasItem(1089) == false and player:hasKeyItem(EXORAY_MOLD_CRUMB3) == false and player:getQuestStatus(JEUNO,IN_DEFIANT_CHALLENGE) == QUEST_ACCEPTED) then player:addKeyItem(EXORAY_MOLD_CRUMB3); player:messageSpecial(KEYITEM_OBTAINED,EXORAY_MOLD_CRUMB3); end if (player:hasKeyItem(EXORAY_MOLD_CRUMB1) and player:hasKeyItem(EXORAY_MOLD_CRUMB2) and player:hasKeyItem(EXORAY_MOLD_CRUMB3)) then if (player:getFreeSlotsCount() >= 1) then player:addItem(1089, 1); player:messageSpecial(ITEM_OBTAINED, 1089); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 1089); end end if (player:hasItem(1089)) then player:delKeyItem(EXORAY_MOLD_CRUMB1); player:delKeyItem(EXORAY_MOLD_CRUMB2); player:delKeyItem(EXORAY_MOLD_CRUMB3); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID2: %u",csid); -- printf("RESULT2: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
gedads/Neodynamis
scripts/zones/Castle_Oztroja/mobs/Tzee_Xicu_the_Manifest.lua
3
1484
----------------------------------- -- Area: Castle Oztroja -- MOB: Tzee Xicu the Manifest ----------------------------------- package.loaded["scripts/zones/Castle_Oztroja/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Castle_Oztroja/TextIDs"); require("scripts/globals/titles"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) -- Needs to be zone wide message -- mob:messagePublic(mob,YAGUDO_KING_ENGAGE); end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) player:addTitle(DEITY_DEBUNKER); -- Needs to be zone wide message -- mob:messagePublic(mob,YAGUDO_KING_DEATH); end; ----------------------------------- -- onMobDespawn ----------------------------------- function onMobDespawn(mob) -- Set Tzee_Xicu_the_Manifest's Window Open Time SetServerVariable("[POP]Tzee_Xicu_the_Manifest", os.time() + 72 * 3600); -- 3 days -- Set Yagudo_Avatar's spawnpoint and respawn time (21-24 hours) SetServerVariable("[PH]Tzee_Xicu_the_Manifest", 0); Yagudo_Avatar = 17396134; DisallowRespawn(Yagudo_Avatar, false); UpdateNMSpawnPoint(Yagudo_Avatar); GetMobByID(Yagudo_Avatar):setRespawnTime(math.random(75600,86400)); end;
gpl-3.0
zzzaaiidd/TCHUKY
plugins/textphoto.lua
16
1343
--[[ ▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀ ▀▄ ▄▀ ▀▄ ▄▀ ▀▄ ▄▀ BY MOHAMMED HISHAM ▀▄ ▄▀ ▀▄ ▄▀ BY MOHAMMEDHISHAM (@TH3BOSS) ▀▄ ▄▀ ▀▄ ▄▀ JUST WRITED BY MOHAMMED HISHAM ▀▄ ▄▀ ▀▄ ▄▀ text photo: تحويل الصورة الى ملصق ▀▄ ▄▀ ▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀ --]] do local function send_title(cb_extra, success, result) if success then send_msg(cb_extra[1], cb_extra[2], ok_cb, false) end end local function run(msg, matches) local eq = URL.escape(matches[1]) local url = "http://latex.codecogs.com/png.download?" .."\\dpi{300}%20\\LARGE%20"..eq local receiver = get_receiver(msg) local title = "Edit LaTeX on www.codecogs.com/eqnedit.php?latex="..eq send_photo_from_url(receiver, url, send_title, {receiver, title}) end return { description = "Convert LaTeX equation to image", usage = { "صورة [equation]: Convert LaTeX equation to image" }, patterns = { "^صوره (.+)$" }, run = run } end
gpl-2.0
gedads/Neodynamis
scripts/globals/items/simit_+1.lua
12
1251
----------------------------------------- -- ID: 5597 -- Item: simit_+1 -- Food Effect: 60Min, All Races ----------------------------------------- -- Health 18 -- Vitality 4 -- Defense 2 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,3600,5597); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 18); target:addMod(MOD_VIT, 4); target:addMod(MOD_DEF, 2); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 18); target:delMod(MOD_VIT, 4); target:delMod(MOD_DEF, 2); end;
gpl-3.0
xmrxx/mrx
plugins/zhrafa_arab_mrx_.lua
1
8515
--[[ DEV_ @mem_cool #ṂṜẌ ]] local function mrx(msg, matches) if #matches < 2 then return "بعد هذا الأمر، من خلال تحديد كلمة المسافة أو العبارة التي تريد إدخال الكتابة الجميلة" end if string.len(matches[2]) > 44 then return "الحد الأقصى المسموح به 40 حرفاالأحرف الإنجليزية والأرقام" end local font_base = "ء,ئ,ا,ب,ت,ث,ج,ح,خ,د,ذ,ر,ز,س,ش,ص,ض,ط,ظ,ع,غ,ق,ف,ك,ل,م,ن,ه,و,ي,0,9,8,7,6,5,4,3,2,1,.,_" local font_hash = "ي,و,ه,ن,م,ل,ك,ف,ق,غ,ع,ظ,ط,ض,ص,ش,س,ز,ر,ذ,د,خ,ح,ج,ث,ت,ب,ا,ئ,ء,0,1,2,3,4,5,6,7,8,9,.,_" local fonts = { "ء,ئ,ٳ,ٻً,تہ,ثہ,جہ,حہ,خہ,دٍ,ذً,ر,ڒٍ,سہ,شہ,صً,ض,طہ,ظً,عـ,غہ,قـً,فُہ,كُہ,لہ,مـْ,نٍ,ه,ﯝ,يہ,0ً,1,2ًً,3ًً,4ًً,5ًً,6ًً,7ََ,8ًً,9ًً,.,_", "ء,ئ,ٳ,بُ,تْ,ثُ,ج,ح,ځ,ڊ,ڏ,ر,ڒٍ,ڛ,شُ,صً,ض,طُ,ظً,عٌ,غٍ,قٌ,فُ,ڪ,لُ,مْ,نْ,ﮩ,وُ,يُ,0,1,2ً,3ً,4ً,5ً,6ً,7َ,8ً,9ً,.,_", "ء,ئ,ٳ,ب,ت,ث,جُ,ح,خ,د,ذ,ر,زٍ,سٍ,ش,ص,ض,طٌ,ظُ,عٍ,غ,ق,ف,گ,ل,ﻤ,ن,هـ,و,يِ,0̶̶,1̶̶,2̶̶ً,3̶̶ً,4̶̶ً,5̶̶ً,6̶̶ً,7̶̶َ,8̶̶ً,9̶̶ً,.,_", "ء,ئ,ٳ,بَ,ت,ث,جٍ,حٍ,خـ,دِ,ذَ,رٍ,زْ,س,شُ,ص,ض,طُ,ظً,عٍ,غ,قٌ,فُ,ڪ,لُِ,م,ن,هـ,وُ,ي,0̲̣̣̥,1̣̣̝̇̇,2ً̲̣̣̣̥,3ً̍̍̍̊,4ً̩̥,5ً̲̣̥,6ً̥̥̲̣̥,7َ̣̣̣̝̇̇̇,8ً̣̝̇,9ً̲̣̣̥,.,_", "ء,ئ,ٳ,ب͠,ت͠,ث͠,ج͠,ح͠,خ͠,د͠,ذ͠,ر,ز͠,س͠,ش͠,ص͠,ض,ط͠,ظ͠,ع͠,غ͠,ق͠,ف͠,گ͠,ل͠,م͠,ن͠,ه͠,و͠,ي͠,0͠,1͠,2ً͠,3ً͠,4ً͠,5ً͠,6ً͠,7َ͠,8ً͠,9ً͠,.,_", "ء,ئ,ٳ,ب̷,ت̷,ث̷,ج̷,ح̷,خ̷,د̷ِ,ذ̷,ر̷,ز̷,س̷,ش̷ُ,ص̷,ض,ط̷ُ,ظ̷ً,ع̷ٍ,غ̷,ق̷,ف̷َ,گ̷,ل̷,م̷,ن̷,ہ̷,ۆ̷,ي̷,0̷,1̷,2̷ً,3̷ً,4̷ً,5̷ً,6̷ً,7̷َ,8̷ً,9̷ً,.,_", "ء,ئ,ٳ,ب̲,ت̲,ث̲,ج̲,ح̲,خ̲,د̲,ذ̲,ر̲,ز̲,س̲,ش̲,ص̲,ض,ط̲,ظً̲,ع̲,غ̲,ق̲,ف̲,ك̲,ل̲,م̲,ن̲,ہ̲,ۆ̲,ي̲,0̲,1̲,2ً̲,3ً̲,4ً̲,5ً̲,6ً̲,7َ̲,8ً̲,9ً̲,.,_", "ء,ئ,ٳ,̜̌ب,تـ,,ثـ,جٍ,و,خ,ﮃ,ذ,رٍ,زً,سًٌُُ,شُ,ص,ض,طُ,ظً,۶,غ,ق,فَ,گ,لُ,مـ,ن,ه̷̸̐,ۈ,يَ,0,⇂,Շً,Ɛً,hً,ʢً,9ً,Lَ,8ً,6ً,.,_", "ء,ئ,ٳ,ب̀́,ت̀́,ث̀́,ج̀́,ح̀́,خ̀́,د̀́,ذ̀́,ر̀́,ز̀́,س̀́,ش̀́,ص̀́,ض,ط̀́,ظ̀́,ع̀́,غ̀́,ق̀́,ف̀́,ك̀́,ل̀́,م̀́,ن̀́,ه̀́,ۈ̀́,ي̀́,0̀́,1̀́,2ً̀́,3ً̀́,4ً̀́,5ً̀́,6ً̀́,7َ̀́,8ً̀́,9ً̀́,.,_", "ء,ئ,ٳ,ب̯͡,ت̯͡,ث̯͡,ج̯͡,ح̯͡,خ̯͡,د̯͡,ذ̯͡,ر̯͡,ز̯͡,س̯͡,ش̯͡,ص̯͡,ض,ط̯͡,ظ̯͡,ع̯͡,غ̯͡,ق̯͡,ف̯͡,ك̯͡,ل̯͡,م̯͡,ن̯͡,ہ̯͡,ۆ̯͡,ي̯͡,0̯͡,1̯͡,2ً̯͡,3ً̯͡,4ً̯͡,5ً̯͡,6ً̯͡,7َ̯͡,8ً̯͡,9ً̯͡,.,_", "ء,ئ,ٳ,ب,ت,ث,جٍ,حٍ,خـ,دِ,ڌ,رٍ,ز,س,شُ,ص,ض,طُ,ظً,عٍ,غ,ق,فَ,گ,لُ,م,ن,ہ,ۆ,يَ,₀,₁,₂ً,₃ً,₄ً,₅ً,₆ً,₇َ,₈ً,₉ً,.,_", "ء,ئ,ٳ,بـ♥̨̥̬̩,تـ♥̨̥̬̩,ثـ♥̨̥̬̩,جـ♥̨̥̬̩,حـ♥̨̥̬̩,خ,د,ذ,ر,ز,س,ش,ص,ض,ط♥̨̥̬̩,ظ♥̨̥̬̩,ع,غ♥̨̥̬̩,قـ♥̨̥̬̩,ف,گ♥̨̥̬̩,ل,مـ♥̨̥̬̩,ن,هـ♥̨̥̬̩,و,ي,⁰,¹,²ً,³ً,⁴ً,⁵ً,⁶ً,⁷َ,⁸ً,⁹ً,.,_", "ء,ئ,ٳ,بّـ,تُ,ثًـ,جَ ـ,حً ـ,خٌ ـ,دُ,ذٌ,ر,زَ,سًسًـ,شّـ,صِـ,ض,طٌ,ظٌـ,عَ ـ,غّ ـ,قَ,فُ,ك,لَ,مِ,نٌ,هِ,وِ,يّ,0,1,2ً,3ً,4ً,5ً,6ً,7َ,8ً,9ً,.,_", "ء,ئ,ٳ,بُـ‘ـُ,تُـ‘ـُ,ثُـ‘ـُ,جُـ‘ـُ,حُـ‘ـُ,خُـ‘ـُ,ډ,ڏ,ر,ڒٍ,سُـ‘ـُ,شُـ‘ـُ,صُـ‘ـُ,ض,طُـ‘ـُ,ظُـ‘ـُ,عُـ‘ـُ,غُـ‘ـُ,قُـ‘ـُ,فُـ‘ـُ,كُـ‘ـُ,لُـ‘ـُ,مُـ‘ـُ,نُـ‘ـُ,هـُ‘ـُ,ۅ,يُـ‘ـُ,0,1,2ً,3ً,4ً,5ً,6ً,7َ,8ً,9ً,.,_", "ء,ئ,ٳ,بـ☻ـ,تـ☻ـ,ثـ☻ـ,جـ☻ـ,حـ☻ـ,خـ☻ـ,د,ذ,ر,ڒٍ,سـ☻ـ,شـ☻ـ,صـ☻ـ,ض,طـ☻ـ,ظـ☻ـ,عـ☻ـ,غـ☻ـ,قـ☻ـ,فـ☻ـ,كـ☻ـ,لـ☻ـ,مـ☻ـ,نـ☻ـ,هـ☻ـ,ۅ,يـ☻ـ,0,1,2ً,3ً,4ً,5ً,6ً,7َ,8ً,9ً,.,_", "ء,ئ,ٳ,بـޢޢـ,تـޢޢـ,ثـޢޢـ,جـޢޢـ,حـޢޢـ,خـޢޢـ,ډ,ڏ,ر,ڒٍ,سـޢޢـ,شـޢޢـ,صـޢޢـ,ض,طـޢޢـ,ظـޢޢـ,عـޢޢـ,غـޢޢـ,قـޢޢـ,فـޢޢـ,كـޢޢـ,لـޢޢـ,مـޢޢـ,نـޢޢـ,هـޢޢـ,ۅ,يـޢޢـ,0,1,2ً,3ً,4ً,5ً,6ً,7َ,8ً,9ً,.,_", "ء,ئ,ٳ,بّ,تُ,ثً,جَ,حً,خٌ,دُ,ذٌ,ر,ز,سً,شّ,صِ,ض,طٌ,ظٌ,ع,غّ,قَ,فُ,ك,ل,م,نٌ,ۂ,وِ,يّ,0,1,2ً,3ً,4ً,5ً,6ً,7َ,8ً,9ً,.,_", "ء,ئ,ٳ,بّےـ,تُےـ,ثًےـ,جَےـ,حًےـ,خٌےـ,دُ,ذٌ,ر,ز,سًےـ,شّےـ,صِےـ,ض,طٌےـ,ظٌےـ,عَےـ,غّےـ,قَےـ,فُےـ,كےـ,ل,مِےـ,نٌےـ,هےـِ,وِ,يّےـ,0,1,2ً,3ً,4ً,5ً,6ً,7َ,8ً,9ً,.,_", "ء,ئـ,ﺂ,ﺑ,ﭠ,ﭥ,ﭴ,פ,ﺧ,ﮃ,ذ,ړُ,ژ,ﺳ,ﺷ,ﺻ,ﺿ,ﻁ,ﻅ,ﻋ,ﻏ̣̐,ﻗ̮ـ̃,ﭬ,گـ,ﻟ,ﻣ̝̚,ﻧ,ھَہّ,ۆ,ﯾ,0,9,8,7,6,5,4,3,2,1,.,_", "ء,ئ,ﺈ̃,ﺑ̐,ﭠ̯,ﺛ,جً,ﺣ̲,خِ,ﮈ̲,ذُ,رُ,زِ,ﺳ̶̷̶,ﺷ̶͠,ﺻ̶̭͠,ﺿ̲,ﻁ̲,ﻇ̲,ﻌ̲,ﻏ̲,ﭰ,ﻓ̲,ﮚ̷,ﻟ̷,ﻣ̮̃,ﻧ̲,ﮬ̲ﮧ̲,وِ,يّ,0,9,8,7,6,5,4,3,2,1,.,_", } ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- local result = {} i=0 for k=1,#fonts do i=i+1 local tar_font = fonts[i]:split(",") local text = matches[2] local text = text:gsub("ء",tar_font[1]) local text = text:gsub("ئ",tar_font[2]) local text = text:gsub("ا",tar_font[3]) local text = text:gsub("ب",tar_font[4]) local text = text:gsub("ت",tar_font[5]) local text = text:gsub("ث",tar_font[6]) local text = text:gsub("ج",tar_font[7]) local text = text:gsub("ح",tar_font[8]) local text = text:gsub("خ",tar_font[9]) local text = text:gsub("د",tar_font[10]) local text = text:gsub("ذ",tar_font[11]) local text = text:gsub("ر",tar_font[12]) local text = text:gsub("ز",tar_font[13]) local text = text:gsub("س",tar_font[14]) local text = text:gsub("ش",tar_font[15]) local text = text:gsub("ص",tar_font[16]) local text = text:gsub("ض",tar_font[17]) local text = text:gsub("ط",tar_font[18]) local text = text:gsub("ظ",tar_font[19]) local text = text:gsub("ع",tar_font[20]) local text = text:gsub("غ",tar_font[21]) local text = text:gsub("ق",tar_font[22]) local text = text:gsub("ف",tar_font[23]) local text = text:gsub("ك",tar_font[24]) local text = text:gsub("ل",tar_font[25]) local text = text:gsub("م",tar_font[26]) local text = text:gsub("ن",tar_font[27]) local text = text:gsub("ه",tar_font[28]) local text = text:gsub("و",tar_font[29]) local text = text:gsub("ي",tar_font[30]) local text = text:gsub("0",tar_font[31]) local text = text:gsub("9",tar_font[32]) local text = text:gsub("8",tar_font[33]) local text = text:gsub("7",tar_font[34]) local text = text:gsub("6",tar_font[35]) local text = text:gsub("5",tar_font[36]) local text = text:gsub("4",tar_font[37]) local text = text:gsub("3",tar_font[38]) local text = text:gsub("2",tar_font[39]) local text = text:gsub("1",tar_font[40]) table.insert(result, text) end local result_text = "❣ زخرفة : "..matches[2].."\n❣ تصميم "..tostring(#fonts).." خط :\n______________________________\n" a=0 for v=1,#result do a=a+1 result_text = result_text..a.."- "..result[a].."\n\n" end return result_text.."______________________________\n #ṂṜẌ " end return { description = "Fantasy Writer", usagehtm = '<tr><td align="center">decoration متن</td><td align="right">مع هذا البرنامج المساعد يمكن النصوص الخاصة بك مع مجموعة متنوعة من الخطوط والتصميم الجميل. أحرف الحد الأقصى المسموح به هو 20 ويمكن فقط استخدام الأحرف الإنجليزية والأرقام</td></tr>', usage = {"decoration [text] : زخرفه النص",}, patterns = { "^(زخرف) (.*)", "^(زخرف)$", }, run = mrx } --[[ DEV_ @mem_cool #ṂṜẌ ]]
gpl-2.0
starlightknight/darkstar
scripts/zones/Windurst_Waters/npcs/Leepe-Hoppe.lua
9
10722
----------------------------------- -- Area: Windurst Waters -- NPC: Leepe-Hoppe -- Involved in Mission 1-3, Mission 7-2 -- !pos 13 -9 -197 238 ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/missions"); require("scripts/globals/keyitems"); local ID = require("scripts/zones/Windurst_Waters/IDs"); ----------------------------------- function onTrigger(player,npc) local moonlitPath = player:getQuestStatus(WINDURST,dsp.quest.id.windurst.THE_MOONLIT_PATH) local realday = tonumber(os.date("%j")); -- %M for next minute, %j for next day local MissionStatus = player:getCharVar("MissionStatus"); -- Check if we are on Windurst Mission 1-3 and haven't already delivered both offerings. if (player:getCurrentMission(WINDURST) == dsp.mission.id.windurst.THE_PRICE_OF_PEACE and MissionStatus < 3) then if (player:hasKeyItem(dsp.ki.FOOD_OFFERINGS) == false and player:hasKeyItem(dsp.ki.DRINK_OFFERINGS) == false) then player:startEvent(140); elseif (MissionStatus >= 1) then player:startEvent(142); -- Keep displaying the instructions end -- Check if we are on Windurst Mission 7-2 elseif (player:getCurrentMission(WINDURST) == dsp.mission.id.windurst.AWAKENING_OF_THE_GODS and player:getCharVar("MissionStatus") == 0) then player:startEvent(734); elseif (player:getCurrentMission(WINDURST) == dsp.mission.id.windurst.AWAKENING_OF_THE_GODS and player:getCharVar("MissionStatus") == 1) then player:startEvent(735); elseif (player:getCurrentMission(WINDURST) == dsp.mission.id.windurst.AWAKENING_OF_THE_GODS and player:getCharVar("MissionStatus") == 2) then player:startEvent(739); elseif (player:getCurrentMission(WINDURST) == dsp.mission.id.windurst.AWAKENING_OF_THE_GODS and player:getCharVar("MissionStatus") == 5 and player:hasKeyItem(dsp.ki.BOOK_OF_THE_GODS)) then player:startEvent(742); --------------------------- elseif (player:getQuestStatus(WINDURST,dsp.quest.id.windurst.FOOD_FOR_THOUGHT) == QUEST_ACCEPTED) then player:startEvent(311); -- The Moonlit Path and Other Fenrir Stuff! elseif (moonlitPath == QUEST_AVAILABLE and player:getFameLevel(WINDURST) >= 6 and player:getFameLevel(SANDORIA) >= 6 and player:getFameLevel(BASTOK) >= 6 and player:getFameLevel(NORG) >= 4) then -- Fenrir flag event player:startEvent(842,0,1125); elseif (moonlitPath == QUEST_ACCEPTED) then if (player:hasKeyItem(dsp.ki.MOON_BAUBLE)) then -- Default text after acquiring moon bauble and before fighting Fenrir player:startEvent(845,0,1125,334); elseif (player:hasKeyItem(dsp.ki.WHISPER_OF_THE_MOON)) then -- First turn-in local availRewards = 0 if not player:hasKeyItem(dsp.ki.TRAINERS_WHISTLE) or player:hasKeyItem(dsp.ki.FENRIR_WHISTLE) then availRewards = availRewards + 128; end -- Mount Pact player:startEvent(846,0,13399,1208,1125,availRewards,18165,13572); elseif (player:hasKeyItem(dsp.ki.WHISPER_OF_FLAMES) and player:hasKeyItem(dsp.ki.WHISPER_OF_TREMORS) and player:hasKeyItem(dsp.ki.WHISPER_OF_TIDES) and player:hasKeyItem(dsp.ki.WHISPER_OF_GALES) and player:hasKeyItem(dsp.ki.WHISPER_OF_FROST) and player:hasKeyItem(dsp.ki.WHISPER_OF_STORMS)) then -- Collected the whispers player:startEvent(844,0,1125,334); else -- Talked to after flag without the whispers player:startEvent(843,0,1125); end elseif (moonlitPath == QUEST_COMPLETED) then if (player:hasKeyItem(dsp.ki.MOON_BAUBLE)) then -- Default text after acquiring moon bauble and before fighting Fenrir player:startEvent(845,0,1125,334); elseif (player:hasKeyItem(dsp.ki.WHISPER_OF_THE_MOON)) then -- Repeat turn-in local availRewards = 0 if (player:hasItem(18165)) then availRewards = availRewards + 1; end -- Fenrir's Stone if (player:hasItem(13572)) then availRewards = availRewards + 2; end -- Fenrir's Cape if (player:hasItem(13138)) then availRewards = availRewards + 4; end -- Fenrir's Torque if (player:hasItem(13399)) then availRewards = availRewards + 8; end -- Fenrir's Earring if (player:hasItem(1208)) then availRewards = availRewards + 16; end -- Ancient's Key if (player:hasSpell(297)) then availRewards = availRewards + 64; end -- Pact if not player:hasKeyItem(dsp.ki.TRAINERS_WHISTLE) or player:hasKeyItem(dsp.ki.FENRIR_WHISTLE) then availRewards = availRewards + 128; end -- Mount Pact player:startEvent(850,0,13399,1208,1125,availRewards,18165,13572); elseif (realday ~= player:getCharVar("MoonlitPath_date")) then --24 hours have passed, flag a new fight player:startEvent(848,0,1125,334); else player:startEvent(847,0,1125); -- Yes, this will indefinitely replace his standard dialogue! end else player:startEvent(345); -- Standard Dialogue? end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) local reward = 0 if (csid == 140) then player:setCharVar("MissionStatus",1); player:setCharVar("ohbiru_dohbiru_talk",0); player:addKeyItem(dsp.ki.FOOD_OFFERINGS); player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.FOOD_OFFERINGS); player:addKeyItem(dsp.ki.DRINK_OFFERINGS); player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.DRINK_OFFERINGS); -- Moonlit Path and Other Fenrir Stuff elseif (csid == 842 and option == 2) then player:addQuest(WINDURST,dsp.quest.id.windurst.THE_MOONLIT_PATH); elseif (csid == 844) then player:addKeyItem(dsp.ki.MOON_BAUBLE); player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.MOON_BAUBLE); player:delKeyItem(dsp.ki.WHISPER_OF_FLAMES); player:delKeyItem(dsp.ki.WHISPER_OF_TREMORS); player:delKeyItem(dsp.ki.WHISPER_OF_TIDES); player:delKeyItem(dsp.ki.WHISPER_OF_GALES); player:delKeyItem(dsp.ki.WHISPER_OF_FROST); player:delKeyItem(dsp.ki.WHISPER_OF_STORMS); player:delQuest(OUTLANDS,dsp.quest.id.outlands.TRIAL_BY_FIRE); player:delQuest(BASTOK,dsp.quest.id.bastok.TRIAL_BY_EARTH); player:delQuest(OUTLANDS,dsp.quest.id.outlands.TRIAL_BY_WATER); player:delQuest(OUTLANDS,dsp.quest.id.outlands.TRIAL_BY_WIND); player:delQuest(SANDORIA,dsp.quest.id.sandoria.TRIAL_BY_ICE); player:delQuest(OTHER_AREAS_LOG,dsp.quest.id.otherAreas.TRIAL_BY_LIGHTNING); elseif (csid == 846) then -- Turn-in event local reward = 0; if (option == 1) then reward = 18165; -- Fenrir's Stone elseif (option == 2) then reward = 13572; -- Fenrir's Cape elseif (option == 3) then reward = 13138; -- Fenrir's Torque elseif (option == 4) then reward = 13399; -- Fenrir's Earring elseif (option == 5) then reward = 1208; -- Ancient's Key elseif (option == 6) then player:addGil(GIL_RATE*15000); player:messageSpecial(ID.text.GIL_OBTAINED,GIL_RATE*15000); -- Gil elseif (option == 7) then player:addSpell(297) -- Pact elseif (option == 8) then player:addKeyItem(dsp.ki.FENRIR_WHISTLE) player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.FENRIR_WHISTLE) -- Pact as Mount end if (reward ~= nil) then player:addTitle(dsp.title.HEIR_OF_THE_NEW_MOON); player:delKeyItem(dsp.ki.WHISPER_OF_THE_MOON); player:setCharVar("MoonlitPath_date", os.date("%j")); -- %M for next minute, %j for next day player:addFame(WINDURST,30); player:completeQuest(WINDURST,dsp.quest.id.windurst.THE_MOONLIT_PATH); end if (player:getFreeSlotsCount() == 0 and reward ~= 0) then player:messageSpecial(ID.text.ITEM_CANNOT_BE_OBTAINED,reward); elseif (reward ~= 0) then player:addItem(reward); player:messageSpecial(ID.text.ITEM_OBTAINED,reward); end if (player:getNation() == dsp.nation.WINDURST and player:getRank() == 10 and player:getQuestStatus(WINDURST,dsp.quest.id.windurst.THE_PROMISE) == QUEST_COMPLETED) then player:addKeyItem(dsp.ki.DARK_MANA_ORB); player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.DARK_MANA_ORB); end elseif (csid == 850) then -- Repeat turn-in event local reward = 0; if (option == 1) then reward = 18165; -- Fenrir's Stone elseif (option == 2) then reward = 13572; -- Fenrir's Cape elseif (option == 3) then reward = 13138; -- Fenrir's Torque elseif (option == 4) then reward = 13399; -- Fenrir's Earring elseif (option == 5) then reward = 1208; -- Ancient's Key elseif (option == 6) then player:addGil(GIL_RATE*15000); player:messageSpecial(ID.text.GIL_OBTAINED,GIL_RATE*15000); -- Gil elseif (option == 7) then player:addSpell(297) -- Pact elseif (option == 8) then player:addKeyItem(dsp.ki.FENRIR_WHISTLE) player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.FENRIR_WHISTLE) -- Pact as Mount end if (reward ~= nil) then player:addTitle(dsp.title.HEIR_OF_THE_NEW_MOON); player:delKeyItem(dsp.ki.WHISPER_OF_THE_MOON); player:setCharVar("MoonlitPath_date", os.date("%j")); -- %M for next minute, %j for next day player:addFame(WINDURST,30); end if (player:getFreeSlotsCount() == 0 and reward ~= 0) then player:messageSpecial(ID.text.ITEM_CANNOT_BE_OBTAINED,reward); elseif (reward ~= 0) then player:addItem(reward); player:messageSpecial(ID.text.ITEM_OBTAINED,reward); end if (player:getNation() == dsp.nation.WINDURST and player:getRank() == 10 and player:getQuestStatus(WINDURST,dsp.quest.id.windurst.THE_PROMISE) == QUEST_COMPLETED) then player:addKeyItem(dsp.ki.DARK_MANA_ORB); player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.DARK_MANA_ORB); end elseif (csid == 848) then player:addKeyItem(dsp.ki.MOON_BAUBLE); player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.MOON_BAUBLE); elseif (csid == 734) then player:setCharVar("MissionStatus",1); elseif (csid == 742) then finishMissionTimeline(player,3,csid,option); end end;
gpl-3.0
pravsingh/Algorithm-Implementations
Heap_Sort/Lua/Yonaba/heapsort.lua
27
2212
-- Heap sort implementation -- See: http://en.wikipedia.org/wiki/Heapsort -- Binary heap data structure implementation -- Based on http://github.com/Yonaba/Binary-Heaps -- Percolates up local function sift_up(heap, index) if index == 1 then return end local pIndex if index <= 1 then return end if index % 2 == 0 then pIndex = index / 2 else pIndex = (index - 1) / 2 end if not heap._sort(heap._array[pIndex], heap._array[index]) then heap._array[pIndex], heap._array[index] = heap._array[index], heap._array[pIndex] sift_up(heap, pIndex) end end -- Percolates down local function sift_down(heap,index) local lfIndex,rtIndex,minIndex lfIndex = 2 * index rtIndex = lfIndex + 1 if rtIndex > #heap._array then if lfIndex > #heap._array then return else minIndex = lfIndex end else if heap._sort(heap._array[lfIndex],heap._array[rtIndex]) then minIndex = lfIndex else minIndex = rtIndex end end if not heap._sort(heap._array[index],heap._array[minIndex]) then heap._array[index], heap._array[minIndex] = heap._array[minIndex], heap._array[index] sift_down(heap, minIndex) end end -- Default comparison function local function f_min(a,b) return a < b end -- Returns a new binary heap local function newHeap(comp) return {_array = {}, _sort = comp or f_min} end -- Checks if the heap is empty function isEmpty(heap) return #heap._array == 0 end -- Adds a new value in the heap -- Note, we could have also implemented a heapify method -- push all the values and then restore the heap property function pushArray(heap, array) for i, value in ipairs(array) do heap._array[#heap._array + 1] = value sift_up(heap, #heap._array) end return heap end -- Pops values from the heap function popArray(heap) local array = {} while not isEmpty(heap) do local root if #heap._array > 0 then root = heap._array[1] heap._array[1] = heap._array[#heap._array] table.remove(heap._array) if #heap._array > 1 then sift_down(heap, 1) end end array[#array + 1] = root end return array end return function(array, comp) if #array <= 1 then return {array[1]} end return popArray(pushArray(newHeap(comp), array)) end
mit
ThisIsArman/UltraKing
plugins/ingroup.lua
202
31524
do local function check_member(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes' } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'You have been promoted as the owner.') end end end local function check_member_modadd(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes' } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Group is added and you have been promoted as the owner ') end end end local function automodadd(msg) local data = load_data(_config.moderation.data) if msg.action.type == 'chat_created' then receiver = get_receiver(msg) chat_info(receiver, check_member,{receiver=receiver, data=data, msg = msg}) end end local function check_member_modrem(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration removal data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = nil save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Group has been removed') end end end local function show_group_settingsmod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local bots_protection = "Yes" if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX.."\nBot protection : "..bots_protection return text end local function set_descriptionmod(msg, data, target, about) if not is_momod(msg) then return "For moderators only!" end local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function get_description(msg, data) local data_cat = 'description' if not data[tostring(msg.to.id)][data_cat] then return 'No description available.' end local about = data[tostring(msg.to.id)][data_cat] local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about return 'About '..about end local function lock_group_arabic(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'yes' then return 'Arabic is already locked' else data[tostring(target)]['settings']['lock_arabic'] = 'yes' save_data(_config.moderation.data, data) return 'Arabic has been locked' end end local function unlock_group_arabic(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'no' then return 'Arabic is already unlocked' else data[tostring(target)]['settings']['lock_arabic'] = 'no' save_data(_config.moderation.data, data) return 'Arabic has been unlocked' end end local function lock_group_bots(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'yes' then return 'Bots protection is already enabled' else data[tostring(target)]['settings']['lock_bots'] = 'yes' save_data(_config.moderation.data, data) return 'Bots protection has been enabled' end end local function unlock_group_bots(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'no' then return 'Bots protection is already disabled' else data[tostring(target)]['settings']['lock_bots'] = 'no' save_data(_config.moderation.data, data) return 'Bots protection has been disabled' end end local function lock_group_namemod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_namemod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end local function lock_group_floodmod(msg, data, target) if not is_owner(msg) then return "Only admins can do it for now" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_floodmod(msg, data, target) if not is_owner(msg) then return "Only admins can do it for now" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end local function lock_group_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end local function unlock_group_photomod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function set_rulesmod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end local function modadd(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then return 'Group is already added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_modadd,{receiver=receiver, data=data, msg = msg}) end local function modrem(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if not data[tostring(msg.to.id)] then return 'Group is not added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg}) end local function get_rules(msg, data) local data_cat = 'rules' if not data[tostring(msg.to.id)][data_cat] then return 'No rules available.' end local rules = data[tostring(msg.to.id)][data_cat] local rules = 'Chat rules:\n'..rules return rules end local function set_group_photo(msg, success, result) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if success then local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) chat_set_photo (receiver, file, ok_cb, false) data[tostring(msg.to.id)]['settings']['set_photo'] = file save_data(_config.moderation.data, data) data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes' save_data(_config.moderation.data, data) send_large_msg(receiver, 'Photo saved!', ok_cb, false) else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end local function promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already a moderator.') end data[group]['moderators'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted.') end local function demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if not data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not a moderator.') end data[group]['moderators'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been demoted.') end local function username_id(cb_extra, success, result) local mod_cmd = cb_extra.mod_cmd local receiver = cb_extra.receiver local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if mod_cmd == 'promote' then return promote(receiver, member_username, member_id) elseif mod_cmd == 'demote' then return demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function modlist(msg) local data = load_data(_config.moderation.data) if not data[tostring(msg.to.id)] then return 'Group is not added.' end -- determine if table is empty if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'No moderator in this group.' end local i = 1 local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do message = message ..i..' - @'..v..' [' ..k.. '] \n' i = i + 1 end return message end local function callbackres(extra, success, result) local user = result.id local name = string.gsub(result.print_name, "_", " ") local chat = 'chat#id'..extra.chatid send_large_msg(chat, user..'\n'..name) return user end local function help() local help_text = tostring(_config.help_text) return help_text end local function cleanmember(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name if success == -1 then return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.') end for k,v in pairs(result.members) do kick_user(v.id, result.id) end end local function run(msg, matches) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) local name_log = user_print_name(msg.from) local group = msg.to.id if msg.media then if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_chat_msg(msg) and is_momod(msg) then load_photo(msg.id, set_group_photo, msg) end end if matches[1] == 'add' then print("group "..msg.to.print_name.."("..msg.to.id..") added") return modadd(msg) end if matches[1] == 'rem' then print("group "..msg.to.print_name.."("..msg.to.id..") removed") return modrem(msg) end if matches[1] == 'chat_created' and msg.from.id == 0 then return automodadd(msg) end if msg.to.id and data[tostring(msg.to.id)] then local settings = data[tostring(msg.to.id)]['settings'] if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local group_member_lock = settings.lock_member local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if group_member_lock == 'yes' and not is_owner2(msg.action.user.id, msg.to.id) then chat_del_user(chat, user, ok_cb, true) elseif group_member_lock == 'yes' and tonumber(msg.from.id) == tonumber(our_id) then return nil elseif group_member_lock == 'no' then return nil end end if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local receiver = 'user#id'..msg.action.user.id local data_cat = 'rules' if not data[tostring(msg.to.id)][data_cat] then return false end local rules = data[tostring(msg.to.id)][data_cat] local rules = 'Welcome to "' .. string.gsub(msg.to.print_name, '_', ' ') ..'" this group has rules that you should follow:\n'..rules savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..msg.action.user.id) send_large_msg(receiver, rules) end if matches[1] == 'chat_del_user' then if not msg.service then return "Are you trying to troll me?" end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..user) end if matches[1] == 'chat_delete_photo' then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:incr(picturehash) --- local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id local picprotectionredis = redis:get(picturehash) if picprotectionredis then if tonumber(picprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(picprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:set(picturehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to deleted picture but failed ") chat_set_photo(receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:incr(picturehash) --- local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id local picprotectionredis = redis:get(picturehash) if picprotectionredis then if tonumber(picprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(picprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:set(picturehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change picture but failed ") chat_set_photo(receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_rename' then if not msg.service then return "Are you trying to troll me?" end local group_name_set = settings.set_name local group_name_lock = settings.lock_name local to_rename = 'chat#id'..msg.to.id if group_name_lock == 'yes' then if group_name_set ~= tostring(msg.to.print_name) then local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id redis:incr(namehash) local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id local nameprotectionredis = redis:get(namehash) if nameprotectionredis then if tonumber(nameprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(nameprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id redis:set(namehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change name but failed ") rename_chat(to_rename, group_name_set, ok_cb, false) end elseif group_name_lock == 'no' then return nil end end if matches[1] == 'setname' and is_momod(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setphoto' and is_momod(msg) then data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) return 'Please send me new group photo now' end if matches[1] == 'promote' and matches[2] then if not is_owner(msg) then return "Only owner can promote" end local member = string.gsub(matches[2], "@", "") local mod_cmd = 'promote' savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member) chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'demote' and matches[2] then if not is_owner(msg) then return "Only owner can demote" end if string.gsub(matches[2], "@", "") == msg.from.username then return "You can't demote yourself" end local member = string.gsub(matches[2], "@", "") local mod_cmd = 'demote' savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member) chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'modlist' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist") return modlist(msg) end if matches[1] == 'about' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group description") return get_description(msg, data) end if matches[1] == 'rules' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules") return get_rules(msg, data) end if matches[1] == 'set' then if matches[2] == 'rules' then rules = matches[3] local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]") return set_rulesmod(msg, data, target) end if matches[2] == 'about' then local data = load_data(_config.moderation.data) local target = msg.to.id local about = matches[3] savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]") return set_descriptionmod(msg, data, target, about) end end if matches[1] == 'lock' then local target = msg.to.id if matches[2] == 'name' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked name ") return lock_group_namemod(msg, data, target) end if matches[2] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ") return lock_group_floodmod(msg, data, target) end if matches[2] == 'arabic' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked arabic ") return lock_group_arabic(msg, data, target) end if matches[2] == 'bots' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots ") return lock_group_bots(msg, data, target) end end if matches[1] == 'unlock' then local target = msg.to.id if matches[2] == 'name' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked name ") return unlock_group_namemod(msg, data, target) end if matches[2] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end if matches[2] == 'photo' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked photo ") return unlock_group_photomod(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood ") return unlock_group_floodmod(msg, data, target) end if matches[2] == 'arabic' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked arabic ") return unlock_group_arabic(msg, data, target) end if matches[2] == 'bots' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked bots ") return unlock_group_bots(msg, data, target) end end if matches[1] == 'settings' then local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group settings ") return show_group_settingsmod(msg, data, target) end if matches[1] == 'newlink' then if not is_momod(msg) then return "For moderators only!" end local function callback (extra , success, result) local receiver = 'chat#'..msg.to.id if success == 0 then return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.') end send_large_msg(receiver, "Created a new link") data[tostring(msg.to.id)]['settings']['set_link'] = result save_data(_config.moderation.data, data) end local receiver = 'chat#'..msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] revoked group link ") return export_chat_link(receiver, callback, true) end if matches[1] == 'link' then if not is_momod(msg) then return "For moderators only!" end local group_link = data[tostring(msg.to.id)]['settings']['set_link'] if not group_link then return "Create a link using /newlink first !" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]") return "Group link:\n"..group_link end if matches[1] == 'setowner' then if not is_owner(msg) then return "For owner only!" end data[tostring(msg.to.id)]['set_owner'] = matches[2] save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as owner") local text = matches[2].." added as owner" return text end if matches[1] == 'owner' then local group_owner = data[tostring(msg.to.id)]['set_owner'] if not group_owner then return "no owner,ask admins in support groups to set owner for your group" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner") return "Group owner is ["..group_owner..']' end if matches[1] == 'setgpowner' then local receiver = "chat#id"..matches[2] if not is_admin(msg) then return "For admins only!" end data[tostring(matches[2])]['set_owner'] = matches[3] save_data(_config.moderation.data, data) local text = matches[3].." added as owner" send_large_msg(receiver, text) return end if matches[1] == 'setflood' then if not is_momod(msg) then return "For moderators only!" end if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then return "Wrong number,range is [5-20]" end local flood_max = matches[2] data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]") return 'Group flood has been set to '..matches[2] end if matches[1] == 'clean' then if not is_owner(msg) then return "Only owner can clean" end if matches[2] == 'member' then if not is_owner(msg) then return "Only admins can clean members" end local receiver = get_receiver(msg) chat_info(receiver, cleanmember, {receiver=receiver}) end if matches[2] == 'modlist' then if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'No moderator in this group.' end local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil save_data(_config.moderation.data, data) end savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist") end if matches[2] == 'rules' then local data_cat = 'rules' data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules") end if matches[2] == 'about' then local data_cat = 'description' data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about") end end if matches[1] == 'help' then if not is_momod(msg) then return end savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end if matches[1] == 'res' and is_momod(msg) then local cbres_extra = { chatid = msg.to.id } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username) return res_user(username, callbackres, cbres_extra) end end end return { patterns = { "^[!/](add)$", "^[!/](rem)$", "^[!/](rules)$", "^[!/](about)$", "^[!/](setname) (.*)$", "^[!/](setphoto)$", "^[!/](promote) (.*)$", "^[!/](help)$", "^[!/](clean) (.*)$", "^[!/](demote) (.*)$", "^[!/](set) ([^%s]+) (.*)$", "^[!/](lock) (.*)$", "^[!/](setowner) (%d+)$", "^[!/](owner)$", "^[!/](res) (.*)$", "^[!/](setgpowner) (%d+) (%d+)$",-- (group id) (owner id) "^[!/](unlock) (.*)$", "^[!/](setflood) (%d+)$", "^[!/](settings)$", "^[!/](modlist)$", "^[!/](newlink)$", "^[!/](link)$", "%[(photo)%]", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
taschemann/kq-lives
scripts/sunarin.lua
2
2706
-- sunarin - "Sunarin Tower" function autoexec() return end function entity_handler(en) if (en == 0) then local x, y = get_ent_tile(HERO1) move_entity(HERO2, x, y + 1) wait_for_entity(HERO2) bubble(en, _"I am the king of thieves!") if (get_progress(P_AYLA_QUEST) == 7 and get_ent_chrx(HERO1) ~= 0) then bubble(HERO1, _"Yea? Well I'm Ayla... you know, "..pick("Daughter of Malkaron", "Princess Ayla", "heir to Dungar's estate").."!") bubble(en, _"Oh really. Is that a fact?") thought(HERO1, _"Uh, oh. Wrong thing to say...") bubble(en, _"Guards!!") move_entity(1, x - 1, y) move_entity(2, x - 1, y + 1) move_entity(3, x + 1, y) move_entity(4, x + 1, y + 1) wait_for_entity(1, 4) set_run(0) combat(61) set_run(1) if (get_alldead() == 1) then bubble(en, _"And now, your remains will be food for the fishes!") return end set_ent_active(1, 0) set_ent_active(2, 0) set_ent_active(3, 0) set_ent_active(4, 0) bubble(en, _"You shall rue the day you came against me!") wait(50) set_ent_active(0, 0) wait(50) bubble(HERO1, _"Whoa! He just disappeared! Oh well, that treasure is still down there.") else bubble(en, _"Honor me, for I am king!") end elseif (en == 1) then bubble(en, _"WE GUARD THE SACRED TREASURE!") elseif (en == 2) then bubble(en, _"None shall inherit the treasure except who joins the guild!") elseif (en == 3) then bubble(en, _"Who are you? Are you trying to steal from us?") elseif (en == 4) then bubble(255, _"The man glowers at you, but says nothing.") end end function postexec() return end function refresh() showch("treasure1", 32) end -- Show the status of treasures function showch(which_marker, which_chest) -- Set tiles if chest already opened if (get_treasure(which_chest) == 1) then set_zone(which_marker, 0) end -- Only treasure1 needs to change its obstacle setting if (which_marker == "treasure1") then set_obs(which_marker, 0) end end function zone_handler(zn) if (zn == 1) then change_map("main", "town5", 2, -1) elseif (zn == 2) then LOC_door("door1") elseif (zn == 3) then touch_fire(party[0]); elseif (zn == 4) then bubble(HERO1, _"The door appears to be locked.") elseif (zn == 5) then bubble(HERO1, _"That's a treasure chest!") bubble(HERO1, _"Stay tuned for KQ 1.0 Final!") end end function LOC_door(which_marker) sfx(25) local x, y = marker(which_marker) set_mtile(x, y, 0) set_mtile(x, y + 1, 0) set_obs(x, y, 0) set_shadow(x, y, 8) set_zone(x, y, 0) end
gpl-2.0
starlightknight/darkstar
scripts/globals/items/galette_des_rois.lua
11
1198
----------------------------------------- -- ID: 5875 -- Item: Galette Des Rois -- Food Effect: 180 Min, All Races ----------------------------------------- -- HP +8 -- MP +3% (cap13) -- Intelligence +2 -- Random Jewel ----------------------------------------- require("scripts/globals/status") require("scripts/globals/msg") ----------------------------------------- function onItemCheck(target) local result = 0 if target:hasStatusEffect(dsp.effect.FOOD) then result = dsp.msg.basic.IS_FULL end if target:getFreeSlotsCount() == 0 then result = dsp.msg.basic.ITEM_NO_USE_INVENTORY end return result end function onItemUse(target) target:addStatusEffect(dsp.effect.FOOD,0,0,10800,5875) local rand = math.random(784,815) target:addItem(rand) -- Random Jewel end function onEffectGain(target,effect) target:addMod(dsp.mod.HP, 8) target:addMod(dsp.mod.FOOD_MPP, 3) target:addMod(dsp.mod.FOOD_MP_CAP, 13) target:addMod(dsp.mod.INT, 2) end function onEffectLose(target, effect) target:delMod(dsp.mod.HP, 8) target:delMod(dsp.mod.FOOD_MPP, 3) target:delMod(dsp.mod.FOOD_MP_CAP, 13) target:delMod(dsp.mod.INT, 2) end
gpl-3.0
starlightknight/darkstar
scripts/zones/Port_Windurst/npcs/Panja-Nanja.lua
12
1374
----------------------------------- -- Area: Port Windurst -- NPC: Panja-Nanja -- Type: Fishing Adv. Image Support -- !pos -194.499 -3 58.692 240 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/crafting"); local ID = require("scripts/zones/Port_Windurst/IDs"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) local guildMember = isGuildMember(player,8); local SkillLevel = player:getSkillLevel(dsp.skill.FISHING); local Cost = getAdvImageSupportCost(player,dsp.skill.FISHING); if (guildMember == 1) then if (player:hasStatusEffect(dsp.effect.FISHING_IMAGERY) == false) then player:startEvent(10011,Cost,SkillLevel,0,239,player:getGil(),0,0,0); -- p1 = skill level else player:startEvent(10011,Cost,SkillLevel,0,239,player:getGil(),38586,30,0); end else player:startEvent(10011); -- Standard Dialogue, incorrect end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) local Cost = getAdvImageSupportCost(player,256); if (csid == 10011 and option == 1) then player:delGil(Cost); player:messageSpecial(ID.text.FISHING_SUPPORT,0,0,0); player:addStatusEffect(dsp.effect.FISHING_IMAGERY,2,0,7200); end end;
gpl-3.0
gedads/Neodynamis
scripts/zones/Temple_of_Uggalepih/mobs/Manipulator.lua
17
2255
---------------------------------- -- Area: Temple of Uggalipeh -- NM: Manipulator -- Notes: Paths around the 2 staircases ----------------------------------- local path = { -17.930, -8.500, -93.215, -18.553, -7.713, -91.224, -20.226, -6.250, -89.091, -21.651, -5.005, -87.401, -23.137, -3.917, -85.818, -24.750, -2.650, -84.440, -26.487, -1.300, -83.362, -28.366, -0.068, -82.488, -30.361, 0.500, -81.880, -32.450, 0.500, -81.498, -34.553, 0.500, -81.367, -36.575, 0.500, -81.401, -38.601, 0.500, -81.632, -40.699, 0.500, -82.133, -43.542, -1.300, -83.312, -45.403, -2.650, -84.455, -47.108, -3.804, -85.804, -48.567, -4.900, -87.243, -49.894, -6.250, -88.891, -50.957, -7.518, -90.686, -51.714, -8.500, -92.696, -52.136, -8.500, -94.655, -52.358, -8.500, -96.757, -52.482, -8.500, -99.253, -52.530, -8.500, -102.142, -52.409, -8.500, -104.364, -51.995, -8.500, -106.498, -51.329, -7.998, -108.403, -50.419, -6.700, -110.216, -49.221, -5.514, -111.939, -47.741, -4.367, -113.588, -46.122, -3.100, -115.009, -44.418, -1.750, -116.181, -42.611, -0.797, -117.185, -40.653, 0.500, -117.857, -38.622, 0.500, -118.275, -36.614, 0.500, -118.518, -34.459, 0.500, -118.650, -32.303, 0.500, -118.591, -30.276, 0.500, -118.249, -28.199, -0.318, -117.605, -26.325, -1.300, -116.748, -24.522, -2.650, -115.637, -22.911, -3.550, -114.378, -21.430, -4.900, -112.942, -20.121, -6.250, -111.382, -18.967, -7.150, -109.509, -18.191, -8.500, -107.518, -17.743, -8.500, -105.495, -17.541, -8.500, -103.466, -17.497, -8.500, -101.427, -17.408, -8.500, -97.263, -17.573, -8.500, -95.179 }; function onMobSpawn(mob) onMobRoam(mob); -- what? end; function onPath(mob) pathfind.patrol(mob, path); end; function onMobRoam(mob) -- move to start position if not moving if (mob:isFollowingPath() == false) then mob:pathThrough(pathfind.first(path)); end end; function onMobDeath(mob, player, isKiller) end; function onMobDespawn(mob) -- Set Manipulator's spawnpoint and respawn time mob:setRespawnTime(7200); -- 2 hours end;
gpl-3.0
starlightknight/darkstar
scripts/globals/items/bowl_of_jack-o-soup.lua
11
1388
----------------------------------------- -- ID: 4522 -- Item: Bowl of Jack-o'-Soup -- Food Effect: 240Min, All Races ----------------------------------------- -- Health % 2 (cap 120) -- Agility 3 -- Vitality -1 -- Health Regen While Healing 5 -- Ranged ACC % 8 -- Ranged ACC Cap 25 ----------------------------------------- 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,4522) end function onEffectGain(target, effect) target:addMod(dsp.mod.FOOD_HPP, 2) target:addMod(dsp.mod.FOOD_HP_CAP, 120) target:addMod(dsp.mod.AGI, 3) target:addMod(dsp.mod.VIT, -1) target:addMod(dsp.mod.HPHEAL, 5) target:addMod(dsp.mod.FOOD_RACCP, 8) target:addMod(dsp.mod.FOOD_RACC_CAP, 25) end function onEffectLose(target, effect) target:delMod(dsp.mod.FOOD_HPP, 2) target:delMod(dsp.mod.FOOD_HP_CAP, 120) target:delMod(dsp.mod.AGI, 3) target:delMod(dsp.mod.VIT, -1) target:delMod(dsp.mod.HPHEAL, 5) target:delMod(dsp.mod.FOOD_RACCP, 8) target:delMod(dsp.mod.FOOD_RACC_CAP, 25) end
gpl-3.0
focusworld/ghost-bot
plugins/img_google.lua
660
3196
do local mime = require("mime") local google_config = load_from_file('data/google.lua') local cache = {} --[[ local function send_request(url) local t = {} local options = { url = url, sink = ltn12.sink.table(t), method = "GET" } local a, code, headers, status = http.request(options) return table.concat(t), code, headers, status end]]-- local function get_google_data(text) local url = "http://ajax.googleapis.com/ajax/services/search/images?" url = url.."v=1.0&rsz=5" url = url.."&q="..URL.escape(text) url = url.."&imgsz=small|medium|large" if google_config.api_keys then local i = math.random(#google_config.api_keys) local api_key = google_config.api_keys[i] if api_key then url = url.."&key="..api_key end end local res, code = http.request(url) if code ~= 200 then print("HTTP Error code:", code) return nil end local google = json:decode(res) return google end -- Returns only the useful google data to save on cache local function simple_google_table(google) local new_table = {} new_table.responseData = {} new_table.responseDetails = google.responseDetails new_table.responseStatus = google.responseStatus new_table.responseData.results = {} local results = google.responseData.results for k,result in pairs(results) do new_table.responseData.results[k] = {} new_table.responseData.results[k].unescapedUrl = result.unescapedUrl new_table.responseData.results[k].url = result.url end return new_table end local function save_to_cache(query, data) -- Saves result on cache if string.len(query) <= 7 then local text_b64 = mime.b64(query) if not cache[text_b64] then local simple_google = simple_google_table(data) cache[text_b64] = simple_google end end end local function process_google_data(google, receiver, query) if google.responseStatus == 403 then local text = 'ERROR: Reached maximum searches per day' send_msg(receiver, text, ok_cb, false) elseif google.responseStatus == 200 then local data = google.responseData if not data or not data.results or #data.results == 0 then local text = 'Image not found.' send_msg(receiver, text, ok_cb, false) return false end -- Random image from table local i = math.random(#data.results) local url = data.results[i].unescapedUrl or data.results[i].url local old_timeout = http.TIMEOUT or 10 http.TIMEOUT = 5 send_photo_from_url(receiver, url) http.TIMEOUT = old_timeout save_to_cache(query, google) else local text = 'ERROR!' send_msg(receiver, text, ok_cb, false) end end function run(msg, matches) local receiver = get_receiver(msg) local text = matches[1] local text_b64 = mime.b64(text) local cached = cache[text_b64] if cached then process_google_data(cached, receiver, text) else local data = get_google_data(text) process_google_data(data, receiver, text) end end return { description = "Search image with Google API and sends it.", usage = "!img [term]: Random search an image with Google API.", patterns = { "^!img (.*)$" }, run = run } end
gpl-2.0
gedads/Neodynamis
scripts/zones/Metalworks/npcs/High_Bear.lua
3
1884
----------------------------------- -- Area: Metalworks -- NPC: High Bear -- Type: Quest Giver -- @zone 237 -- !pos 25.231 -14.999 4.552 ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/globals/titles"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local BeaSmog = player:getQuestStatus(BASTOK,BEADEAUX_SMOG); local keyitem = player:hasKeyItem(CORRUPTED_DIRT); if (BeaSmog == QUEST_AVAILABLE and player:getFameLevel(BASTOK) >= 4) then player:startEvent(0x02DB); elseif (BeaSmog == QUEST_ACCEPTED and keyitem == false or BeaSmog == QUEST_COMPLETED) then player:startEvent(0x02da); elseif (BeaSmog == QUEST_ACCEPTED and keyitem == true) then player:startEvent(0x02dc); 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 == 0x2DB) then player:addQuest(BASTOK,BEADEAUX_SMOG); elseif (csid == 0x2dc) then player:addFame(BASTOK,30); player:delKeyItem(CORRUPTED_DIRT); player:addItem(17284,1); player:messageSpecial(QUEST_COMPLETED); player:messageSpecial(ITEM_OBTAINED,17284); player:completeQuest(BASTOK,BEADEAUX_SMOG); player:setTitle(BEADEAUX_SURVEYOR); end end;
gpl-3.0
starlightknight/darkstar
scripts/zones/Gustav_Tunnel/npcs/qm2.lua
9
1354
----------------------------------- -- Area: Gustav tunnel -- NPC: qm2 (???) -- Note: Part of mission "The Salt of the Earth" -- !pos -130 1.256 252.696 212 ----------------------------------- local ID = require("scripts/zones/Gustav_Tunnel/IDs"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) local basty = player:getCurrentMission(BASTOK); local soteStat = player:getCharVar("BASTOK91"); local anyPlasmsAlive = false; for i = ID.mob.GIGAPLASM, ID.mob.GIGAPLASM + 14 do if (GetMobByID(i):isAlive()) then anyPlasmsAlive = true; break; end end if (basty == dsp.mission.id.bastok.THE_SALT_OF_THE_EARTH and soteStat == 2 and not anyPlasmsAlive) then SpawnMob(ID.mob.GIGAPLASM):updateClaim(player); elseif (basty == dsp.mission.id.bastok.THE_SALT_OF_THE_EARTH and soteStat == 3 and not player:hasKeyItem(dsp.ki.MIRACLESALT)) then player:addKeyItem(dsp.ki.MIRACLESALT); player:messageSpecial(ID.text.KEYITEM_OBTAINED, dsp.ki.MIRACLESALT); else player:messageSpecial(ID.text.NOTHING_OUT_OF_ORDINARY); end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) end;
gpl-3.0
gedads/Neodynamis
scripts/globals/weaponskills/gust_slash.lua
23
1283
----------------------------------- -- Gust Slash -- Dagger weapon skill -- Skill level: 40 -- Deals wind elemental damage. Damage varies with TP. -- Will not stack with Sneak Attack. -- Aligned with the Breeze Gorget. -- Aligned with the Breeze Belt. -- Element: Wind -- Modifiers: DEX:20% ; INT:20% -- 100%TP 200%TP 300%TP -- 1.00 2.00 2.50 ----------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar) local params = {}; params.ftp100 = 1; params.ftp200 = 2; params.ftp300 = 2.5; params.str_wsc = 0.0; params.dex_wsc = 0.2; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.2; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.ele = ELE_WIND; params.skill = SKILL_DAG; params.includemab = true; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.dex_wsc = 0.4; params.int_wsc = 0.4; end local damage, criticalHit, tpHits, extraHits = doMagicWeaponskill(player, target, wsID, tp, primary, action, params); return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
ironjade/DevStack
LanCom/DesignPattern/LUA/OpenScatterTable.lua
1
6208
#!/usr/local/bin/lua --[[ Copyright (c) 2004 by Bruno R. Preiss, P.Eng. $Author: brpreiss $ $Date: 2004/12/05 14:47:20 $ $RCSfile: OpenScatterTable.lua,v $ $Revision: 1.4 $ $Id: OpenScatterTable.lua,v 1.4 2004/12/05 14:47:20 brpreiss Exp $ --]] require "HashTable" require "Array" --{ -- Open scatter table implemented using an array. OpenScatterTable = Class.new("OpenScatterTable", HashTable) -- Entry state is empty. OpenScatterTable.EMPTY = 0 -- Entry state is occupied. OpenScatterTable.OCCUPIED = 1 -- Entry state is deleted. OpenScatterTable.DELETED = 2 -- An entry in an open scatter table. OpenScatterTable.Entry = Class.new("OpenScatterTable.Entry") -- Constructs an entry in an open scatter table -- with the given state and object. -- @param state The state of the entry. -- @param obj An object. function OpenScatterTable.Entry.methods:initialize(state, obj) OpenScatterTable.Entry.super(self) self.state = state self.obj = obj end -- The state of this entry. OpenScatterTable.Entry:attr_accessor("state") -- The object. OpenScatterTable.Entry:attr_accessor("obj") --}>a --{ -- Constructs an open scatter table with the given size. -- @param length The length of the array. function OpenScatterTable.methods:initialize(length) OpenScatterTable.super(self) self.array = Array.new(length) for i = 0, length - 1 do self.array[i] = OpenScatterTable.Entry.new( OpenScatterTable.EMPTY, nil) end end -- The length of the array. function OpenScatterTable.methods:get_length() return self.array:get_length() end -- Purges this hash table. function OpenScatterTable.methods:purge() for i = 0, self:get_length() - 1 do self.array[i] = OpenScatterTable.Entry.new( OpenScatterTable.EMPTY, nil) end self.count = 0 end --}>b --{ -- The probing sequence function. -- @param i The probe number. function OpenScatterTable.methods:c(i) return i end -- Returns the index of an unoccupied entry -- where the given object may be inserted. -- The state of an unoccupied entry is either EMPTY or DELETED. -- @param obj The object to be inserted. function OpenScatterTable.methods:findUnoccupied(obj) local hash = self:h(obj) for i = 0, self:get_length() - 1 do local probe = math.mod(hash + self:c(i), self:get_length()) if self.array[probe].state ~= OpenScatterTable.OCCUPIED then return probe end end error "ContainerFull" end -- Inserts the given object into this hash table. -- @param obj An object. function OpenScatterTable.methods:insert(obj) if self.count == self:get_length() then error "ContainerFull" end local offset = self:findUnoccupied(obj) self.array[offset] = OpenScatterTable.Entry.new( OpenScatterTable.OCCUPIED, obj) self.count = self.count + 1 end --}>c --{ -- Returns the index of the entry that contain an object -- that equals the given object. -- @param obj An object. function OpenScatterTable.methods:findMatch(obj) local hash = self:h(obj) for i = 0, self:get_length() do probe = math.mod(hash + self:c(i), self:get_length()) if self.array[probe].state == OpenScatterTable.EMPTY then break end if self.array[probe].state == OpenScatterTable.OCCUPIED and self.array[probe].obj == obj then return probe end end return -1 end -- Returns the object in this hash table -- that equals the given object. -- @param obj An object. function OpenScatterTable.methods:find(obj) local offset = self:findMatch(obj) if offset >= 0 then return self.array[offset].obj else return nil end end --}>d --{ -- Withdraws the given object from this hash table. -- @param obj The object to withdraw. function OpenScatterTable.methods:withdraw(obj) if self.count == 0 then error "ContainerEmpty" end local offset = self:findInstance(obj) if offset < 0 then error "ArgumentError" end self.array[offset] = OpenScatterTable.Entry.new( OpenScatterTable.DELETED, nil) self.count = self.count - 1 end --}>e -- Returns the index of the entry that contains the given object instance. -- @param obj An object. function OpenScatterTable.methods:findInstance(obj) local hash = self:h(obj) for i = 0, self:get_length() do local probe = math.mod(hash + self:c(i), self:get_length()) if self.array[probe].state == OpenScatterTable.EMPTY then break end if self.array[probe].state == OpenScatterTable.OCCUPIED and self.array[probe].obj:is(obj) then return probe end end return -1 end -- True if this hash table is full. function OpenScatterTable.methods:is_full() return self.count == self:get_length() end -- Class the given visitor function for each object in this open scatter table. -- @param visitor A visitor function. function OpenScatterTable.methods:each(visitor) for i = 0, self:get_length() - 1 do if self.array[i].state == OpenScatterTable.OCCUPIED then visitor(self.array[i].obj) end end end -- Returns an iterator that enumerates -- the object contained in an open scatter table. function OpenScatterTable.methods:iter() local position = 0 -- Iterator state. while position < self.array:get_length() do if self.array[position].state == OpenScatterTable.OCCUPIED then break end position = position + 1 end return function() local result = nil if position < self.array:get_length() then result = self.array[position].obj position = position + 1 while position < self.array:get_length() do if self.array[position].state == OpenScatterTable.OCCUPIED then break end position = position + 1 end end return result end end -- True if the given object is in this hash table. -- @param obj An object. function OpenScatterTable.methods:contains(obj) return self:findInstance(obj) >= 0 end -- OpenScatterTable test program. -- @param arg Command-line arguments. function OpenScatterTable.main(arg) print "OpenScatterTable test program." local hashTable = OpenScatterTable.new(57) print(hashTable) HashTable.test(hashTable) return 0 end if _REQUIREDNAME == nil then os.exit( OpenScatterTable.main(arg) ) end
apache-2.0
starlightknight/darkstar
scripts/globals/items/pepperoni_pizza_+1.lua
11
1264
----------------------------------------- -- ID: 5698 -- Item: pepperoni_pizza_+1 -- Food Effect: 4 hours, all Races ----------------------------------------- -- HP +35 -- Strength 2 -- Accuracy 9% (caps @ 11) -- Attack 10% (caps @ 16) ----------------------------------------- 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,5698) end function onEffectGain(target,effect) target:addMod(dsp.mod.HP, 35) target:addMod(dsp.mod.STR, 2) target:addMod(dsp.mod.FOOD_ATTP, 10) target:addMod(dsp.mod.FOOD_ATT_CAP, 16) target:addMod(dsp.mod.FOOD_ACCP, 9) target:addMod(dsp.mod.FOOD_ACC_CAP, 11) end function onEffectLose(target, effect) target:delMod(dsp.mod.HP, 35) target:delMod(dsp.mod.STR, 2) target:delMod(dsp.mod.FOOD_ATTP, 10) target:delMod(dsp.mod.FOOD_ATT_CAP, 16) target:delMod(dsp.mod.FOOD_ACCP, 9) target:delMod(dsp.mod.FOOD_ACC_CAP, 11) end
gpl-3.0
starlightknight/darkstar
scripts/zones/Outer_Horutoto_Ruins/IDs.lua
9
2791
----------------------------------- -- Area: Outer_Horutoto_Ruins ----------------------------------- require("scripts/globals/zone") ----------------------------------- zones = zones or {} zones[dsp.zone.OUTER_HORUTOTO_RUINS] = { text = { ORB_ALREADY_PLACED = 0, -- A dark Mana Orb is already placed here. CONQUEST_BASE = 15, -- Tallying conquest results... DEVICE_NOT_WORKING = 188, -- The device is not working. SYS_OVERLOAD = 197, -- Warning! Sys...verload! Enterin...fety mode. ID eras...d. YOU_LOST_THE = 202, -- You lost the <item>. ITEM_CANNOT_BE_OBTAINED = 6587, -- You cannot obtain the <item>. Come back after sorting your inventory. ITEM_OBTAINED = 6593, -- Obtained: <item>. GIL_OBTAINED = 6594, -- Obtained <number> gil. KEYITEM_OBTAINED = 6596, -- Obtained key item: <keyitem>. GEOMAGNETRON_ATTUNED = 7215, -- Your <keyitem> has been attuned to a geomagnetic fount in the corresponding locale. DOOR_FIRMLY_SHUT = 7254, -- The door is firmly shut. ALL_G_ORBS_ENERGIZED = 7257, -- The six Mana Orbs have been successfully energized with magic! CHEST_UNLOCKED = 7280, -- You unlock the chest! PLAYER_OBTAINS_ITEM = 8257, -- <name> obtains <item>! UNABLE_TO_OBTAIN_ITEM = 8258, -- You were unable to obtain the item. PLAYER_OBTAINS_TEMP_ITEM = 8259, -- <name> obtains the temporary item: <item>! ALREADY_POSSESS_TEMP = 8260, -- You already possess that temporary item. NO_COMBINATION = 8265, -- You were unable to enter a combination. REGIME_REGISTERED = 10343, -- New training regime registered! }, mob = { DESMODONT_PH = { [17571868] = 17571870, }, AH_PUCH_PH = { [17571893] = 17571903, -- -418,-1,629 [17571894] = 17571903, -- -419,-1,570 [17571895] = 17571903, -- -419,-1,581 [17571896] = 17571903, -- -418,-1,590 [17571897] = 17571903, -- -418,-1,597 [17571898] = 17571903, -- -417,-1,640 [17571899] = 17571903, -- -419,-1,615 [17571900] = 17571903, -- -417,-1,661 }, BALLOON_NM_OFFSET = 17572141, FULL_MOON_FOUNTAIN_OFFSET = 17572197, JESTER_WHO_D_BE_KING_OFFSET = 17572201, APPARATUS_ELEMENTAL = 17572203, }, npc = { CASKET_BASE = 17572223, GATE_MAGICAL_GIZMO = 17572248, TREASURE_CHEST = 17572290, }, } return zones[dsp.zone.OUTER_HORUTOTO_RUINS]
gpl-3.0
hades2013/openwrt-mtk
package/ralink/ui/luci-mtk/src/applications/luci-watchcat/luasrc/model/cbi/watchcat/watchcat.lua
30
2105
--[[ LuCI - Lua Configuration Interface Copyright 2012 Christian Gagneraud <chris@techworks.ie> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- m = Map("system", translate("Watchcat"), translate("Watchcat allows configuring a periodic reboot when the " .. "Internet connection has been lost for a certain period of time." )) s = m:section(TypedSection, "watchcat") s.anonymous = true s.addremove = true mode = s:option(ListValue, "mode", translate("Operating mode")) mode.default = "allways" mode:value("ping", "Reboot on internet connection lost") mode:value("allways", "Periodic reboot") forcedelay = s:option(Value, "forcedelay", translate("Forced reboot delay"), translate("When rebooting the system, the watchcat will trigger a soft reboot. " .. "Entering a non zero value here will trigger a delayed hard reboot " .. "if the soft reboot fails. Enter a number of seconds to enable, " .. "use 0 to disable")) forcedelay.datatype = "uinteger" forcedelay.default = "0" period = s:option(Value, "period", translate("Period"), translate("In periodic mode, it defines the reboot period. " .. "In internet mode, it defines the longest period of " .. "time without internet access before a reboot is engaged." .. "Default unit is seconds, you can use the " .. "suffix 'm' for minutes, 'h' for hours or 'd' " .. "for days")) pinghost = s:option(Value, "pinghost", translate("Ping host"), translate("Host address to ping")) pinghost.datatype = "host" pinghost.default = "8.8.8.8" pinghost:depends({mode="ping"}) pingperiod = s:option(Value, "pingperiod", translate("Ping period"), translate("How often to check internet connection. " .. "Default unit is seconds, you can you use the " .. "suffix 'm' for minutes, 'h' for hours or 'd' " .. "for days")) pingperiod:depends({mode="ping"}) return m
gpl-2.0
gedads/Neodynamis
scripts/zones/Bastok_Markets/npcs/Lamepaue.lua
3
11031
----------------------------------- -- Area: Bastok Markets -- NPC: Lamepaue -- Type: Past Event Watcher -- !pos -172.136 -5 -69.632 235 ----------------------------------- package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Bastok_Markets/TextIDs"); require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) -- Bastok Missions. local BastokMissions = 0xFFFFFFFE; if (player:hasCompletedMission (BASTOK,FETICHISM)) then BastokMissions = BastokMissions - 2; -- Fetichism. end if (player:hasCompletedMission (BASTOK,TO_THE_FORSAKEN_MINES)) then BastokMissions = BastokMissions - 4; -- To the Forsaken Mines. end -- Bastok Quests. local BastokQuests = 0xFFFFFFFE; if (player:hasCompleteQuest(BASTOK,THE_RETURN_OF_THE_ADVENTURER)) then BastokQuests = BastokQuests - 2; -- The Return of the Adventurer end -- *Need the correct csid -- if (player:hasCompleteQuest(BASTOK,THE_FIRST_MEETING)) then -- BastokQuests = BastokQuests - 4; -- The First Meeting -- end if (player:hasCompleteQuest(BASTOK,WISH_UPON_A_STAR)) then BastokQuests = BastokQuests - 8; -- Wish Upon a Star (pt.1) BastokQuests = BastokQuests - 16; -- Wish Upon a Star (pt.2) BastokQuests = BastokQuests - 32; -- Wish Upon a Star (pt.3) end -- *Need the correct csid/parameters -- if (player:hasCompleteQuest(BASTOK,ALL_BY_MYSELF)) then -- BastokQuests = BastokQuests - 64; -- All by Myself -- end if (player:hasCompleteQuest(BASTOK,ACHIEVING_TRUE_POWER)) then BastokQuests = BastokQuests - 128; -- Achieving True Power end if (player:hasCompleteQuest(BASTOK,TOO_MANY_CHEFS)) then BastokQuests = BastokQuests - 512; -- Too Many Chefs end if (player:hasCompleteQuest(BASTOK,A_PROPER_BURIAL)) then BastokQuests = BastokQuests - 1024; -- A Proper Burial (pt.1) BastokQuests = BastokQuests - 2048; -- A Proper Burial (pt.2) BastokQuests = BastokQuests - 4096; -- A Proper Burial (pt.3) BastokQuests = BastokQuests - 8192; -- A Proper Burial (pt.4) BastokQuests = BastokQuests - 16384; -- A Proper Burial (pt.5) BastokQuests = BastokQuests - 32768; -- A Proper Burial (pt.6) end -- Other Quests. local OtherQuests = 0xFFFFFFFE; if (player:hasCompleteQuest(JEUNO,BEAT_AROUND_THE_BUSHIN)) then OtherQuests = OtherQuests - 2; -- Beat Around the Bushin end if (player:hasCompleteQuest(OTHER_AREAS,CONFESSIONS_OF_A_BELLMAKER)) then OtherQuests = OtherQuests - 4; -- Confessions of a Bellmaker end if (player:hasCompleteQuest(OTHER_AREAS,PICTURE_PERFECT)) then OtherQuests = OtherQuests - 8; -- Picture Perfect (pt.1) OtherQuests = OtherQuests - 16; -- Picture Perfect (pt.2) OtherQuests = OtherQuests - 32; -- Picture Perfect (pt.3) OtherQuests = OtherQuests - 64; -- Picture Perfect (pt.4) end if (player:hasCompleteQuest(AHT_URHGAN,NO_STRINGS_ATTACHED)) then OtherQuests = OtherQuests - 128; -- No Strings Attached end if (player:hasCompleteQuest(AHT_URHGAN,PUPPETMASTER_BLUES)) then OtherQuests = OtherQuests - 256; -- Puppetmaster Blues (pt.1) OtherQuests = OtherQuests - 512; -- Puppetmaster Blues (pt.2) end if (player:hasCompleteQuest(JEUNO,COMEBACK_QUEEN)) then OtherQuests = OtherQuests - 1024; -- Comeback Queen end -- *This quest,as of the time this script was written,is not yet defined in the Darkstar Project. -- if (player:hasCompleteQuest(**Unknown**,DANCER_ATTIRE)) then -- OtherQuests = OtherQuests - 2048; -- Dancer Attire (pt.1) -- OtherQuests = OtherQuests - 4096; -- Dancer Attire (pt.2) -- end if (player:hasCompleteQuest(CRYSTAL_WAR,DRAFTED_BY_THE_DUCHY)) then OtherQuests = OtherQuests - 8192; -- Drafted by the Duchy end if (player:hasCompleteQuest(CRYSTAL_WAR,BATTLE_ON_A_NEW_FRONT)) then OtherQuests = OtherQuests - 16384; -- Battle on a New Front end if (player:hasCompleteQuest(CRYSTAL_WAR,VOIDWALKER_OP_126)) then OtherQuests = OtherQuests - 32768; -- VW Op. #126: Qufim Incursion end -- *This quest,as of the time this script was written,is not yet defined in the Darkstar Project. -- if (player:hasCompleteQuest(**Unknown**,RECORDS_OF_EMINENCE)) then -- OtherQuests = OtherQuests - 65536; -- Records of Eminence -- end -- *This quest,as of the time this script was written,is not yet defined in the Darkstar Project. -- if (player:hasCompleteQuest(**Unknown**,TRUST_MUMOR)) then -- OtherQuests = OtherQuests - 131072; -- Trust (Mumor) -- end -- *This quest,as of the time this script was written,is not yet defined in the Darkstar Project. -- if (player:hasCompleteQuest(**Unknown**,UNITY_CONCORD)) then -- OtherQuests = OtherQuests - 262144; -- Unity Concord (pt.1) -- OtherQuests = OtherQuests - 524288; -- Unity Concord (pt.2) -- end -- Seekers of Adoulin local SeekersOfAdoulin = 0xFFFFFFFE; -- *Need the correct csid -- if (player:hasCompletedMission (SOA,RUMORS_FROM_THE_WEST)) then -- SeekersOfAdoulin = SeekersOfAdoulin - 2; -- Rumors from the West -- end -- Determine if any cutscenes are available for the player. local gil = player:getGil(); if (BastokMissions == 0xFFFFFFFE and BastokQuests == 0xFFFFFFFE and OtherQuests == 0xFFFFFFFE and SeekersOfAdoulin == 0xFFFFFFFE) then -- Player has no cutscenes available to be viewed. gil = 0; -- Setting gil to a value less than 10(cost) will trigger the appropriate response from this npc. end player:startEvent(0x0146,BastokMissions,BastokQuests,OtherQuests,SeekersOfAdoulin,0xFFFFFFFE,0xFFFFFFFE,10,gil); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf ("CSID: %u",csid); -- printf ("RESULT: %u",option); if (player:delGil(10) == false) then player:setLocalVar("Lamepaue_PlayCutscene", 2) ; -- Cancel the cutscene. player:updateEvent(0); else player:setLocalVar("Lamepaue_PlayCutscene", 1) end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf ("CSID: %u",csid); -- printf ("RESULT: %u",option); if (player:getLocalVar("Lamepaue_PlayCutscene") < 2) then if (option == 1) then -- Fetichism. player:startEvent(0x03F0); elseif (option == 2) then -- To the Forsaken Mines. player:startEvent(0x03F2); elseif (option == 33) then -- The Return of the Adventurer player:startEvent(0x00F3); -- elseif (option == 34) then -- The First Meeting -- player:startEvent(CSID); elseif (option == 35) then -- Wish Upon a Star (pt.1) player:startEvent(0x0149); elseif (option == 36) then -- Wish Upon a Star (pt.2) player:startEvent(0x014C); elseif (option == 37) then -- Wish Upon a Star (pt.3) player:startEvent(0x014E); -- elseif (option == 38) then -- All by Myself -- player:startEvent(0x00B9); elseif (option == 39) then -- Achieving True Power player:startEvent(0x01B9); elseif (option == 40) then -- Too Many Chefs player:startEvent(0x019B); elseif (option == 41) then -- A Proper Burial (pt.1) player:startEvent(0x01DB); elseif (option == 42) then -- A Proper Burial (pt.2) player:startEvent(0x01DD); elseif (option == 43) then -- A Proper Burial (pt.3) player:startEvent(0x01DF); elseif (option == 44) then -- A Proper Burial (pt.4) player:startEvent(0x01E1); elseif (option == 45) then -- A Proper Burial (pt.5) player:startEvent(0x01E3); elseif (option == 46) then -- A Proper Burial (pt.6) player:startEvent(0x01E5); elseif (option == 65) then -- Beat Around the Bushin player:startEvent(0x0156); elseif (option == 66) then -- Confessions of a Bellmaker player:startEvent(0x0192); -- Picture Perfect cutscenes need to be verified. elseif (option == 67) then -- Picture Perfect (pt.1) player:startEvent(0x0193); elseif (option == 68) then -- Picture Perfect (pt.2) player:startEvent(0x0194); elseif (option == 69) then -- Picture Perfect (pt.3) player:startEvent(0x0195); elseif (option == 70) then -- Picture Perfect (pt.4) player:startEvent(0x0196); elseif (option == 71) then -- No Strings Attached player:startEvent(0x01B2); elseif (option == 72) then -- Puppetmaster Blues (pt.1) player:startEvent(0x01B5); elseif (option == 73) then -- Puppetmaster Blues (pt.2) player:startEvent(0x01B7); elseif (option == 74) then -- Comeback Queen player:startEvent(0x01EA); -- elseif (option == 75) then -- Dancer Attire (pt.1) -- player:startEvent(CSID); -- elseif (option == 76) then -- Dancer Attire (pt.2) -- player:startEvent(CSID); -- Drafted by the Duchy and Battle on a New Front cutscenes need to be verified,ids may need to be changed or have additional parameters. elseif (option == 77) then -- Drafted by the Duchy player:startEvent(0x0012); elseif (option == 78) then -- Battle on a New Front player:startEvent(0x000C); elseif (option == 79) then -- VW Op. #126: Qufim Incursion player:startEvent(0x0102); -- elseif (option == 80) then -- Records of Eminence -- player:startEvent(CSID); -- elseif (option == 81) then -- Trust (Mumor) -- player:startEvent(CSID); -- elseif (option == 82) then -- Unity Concord (pt.1) -- player:startEvent(CSID); -- elseif (option == 83) then -- Unity Concord (pt.2) -- player:startEvent(CSID); -- elseif (option == 129) then -- Rumors from the West -- player:startEvent(CSID); end end player:setLocalVar("Lamepaue_PlayCutscene", 0) end;
gpl-3.0
pedro-andrade-inpe/terrame
test/packages/onerror/tests/alternative/Utils.lua
3
4120
------------------------------------------------------------------------------------------- -- TerraME - a software platform for multiple scale spatially-explicit dynamic modeling. -- Copyright (C) 2001-2014 INPE and TerraLAB/UFOP. -- -- This code is part of the TerraME framework. -- This framework is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public -- License as published by the Free Software Foundation; either -- version 2.1 of the License, or (at your option) any later version. -- -- You should have received a copy of the GNU Lesser General Public -- License along with this library. -- -- The authors reassure the license terms regarding the warranties. -- They specifically disclaim any warranties, including, but not limited to, -- the implied warranties of merchantability and fitness for a particular purpose. -- The framework provided hereunder is on an "as is" basis, and the authors have no -- obligation to provide maintenance, support, updates, enhancements, or modifications. -- In no event shall INPE and TerraLAB / UFOP be held liable to any party for direct, -- indirect, special, incidental, or consequential damages arising out of the use -- of this library and its documentation. -- -- Authors: Tiago Garcia de Senna Carneiro (tiago@dpi.inpe.br) -- Pedro R. Andrade (pedro.andrade@inpe.br) ------------------------------------------------------------------------------------------- return{ belong2 = function(unitTest) local error_func = function() belong2("2", "2") end unitTest:assertError(error_func, incompatibleTypeMsg(2, "table", "2")) end, call2 = function(unitTest) local error_func = function() call2(Cell{}, "sum") end unitTest:assertError(error_func, "Function 'sum' does not exist.") end, getExtension2 = function(unitTest) local error_func = function() getExtension2(2) end unitTest:assertError(error_func, incompatibleTypeMsg(1, "string", 2)) end, getn2 = function(unitTest) local error_func = function() getn2("2") end unitTest:assertError(error_func, incompatibleTypeMsg(1, "table", "2")) end, greaterByAttribute = function(unitTest) local error_func = function() local gt = greaterByAttribute(2) end unitTest:assertError(error_func, incompatibleTypeMsg(1, "string", 2)) error_func = function() local gt = greaterByAttribute("cover", "==") end unitTest:assertError(error_func, incompatibleValueMsg(2, "<, >, <=, or >=", "==")) end, greaterByCoord2 = function(unitTest) local error_func = function() local gt = greaterByCoord2("==") end unitTest:assertError(error_func, incompatibleValueMsg(1, "<, >, <=, or >=", "==")) end, round2 = function(unitTest) local error_func = function() x = round2("a") end unitTest:assertError(error_func, incompatibleTypeMsg(1, "number", "a")) error_func = function() x = round2(2.5, "a") end unitTest:assertError(error_func, incompatibleTypeMsg(2, "number", "a")) end, switch2 = function(unitTest) local error_func = function() switch2("aaaab") end unitTest:assertError(error_func, incompatibleTypeMsg(1, "table", "aaaab")) error_func = function() switch2({}, 2) end unitTest:assertError(error_func, incompatibleTypeMsg(2, "string", 2)) error_func = function() local data = {att = "abd"} switch2(data, "att"):caseof{ abc = function() end } end unitTest:assertError(error_func, switchInvalidArgumentSuggestionMsg("abd", "att", "abc")) local options = { xxx = true } error_func = function() local data = {att = "abd"} switch2(data, "att"):caseof{ xxx = function() end } end unitTest:assertError(error_func, switchInvalidArgumentMsg("abd", "att", options)) error_func = function() local data = {att = "abd"} switch2(data, "att"):caseof(2) end unitTest:assertError(error_func, namedArgumentsMsg()) error_func = function() local data = {att = "abd"} switch2(data, "att"):caseof{ abd = 2 } end unitTest:assertError(error_func, "Case 'abd' should be a function, got number.") end }
lgpl-3.0
telergybot/zspam
plugins/webshot.lua
919
1473
local helpers = require "OAuth.helpers" local base = 'https://screenshotmachine.com/' local url = base .. 'processor.php' local function get_webshot_url(param) local response_body = {} local request_constructor = { url = url, method = "GET", sink = ltn12.sink.table(response_body), headers = { referer = base, dnt = "1", origin = base, ["User-Agent"] = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36" }, redirect = false } local arguments = { urlparam = param, size = "FULL" } request_constructor.url = url .. "?" .. helpers.url_encode_arguments(arguments) local ok, response_code, response_headers, response_status_line = https.request(request_constructor) if not ok or response_code ~= 200 then return nil end local response = table.concat(response_body) return string.match(response, "href='(.-)'") end local function run(msg, matches) local find = get_webshot_url(matches[1]) if find then local imgurl = base .. find local receiver = get_receiver(msg) send_photo_from_url(receiver, imgurl) end end return { description = "Send an screenshot of a website.", usage = { "!webshot [url]: Take an screenshot of the web and send it back to you." }, patterns = { "^!webshot (https?://[%w-_%.%?%.:/%+=&]+)$", }, run = run }
gpl-2.0
padrinoo1/televagir
plugins/webshot.lua
919
1473
local helpers = require "OAuth.helpers" local base = 'https://screenshotmachine.com/' local url = base .. 'processor.php' local function get_webshot_url(param) local response_body = {} local request_constructor = { url = url, method = "GET", sink = ltn12.sink.table(response_body), headers = { referer = base, dnt = "1", origin = base, ["User-Agent"] = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36" }, redirect = false } local arguments = { urlparam = param, size = "FULL" } request_constructor.url = url .. "?" .. helpers.url_encode_arguments(arguments) local ok, response_code, response_headers, response_status_line = https.request(request_constructor) if not ok or response_code ~= 200 then return nil end local response = table.concat(response_body) return string.match(response, "href='(.-)'") end local function run(msg, matches) local find = get_webshot_url(matches[1]) if find then local imgurl = base .. find local receiver = get_receiver(msg) send_photo_from_url(receiver, imgurl) end end return { description = "Send an screenshot of a website.", usage = { "!webshot [url]: Take an screenshot of the web and send it back to you." }, patterns = { "^!webshot (https?://[%w-_%.%?%.:/%+=&]+)$", }, run = run }
gpl-2.0
dani-sj/mahandany
plugins/time.lua
771
2865
-- Implement a command !time [area] which uses -- 2 Google APIs to get the desired result: -- 1. Geocoding to get from area to a lat/long pair -- 2. Timezone to get the local time in that lat/long location -- Globals -- If you have a google api key for the geocoding/timezone api api_key = nil base_api = "https://maps.googleapis.com/maps/api" dateFormat = "%A %d %B - %H:%M:%S" -- Need the utc time for the google api function utctime() return os.time(os.date("!*t")) end -- Use the geocoding api to get the lattitude and longitude with accuracy specifier -- CHECKME: this seems to work without a key?? function get_latlong(area) local api = base_api .. "/geocode/json?" local parameters = "address=".. (URL.escape(area) or "") if api_key ~= nil then parameters = parameters .. "&key="..api_key end -- Do the request local res, code = https.request(api..parameters) if code ~=200 then return nil end local data = json:decode(res) if (data.status == "ZERO_RESULTS") then return nil end if (data.status == "OK") then -- Get the data lat = data.results[1].geometry.location.lat lng = data.results[1].geometry.location.lng acc = data.results[1].geometry.location_type types= data.results[1].types return lat,lng,acc,types end end -- Use timezone api to get the time in the lat, -- Note: this needs an API key function get_time(lat,lng) local api = base_api .. "/timezone/json?" -- Get a timestamp (server time is relevant here) local timestamp = utctime() local parameters = "location=" .. URL.escape(lat) .. "," .. URL.escape(lng) .. "&timestamp="..URL.escape(timestamp) if api_key ~=nil then parameters = parameters .. "&key="..api_key end local res,code = https.request(api..parameters) if code ~= 200 then return nil end local data = json:decode(res) if (data.status == "ZERO_RESULTS") then return nil end if (data.status == "OK") then -- Construct what we want -- The local time in the location is: -- timestamp + rawOffset + dstOffset local localTime = timestamp + data.rawOffset + data.dstOffset return localTime, data.timeZoneId end return localTime end function getformattedLocalTime(area) if area == nil then return "The time in nowhere is never" end lat,lng,acc = get_latlong(area) if lat == nil and lng == nil then return 'It seems that in "'..area..'" they do not have a concept of time.' end local localTime, timeZoneId = get_time(lat,lng) return "The local time in "..timeZoneId.." is: ".. os.date(dateFormat,localTime) end function run(msg, matches) return getformattedLocalTime(matches[1]) end return { description = "Displays the local time in an area", usage = "!time [area]: Displays the local time in that area", patterns = {"^!time (.*)$"}, run = run }
gpl-2.0
hyee/dbcli
db2/db2.lua
1
6190
local env,java=env,java local event,packer,cfg,init=env.event.callback,env.packer,env.set,env.init local set_command,exec_command=env.set_command,env.exec_command local db2=env.class(env.db_core) db2.module_list={ "sqlstate", "snap", "sql", "chart", "ssh", } function db2:ctor(isdefault) self.type="db2" self.C,self.props={},{} end function db2:connect(conn_str) java.system:setProperty('db2.jcc.charsetDecoderEncoder',3) local args local usr,pwd,conn_desc if type(conn_str)=="table" then args=conn_str usr,pwd,conn_desc=conn_str.user, packer.unpack_str(conn_str.password), conn_str.url:match("//(.*)$")--..(conn_str.internal_logon and " as "..conn_str.internal_logon or "") args.password=pwd conn_str=string.format("%s/%s@%s",usr,pwd,conn_desc) else usr,pwd,conn_desc = string.match(conn_str or "","(.*)/(.*)@(.+)") end if conn_desc == nil then return exec_command("HELP",{"CONNECT"}) end conn_desc=conn_desc:gsub('^(/+)','') local server,port,alt,database=conn_desc:match('^([^:/%^]+)(:?%d*)(%^?[^/]*)/(.+)$') if database then if port=="" then port=':50000' end conn_desc=server..port..'/'..database local alt_addr,alt_port=alt:gsub('[%s%^]+',''):match('([^:]+)(:*.*)') else database=conn_desc end self.MAX_CACHE_SIZE=cfg.get('SQLCACHESIZE') local url, isdba=conn_desc:match('^(.*) as (%w+)$') url = url or conn_desc args=args or {user=usr,password=pwd,url="jdbc:db2://"..url, internal_logon=isdba, server=server, database=database, enableSysplexWLB='true', enableSeamlessFailover='1', clientRerouteAlternateServerName=alt_addr, clientRerouteAlternatePortNumber=alt_addr and (alt_port or port):sub(2)} self:merge_props( {driverClassName="com.ibm.db2.jcc.DB2Driver", retrieveMessagesFromServerOnGetMessage='true', clientProgramName='SQL Developer', useCachedCursor=self.MAX_CACHE_SIZE },args) self:load_config(url,args) local prompt=(args.jdbc_alias or url):match('([^:/@]+)$') if event then event("BEFORE_DB2_CONNECT",self,sql,args,result) end env.set_title("") self.super.connect(self,args) self.conn=java.cast(self.conn,"com.ibm.db2.jcc.DB2Connection") self.MAX_CACHE_SIZE=cfg.get('SQLCACHESIZE') local version=self:get_value("select SERVICE_LEVEL FROM TABLE(sysproc.env_get_inst_info())") table.clear(self.props) self.props.db_version=version:gsub('DB2',''):match('([%d%.]+)') self.props.db_user=args.user:upper() self.props.database=database self.conn_str=packer.pack_str(conn_str) prompt=(prompt or database:upper()):match("^([^,%.&]+)") env.set_prompt(nil,prompt,nil,2) env.set_title(('%s - User: %s Server: %s Version: DB2(%s)'):format(database,self.props.db_user,server,self.props.db_version)) if event then event("AFTER_DB2_CONNECT",self,sql,args,result) end print("Database connected.") end function db2:exec(sql,...) local bypass=self:is_internal_call(sql) local args,prep_params=nil,{} local is_not_prep=type(sql)~="userdata" if type(select(1,...) or "")=="table" then args=select(1,...) if type(select(2,...) or "")=="table" then prep_params=select(2,...) end else args={...} end if is_not_prep then sql=event("BEFORE_DB2_EXEC",{self,sql,args}) [2] end local result=self.super.exec(self,sql,...) if is_not_prep and not bypass then event("AFTER_DB2_EXEC",self,sql,args,result) self.print_feed(sql,result) end return result end function db2:command_call(sql,...) local bypass=self:is_internal_call(sql) local args=type(select(1,...)=="table") and ... or {...} sql=event("BEFORE_DB2_EXEC",{self,sql,args}) [2] local result=self.super.exec(self,sql,{args}) if not bypass then event("AFTER_DB2_EXEC",self,sql,args,result) end self:print_result(result,sql) end function db2:admin_cmd(cmd) env.checkhelp(cmd) self:command_call('call sysproc.admin_cmd(:1)',cmd or "") end function db2:onload() local default_desc='#DB2 database SQL statement' local function add_default_sql_stmt(...) for i=1,select('#',...) do set_command(self,select(i,...), default_desc,self.command_call,true,1,true) end end add_default_sql_stmt('update','delete','insert','merge','truncate','drop') add_default_sql_stmt('explain','lock','analyze','grant','revoke','call','select','with') local conn_help = [[ Connect to db2 database. Usage: conn <user>/<password>@[//]<host>[:<port>][^<alt_purescale_hosts>[:<alt_purescale_ports>] ]/<database> Example: 1) Connect to local db port 50000 : conn db2admin/db2pwd@localhost/sample 2) Connect to remote db port 60000 : conn db2admin/db2pwd@remote_host:60000/sample 3) Connect to remote PureScale db#1: conn db2admin/db2pwd@192.168.6.1:60000^192.168.6.2,192.168.6.3/sample 4) Connect to remote PureScale db#2: conn db2admin/db2pwd@192.168.6.1:60001^192.168.6.2:60002/sample ]] set_command(self,{"connect",'conn'}, conn_help,self.connect,false,2) set_command(self,{"declare","begin"}, default_desc, self.command_call ,self.check_completion,1,true) set_command(self,"create", default_desc, self.command_call ,self.check_completion,1,true) set_command(self,"alter" , default_desc, self.command_call ,true,1,true) for _,k in ipairs{'DESCRIBE','add','AUTOCONFIGURE','BACKUP','LOAD','IMPORT','EXPORT','FORCE','QUIESCE','PRUNE', 'REDISTRIBUTE','RUNSTATS','UNQUIESCE','REWIND','RESET'} do set_command(self,k, default_desc,self.admin_cmd,true,1,true) end set_command(self,'adm', 'Run procedure ADMIN_CMD. Usage: adm <statement>',self.admin_cmd,true,2,true) --env.event.snoop('ON_SQL_ERROR',self.handle_error,nil,1) end function db2:onunload() env.set_title("") end return db2.new()
mit
starlightknight/darkstar
scripts/globals/weaponskills/quietus.lua
10
1867
----------------------------------- -- Quietus -- Scythe weapon skill -- Skill Level: N/A -- Delivers a triple damage attack that ignores target's defense. Amount ignored varies with TP. Redemption: Aftermath. -- Available only when equipped with Redemption (85)/(90)/(95)/(99) or Penitence +1/+2/+3/Umiliati. -- Aligned with the Shadow Gorget, Aqua Gorget & Snow Gorget. -- Aligned with the Shadow Belt, Aqua Belt & Snow Belt. -- Element: None -- Modifiers: STR: 60% MND: 60% -- 100%TP 200%TP 300%TP -- 3.00 3.00 3.00 ----------------------------------- require("scripts/globals/aftermath") require("scripts/globals/settings") require("scripts/globals/status") require("scripts/globals/weaponskills") ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar) local params = {} params.numHits = 1 params.ftp100 = 3.0 params.ftp200 = 3.0 params.ftp300 = 3.0 params.str_wsc = 0.4 params.dex_wsc = 0.0 params.vit_wsc = 0.0 params.agi_wsc = 0.0 params.int_wsc = 0.0 params.mnd_wsc = 0.4 params.chr_wsc = 0.0 params.crit100 = 0.0 params.crit200 = 0.0 params.crit300 = 0.0 params.canCrit = false params.acc100 = 0.0 params.acc200 = 0.0 params.acc300 = 0.0 params.atk100 = 1; params.atk200 = 1; params.atk300 = 1; params.ignoresDef = true params.ignored100 = 0.1 params.ignored200 = 0.3 params.ignored300 = 0.5 if USE_ADOULIN_WEAPON_SKILL_CHANGES then params.str_wsc = 0.6 params.mnd_wsc = 0.6 end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, params, tp, action, primary, taChar) -- Apply aftermath if damage > 0 then dsp.aftermath.addStatusEffect(player, tp, dsp.slot.MAIN, dsp.aftermath.type.EMPYREAN) end return tpHits, extraHits, criticalHit, damage end
gpl-3.0
gedads/Neodynamis
scripts/zones/Port_Bastok/npcs/Mine_Konte.lua
17
1124
----------------------------------- -- Area: Port Bastok -- NPC: Mine Konte -- Involved in Quest: Out of One's Shell ----------------------------------- require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) OutOfOneShell = player:getQuestStatus(BASTOK,OUT_OF_ONE_S_SHELL); if (OutOfOneShell == QUEST_ACCEPTED and player:getVar("OutOfTheShellZone") == 0) then player:startEvent(0x0053); else player:startEvent(0x002a); 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
laino/luakit
lib/lousy/widget/menu.lua
8
8385
------------------------------------------------------------- -- @author Mason Larobina &lt;mason.larobina@gmail.com&gt; -- -- @copyright 2010 Mason Larobina -- ------------------------------------------------------------- -- Grab environment we need local capi = { widget = widget } local setmetatable = setmetatable local math = require "math" local signal = require "lousy.signal" local type = type local assert = assert local ipairs = ipairs local table = table local util = require "lousy.util" local get_theme = require("lousy.theme").get module "lousy.widget.menu" local data = setmetatable({}, { __mode = "k" }) function update(menu) assert(data[menu] and type(menu.widget) == "widget", "invalid menu widget") -- Get private menu widget data local d = data[menu] -- Get theme table local theme = get_theme() local fg, bg, font = theme.menu_fg, theme.menu_bg, theme.menu_font local sfg, sbg = theme.menu_selected_fg, theme.menu_selected_bg -- Hide widget while re-drawing menu.widget:hide() -- Build & populate rows for i = 1, math.max(d.max_rows, #(d.table)) do -- Get row local index = i + d.offset - 1 local row = (i <= d.max_rows) and d.rows[index] -- Get row widget table local rw = d.table[i] -- Make new row if row and not rw then -- Row widget struct rw = { ebox = capi.widget{type = "eventbox"}, hbox = capi.widget{type = "hbox"}, cols = {}, } rw.ebox.child = rw.hbox d.table[i] = rw -- Add to main vbox menu.widget:pack(rw.ebox) -- Remove row elseif not row and rw then -- Destroy row columns (label widgets) for _, l in ipairs(rw.cols) do rw.hbox:remove(l) l:destroy() end rw.ebox:remove(rw.hbox) rw.hbox:destroy() menu.widget:remove(rw.ebox) rw.ebox:destroy() d.table[i] = nil end -- Populate columns if row and rw then -- Match up row data with row widget (for callbacks) rw.data = row -- Try to find last off-screen title row and replace with current if i == 1 and not row.title and d.offset > 1 then local j = d.offset - 1 while j > 0 do local r = d.rows[j] -- Only check rows with same number of columns if r.ncols ~= row.ncols then break end -- Check if title row if r.title then row, index = r, j break end j = j - 1 end end -- Is this the selected row? selected = not row.title and index == d.cursor -- Set row bg local rbg if row.title then rbg = (row.bg or theme.menu_title_bg) or bg else rbg = (selected and (row.selected_bg or sbg)) or row.bg or bg end if rw.ebox.bg ~= rbg then rw.ebox.bg = rbg end for c = 1, math.max(row.ncols, #(rw.cols)) do -- Get column text local text = row[c] text = (type(text) == "function" and text(row)) or text -- Get table cell local cell = rw.cols[c] -- Make new row column widget if text and not cell then cell = capi.widget{type = "label"} rw.hbox:pack(cell, { expand = true, fill = true }) rw.cols[c] = cell cell.font = font cell.width = 1 -- Remove row column widget elseif not text and cell then rw.hbox:remove(cell) rw.cols[c] = nil cell:destroy() end -- Set cell props if text and cell and row.title then cell.text = text local fg = row.fg or (c == 1 and theme.menu_primary_title_fg or theme.menu_secondary_title_fg) or fg if cell.fg ~= fg then cell.fg = fg end elseif text and cell then cell.text = text local fg = (selected and (row.selected_fg or sfg)) or row.fg or fg if cell.fg ~= fg then cell.fg = fg end end end end end -- Show widget menu.widget:show() end function build(menu, rows) assert(data[menu] and type(menu.widget) == "widget", "invalid menu widget") -- Get private menu widget data local d = data[menu] -- Check rows for i, row in ipairs(rows) do assert(type(row) == "table", "invalid row in rows table") assert(#row >= 1, "empty row") row.ncols = #row end d.rows = rows d.nrows = #rows -- Initial positions d.cursor = 0 d.offset = 1 update(menu) end local function calc_offset(menu) local d = data[menu] if d.cursor < 1 then return elseif d.cursor <= d.offset then d.offset = math.max(d.cursor - 1, 1) elseif d.cursor > (d.offset + d.max_rows - 1) then d.offset = math.max(d.cursor - d.max_rows + 1, 1) end end function move_up(menu) assert(data[menu] and type(menu.widget) == "widget", "invalid menu widget") -- Get private menu widget data local d = data[menu] -- Move cursor if not d.cursor or d.cursor < 1 then d.cursor = d.nrows else d.cursor = d.cursor - 1 end -- Get next non-title row (you can't select titles) while d.cursor > 0 and d.cursor <= d.nrows and d.rows[d.cursor].title do d.cursor = d.cursor - 1 end calc_offset(menu) update(menu) -- Emit changed signals menu:emit_signal("changed", menu:get()) end function move_down(menu) assert(data[menu] and type(menu.widget) == "widget", "invalid menu widget") -- Get private menu widget data local d = data[menu] -- Move cursor if d.cursor == d.nrows then d.cursor = 0 else d.cursor = (d.cursor or 0) + 1 end -- Get next non-title row (you can't select titles) while d.cursor > 0 and d.cursor <= d.nrows and d.rows[d.cursor].title do d.cursor = d.cursor + 1 end calc_offset(menu) update(menu) -- Emit changed signals menu:emit_signal("changed", menu:get()) end function get(menu, index) assert(data[menu] and type(menu.widget) == "widget", "invalid menu widget") -- Get private menu widget data local d = data[menu] -- Return row at given index or current cursor position. return d.rows[index or d.cursor] end function del(menu, index) assert(data[menu] and type(menu.widget) == "widget", "invalid menu widget") -- Get private menu widget data local d = data[menu] -- Unable to delete this index, return if d.cursor < 1 then return end table.remove(d.rows, d.cursor) -- Update rows count d.nrows = #(d.rows) -- Check cursor d.cursor = math.min(d.cursor, d.nrows) d.offset = math.min(d.offset, math.max(d.nrows - d.max_rows + 1, 1)) update(menu) -- Emit changed signals menu:emit_signal("changed", menu:get()) end function new(args) args = args or {} local menu = { widget = capi.widget{type = "vbox"}, -- Add widget methods build = build, update = update, get = get, del = del, move_up = move_up, move_down = move_down, hide = function(menu) menu.widget:hide() end, show = function(menu) menu.widget:show() end, } -- Save private widget data data[menu] = { -- Hold the rows & columns of label widgets which construct the -- menu list widget. table = {}, max_rows = args.max_rows or 10, nrows = 0, rows = {}, } -- Setup class signals signal.setup(menu) return menu end setmetatable(_M, { __call = function(_, ...) return new(...) end })
gpl-3.0
gedads/Neodynamis
scripts/zones/Abyssea-Attohwa/npcs/qm14.lua
3
1385
----------------------------------- -- Zone: Abyssea-Attohwa -- NPC: qm14 (???) -- Spawns Smok -- !pos ? ? ? 215 ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/status"); ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) --[[ if (GetMobAction(17658274) == ACTION_NONE) then -- NM not already spawned from this if (player:hasKeyItem(HOLLOW_DRAGON_EYE)) then player:startEvent(1022, HOLLOW_DRAGON_EYE); -- Ask if player wants to use KIs else player:startEvent(1023, HOLLOW_DRAGON_EYE); -- Do not ask, because player is missing at least 1. end end ]] end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID2: %u",csid); -- printf("RESULT2: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 1022 and option == 1) then SpawnMob(17658274):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe) player:delKeyItem(HOLLOW_DRAGON_EYE); end end;
gpl-3.0
starlightknight/darkstar
scripts/globals/spells/bluemagic/magnetite_cloud.lua
12
1868
----------------------------------------- -- Spell: Magnetite Cloud -- Deals earth damage to enemies within a fan-shaped area originating from the caster. Additional effect: Weight -- Spell cost: 86 MP -- Monster Type: Beastmen -- Spell Type: Magical (Earth) -- Blue Magic Points: 3 -- Stat Bonus: VIT+2 -- Level: 46 -- Casting Time: 4.5 seconds -- Recast Time: 29.25 seconds -- Magic Bursts on: Scission, Gravitation, and Darkness -- Combos: Magic Defense Bonus ----------------------------------------- require("scripts/globals/bluemagic") require("scripts/globals/status") require("scripts/globals/magic") ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0 end function onSpellCast(caster,target,spell) local params = {} params.diff = caster:getStat(dsp.mod.INT) - target:getStat(dsp.mod.INT) params.attribute = dsp.mod.INT params.skillType = dsp.skill.BLUE_MAGIC params.bonus = 1.0 -- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage params.multiplier = 2.0 params.tMultiplier = 1.0 params.duppercap = 56 params.str_wsc = 0.0 params.dex_wsc = 0.0 params.vit_wsc = 0.0 params.agi_wsc = 0.0 params.int_wsc = 0.0 params.mnd_wsc = 0.0 params.chr_wsc = 0.2 local resist = applyResistance(caster, target, spell, params) local damage = BlueMagicalSpell(caster, target, spell, params, CHR_BASED) damage = BlueFinalAdjustments(caster, target, spell, damage, params) if (damage > 0 and resist > 0.0625) then local typeEffect = dsp.effect.WEIGHT target:delStatusEffect(typeEffect) target:addStatusEffect(typeEffect,25,0,getBlueEffectDuration(caster,resist,typeEffect)) end return damage end
gpl-3.0
ironjade/DevStack
LanCom/DesignPattern/LUA/OrderedListAsLinkedList.lua
1
5186
#!/usr/local/bin/lua --[[ Copyright (c) 2004 by Bruno R. Preiss, P.Eng. $Author: brpreiss $ $Date: 2004/12/05 14:47:20 $ $RCSfile: OrderedListAsLinkedList.lua,v $ $Revision: 1.6 $ $Id: OrderedListAsLinkedList.lua,v 1.6 2004/12/05 14:47:20 brpreiss Exp $ --]] require "OrderedList" require "LinkedList" require "Cursor" --{ -- An ordered list implemented using a linked list. OrderedListAsLinkedList = Class.new("OrderedListAsLinkedList", OrderedList) -- Constructor. function OrderedListAsLinkedList.methods:initialize() OrderedListAsLinkedList.super(self) self.linkedList = LinkedList.new() end -- The linked list. OrderedListAsLinkedList:attr_reader("linkedList") -- The number of objects in this list. OrderedListAsLinkedList:attr_accessor("count") --}>a --{ -- Inserts the given object in this ordered list -- (at the end of the list). -- @param obj The object to insert. function OrderedListAsLinkedList.methods:insert(obj) self.linkedList:append(obj) self.count = self.count + 1 end -- Returns the object in this list at the given offset. -- @param offset An offset. function OrderedListAsLinkedList.methods:getitem(offset) assert(offset >= 0 and offset < self.count, "IndexError") local ptr = self.linkedList:get_head() local i = 0 while i < offset and ptr do ptr = ptr:get_succ() i = i + 1 end return ptr:get_datum() end --}>b --{ -- True if the given object is in this ordered list. -- @param obj An object. function OrderedListAsLinkedList.methods:contains(obj) local ptr = self.linkedList:get_head() while ptr do if ptr.datum:is(obj) then return true end ptr = ptr:get_succ() end return false end -- Returns the object in this ordered list -- that is equal to the given object. -- @param obj An object. function OrderedListAsLinkedList.methods:find(arg) local ptr = self.linkedList:get_head() while ptr do if ptr:get_datum() == arg then return ptr:get_datum() end ptr = ptr:get_succ() end return nil end --}>c --{ -- Withdraws the given object from this ordered list. -- @param obj The object to withdraw. function OrderedListAsLinkedList.methods:withdraw(obj) assert(self.count ~= 0, "ContainerEmpty") self.linkedList:extract(obj) self.count = self.count - 1 end --}>d --{ -- Returns a cursor that represents the position in this list -- of the object that is equal to the given object. -- +obj+:: An object. function OrderedListAsLinkedList.methods:findPosition(obj) local ptr = self.linkedList:get_head() while ptr do if ptr:get_datum() == obj then break end ptr = ptr:get_succ() end return OrderedListAsLinkedList.Cursor.new(self, ptr) end --}>e --{ -- Represents a position in an ordered list. OrderedListAsLinkedList.Cursor = Class.new("OrderedListAsLinkedList.Cursor", Cursor) -- Inserts the given object in the ordered list -- after this position. -- +obj+:: The object to insert. function OrderedListAsLinkedList.Cursor.methods:insertAfter(obj) self.element:insertAfter(obj) self.list.count = self.list.count + 1 end --}>f --{ -- Withdraws the object in the ordered list at this position. function OrderedListAsLinkedList.Cursor.methods:withdraw() self.list.linkedList:extract(self.element:get_datum()) self.list.count = self.list.count - 1 end --}>g --{ -- Constructs a cursor that represents the position -- in the given list of the given list element. -- +list+:: An ordered list. -- +element+:: A linked list element. function OrderedListAsLinkedList.Cursor.methods:initialize( list, element) OrderedListAsLinkedList.Cursor.super(self) self.list = list self.element = element end -- Returns the object in the ordered list at this position. function OrderedListAsLinkedList.Cursor.methods:get_datum() self.element.get_datum() end --}>h -- Inserts the given object in the ordered list -- before this position. -- +obj+:: The object to insert. function OrderedListAsLinkedList.Cursor.methods:insertBefore(obj) self.element:insertBefore(obj) self.list.count = self.list.count + 1 end -- Purges this ordered list. function OrderedListAsLinkedList.methods:purge() self.linkedList = LinkedList.new() self.count = 0 end -- Calls the given visitor function -- for each object in this ordered list. -- @para visitor A visitor function. function OrderedListAsLinkedList.methods:each(visitor) self.linkedList:each(visitor) end -- Returns an iterator that enumerates -- the objects in an ordered list. function OrderedListAsLinkedList.methods:iter() local position = self.linkedList:get_head() -- Iterator state return function() local result = nil if position then result = position:get_datum() position = position:get_succ() end return result end end -- OrderedListAsLinkedList test program." -- @param arg Command-line arguments. function OrderedListAsLinkedList.main(arg) print "OrderedListAsLinkedList test program." local list = OrderedListAsLinkedList.new() OrderedList.test(list) return 0 end if _REQUIREDNAME == nil then os.exit( OrderedListAsLinkedList.main(arg) ) end
apache-2.0
APItools/autoswagger.lua
spec/operation_spec.lua
1
4243
local Host = require 'autoswagger.host' local API = require 'autoswagger.api' local Operation = require 'autoswagger.operation' describe('Operation', function() local host, api before_each(function() host = Host:new('google.com', nil, nil, nil, 'host_guid') api = API:new(host, '/foo', 'api_guid') end) it('can be created', function() local o = Operation:new(api, 'GET', 'operation', 'operation_guid') assert.equals(o.method, 'GET') assert.equals(o.api, api) end) describe(':parse_path_parameters', function() it('#focus reads the parameters of a given path, using its api', function() local api = API:new(host, '/applications/*/users/*', 'api_guid') local o = Operation:new(api, 'GET', 'operation_guid') local params = o:parse_path_parameters('/applications/1/users/2') assert.same({application_id = '1', user_id = '2'}, params) end) end) describe(':add_parameter_info', function() it('reads params from the path', function() local api = API:new(host, '/users/*/app/*.xml', 'api_guid') local o = Operation:new(api, 'GET', 'operation_guid') for i=1,5 do o:add_parameter_info('/users/' .. tostring(i) .. '/app/' .. tostring(id) .. '.xml') end assert.same(o:get_parameter_names(), {'app_id', 'user_id'}) end) end) describe(':get_summary', function() local function test_summary(method, path, result) local api = API:new(host, path, 'api_guid') assert.equal(Operation:new(api, method, 'operation_guid'):get_summary(), result) end it('works in the usual simple cases', function() test_summary("GET", "/v1/api/word/*", "Get word by id") test_summary("GET", "/v1/api/word/*.json", "Get word by id") test_summary("POST", "/v1/api/word.xml", "Create word") test_summary("PUT", "/v1/api/word/*", "Modify word by id") test_summary("DELETE", "/v1/api/word/*", "Delete word by id") test_summary("DELETE", "/*.xml", "Delete by id") end) it('uses the last element when there are no wildcards', function() test_summary("GET","/api/accounts.xml", "List accounts") test_summary("GET","/api/accounts", "List accounts") test_summary("POST","/api/accounts.xml", "Create accounts") test_summary("PUT","/api/accounts.xml", "Modify accounts") test_summary("DELETE","/api/accounts.xml", "Delete accounts") end) it('assumes that the action is a verb for PUT methods when it finds combinations of type word/*/action', function() test_summary("PUT", "/v1/api/word/*/suspend", "Suspend word by id") test_summary("PUT", "/v1/api/word/*/suspend.xml", "Suspend word by id") test_summary("POST", "/v1/api/word/*/activate.xml", "Create activate of word") end) it('works ok with more than one *', function() test_summary("GET", "/v1/api/account/*/application/*.xml", "Get application of account") test_summary("DELETE", "/v1/api/account/*/application/*.xml", "Delete application of account") test_summary("PUT", "/v1/api/account/*/application/*.xml", "Modify application of account") test_summary("PUT", "/*/application/*.xml", "Modify application") test_summary("POST", "/v1/api/account/*/application.xml", "Create application of account") end) it('works on edge cases', function() test_summary("POST", "/v1", "Create v1") test_summary("POST", "/", "Create") test_summary("GET", "/v1", "List v1") test_summary("GET", "/", "List") test_summary("DELETE", "/", "Delete") end) end) describe(':new_from_table', function() it('creates a new operation from a table', function() local tbl = { method = 'GET', guid = 'guid1', parameters = { { paramType = 'path', name = 'app_id', values = {'8', '9', '10'}, }, { paramType = 'path', name = 'user_id', values = {'8', '9', '10'}, } } } local operation = Operation:new_from_table(api, tbl) assert.equal(operation.method, 'GET') assert.same(operation:get_parameter_names(), {'app_id', 'user_id'}) end) end) end)
mit
gedads/Neodynamis
scripts/zones/Windurst_Waters_[S]/npcs/Scotwick.lua
3
1078
----------------------------------- -- Area: Windurst Waters (S) -- NPC: Scotwick -- Type: Allied Notes Notorious Monsters -- @zone 94 -- !pos 153.785 -3.134 9.895 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0010); 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
starlightknight/darkstar
scripts/globals/items/icefish.lua
11
1046
----------------------------------------- -- ID: 4470 -- Item: icefish -- Food Effect: 5Min, Mithra only ----------------------------------------- -- Dexterity 3 -- Mind -5 ----------------------------------------- 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,4470) end function onEffectGain(target, effect) target:addMod(dsp.mod.DEX, 3) target:addMod(dsp.mod.MND, -5) end function onEffectLose(target, effect) target:delMod(dsp.mod.DEX, 3) target:delMod(dsp.mod.MND, -5) end
gpl-3.0
arrayfire/arrayfire_lua
examples/image_processing/brain_segmentation.lua
4
3850
--[[ /******************************************************* * Copyright (c) 2014, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #include <string.h> #include <stdio.h> #include <math.h> #include <arrayfire.h> #include "../common/progress.h" using namespace af; const float h_sx_kernel[] = { 1, 2, 1, 0, 0, 0, -1, -2, -1 }; const float h_sy_kernel[] = { -1, 0, 1, -2, 0, 2, -1, 0, 1 }; const float h_lp_kernel[] = { -0.5f, -1.0f, -0.5f, -1.0f, 6.0f, -1.0f, -0.5f, -1.0f, -0.5f }; array edges_slice(array x) { array ret; static array kernelx = array(dim4(3, 3), h_sx_kernel); static array kernely = array(dim4(3, 3), h_sy_kernel); ret = convolve(x, kernelx) + convolve(x, kernely); return abs(ret); } array gauss(array x, float u, float s) { double f = 1 / sqrt(2 * af::Pi * s * s); array e = exp(-pow((x - u), 2) / (2 * s * s)); return f * e; } array segment_volume(array A, int k) { array I1 = A(span, span, k); float mx = max<float>(I1); float mn = min<float>(I1); float u0 = 0.9 * mx; float s0 = (mx - mn) / 2; float u1 = 1.1 * mn; float s1 = (mx - mn) / 2; array L0 = gauss(I1, u0, s0); array L11 = gauss(I1, u1, s1); array L10; array L12; static array kernel = constant(1, 3, 3) / 9; static array L11_old; static array L12_old; if (k == 0) { L11 = convolve(L11, kernel); L10 = L11; } else { L10 = L11_old; L11 = L12_old; } if (k < A.dims(2) - 1) { L12 = gauss(A(span, span, k + 1), u1, s1); L12 = convolve(L12, kernel); } else { L12 = L11; } L11_old = L11; L12_old = L12; array L1 = (L10 + L11 + L12) / 3; array S = (L0 > L1); return S.as(A.type()); } void brain_seg(bool console) { af::Window wnd("Brain Segmentation Demo"); wnd.setColorMap(AF_COLORMAP_HEAT); double time_total = 30; // run for N seconds array B = loadImage(ASSETS_DIR "/examples/images/brain.png"); int slices = 256; B = moddims(B, dim4(B.dims(0), B.dims(1)/slices, slices)); af::sync(); int N = 2 * slices - 1; timer t = timer::start(); int iter = 0; /* loop forward and backward for 100 frames * exit if the user presses escape or the animation * ends */ for (int i = 0; !wnd.close(); i++) { iter++; int j = i % N; int k = std::min(j, N - j); array Bi = B(span, span, k); /* process */ array Si = segment_volume(B, k); array Ei = edges_slice(Si); array Mi = meanShift(Bi, 10, 10, 5); /* visualization */ if (!console) { wnd.grid(2, 2); wnd(0, 0).image(Bi/255.f, "Input"); wnd(1, 0).image(Ei, "Edges"); wnd(0, 1).image(Mi/255.f, "Meanshift"); wnd(1, 1).image(Si, "Segmented"); wnd.show(); } else { /* sync the operations so that current * iteration comptation finishes * */ af::sync(); } /* we have had ran throuh simlation results * exit the rendering loop */ if (!progress(iter, t, time_total)) break; if (!(i<100*N)) break; } } int main(int argc, char* argv[]) { int device = argc > 1 ? atoi(argv[1]) : 0; bool console = argc > 2 ? argv[2][0] == '-' : false; try { af::setDevice(device); af::info(); printf("Brain segmentation example\n"); brain_seg(console); } catch (af::exception& e) { fprintf(stderr, "%s\n", e.what()); } return 0; } ]]
bsd-3-clause
ABrandau/OpenRA
mods/ra/maps/allies-04/allies04.lua
4
5171
--[[ Copyright 2007-2019 The OpenRA Developers (see AUTHORS) This file is part of OpenRA, which is free software. It is made available to you under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. For more information, see COPYING. ]] ConvoyUnits = { { "ftrk", "ftrk", "truk", "truk", "apc", "ftrk" }, { "ftrk", "3tnk", "truk", "truk", "apc" }, { "3tnk", "3tnk", "truk", "truk", "ftrk" } } ConvoyRallyPoints = { { SovietEntry1.Location, SovietRally1.Location, SovietRally3.Location, SovietRally5.Location, SovietRally4.Location, SovietRally6.Location }, { SovietEntry2.Location, SovietRally10.Location, SovietRally11.Location } } ConvoyDelays = { easy = { DateTime.Minutes(4), DateTime.Minutes(5) + DateTime.Seconds(20) }, normal = { DateTime.Minutes(2) + DateTime.Seconds(30), DateTime.Minutes(4) }, hard = { DateTime.Minutes(1) + DateTime.Seconds(30), DateTime.Minutes(2) + DateTime.Seconds(30) }, tough = { DateTime.Minutes(1), DateTime.Minutes(1) + DateTime.Seconds(15) } } Convoys = { easy = 2, normal = 3, hard = 5, tough = 10 } ParadropDelays = { easy = { DateTime.Seconds(40), DateTime.Seconds(90) }, normal = { DateTime.Seconds(30), DateTime.Seconds(70) }, hard = { DateTime.Seconds(20), DateTime.Seconds(50) }, tough = { DateTime.Seconds(10), DateTime.Seconds(25) } } ParadropWaves = { easy = 4, normal = 6, hard = 10, tough = 25 } ParadropLZs = { ParadropPoint1.CenterPosition, ParadropPoint2.CenterPosition, ParadropPoint3.CenterPosition } Paradropped = 0 Paradrop = function() Trigger.AfterDelay(Utils.RandomInteger(ParadropDelay[1], ParadropDelay[2]), function() local units = PowerProxy.SendParatroopers(Utils.Random(ParadropLZs)) Utils.Do(units, function(unit) Trigger.OnAddedToWorld(unit, IdleHunt) end) Paradropped = Paradropped + 1 if Paradropped <= ParadropWaves[Map.LobbyOption("difficulty")] then Paradrop() end end) end ConvoysSent = 0 SendConvoys = function() Trigger.AfterDelay(Utils.RandomInteger(ConvoyDelay[1], ConvoyDelay[2]), function() local path = Utils.Random(ConvoyRallyPoints) local units = Reinforcements.Reinforce(ussr, Utils.Random(ConvoyUnits), { path[1] }) local lastWaypoint = path[#path] Utils.Do(units, function(unit) Trigger.OnAddedToWorld(unit, function() if unit.Type == "truk" then Utils.Do(path, function(waypoint) unit.Move(waypoint) end) Trigger.OnIdle(unit, function() unit.Move(lastWaypoint) end) else unit.Patrol(path) Trigger.OnIdle(unit, function() unit.AttackMove(lastWaypoint) end) end end) end) local id = Trigger.OnEnteredFootprint({ lastWaypoint }, function(a, id) if a.Owner == ussr and Utils.Any(units, function(unit) return unit == a end) then -- We are at our destination and thus don't care about other queued actions anymore a.Stop() a.Destroy() if a.Type == "truk" then player.MarkFailedObjective(DestroyConvoys) end end end) Trigger.OnAllRemovedFromWorld(units, function() Trigger.RemoveFootprintTrigger(id) ConvoysSent = ConvoysSent + 1 if ConvoysSent <= Convoys[Map.LobbyOption("difficulty")] then SendConvoys() else player.MarkCompletedObjective(DestroyConvoys) end end) Media.PlaySpeechNotification(player, "ConvoyApproaching") end) end Tick = function() if player.HasNoRequiredUnits() then player.MarkFailedObjective(KillUSSR) end if ussr.HasNoRequiredUnits() then player.MarkCompletedObjective(KillUSSR) -- We don't care about future convoys anymore player.MarkCompletedObjective(DestroyConvoys) end end InitObjectives = function() Trigger.OnObjectiveAdded(player, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective") end) KillUSSR = player.AddPrimaryObjective("Destroy all Soviet units and buildings in this region.") DestroyConvoys = player.AddSecondaryObjective("Eliminate all passing Soviet convoys.") Trigger.OnObjectiveCompleted(player, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed") end) Trigger.OnObjectiveFailed(player, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed") end) Trigger.OnPlayerLost(player, function() Trigger.AfterDelay(DateTime.Seconds(1), function() Media.PlaySpeechNotification(player, "MissionFailed") end) end) Trigger.OnPlayerWon(player, function() Trigger.AfterDelay(DateTime.Seconds(1), function() Media.PlaySpeechNotification(player, "MissionAccomplished") end) end) end WorldLoaded = function() player = Player.GetPlayer("Greece") ussr = Player.GetPlayer("USSR") Camera.Position = AlliedConyard.CenterPosition InitObjectives() local difficulty = Map.LobbyOption("difficulty") ConvoyDelay = ConvoyDelays[difficulty] ParadropDelay = ParadropDelays[difficulty] PowerProxy = Actor.Create("powerproxy.paratroopers", false, { Owner = ussr }) Paradrop() SendConvoys() Trigger.AfterDelay(0, ActivateAI) end
gpl-3.0
starlightknight/darkstar
scripts/zones/The_Garden_of_RuHmet/npcs/_0z0.lua
9
1306
----------------------------------- -- Area: The_Garden_of_RuHmet -- NPC: _0z0 ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/missions"); require("scripts/globals/keyitems"); require("scripts/globals/bcnm"); function onTrade(player,npc,trade) if (TradeBCNM(player,npc,trade)) then return; end end; function onTrigger(player,npc) --player:addMission(COP, dsp.mission.id.cop.WHEN_ANGELS_FALL); --player:setCharVar("PromathiaStatus",3); if (player:getCurrentMission(COP) == dsp.mission.id.cop.WHEN_ANGELS_FALL and player:getCharVar("PromathiaStatus")==3) then player:startEvent(203); elseif (EventTriggerBCNM(player,npc)) then elseif (player:getCurrentMission(COP) == dsp.mission.id.cop.WHEN_ANGELS_FALL and player:getCharVar("PromathiaStatus")==5) then player:startEvent(205); end return 1; end; function onEventUpdate(player,csid,option,extras) EventUpdateBCNM(player,csid,option,extras); end; function onEventFinish(player,csid,option) -- printf("onFinish CSID: %u",csid); -- printf("onFinish RESULT: %u",option); if ( csid == 203) then player:setCharVar("PromathiaStatus",4); elseif (EventFinishBCNM(player,csid,option)) then return; end end
gpl-3.0
deathshadow85/max
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
gpl-2.0
pospanet/nodemcu-httpserver
http/file_list.lua
1
1290
return function (connection, args) connection:send("HTTP/1.0 200 OK\r\nContent-Type: text/html\r\nCache-Control: private, no-store\r\n\r\n") connection:send('<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>Server File Listing</title></head>') connection:send('<body>') coroutine.yield() connection:send('<h1>Server File Listing</h1>') local remaining, used, total=file.fsinfo() connection:send("<b>Total size: </b> " .. total .. " bytes<br/>\n") connection:send("<b>In Use: </b> " .. used .. " bytes<br/>\n") connection:send("<b>Free: </b> " .. remaining .. " bytes<br/>\n") connection:send("<p>\n") connection:send("<b>Files:</b><br/>\n") connection:send("<ul>\n") for name, size in pairs(file.list()) do local isHttpFile = string.match(name, "(http/)") ~= nil if isHttpFile then local url = string.match(name, ".*/(.*)") connection:send(' <li><a href="' .. url .. '">' .. url .. "</a> (" .. size .. " bytes)</li>\n") -- this list could be very long, so we'll yield in order to avoid overflowing the send buffer. coroutine.yield() end end connection:send("</ul>\n") connection:send("</p>\n") connection:send('</body></html>') end
gpl-2.0
gedads/Neodynamis
scripts/zones/Quicksand_Caves/npcs/_5s0.lua
3
1265
----------------------------------- -- Area: Quicksand Caves -- NPC: Ornate Door -- Door blocked by Weight system -- !pos -21 0 -60 208 ----------------------------------- package.loaded["scripts/zones/Quicksand_Caves/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Quicksand_Caves/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local difX = player:getXPos()-(-30); local difZ = player:getZPos()-(-60); local Distance = math.sqrt( math.pow(difX,2) + math.pow(difZ,2) ); if (Distance < 3) then return -1; end player:messageSpecial(DOOR_FIRMLY_SHUT); 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
gedads/Neodynamis
scripts/zones/Southern_San_dOria_[S]/npcs/PalardaifaultVDraffles.lua
3
1157
----------------------------------- -- Area: Southern SandOria [S] -- NPC: Palardaifault V Draffles -- @zone 80 -- !pos 9 1 -35 ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria_[S]/TextIDs"] = nil; require("scripts/zones/Southern_San_dOria_[S]/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc, 11024); -- Greetings, I am Curate Palardaifaut, and I have been assigned to the Knights of the Iron Ram to ensure that its members stray not from the path of the Goddess. 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
MmxBoy/mmx-bot
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
gedads/Neodynamis
scripts/zones/Windurst_Woods/npcs/Cayu_Pensharhumi.lua
3
1460
----------------------------------- -- Area: Windurst Woods -- NPC: Cayu Pensharhumi -- Type: Standard NPC -- !pos 39.437 -0.91 -40.808 241 ----------------------------------- package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/zones/Windurst_Woods/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,2) == false) then player:startEvent(0x02dd); else player:startEvent(0x0103); 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 == 0x02dd) then player:setMaskBit(player:getVar("WildcatWindurst"),"WildcatWindurst",2,true); end end;
gpl-3.0
thatoneprogrammerkid/gameofsquares
debugGraph.lua
2
4195
--Love Debug Graph (https://github.com/Mechazawa/Love-Debug-Graph) by Mechazawa --[[ UNLICENSE This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTBILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT, IN NO EVENT SHALL THE AUTHORS 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. For more information, please refer to <http://unlicense.org/> ]] -- Code based on https://github.com/icrawler/FPSGraph local debugGraph = {} function debugGraph:new(type, x, y, width, height, delay, label, font) if ({mem=0, fps=0, custom=0})[type] == nil then error('Acceptable types: mem, fps, custom') end local instance = { x = x or 0, -- X position y = y or 0, -- Y position width = width or 50, -- Graph width height = height or 30, -- Graph height delay = delay or 0.5, -- Update delay label = label or type, -- Graph label font = font or love.graphics.newFont(8), data = {}, _max = 0, _time = 0, _type = type, } -- Build base data for i = 0, math.floor(instance.width / 2) do table.insert(instance.data, 0) end -- Updating the graph function instance:update(dt, val) local lastTime = self._time self._time = (self._time + dt) % self.delay -- Check if the minimum amount of time has past if dt > self.delay or lastTime > self._time then -- Fetch data if needed if val == nil then if self._type == 'fps' then -- Collect fps info and update the label val = 0.75 * 1 / dt + 0.25 * love.timer.getFPS() self.label = "FPS: " .. math.floor(val * 10) / 10 elseif self._type == 'mem' then -- Collect memory info and update the label val = collectgarbage('count') self.label = "Memory (KB): " .. math.floor(val * 10) / 10 else -- If the val is nil then we'll just skip this time return end end -- pop the old data and push new data table.remove(self.data, 1) table.insert(self.data, val) -- Find the highest value local max = 0 for i=1, #self.data do local v = self.data[i] if v > max then max = v end end self._max = max end end function instance:draw() -- Store the currently set font and change the font to our own local fontCache = love.graphics.getFont() love.graphics.setFont(self.font) local max = math.ceil(self._max/10) * 10 + 20 local len = #self.data local steps = self.width / len -- Build the line data local lineData = {} for i=1, len do -- Build the X and Y of the point local x = steps * (i - 1) + self.x local y = self.height * (-self.data[i] / max + 1) + self.y -- Append it to the line table.insert(lineData, x) table.insert(lineData, y) end -- Draw the line love.graphics.line(unpack(lineData)) -- Print the label if self.label ~= '' then love.graphics.print(self.label, self.x, self.y + self.height - self.font:getHeight()) end -- Reset the font love.graphics.setFont(fontCache) end return instance end return debugGraph
mit
starlightknight/darkstar
scripts/globals/effects/auspice.lua
12
1611
-------------------------------------- -- -- dsp.effect.AUSPICE -- -- Power: Used for Enspell Effect -- SubPower: Tracks Subtle Blow Bonus -- Tier: Used for Enspell Calculation -- -------------------------------------- function onEffectGain(target,effect) --Auspice Reduces TP via adding to your Subtle Blow Mod local subtleBlowBonus = 10 + target:getMod(dsp.mod.AUSPICE_EFFECT) --printf("AUSPICE: Adding Subtle Blow +%d!", subtleBlowBonus) effect:setSubPower(subtleBlowBonus) target:addMod(dsp.mod.SUBTLE_BLOW, subtleBlowBonus) --Afflatus Misery Bonuses if (target:hasStatusEffect(dsp.effect.AFFLATUS_MISERY)) then target:getStatusEffect(dsp.effect.AFFLATUS_MISERY):setSubPower(0) target:addMod(dsp.mod.ENSPELL,18) target:addMod(dsp.mod.ENSPELL_DMG,effect:getPower()) end end function onEffectTick(target,effect) end function onEffectLose(target,effect) local subtleBlow = effect:getSubPower() --printf("AUSPICE: Removing Subtle Blow +%d!", subtleBlow) target:delMod(dsp.mod.SUBTLE_BLOW, subtleBlow) --Clean Up Any Bonuses That From Afflatus Misery Combo if (target:hasStatusEffect(dsp.effect.AFFLATUS_MISERY)) then local accuracyBonus = target:getStatusEffect(dsp.effect.AFFLATUS_MISERY):getSubPower() --printf("AUSPICE: Removing Accuracy Bonus +%d!", accuracyBonus) target:delMod(dsp.mod.ACC, accuracyBonus) local accuracyBonus = target:getStatusEffect(dsp.effect.AFFLATUS_MISERY):setSubPower(0) target:setMod(dsp.mod.ENSPELL_DMG,0) target:setMod(dsp.mod.ENSPELL,0) end end
gpl-3.0
gedads/Neodynamis
scripts/globals/items/slice_of_lynx_meat.lua
12
1352
----------------------------------------- -- ID: 5667 -- Item: Slice of Lynx Meat -- Food Effect: 5 Min, Galka only ----------------------------------------- -- Strength 5 -- Intelligence -7 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:getRace() ~= 8) then result = 247; end if (target:getMod(MOD_EAT_RAW_MEAT) == 1) then result = 0; end if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,5667); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR, 5); target:addMod(MOD_INT, -7); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_STR, 5); target:delMod(MOD_INT, -7); end;
gpl-3.0