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 |
|---|---|---|---|---|---|
CtopCsUtahEdu/chill-dev | examples/cuda-chill/tmv.lua | 3 | 1585 | init("tmv.c","normalMV",0)
dofile("cudaize.lua") --defines custom tile_by_index, copy_to_registers,
--copy_to_shared methods
N=1024
--N= 8209
--N=129
TI=64
N=1024
TI=32
--tile, "k" for the control loop for the "j" tile, with the final order
--of {"ii", "k", "i", "j"}
tile_by_index({"i","j"}, {TI,TI}, {l1_control="ii", l2_control="k"}, {"ii", "k", "i", "j"})
--tile_by_index({"i"}, {TI}, {l1_control="ii"}, {"ii", "i", "j"})
--print_code()
--tile_by_index({"i"}, {TI/32}, {l1_control="iii"}, {"ii", "k", "iii","i", "j"})
--print_code()
--Normalize indx will do a tile size of one over the loop level specified
--by the input index. This is useful to get a zero lower bound and hard
--upper bound on a loop instead of it being relative to previous loop
--levels.
--normalize_index("i")
--print_code()
--Cudaize now determines the grid dimentions from the loops themselves
--(the upper bounds of the block and thread loops). It also renames the
--given block and thread loops's indexes to the approviate values from
--the set {"bx","by","tx","ty","tz"}. The second parameter specifies the
--size of the arrays to be copied in the CUDA scaffolding.
cudaize("tmv_GPU", {a=N, b=N, c=N*N},{block={"ii"}, thread={"i"}})
--print_code()
--Does a datacopy, tile, and add_sync to get a shared memory copy
copy_to_shared("tx", "b", 1)
--copy_to_texture("b")
--print_code()
copy_to_shared("tx", "c", -16)
--copy_to_texture("c")
--print_code()
copy_to_registers("k", "a")
print_code()
--unroll(0,5,0)
--unroll(0,4,0)
--unroll(2,4,16)
unroll_to_depth(1)
--print_code()
| gpl-3.0 |
slowglass/Restacker | libs/LibAddonMenu-2.0/controls/divider.lua | 7 | 1437 | --[[dividerData = {
type = "divider",
width = "full", --or "half" (optional)
height = 10, (optional)
alpha = 0.25, (optional)
reference = "MyAddonDivider" -- unique global reference to control (optional)
} ]]
local widgetVersion = 2
local LAM = LibStub("LibAddonMenu-2.0")
if not LAM:RegisterWidget("divider", widgetVersion) then return end
local wm = WINDOW_MANAGER
local MIN_HEIGHT = 10
local MAX_HEIGHT = 50
local MIN_ALPHA = 0
local MAX_ALPHA = 1
local DEFAULT_ALPHA = 0.25
local function GetValueInRange(value, min, max, default)
if not value or type(value) ~= "number" then
return default
end
return math.min(math.max(min, value), max)
end
function LAMCreateControl.divider(parent, dividerData, controlName)
local control = LAM.util.CreateBaseControl(parent, dividerData, controlName)
local isHalfWidth = control.isHalfWidth
local width = control:GetWidth()
local height = GetValueInRange(dividerData.height, MIN_HEIGHT, MAX_HEIGHT, MIN_HEIGHT)
local alpha = GetValueInRange(dividerData.alpha, MIN_ALPHA, MAX_ALPHA, DEFAULT_ALPHA)
control:SetDimensions(isHalfWidth and width / 2 or width, height)
control.divider = wm:CreateControlFromVirtual(nil, control, "ZO_Options_Divider")
local divider = control.divider
divider:SetWidth(isHalfWidth and width / 2 or width)
divider:SetAnchor(TOPLEFT)
divider:SetAlpha(alpha)
return control
end
| mit |
alinfrat/nefratrobot | bot/seedbot.lua | 1 | 8430 | package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua'
..';.luarocks/share/lua/5.2/?/init.lua'
package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so'
require("./bot/utils")
VERSION = '1.0'
-- This function is called when tg receive a msg
function on_msg_receive (msg)
if not started then
return
end
local receiver = get_receiver(msg)
print (receiver)
-- vardump(msg)
msg = pre_process_service_msg(msg)
if msg_valid(msg) then
msg = pre_process_msg(msg)
if msg then
match_plugins(msg)
-- mark_read(receiver, ok_cb, false)
end
end
end
function ok_cb(extra, success, result)
end
function on_binlog_replay_end()
started = true
postpone (cron_plugins, false, 60*5.0)
_config = load_config()
-- load plugins
plugins = {}
load_plugins()
end
function msg_valid(msg)
-- Don't process outgoing messages
if msg.out then
print('\27[36mNot valid: msg from us\27[39m')
return false
end
-- Before bot was started
if msg.date < now then
print('\27[36mNot valid: old msg\27[39m')
return false
end
if msg.unread == 0 then
print('\27[36mNot valid: readed\27[39m')
return false
end
if not msg.to.id then
print('\27[36mNot valid: To id not provided\27[39m')
return false
end
if not msg.from.id then
print('\27[36mNot valid: From id not provided\27[39m')
return false
end
if msg.from.id == our_id then
print('\27[36mNot valid: Msg from our id\27[39m')
return false
end
if msg.to.type == 'encr_chat' then
print('\27[36mNot valid: Encrypted chat\27[39m')
return false
end
if msg.from.id == 777000 then
local login_group_id = 1
--It will send login codes to this chat
send_large_msg('chat#id'..login_group_id, msg.text)
end
return true
end
--
function pre_process_service_msg(msg)
if msg.service then
local action = msg.action or {type=""}
-- Double ! to discriminate of normal actions
msg.text = "!!tgservice " .. action.type
-- wipe the data to allow the bot to read service messages
if msg.out then
msg.out = false
end
if msg.from.id == our_id then
msg.from.id = 0
end
end
return msg
end
-- Apply plugin.pre_process function
function pre_process_msg(msg)
for name,plugin in pairs(plugins) do
if plugin.pre_process and msg then
print('Preprocess', name)
msg = plugin.pre_process(msg)
end
end
return msg
end
-- Go over enabled plugins patterns.
function match_plugins(msg)
for name, plugin in pairs(plugins) do
match_plugin(plugin, name, msg)
end
end
-- Check if plugin is on _config.disabled_plugin_on_chat table
local function is_plugin_disabled_on_chat(plugin_name, receiver)
local disabled_chats = _config.disabled_plugin_on_chat
-- Table exists and chat has disabled plugins
if disabled_chats and disabled_chats[receiver] then
-- Checks if plugin is disabled on this chat
for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do
if disabled_plugin == plugin_name and disabled then
local warning = 'Plugin '..disabled_plugin..' is disabled on this chat'
print(warning)
send_msg(receiver, warning, ok_cb, false)
return true
end
end
end
return false
end
function match_plugin(plugin, plugin_name, msg)
local receiver = get_receiver(msg)
-- Go over patterns. If one matches it's enough.
for k, pattern in pairs(plugin.patterns) do
local matches = match_pattern(pattern, msg.text)
if matches then
print("msg matches: ", pattern)
if is_plugin_disabled_on_chat(plugin_name, receiver) then
return nil
end
-- Function exists
if plugin.run then
-- If plugin is for privileged users only
if not warns_user_not_allowed(plugin, msg) then
local result = plugin.run(msg, matches)
if result then
send_large_msg(receiver, result)
end
end
end
-- One patterns matches
return
end
end
end
-- DEPRECATED, use send_large_msg(destination, text)
function _send_msg(destination, text)
send_large_msg(destination, text)
end
-- Save the content of _config to config.lua
function save_config( )
serialize_to_file(_config, './data/config.lua')
print ('saved config into ./data/config.lua')
end
-- Returns the config from config.lua file.
-- If file doesn't exist, create it.
function load_config( )
local f = io.open('./data/config.lua', "r")
-- If config.lua doesn't exist
if not f then
print ("Created new config file: data/config.lua")
create_config()
else
f:close()
end
local config = loadfile ("./data/config.lua")()
for v,user in pairs(config.sudo_users) do
print("Allowed user: " .. user)
end
return config
end
-- Create a basic config.json file and saves it.
function create_config( )
-- A simple config with basic plugins and ourselves as privileged user
config = {
enabled_plugins = {
"onservice",
"inrealm",
"ingroup",
"inpm",
"banhammer",
"stats",
"anti_spam",
"owners",
"arabic_lock",
"set",
"get",
"broadcast",
"download_media",
"invite"
},
sudo_users = {93068445,110509621,000000000,tonumber(our_id)},--Sudo users
disabled_channels = {},
realm = {58637980},--Realms Id
moderation = {data = 'data/moderation.json'},
about_text = [[admin : @nefr4t
nefrat robot
]],
help_text = [[
Commands list :
!kick [username|id]
You can also do it by reply
!ban [ username|id]
You can also do it by reply
!unban [id]
You can also do it by reply
!who
Members list
!modlist
Moderators list
!promote [username]
Promote someone
!demote [username]
Demote someone
!kickme
Will kick user
!about
Group description
!setphoto
Set and locks group photo
!setname [name]
Set group name
!rules
Group rules
!id
return group id or user id
!help
!lock [member|name|bots]
Locks [member|name|bots]
!unlock [member|name|photo|bots]
Unlocks [member|name|photo|bots]
!set rules <text>
Set <text> as rules
!set about <text>
Set <text> as about
!settings
Returns group settings
!newlink
create/revoke your group link
!link
returns group link
!owner
returns group owner id
!setowner [id]
Will set id as owner
!setflood [value]
Set [value] as flood sensitivity
!stats
Simple message statistics
!save [value] <text>
Save <text> as [value]
!get [value]
Returns text of [value]
!clean [modlist|rules|about]
Will clear [modlist|rules|about] and set it to nil
!res [username]
returns user id
"!res @username"
!log
will return group logs
!banlist
will return group ban list
**U can use both "/" and "!"
*Only owner and mods can add bots in group
*Only moderators and owner can use kick,ban,unban,newlink,link,setphoto,setname,lock,unlock,set rules,set about and settings commands
*Only owner can use res,setowner,promote,demote and log commands
]]
}
serialize_to_file(config, './data/config.lua')
print('saved config into ./data/config.lua')
end
function on_our_id (id)
our_id = id
end
function on_user_update (user, what)
--vardump (user)
end
function on_chat_update (chat, what)
end
function on_secret_chat_update (schat, what)
--vardump (schat)
end
function on_get_difference_end ()
end
-- Enable plugins in config.json
function load_plugins()
for k, v in pairs(_config.enabled_plugins) do
print("Loading plugin", v)
local ok, err = pcall(function()
local t = loadfile("plugins/"..v..'.lua')()
plugins[v] = t
end)
if not ok then
print('\27[31mError loading plugin '..v..'\27[39m')
print('\27[31m'..err..'\27[39m')
end
end
end
-- custom add
function load_data(filename)
local f = io.open(filename)
if not f then
return {}
end
local s = f:read('*all')
f:close()
local data = JSON.decode(s)
return data
end
function save_data(filename, data)
local s = JSON.encode(data)
local f = io.open(filename, 'w')
f:write(s)
f:close()
end
-- Call and postpone execution for cron plugins
function cron_plugins()
for name, plugin in pairs(plugins) do
-- Only plugins with cron function
if plugin.cron ~= nil then
plugin.cron()
end
end
-- Called again in 2 mins
postpone (cron_plugins, false, 120)
end
-- Start and load values
our_id = 0
now = os.time()
math.randomseed(now)
started = false
| gpl-2.0 |
masterweb121/telegram-bot | plugins/isup.lua | 741 | 3095 | do
local socket = require("socket")
local cronned = load_from_file('data/isup.lua')
local function save_cron(msg, url, delete)
local origin = get_receiver(msg)
if not cronned[origin] then
cronned[origin] = {}
end
if not delete then
table.insert(cronned[origin], url)
else
for k,v in pairs(cronned[origin]) do
if v == url then
table.remove(cronned[origin], k)
end
end
end
serialize_to_file(cronned, 'data/isup.lua')
return 'Saved!'
end
local function is_up_socket(ip, port)
print('Connect to', ip, port)
local c = socket.try(socket.tcp())
c:settimeout(3)
local conn = c:connect(ip, port)
if not conn then
return false
else
c:close()
return true
end
end
local function is_up_http(url)
-- Parse URL from input, default to http
local parsed_url = URL.parse(url, { scheme = 'http', authority = '' })
-- Fix URLs without subdomain not parsed properly
if not parsed_url.host and parsed_url.path then
parsed_url.host = parsed_url.path
parsed_url.path = ""
end
-- Re-build URL
local url = URL.build(parsed_url)
local protocols = {
["https"] = https,
["http"] = http
}
local options = {
url = url,
redirect = false,
method = "GET"
}
local response = { protocols[parsed_url.scheme].request(options) }
local code = tonumber(response[2])
if code == nil or code >= 400 then
return false
end
return true
end
local function isup(url)
local pattern = '^(%d%d?%d?%.%d%d?%d?%.%d%d?%d?%.%d%d?%d?):?(%d?%d?%d?%d?%d?)$'
local ip,port = string.match(url, pattern)
local result = nil
-- !isup 8.8.8.8:53
if ip then
port = port or '80'
result = is_up_socket(ip, port)
else
result = is_up_http(url)
end
return result
end
local function cron()
for chan, urls in pairs(cronned) do
for k,url in pairs(urls) do
print('Checking', url)
if not isup(url) then
local text = url..' looks DOWN from here. 😱'
send_msg(chan, text, ok_cb, false)
end
end
end
end
local function run(msg, matches)
if matches[1] == 'cron delete' then
if not is_sudo(msg) then
return 'This command requires privileged user'
end
return save_cron(msg, matches[2], true)
elseif matches[1] == 'cron' then
if not is_sudo(msg) then
return 'This command requires privileged user'
end
return save_cron(msg, matches[2])
elseif isup(matches[1]) then
return matches[1]..' looks UP from here. 😃'
else
return matches[1]..' looks DOWN from here. 😱'
end
end
return {
description = "Check if a website or server is up.",
usage = {
"!isup [host]: Performs a HTTP request or Socket (ip:port) connection",
"!isup cron [host]: Every 5mins check if host is up. (Requires privileged user)",
"!isup cron delete [host]: Disable checking that host."
},
patterns = {
"^!isup (cron delete) (.*)$",
"^!isup (cron) (.*)$",
"^!isup (.*)$",
"^!ping (.*)$",
"^!ping (cron delete) (.*)$",
"^!ping (cron) (.*)$"
},
run = run,
cron = cron
}
end
| gpl-2.0 |
deepak78/new-luci | libs/luci-lib-nixio/docsrc/nixio.TLSContext.lua | 173 | 1393 | --- Transport Layer Security Context Object.
-- @cstyle instance
module "nixio.TLSContext"
--- Create a TLS Socket from a socket descriptor.
-- @class function
-- @name TLSContext.create
-- @param socket Socket Object
-- @return TLSSocket Object
--- Assign a PEM certificate to this context.
-- @class function
-- @name TLSContext.set_cert
-- @usage This function calls SSL_CTX_use_certificate_chain_file().
-- @param path Certificate File path
-- @return true
--- Assign a PEM private key to this context.
-- @class function
-- @name TLSContext.set_key
-- @usage This function calls SSL_CTX_use_PrivateKey_file().
-- @param path Private Key File path
-- @return true
--- Set the available ciphers for this context.
-- @class function
-- @name TLSContext.set_ciphers
-- @usage This function calls SSL_CTX_set_cipher_list().
-- @param cipherlist String containing a list of ciphers
-- @return true
--- Set the verification depth of this context.
-- @class function
-- @name TLSContext.set_verify_depth
-- @usage This function calls SSL_CTX_set_verify_depth().
-- @param depth Depth
-- @return true
--- Set the verification flags of this context.
-- @class function
-- @name TLSContext.set_verify
-- @usage This function calls SSL_CTX_set_verify().
-- @param flag1 First Flag ["none", "peer", "verify_fail_if_no_peer_cert",
-- "client_once"]
-- @param ... More Flags [-"-]
-- @return true | apache-2.0 |
InkblotAdmirer/packages | utils/yunbridge/files/usr/lib/lua/luci/sha256.lua | 106 | 5170 | --
-- Code merged by gravityscore at http://pastebin.com/gsFrNjbt
--
-- Adaptation of the Secure Hashing Algorithm (SHA-244/256)
-- Found Here: http://lua-users.org/wiki/SecureHashAlgorithm
--
-- Using an adapted version of the bit library
-- Found Here: https://bitbucket.org/Boolsheet/bslf/src/1ee664885805/bit.lua
--
module("luci.sha256", package.seeall)
local MOD = 2 ^ 32
local MODM = MOD - 1
local function memoize(f)
local mt = {}
local t = setmetatable({}, mt)
function mt:__index(k)
local v = f(k)
t[k] = v
return v
end
return t
end
local function make_bitop_uncached(t, m)
local function bitop(a, b)
local res, p = 0, 1
while a ~= 0 and b ~= 0 do
local am, bm = a % m, b % m
res = res + t[am][bm] * p
a = (a - am) / m
b = (b - bm) / m
p = p * m
end
res = res + (a + b) * p
return res
end
return bitop
end
local function make_bitop(t)
local op1 = make_bitop_uncached(t, 2 ^ 1)
local op2 = memoize(function(a) return memoize(function(b) return op1(a, b) end) end)
return make_bitop_uncached(op2, 2 ^ (t.n or 1))
end
local bxor1 = make_bitop({ [0] = { [0] = 0, [1] = 1 }, [1] = { [0] = 1, [1] = 0 }, n = 4 })
local function bxor(a, b, c, ...)
local z = nil
if b then
a = a % MOD
b = b % MOD
z = bxor1(a, b)
if c then z = bxor(z, c, ...) end
return z
elseif a then return a % MOD
else return 0
end
end
local function band(a, b, c, ...)
local z
if b then
a = a % MOD
b = b % MOD
z = ((a + b) - bxor1(a, b)) / 2
if c then z = bit32_band(z, c, ...) end
return z
elseif a then return a % MOD
else return MODM
end
end
local function bnot(x) return (-1 - x) % MOD end
local function rshift1(a, disp)
if disp < 0 then return lshift(a, -disp) end
return math.floor(a % 2 ^ 32 / 2 ^ disp)
end
local function rshift(x, disp)
if disp > 31 or disp < -31 then return 0 end
return rshift1(x % MOD, disp)
end
local function lshift(a, disp)
if disp < 0 then return rshift(a, -disp) end
return (a * 2 ^ disp) % 2 ^ 32
end
local function rrotate(x, disp)
x = x % MOD
disp = disp % 32
local low = band(x, 2 ^ disp - 1)
return rshift(x, disp) + lshift(low, 32 - disp)
end
local k = {
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
}
local function str2hexa(s)
return (string.gsub(s, ".", function(c) return string.format("%02x", string.byte(c)) end))
end
local function num2s(l, n)
local s = ""
for i = 1, n do
local rem = l % 256
s = string.char(rem) .. s
l = (l - rem) / 256
end
return s
end
local function s232num(s, i)
local n = 0
for i = i, i + 3 do n = n * 256 + string.byte(s, i) end
return n
end
local function preproc(msg, len)
local extra = 64 - ((len + 9) % 64)
len = num2s(8 * len, 8)
msg = msg .. "\128" .. string.rep("\0", extra) .. len
assert(#msg % 64 == 0)
return msg
end
local function initH256(H)
H[1] = 0x6a09e667
H[2] = 0xbb67ae85
H[3] = 0x3c6ef372
H[4] = 0xa54ff53a
H[5] = 0x510e527f
H[6] = 0x9b05688c
H[7] = 0x1f83d9ab
H[8] = 0x5be0cd19
return H
end
local function digestblock(msg, i, H)
local w = {}
for j = 1, 16 do w[j] = s232num(msg, i + (j - 1) * 4) end
for j = 17, 64 do
local v = w[j - 15]
local s0 = bxor(rrotate(v, 7), rrotate(v, 18), rshift(v, 3))
v = w[j - 2]
w[j] = w[j - 16] + s0 + w[j - 7] + bxor(rrotate(v, 17), rrotate(v, 19), rshift(v, 10))
end
local a, b, c, d, e, f, g, h = H[1], H[2], H[3], H[4], H[5], H[6], H[7], H[8]
for i = 1, 64 do
local s0 = bxor(rrotate(a, 2), rrotate(a, 13), rrotate(a, 22))
local maj = bxor(band(a, b), band(a, c), band(b, c))
local t2 = s0 + maj
local s1 = bxor(rrotate(e, 6), rrotate(e, 11), rrotate(e, 25))
local ch = bxor(band(e, f), band(bnot(e), g))
local t1 = h + s1 + ch + k[i] + w[i]
h, g, f, e, d, c, b, a = g, f, e, d + t1, c, b, a, t1 + t2
end
H[1] = band(H[1] + a)
H[2] = band(H[2] + b)
H[3] = band(H[3] + c)
H[4] = band(H[4] + d)
H[5] = band(H[5] + e)
H[6] = band(H[6] + f)
H[7] = band(H[7] + g)
H[8] = band(H[8] + h)
end
function sha256(msg)
msg = preproc(msg, #msg)
local H = initH256({})
for i = 1, #msg, 64 do digestblock(msg, i, H) end
return str2hexa(num2s(H[1], 4) .. num2s(H[2], 4) .. num2s(H[3], 4) .. num2s(H[4], 4) ..
num2s(H[5], 4) .. num2s(H[6], 4) .. num2s(H[7], 4) .. num2s(H[8], 4))
end | gpl-2.0 |
ProtectionTeam/PCT | plugins/Lucas.lua | 1 | 243867 | local function modadd(msg)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
if not lang then
return '_You are not bot admin_'
else
return 'شما مدیر ربات نمیباشید'
end
end
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if not lang then
return '_Group is already added_'
else
return 'گروه در لیست گروه های مدیریتی ربات هم اکنون موجود است'
end
end
-- create data array in moderation.json
data[tostring(msg.to.id)] = {
owners = {},
mods ={},
banned ={},
is_silent_users ={},
filterlist ={},
whitelist ={},
settings = {
set_name = msg.to.title,
lock_link = 'yes',
lock_tag = 'yes',
lock_username = 'yes',
lock_spam = 'yes',
lock_webpage = 'no',
lock_mention = 'no',
lock_markdown = 'no',
lock_flood = 'yes',
lock_bots = 'yes',
lock_pin = 'no',
welcome = 'no',
lock_join = 'no',
lock_badword = 'no',
lock_tabchi = 'no',
lock_english = 'no',
mute_fwd = 'no',
mute_audio = 'no',
mute_video = 'no',
mute_contact = 'no',
mute_text = 'no',
mute_photos = 'no',
mute_gif = 'no',
mute_loc = 'no',
mute_doc = 'no',
mute_sticker = 'no',
mute_voice = 'no',
mute_all = 'no',
mute_keyboard = 'no'
},
}
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
if not lang then
return "`Group` *has been added*\n*OяƊєя Ɓу :* `"..msg.from.id.."` "
else
return 'گروه با موفقیت به لیست گروه های مدیریتی ربات افزوده شد'
end
end
local function modrem(msg)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
if not lang then
return '_You are not bot admin_'
else
return 'شما مدیر ربات نمیباشید'
end
end
local data = load_data(_config.moderation.data)
local receiver = msg.to.id
if not data[tostring(msg.to.id)] then
if not lang then
return '_Group is not added_'
else
return 'گروه به لیست گروه های مدیریتی ربات اضافه نشده است'
end
end
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)
if not lang then
return "`Group` *has been removed*\n*OяƊєя Ɓу :* `"..msg.from.id.."` "
else
return 'گروه با موفیت از لیست گروه های مدیریتی ربات حذف شد'
end
end
local function config_cb(arg, data)
local hash = "gp_lang:"..arg.chat_id
local lang = redis:get(hash)
print(serpent.block(data))
for k,v in pairs(data.members_) do
local function config_mods(arg, data)
local administration = load_data(_config.moderation.data)
if data.username_ then
user_name = '@'..check_markdown(data.username_)
else
user_name = check_markdown(data.first_name_)
end
if administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] then
return
end
administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] = user_name
save_data(_config.moderation.data, administration)
end
tdcli_function ({
ID = "GetUser",
user_id_ = v.user_id_
}, config_mods, {chat_id=arg.chat_id,user_id=v.user_id_})
if data.members_[k].status_.ID == "ChatMemberStatusCreator" then
owner_id = v.user_id_
local function config_owner(arg, data)
print(serpent.block(data))
local administration = load_data(_config.moderation.data)
if data.username_ then
user_name = '@'..check_markdown(data.username_)
else
user_name = check_markdown(data.first_name_)
end
if administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] then
return
end
administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] = user_name
save_data(_config.moderation.data, administration)
end
tdcli_function ({
ID = "GetUser",
user_id_ = owner_id
}, config_owner, {chat_id=arg.chat_id,user_id=owner_id})
end
end
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_All group admins has been promoted and group creator is now group owner_", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_تمام ادمین های گروه به مقام مدیر منتصب شدند و سازنده گروه به مقام مالک گروه منتصب شد_", 0, "md")
end
end
local function filter_word(msg, word)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
local data = load_data(_config.moderation.data)
if not data[tostring(msg.to.id)]['filterlist'] then
data[tostring(msg.to.id)]['filterlist'] = {}
save_data(_config.moderation.data, data)
end
if data[tostring(msg.to.id)]['filterlist'][(word)] then
if not lang then
return "_Word_ *"..word.."* _is already filtered_"
else
return "_کلمه_ *"..word.."* _از قبل فیلتر بود_"
end
end
data[tostring(msg.to.id)]['filterlist'][(word)] = true
save_data(_config.moderation.data, data)
if not lang then
return "_Word_ *"..word.."* _added to filtered words list_"
else
return "_کلمه_ *"..word.."* _به لیست کلمات فیلتر شده اضافه شد_"
end
end
local function unfilter_word(msg, word)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
local data = load_data(_config.moderation.data)
if not data[tostring(msg.to.id)]['filterlist'] then
data[tostring(msg.to.id)]['filterlist'] = {}
save_data(_config.moderation.data, data)
end
if data[tostring(msg.to.id)]['filterlist'][word] then
data[tostring(msg.to.id)]['filterlist'][(word)] = nil
save_data(_config.moderation.data, data)
if not lang then
return "_Word_ *"..word.."* _removed from filtered words list_"
elseif lang then
return "_کلمه_ *"..word.."* _از لیست کلمات فیلتر شده حذف شد_"
end
else
if not lang then
return "_Word_ *"..word.."* _is not filtered_"
elseif lang then
return "_کلمه_ *"..word.."* _از قبل فیلتر نبود_"
end
end
end
local function modlist(msg)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
local data = load_data(_config.moderation.data)
local i = 1
if not data[tostring(msg.chat_id_)] then
if not lang then
return "_Group is not added_"
else
return "گروه به لیست گروه های مدیریتی ربات اضافه نشده است"
end
end
-- determine if table is empty
if next(data[tostring(msg.to.id)]['mods']) == nil then --fix way
if not lang then
return "_No_ *moderator* _in this group_"
else
return "در حال حاضر هیچ مدیری برای گروه انتخاب نشده است"
end
end
if not lang then
message = '*List of moderators :*\n'
else
message = '*لیست مدیران گروه :*\n'
end
for k,v in pairs(data[tostring(msg.to.id)]['mods'])
do
message = message ..i.. '- '..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function ownerlist(msg)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
local data = load_data(_config.moderation.data)
local i = 1
if not data[tostring(msg.to.id)] then
if not lang then
return "_Group is not added_"
else
return "گروه به لیست گروه های مدیریتی ربات اضافه نشده است"
end
end
-- determine if table is empty
if next(data[tostring(msg.to.id)]['owners']) == nil then --fix way
if not lang then
return "_No_ *owner* _in this group_"
else
return "در حال حاضر هیچ مالکی برای گروه انتخاب نشده است"
end
end
if not lang then
message = '*List of owners :*\n'
else
message = '*لیست مالکین گروه :*\n'
end
for k,v in pairs(data[tostring(msg.to.id)]['owners']) do
message = message ..i.. '- '..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function action_by_reply(arg, data)
local hash = "gp_lang:"..data.chat_id_
local lang = redis:get(hash)
local cmd = arg.cmd
local administration = load_data(_config.moderation.data)
if not tonumber(data.sender_user_id_) then return false end
if data.sender_user_id_ then
if not administration[tostring(data.chat_id_)] then
if not lang then
return tdcli.sendMessage(data.chat_id_, "", 0, "_Group is not added_", 0, "md")
else
return tdcli.sendMessage(data.chat_id_, "", 0, "_گروه به لیست گروه های مدیریتی ربات اضافه نشده است_", 0, "md")
end
end
if cmd == "ban" then
local function ban_cb(arg, data)
local hash = "gp_lang:"..arg.chat_id
local lang = redis:get(hash)
local administration = load_data(_config.moderation.data)
if data.username_ then
user_name = '@'..check_markdown(data.username_)
else
user_name = check_markdown(data.first_name_)
end
if is_mod1(arg.chat_id, data.id_) then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_You can't ban_ *mods,owners and bot admins*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "*شما نمیتوانید مدیران،صاحبان گروه، و ادمین های ربات رو از گروه محروم کنید*", 0, "md")
end
end
if administration[tostring(arg.chat_id)]['banned'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already_ *banned*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* * از گروه محروم بود*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['banned'][tostring(data.id_)] = user_name
save_data(_config.moderation.data, administration)
kick_user(data.id_, arg.chat_id)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *banned*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از گروه محروم شد*", 0, "md")
end
end
tdcli_function ({
ID = "GetUser",
user_id_ = data.sender_user_id_
}, ban_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_})
end
if cmd == "unban" then
local function unban_cb(arg, data)
local hash = "gp_lang:"..arg.chat_id
local lang = redis:get(hash)
local administration = load_data(_config.moderation.data)
if data.username_ then
user_name = '@'..check_markdown(data.username_)
else
user_name = check_markdown(data.first_name_)
end
if not administration[tostring(arg.chat_id)]['banned'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not_ *banned*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از گروه محروم نبود*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['banned'][tostring(data.id_)] = nil
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *unbanned*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از محرومیت گروه خارج شد*", 0, "md")
end
end
tdcli_function ({
ID = "GetUser",
user_id_ = data.sender_user_id_
}, unban_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_})
end
if cmd == "silent" then
local function silent_cb(arg, data)
local hash = "gp_lang:"..arg.chat_id
local lang = redis:get(hash)
local administration = load_data(_config.moderation.data)
if data.username_ then
user_name = '@'..check_markdown(data.username_)
else
user_name = check_markdown(data.first_name_)
end
if is_mod1(arg.chat_id, data.id_) then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_You can't silent_ *mods,owners and bot admins*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "*شما نمیتوانید توانایی چت کردن رو از مدیران،صاحبان گروه، و ادمین های ربات بگیرید*", 0, "md")
end
end
if administration[tostring(arg.chat_id)]['is_silent_users'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already_ *silent*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل توانایی چت کردن رو نداشت*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['is_silent_users'][tostring(data.id_)] = user_name
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _added to_ *silent users list*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *توانایی چت کردن رو از دست داد*", 0, "md")
end
end
tdcli_function ({
ID = "GetUser",
user_id_ = data.sender_user_id_
}, silent_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_})
end
if cmd == "unsilent" then
local function unsilent_cb(arg, data)
local hash = "gp_lang:"..arg.chat_id
local lang = redis:get(hash)
local administration = load_data(_config.moderation.data)
if data.username_ then
user_name = '@'..check_markdown(data.username_)
else
user_name = check_markdown(data.first_name_)
end
if not administration[tostring(arg.chat_id)]['is_silent_users'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not_ *silent*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل توانایی چت کردن را داشت*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['is_silent_users'][tostring(data.id_)] = nil
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _removed from_ *silent users list*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *توانایی چت کردن رو به دست آورد*", 0, "md")
end
end
tdcli_function ({
ID = "GetUser",
user_id_ = data.sender_user_id_
}, unsilent_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_})
end
if cmd == "banall" then
local function gban_cb(arg, data)
local hash = "gp_lang:"..arg.chat_id
local lang = redis:get(hash)
local administration = load_data(_config.moderation.data)
if data.username_ then
user_name = '@'..check_markdown(data.username_)
else
user_name = check_markdown(data.first_name_)
end
if not administration['gban_users'] then
administration['gban_users'] = {}
save_data(_config.moderation.data, administration)
end
if is_admin1(data.id_) then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_You can't_ *globally ban* _other admins_", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "*شما نمیتوانید ادمین های ربات رو از تمامی گروه های ربات محروم کنید*", 0, "md")
end
end
if is_gbanned(data.id_) then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already_ *globally banned*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از گروه های ربات محروم بود*", 0, "md")
end
end
administration['gban_users'][tostring(data.id_)] = user_name
save_data(_config.moderation.data, administration)
kick_user(data.id_, arg.chat_id)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *globally banned*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از تمام گروه های ربات محروم شد*", 0, "md")
end
end
tdcli_function ({
ID = "GetUser",
user_id_ = data.sender_user_id_
}, gban_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_})
end
if cmd == "unbanall" then
local function ungban_cb(arg, data)
local hash = "gp_lang:"..arg.chat_id
local lang = redis:get(hash)
local administration = load_data(_config.moderation.data)
if data.username_ then
user_name = '@'..check_markdown(data.username_)
else
user_name = check_markdown(data.first_name_)
end
if not administration['gban_users'] then
administration['gban_users'] = {}
save_data(_config.moderation.data, administration)
end
if not is_gbanned(data.id_) then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not_ *globally banned*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از گروه های ربات محروم نبود*", 0, "md")
end
end
administration['gban_users'][tostring(data.id_)] = nil
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *globally unbanned*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از محرومیت گروه های ربات خارج شد*", 0, "md")
end
end
tdcli_function ({
ID = "GetUser",
user_id_ = data.sender_user_id_
}, ungban_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_})
end
if cmd == "kick" then
if is_mod1(data.chat_id_, data.sender_user_id_) then
if not lang then
return tdcli.sendMessage(data.chat_id_, "", 0, "_You can't kick_ *mods,owners and bot admins*", 0, "md")
elseif lang then
return tdcli.sendMessage(data.chat_id_, "", 0, "*شما نمیتوانید مدیران،صاحبان گروه و ادمین های ربات رو اخراج کنید*", 0, "md")
end
else
kick_user(data.sender_user_id_, data.chat_id_)
end
end
if cmd == "delall" then
if is_mod1(data.chat_id_, data.sender_user_id_) then
if not lang then
return tdcli.sendMessage(data.chat_id_, "", 0, "_You can't delete messages_ *mods,owners and bot admins*", 0, "md")
elseif lang then
return tdcli.sendMessage(data.chat_id_, "", 0, "*شما نمیتوانید پیام های مدیران،صاحبان گروه و ادمین های ربات رو پاک کنید*", 0, "md")
end
else
tdcli.deleteMessagesFromUser(data.chat_id_, data.sender_user_id_, dl_cb, nil)
if not lang then
return tdcli.sendMessage(data.chat_id_, "", 0, "_All_ *messages* _of_ *[ "..data.sender_user_id_.." ]* _has been_ *deleted*", 0, "md")
elseif lang then
return tdcli.sendMessage(data.chat_id_, "", 0, "*تمام پیام های* *[ "..data.sender_user_id_.." ]* *پاک شد*", 0, "md")
end
end
end
if cmd == "setmanager" then
local function manager_cb(arg, data)
local hash = "gp_lang:"..arg.chat_id
local lang = redis:get(hash)
if data.username_ then
user_name = '@'..check_markdown(data.username_)
else
user_name = check_markdown(data.first_name_)
end
channel_set_admin(arg.chat_id, data.id_)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is now the_ *group manager*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *ادمین گروه شد*", 0, "md")
end
end
tdcli_function ({
ID = "GetUser",
user_id_ = data.sender_user_id_
}, manager_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_})
end
if cmd == "remmanager" then
local function rem_manager_cb(arg, data)
local hash = "gp_lang:"..arg.chat_id
local lang = redis:get(hash)
if data.username_ then
user_name = '@'..check_markdown(data.username_)
else
user_name = check_markdown(data.first_name_)
end
channel_demote(arg.chat_id, data.id_)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is no longer_ *group manager*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از ادمینی گروه برکنار شد*", 0, "md")
end
end
tdcli_function ({
ID = "GetUser",
user_id_ = data.sender_user_id_
}, rem_manager_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_})
end
if cmd == "setwhitelist" then
local function setwhitelist_cb(arg, data)
local hash = "gp_lang:"..arg.chat_id
local lang = redis:get(hash)
local administration = load_data(_config.moderation.data)
if data.username_ then
user_name = '@'..check_markdown(data.username_)
else
user_name = check_markdown(data.first_name_)
end
if not administration[tostring(arg.chat_id)]['whitelist'] then
administration[tostring(arg.chat_id)]['whitelist'] = {}
save_data(_config.moderation.data, administration)
end
if administration[tostring(arg.chat_id)]['whitelist'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already in_ *white list*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل در لیست سفید بود*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['whitelist'][tostring(data.id_)] = user_name
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been added to_ *white list*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *به لیست سفید اضافه شد*", 0, "md")
end
end
tdcli_function ({
ID = "GetUser",
user_id_ = data.sender_user_id_
}, setwhitelist_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_})
end
if cmd == "remwhitelist" then
local function remwhitelist_cb(arg, data)
local administration = load_data(_config.moderation.data)
if data.username_ then
user_name = '@'..check_markdown(data.username_)
else
user_name = check_markdown(data.first_name_)
end
if not administration[tostring(arg.chat_id)]['whitelist'] then
administration[tostring(arg.chat_id)]['whitelist'] = {}
save_data(_config.moderation.data, administration)
end
if not administration[tostring(arg.chat_id)]['whitelist'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not in_ *white list*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل در لیست سفید نبود*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['whitelist'][tostring(data.id_)] = nil
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been removed from_ *white list*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از لیست سفید حذف شد*", 0, "md")
end
end
tdcli_function ({
ID = "GetUser",
user_id_ = data.sender_user_id_
}, remwhitelist_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_})
end
if cmd == "setowner" then
local function owner_cb(arg, data)
local hash = "gp_lang:"..arg.chat_id
local lang = redis:get(hash)
local administration = load_data(_config.moderation.data)
if data.username_ then
user_name = '@'..check_markdown(data.username_)
else
user_name = check_markdown(data.first_name_)
end
if administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *group owner*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل صاحب گروه بود*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] = user_name
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is now the_ *group owner*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *به مقام صاحب گروه منتصب شد*", 0, "md")
end
end
tdcli_function ({
ID = "GetUser",
user_id_ = data.sender_user_id_
}, owner_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_})
end
if cmd == "promote" then
local function promote_cb(arg, data)
local hash = "gp_lang:"..arg.chat_id
local lang = redis:get(hash)
local administration = load_data(_config.moderation.data)
if data.username_ then
user_name = '@'..check_markdown(data.username_)
else
user_name = check_markdown(data.first_name_)
end
if administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *moderator*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل مدیر گروه بود*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] = user_name
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *promoted*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *به مقام مدیر گروه منتصب شد*", 0, "md")
end
end
tdcli_function ({
ID = "GetUser",
user_id_ = data.sender_user_id_
}, promote_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_})
end
if cmd == "remowner" then
local function rem_owner_cb(arg, data)
local hash = "gp_lang:"..arg.chat_id
local lang = redis:get(hash)
local administration = load_data(_config.moderation.data)
if data.username_ then
user_name = '@'..check_markdown(data.username_)
else
user_name = check_markdown(data.first_name_)
end
if not administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *group owner*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* *از قبل صاحب گروه نبود*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] = nil
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is no longer a_ *group owner*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از مقام صاحب گروه برکنار شد*", 0, "md")
end
end
tdcli_function ({
ID = "GetUser",
user_id_ = data.sender_user_id_
}, rem_owner_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_})
end
if cmd == "demote" then
local function demote_cb(arg, data)
local administration = load_data(_config.moderation.data)
if data.username_ then
user_name = '@'..check_markdown(data.username_)
else
user_name = check_markdown(data.first_name_)
end
if not administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *moderator*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل مدیر گروه نبود*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] = nil
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *demoted*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از مقام مدیر گروه برکنار شد*", 0, "md")
end
end
tdcli_function ({
ID = "GetUser",
user_id_ = data.sender_user_id_
}, demote_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_})
end
if cmd == "id" then
local function id_cb(arg, data)
return tdcli.sendMessage(arg.chat_id, "", 0, "*"..data.id_.."*", 0, "md")
end
tdcli_function ({
ID = "GetUser",
user_id_ = data.sender_user_id_
}, id_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_})
end
else
if lang then
return tdcli.sendMessage(data.chat_id_, "", 0, "_کاربر یافت نشد_", 0, "md")
else
return tdcli.sendMessage(data.chat_id_, "", 0, "*User Not Found*", 0, "md")
end
end
end
local function action_by_username(arg, data)
local hash = "gp_lang:"..arg.chat_id
local lang = redis:get(hash)
local cmd = arg.cmd
local administration = load_data(_config.moderation.data)
if not administration[tostring(arg.chat_id)] then
if not lang then
return tdcli.sendMessage(data.chat_id_, "", 0, "_Group is not added_", 0, "md")
else
return tdcli.sendMessage(data.chat_id_, "", 0, "_گروه به لیست گروه های مدیریتی ربات اضافه نشده است_", 0, "md")
end
end
if not arg.username then return false end
if data.id_ then
if data.type_.user_.username_ then
user_name = '@'..check_markdown(data.type_.user_.username_)
else
user_name = check_markdown(data.title_)
end
if cmd == "ban" then
if is_mod1(arg.chat_id, data.id_) then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_You can't ban_ *mods,owners and bot admins*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "*شما نمیتوانید مدیران،صاحبان گروه، و ادمین های ربات رو از گروه محروم کنید*", 0, "md")
end
end
if administration[tostring(arg.chat_id)]['banned'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already_ *banned*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* * از گروه محروم بود*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['banned'][tostring(data.id_)] = user_name
save_data(_config.moderation.data, administration)
kick_user(data.id_, arg.chat_id)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *banned*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از گروه محروم شد*", 0, "md")
end
end
if cmd == "unban" then
if not administration[tostring(arg.chat_id)]['banned'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not_ *banned*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از گروه محروم نبود*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['banned'][tostring(data.id_)] = nil
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *unbanned*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از محرومیت گروه خارج شد*", 0, "md")
end
end
if cmd == "silent" then
if is_mod1(arg.chat_id, data.id_) then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_You can't silent_ *mods,owners and bot admins*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "*شما نمیتوانید توانایی چت کردن رو از مدیران،صاحبان گروه، و ادمین های ربات بگیرید*", 0, "md")
end
end
if administration[tostring(arg.chat_id)]['is_silent_users'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already_ *silent*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل توانایی چت کردن رو نداشت*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['is_silent_users'][tostring(data.id_)] = user_name
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _added to_ *silent users list*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *توانایی چت کردن رو از دست داد*", 0, "md")
end
end
if cmd == "unsilent" then
if not administration[tostring(arg.chat_id)]['is_silent_users'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not_ *silent*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل توانایی چت کردن را داشت*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['is_silent_users'][tostring(data.id_)] = nil
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _removed from_ *silent users list*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *توانایی چت کردن رو به دست آورد*", 0, "md")
end
end
if cmd == "banall" then
if not administration['gban_users'] then
administration['gban_users'] = {}
save_data(_config.moderation.data, administration)
end
if is_admin1(data.id_) then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_You can't_ *globally ban* _other admins_", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "*شما نمیتوانید ادمین های ربات رو از تمامی گروه های ربات محروم کنید*", 0, "md")
end
end
if is_gbanned(data.id_) then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already_ *globally banned*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از گروه های ربات محروم بود*", 0, "md")
end
end
administration['gban_users'][tostring(data.id_)] = user_name
save_data(_config.moderation.data, administration)
kick_user(data.id_, arg.chat_id)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *globally banned*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از تمام گروه های ربات محروم شد*", 0, "md")
end
end
if cmd == "unbanall" then
if not administration['gban_users'] then
administration['gban_users'] = {}
save_data(_config.moderation.data, administration)
end
if not is_gbanned(data.id_) then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not_ *globally banned*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از گروه های ربات محروم نبود*", 0, "md")
end
end
administration['gban_users'][tostring(data.id_)] = nil
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *globally unbanned*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از محرومیت گروه های ربات خارج شد*", 0, "md")
end
end
if cmd == "kick" then
if is_mod1(arg.chat_id, data.id_) then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_You can't kick_ *mods,owners and bot admins*", 0, "md")
elseif lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "*شما نمیتوانید مدیران،صاحبان گروه و ادمین های ربات رو اخراج کنید*", 0, "md")
end
else
kick_user(data.id_, arg.chat_id)
end
end
if cmd == "delall" then
if is_mod1(arg.chat_id, data.id_) then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_You can't delete messages_ *mods,owners and bot admins*", 0, "md")
elseif lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "*شما نمیتوانید پیام های مدیران،صاحبان گروه و ادمین های ربات رو پاک کنید*", 0, "md")
end
else
tdcli.deleteMessagesFromUser(arg.chat_id, data.id_, dl_cb, nil)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_All_ *messages* _of_ "..user_name.." *[ "..data.id_.." ]* _has been_ *deleted*", 0, "md")
elseif lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "*تمام پیام های* "..user_name.." *[ "..data.id_.." ]* *پاک شد*", 0, "md")
end
end
end
if cmd == "setmanager" then
channel_set_admin(arg.chat_id, data.id_)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is now the_ *group manager*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *ادمین گروه شد*", 0, "md")
end
end
if cmd == "remmanager" then
channel_demote(arg.chat_id, data.id_)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is no longer_ *group manager*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از ادمینی گروه برکنار شد*", 0, "md")
end
end
if cmd == "setwhitelist" then
if not administration[tostring(arg.chat_id)]['whitelist'] then
administration[tostring(arg.chat_id)]['whitelist'] = {}
save_data(_config.moderation.data, administration)
end
if administration[tostring(arg.chat_id)]['whitelist'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already in_ *white list*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل در لیست سفید بود*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['whitelist'][tostring(data.id_)] = user_name
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been added to_ *white list*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *به لیست سفید اضافه شد*", 0, "md")
end
end
if cmd == "remwhitelist" then
if not administration[tostring(arg.chat_id)]['whitelist'] then
administration[tostring(arg.chat_id)]['whitelist'] = {}
save_data(_config.moderation.data, administration)
end
if not administration[tostring(arg.chat_id)]['whitelist'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not in_ *white list*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل در لیست سفید نبود*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['whitelist'][tostring(data.id_)] = nil
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been removed from_ *white list*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از لیست سفید حذف شد*", 0, "md")
end
end
if cmd == "setowner" then
if administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *group owner*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل صاحب گروه بود*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] = user_name
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is now the_ *group owner*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *به مقام صاحب گروه منتصب شد*", 0, "md")
end
end
if cmd == "promote" then
if administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *moderator*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل مدیر گروه بود*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] = user_name
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *promoted*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *به مقام مدیر گروه منتصب شد*", 0, "md")
end
end
if cmd == "remowner" then
if not administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *group owner*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* *از قبل صاحب گروه نبود*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] = nil
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is no longer a_ *group owner*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از مقام صاحب گروه برکنار شد*", 0, "md")
end
end
if cmd == "demote" then
if not administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *moderator*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل مدیر گروه نبود*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] = nil
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *demoted*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از مقام مدیر گروه برکنار شد*", 0, "md")
end
end
if cmd == "id" then
return tdcli.sendMessage(arg.chat_id, "", 0, "*"..data.id_.."*", 0, "md")
end
if cmd == "res" then
if not lang then
text = "Result for [ "..check_markdown(data.type_.user_.username_).." ] :\n"
.. ""..check_markdown(data.title_).."\n"
.. " ["..data.id_.."]"
else
text = "اطلاعات برای [ "..check_markdown(data.type_.user_.username_).." ] :\n"
.. "".. check_markdown(data.title_) .."\n"
.. " [".. data.id_ .."]"
end
return tdcli.sendMessage(arg.chat_id, 0, 1, text, 1, 'md')
end
else
if lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر یافت نشد_", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "*User Not Found*", 0, "md")
end
end
end
local function action_by_id(arg, data)
local hash = "gp_lang:"..arg.chat_id
local lang = redis:get(hash)
local cmd = arg.cmd
local administration = load_data(_config.moderation.data)
if not administration[tostring(arg.chat_id)] then
if not lang then
return tdcli.sendMessage(data.chat_id_, "", 0, "_Group is not added_", 0, "md")
else
return tdcli.sendMessage(data.chat_id_, "", 0, "_گروه به لیست گروه های مدیریتی ربات اضافه نشده است_", 0, "md")
end
end
if not tonumber(arg.user_id) then return false end
if data.id_ then
if data.first_name_ then
if data.username_ then
user_name = '@'..check_markdown(data.username_)
else
user_name = check_markdown(data.first_name_)
end
if cmd == "setmanager" then
channel_set_admin(arg.chat_id, data.id_)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is now the_ *group manager*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *ادمین گروه شد*", 0, "md")
end
end
if cmd == "remmanager" then
channel_demote(arg.chat_id, data.id_)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is no longer_ *group manager*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از ادمینی گروه برکنار شد*", 0, "md")
end
end
if cmd == "setwhitelist" then
if not administration[tostring(arg.chat_id)]['whitelist'] then
administration[tostring(arg.chat_id)]['whitelist'] = {}
save_data(_config.moderation.data, administration)
end
if administration[tostring(arg.chat_id)]['whitelist'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already in_ *white list*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل در لیست سفید بود*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['whitelist'][tostring(data.id_)] = user_name
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been added to_ *white list*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *به لیست سفید اضافه شد*", 0, "md")
end
end
if cmd == "remwhitelist" then
if not administration[tostring(arg.chat_id)]['whitelist'] then
administration[tostring(arg.chat_id)]['whitelist'] = {}
save_data(_config.moderation.data, administration)
end
if not administration[tostring(arg.chat_id)]['whitelist'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not in_ *white list*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل در لیست سفید نبود*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['whitelist'][tostring(data.id_)] = nil
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been removed from_ *white list*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از لیست سفید حذف شد*", 0, "md")
end
end
if cmd == "setowner" then
if administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *group owner*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل صاحب گروه بود*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] = user_name
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is now the_ *group owner*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *به مقام صاحب گروه منتصب شد*", 0, "md")
end
end
if cmd == "promote" then
if administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *moderator*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل مدیر گروه بود*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] = user_name
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *promoted*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *به مقام مدیر گروه منتصب شد*", 0, "md")
end
end
if cmd == "remowner" then
if not administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *group owner*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* *از قبل صاحب گروه نبود*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] = nil
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is no longer a_ *group owner*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از مقام صاحب گروه برکنار شد*", 0, "md")
end
end
if cmd == "demote" then
if not administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *moderator*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل مدیر گروه نبود*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] = nil
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *demoted*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از مقام مدیر گروه برکنار شد*", 0, "md")
end
end
if cmd == "whois" then
if data.username_ then
username = '@'..check_markdown(data.username_)
else
if not lang then
username = 'not found'
else
username = 'ندارد'
end
end
if not lang then
return tdcli.sendMessage(arg.chat_id, 0, 1, 'Info for [ '..data.id_..' ] :\nUserName : '..username..'\nName : '..data.first_name_, 1)
else
return tdcli.sendMessage(arg.chat_id, 0, 1, 'اطلاعات برای [ '..data.id_..' ] :\nیوزرنیم : '..username..'\nنام : '..data.first_name_, 1)
end
end
else
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User not founded_", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر یافت نشد_", 0, "md")
end
end
else
if lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر یافت نشد_", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "*User Not Found*", 0, "md")
end
end
end
---------------Lock Link-------------------
local function lock_link(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_link = data[tostring(target)]["settings"]["lock_link"]
if lock_link == "yes" then
if not lang then
return "`Lιηк` *Ƥσѕтιηg Iѕ AƖяєαɗу Lσcкєɗ*⚠️♻️"
elseif lang then
return "ارسال لینک در گروه هم اکنون ممنوع است⚠️♻️"
end
else
data[tostring(target)]["settings"]["lock_link"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "`Lιηк` *Ƥσѕтιηg Hαѕ Ɓєєη Lσcкєɗ*🔒\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "ارسال لینک در گروه ممنوع شد🔒\n*توسط :* `"..msg.from.id.."`"
end
end
end
local function unlock_link(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_link = data[tostring(target)]["settings"]["lock_link"]
if lock_link == "no" then
if not lang then
return "`Lιηк` *Ƥσѕтιηg Iѕ Ɲσт Lσcкєɗ*⚠️🚫"
elseif lang then
return "ارسال لینک در گروه ممنوع نمیباشد⚠️🚫"
end
else
data[tostring(target)]["settings"]["lock_link"] = "no" save_data(_config.moderation.data, data)
if not lang then
return "`Lιηк` *Ƥσѕтιηg Hαѕ Ɓєєη UηƖσcкєɗ*🔓\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "ارسال لینک در گروه آزاد شد🔓\n*توسط :* `"..msg.from.id.."`"
end
end
end
---------------Lock Tag-------------------
local function lock_tag(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_tag = data[tostring(target)]["settings"]["lock_tag"]
if lock_tag == "yes" then
if not lang then
return "`Ƭαg` *Ƥσѕтιηg Iѕ AƖяєαɗу Lσcкєɗ*⚠️♻️"
elseif lang then
return "ارسال تگ در گروه هم اکنون ممنوع است⚠️♻️"
end
else
data[tostring(target)]["settings"]["lock_tag"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "`Ƭαg` *Ƥσѕтιηg Hαѕ Ɓєєη Lσcкєɗ*🔒\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "ارسال تگ در گروه ممنوع شد🔒\n*توسط :* `"..msg.from.id.."`"
end
end
end
local function unlock_tag(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_tag = data[tostring(target)]["settings"]["lock_tag"]
if lock_tag == "no" then
if not lang then
return "`Ƭαg` *Ƥσѕтιηg Iѕ Ɲσт Lσcкєɗ*⚠️🚫"
elseif lang then
return "ارسال تگ در گروه ممنوع نمیباشد⚠️🚫"
end
else
data[tostring(target)]["settings"]["lock_tag"] = "no" save_data(_config.moderation.data, data)
if not lang then
return "`Ƭαg` *Ƥσѕтιηg Hαѕ Ɓєєη UηƖσcкєɗ*🔓\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "ارسال تگ در گروه آزاد شد🔓\n*توسط :* `"..msg.from.id.."`"
end
end
end
---------------Lock Username-------------------
local function lock_username(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_username = data[tostring(target)]["settings"]["lock_username"]
if lock_username == "yes" then
if not lang then
return "`UѕєяƝαмє` *Ƥσѕтιηg Iѕ AƖяєαɗу Lσcкєɗ*⚠️♻️"
elseif lang then
return "ارسال فحش در گروه هم اکنون ممنوع است⚠️♻️"
end
else
data[tostring(target)]["settings"]["lock_username"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "`UѕєяƝαмє` *Ƥσѕтιηg Hαѕ Ɓєєη Lσcкєɗ*🔒\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "ارسال یوزرنیم در گروه ممنوع شد🔒\n*توسط :* `"..msg.from.id.."`"
end
end
end
local function unlock_username(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_username = data[tostring(target)]["settings"]["lock_username"]
if lock_username == "no" then
if not lang then
return "`UѕєяƝαмє` *Ƥσѕтιηg Iѕ Ɲσт Lσcкєɗ*⚠️🚫"
elseif lang then
return "ارسال یوزرنیم در گروه ممنوع نمیباشد⚠️🚫"
end
else
data[tostring(target)]["settings"]["lock_username"] = "no" save_data(_config.moderation.data, data)
if not lang then
return "`UѕєяƝαмє` *Ƥσѕтιηg Hαѕ Ɓєєη UηƖσcкєɗ*🔓\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "ارسال یوزرنیم در گروه آزاد شد🔓\n*توسط :* `"..msg.from.id.."`"
end
end
end
---------------Lock Mention-------------------
local function lock_mention(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_mention = data[tostring(target)]["settings"]["lock_mention"]
if lock_mention == "yes" then
if not lang then
return "`Mєηтιση` *Ƥσѕтιηg Iѕ AƖяєαɗу Lσcкєɗ*⚠️♻️"
elseif lang then
return "ارسال فراخوانی افراد هم اکنون ممنوع است⚠️♻️"
end
else
data[tostring(target)]["settings"]["lock_mention"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "`Mєηтιση` *Ƥσѕтιηg Hαѕ Ɓєєη Lσcкєɗ*🔒\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "ارسال فراخوانی افراد در گروه ممنوع شد🔒\n*توسط :* `"..msg.from.id.."`"
end
end
end
local function unlock_mention(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_mention = data[tostring(target)]["settings"]["lock_mention"]
if lock_mention == "no" then
if not lang then
return "`Mєηтιση` *Ƥσѕтιηg Iѕ Ɲσт Lσcкєɗ*⚠️🚫"
elseif lang then
return "ارسال فراخوانی افراد در گروه ممنوع نمیباشد⚠️🚫"
end
else
data[tostring(target)]["settings"]["lock_mention"] = "no" save_data(_config.moderation.data, data)
if not lang then
return "`Mєηтιση` *Ƥσѕтιηg Hαѕ Ɓєєη UηƖσcкєɗ*🔓\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "ارسال فراخوانی افراد در گروه آزاد شد🔓\n*توسط :* `"..msg.from.id.."`"
end
end
end
---------------Lock Arabic--------------
local function lock_arabic(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_arabic = data[tostring(target)]["settings"]["lock_arabic"]
if lock_arabic == "yes" then
if not lang then
return "`Aяαвιc/Ƥєяѕιαη` *Ƥσѕтιηg Iѕ AƖяєαɗу Lσcкєɗ*⚠️♻️"
elseif lang then
return "ارسال کلمات عربی/فارسی در گروه هم اکنون ممنوع است"
end
else
data[tostring(target)]["settings"]["lock_arabic"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "`Aяαвιc/Ƥєяѕιαη` *Ƥσѕтιηg Hαѕ Ɓєєη Lσcкєɗ*🔒\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "ارسال کلمات عربی/فارسی در گروه ممنوع شد🔒\n*توسط :* `"..msg.from.id.."`"
end
end
end
local function unlock_arabic(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_arabic = data[tostring(target)]["settings"]["lock_arabic"]
if lock_arabic == "no" then
if not lang then
return "`Aяαвιc/Ƥєяѕιαη` *Ƥσѕтιηg Iѕ Ɲσт Lσcкєɗ*⚠️🚫"
elseif lang then
return "ارسال کلمات عربی/فارسی در گروه ممنوع نمیباشد⚠️🚫"
end
else
data[tostring(target)]["settings"]["lock_arabic"] = "no" save_data(_config.moderation.data, data)
if not lang then
return "`Aяαвιc/Ƥєяѕιαη` *Ƥσѕтιηg Hαѕ Ɓєєη UηƖσcкєɗ*🔓\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "ارسال کلمات عربی/فارسی در گروه آزاد شد🔓\n*توسط :* `"..msg.from.id.."`"
end
end
end
---------------Lock Edit-------------------
local function lock_edit(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_edit = data[tostring(target)]["settings"]["lock_edit"]
if lock_edit == "yes" then
if not lang then
return "`Edιтιɴɢ` *Iѕ AƖяєαɗу Lσcкєɗ*⚠️♻️"
elseif lang then
return "ویرایش پیام هم اکنون ممنوع است⚠️♻️"
end
else
data[tostring(target)]["settings"]["lock_edit"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "`Edιтιɴɢ` *Hαѕ Ɓєєη Lσcкєɗ*🔒\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "ویرایش پیام در گروه ممنوع شد🔒\n*توسط :* `"..msg.from.id.."`"
end
end
end
local function unlock_edit(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_edit = data[tostring(target)]["settings"]["lock_edit"]
if lock_edit == "no" then
if not lang then
return "`Edιтιɴɢ` *Iѕ Ɲσт Lσcкєɗ*⚠️🚫"
elseif lang then
return "ویرایش پیام در گروه ممنوع نمیباشد⚠️🚫"
end
else
data[tostring(target)]["settings"]["lock_edit"] = "no" save_data(_config.moderation.data, data)
if not lang then
return "`Edιтιɴɢ` *Hαѕ Ɓєєη UηƖσcкєɗ*🔓\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "ویرایش پیام در گروه آزاد شد🔓\n*توسط :* `"..msg.from.id.."`"
end
end
end
---------------Lock spam-------------------
local function lock_spam(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_spam = data[tostring(target)]["settings"]["lock_spam"]
if lock_spam == "yes" then
if not lang then
return "`Sραм` *Iѕ AƖяєαɗу Lσcкєɗ*⚠️♻️"
elseif lang then
return "ارسال هرزنامه در گروه هم اکنون ممنوع است⚠️♻️"
end
else
data[tostring(target)]["settings"]["lock_spam"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "`Sραм` *Hαѕ Ɓєєη Lσcкєɗ*🔒\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "ارسال هرزنامه در گروه ممنوع شد🔒\n*توسط :* `"..msg.from.id.."`"
end
end
end
local function unlock_spam(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_spam = data[tostring(target)]["settings"]["lock_spam"]
if lock_spam == "no" then
if not lang then
return "`Sραм` *Ƥσѕтιηg Iѕ Ɲσт Lσcкєɗ*⚠️🚫"
elseif lang then
return "ارسال هرزنامه در گروه ممنوع نمیباشد⚠️🚫"
end
else
data[tostring(target)]["settings"]["lock_spam"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "`Sραм` *Ƥσѕтιηg Hαѕ Ɓєєη UηƖσcкєɗ*🔓\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "ارسال هرزنامه در گروه آزاد شد🔓\n*توسط :* `"..msg.from.id.."`"
end
end
end
---------------Lock Badword-------------------
local function lock_badword(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_badword = data[tostring(target)]["settings"]["lock_badword"]
if lock_badword == "yes" then
if not lang then
return "`Ɓαɗωσяɗ` *Ƥσѕтιηg Iѕ AƖяєαɗу Lσcкєɗ*⚠️♻️"
elseif lang then
return "ارسال فحش در گروه هم اکنون ممنوع است⚠️♻️"
end
else
data[tostring(target)]["settings"]["lock_badword"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "`Ɓαɗωσяɗ` *Ƥσѕтιηg Hαѕ Ɓєєη Lσcкєɗ*🔒\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "ارسال فحش در گروه ممنوع شد🔒\n*توسط :* `"..msg.from.id.."`"
end
end
end
local function unlock_badword(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_badword = data[tostring(target)]["settings"]["lock_badword"]
if lock_badword == "no" then
if not lang then
return "`Ɓαɗωσяɗ` *Ƥσѕтιηg Iѕ Ɲσт Lσcкєɗ*⚠️🚫"
elseif lang then
return "ارسال فحش در گروه ممنوع نمیباشد⚠️🚫"
end
else
data[tostring(target)]["settings"]["lock_badword"] = "no" save_data(_config.moderation.data, data)
if not lang then
return "`Ɓαɗωσяɗ` *Ƥσѕтιηg Hαѕ Ɓєєη UηƖσcкєɗ*🔓\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "ارسال فحش در گروه آزاد شد🔓\n*توسط :* `"..msg.from.id.."`"
end
end
end
---------------Lock Flood-------------------
local function lock_flood(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_flood = data[tostring(target)]["settings"]["lock_flood"]
if lock_flood == "yes" then
if not lang then
return "`ƑƖσσɗιηg` *Iѕ AƖяєαɗу Lσcкєɗ*⚠️♻️"
elseif lang then
return "ارسال پیام مکرر در گروه هم اکنون ممنوع است⚠️♻️"
end
else
data[tostring(target)]["settings"]["lock_flood"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "`ƑƖσσɗιηg` *Hαѕ Ɓєєη Lσcкєɗ*🔒\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "ارسال پیام مکرر در گروه ممنوع شد🔒\n*توسط :* `"..msg.from.id.."`"
end
end
end
local function unlock_flood(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_flood = data[tostring(target)]["settings"]["lock_flood"]
if lock_flood == "no" then
if not lang then
return "`ƑƖσσɗιηg` *Iѕ Ɲσт Lσcкєɗ*⚠️🚫"
elseif lang then
return "ارسال پیام مکرر در گروه ممنوع نمیباشد⚠️🚫"
end
else
data[tostring(target)]["settings"]["lock_flood"] = "no" save_data(_config.moderation.data, data)
if not lang then
return "`ƑƖσσɗιηg` *Hαѕ Ɓєєη UηƖσcкєɗ*🔓\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "ارسال پیام مکرر در گروه آزاد شد🔓\n*توسط :* `"..msg.from.id.."`"
end
end
end
---------------Lock Bots-------------------
local function lock_bots(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_bots = data[tostring(target)]["settings"]["lock_bots"]
if lock_bots == "yes" then
if not lang then
return "`Ɓσтѕ` *Ƥяσтєcтιση Iѕ AƖяєαɗу ƐηαвƖєɗ*⚠️♻️"
elseif lang then
return "محافظت از گروه در برابر ربات ها هم اکنون فعال است⚠️♻️"
end
else
data[tostring(target)]["settings"]["lock_bots"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "`Ɓσтѕ` *Ƥяσтєcтιση Hαѕ Ɓєєη ƐηαвƖєɗ*🔒\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "محافظت از گروه در برابر ربات ها فعال شد🔒\n*توسط :* `"..msg.from.id.."`"
end
end
end
local function unlock_bots(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_bots = data[tostring(target)]["settings"]["lock_bots"]
if lock_bots == "no" then
if not lang then
return "`Ɓσтѕ` *Ƥяσтєcтιση Iѕ Ɲσт Ɛηαвℓє∂*⚠️🚫"
elseif lang then
return "محافظت از گروه در برابر ربات ها غیر فعال است⚠️🚫"
end
else
data[tostring(target)]["settings"]["lock_bots"] = "no" save_data(_config.moderation.data, data)
if not lang then
return "`Ɓσтѕ` *Ƥяσтєcтιση Hαѕ Ɓєєη ƊιѕαвƖєɗ*🔓\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "محافظت از گروه در برابر ربات ها غیر فعال شد🔓\n*توسط :* `"..msg.from.id.."`"
end
end
end
---------------Lock Join-------------------
local function lock_join(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_join = data[tostring(target)]["settings"]["lock_join"]
if lock_join == "yes" then
if not lang then
return "`Jσιη` *Iѕ AƖяєαɗу Lσcкєɗ*⚠️♻️"
elseif lang then
return "ورود به گروه هم اکنون ممنوع است⚠️♻️"
end
else
data[tostring(target)]["settings"]["lock_join"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "`Jσιη` *Hαѕ Ɓєєη Lσcкєɗ*🔒\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "ورود به گروه ممنوع شد🔒\n*توسط :* `"..msg.from.id.."`"
end
end
end
local function unlock_join(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_join = data[tostring(target)]["settings"]["lock_join"]
if lock_join == "no" then
if not lang then
return "`Jσιη` *Iѕ Ɲσт Lσcкєɗ*⚠️🚫"
elseif lang then
return "ورود به گروه ممنوع نمیباشد⚠️🚫"
end
else
data[tostring(target)]["settings"]["lock_join"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "`Jσιη` *Hαѕ Ɓєєη UηƖσcкєɗ*🔓\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "ورود به گروه آزاد شد🔓\n*توسط :* `"..msg.from.id.."`"
end
end
end
---------------Lock Tabchi-------------------
local function lock_tabchi(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_tabchi = data[tostring(target)]["settings"]["lock_tabchi"]
if lock_tabchi == "yes" then
if not lang then
return "`Ƭαвcнι` *Ƥσѕтιηg Iѕ AƖяєαɗу Lσcкєɗ*⚠️♻️"
elseif lang then
return "تبچی در گروه هم اکنون ممنوع است⚠️♻️"
end
else
data[tostring(target)]["settings"]["lock_tabchi"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "`Ƭαвcнι` *Ƥσѕтιηg Hαѕ Ɓєєη Lσcкєɗ*🔒\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "تبچی در گروه ممنوع شد🔒\n*توسط :* `"..msg.from.id.."`"
end
end
end
local function unlock_tabchi(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_tabchi = data[tostring(target)]["settings"]["lock_tabchi"]
if lock_tabchi == "no" then
if not lang then
return "`Ƭαвcнι` *Ƥσѕтιηg Iѕ Ɲσт Lσcкєɗ*⚠️🚫"
elseif lang then
return "تبچی در گروه ممنوع نمیباشد⚠️🚫"
end
else
data[tostring(target)]["settings"]["lock_tabchi"] = "no" save_data(_config.moderation.data, data)
if not lang then
return "`Ƭαвcнι` *Ƥσѕтιηg Hαѕ Ɓєєη UηƖσcкєɗ*🔓\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "تبچی در گروه آزاد شد🔓\n*توسط :* `"..msg.from.id.."`"
end
end
end
---------------Lock Markdown-------------------
local function lock_markdown(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_markdown = data[tostring(target)]["settings"]["lock_markdown"]
if lock_markdown == "yes" then
if not lang then
return "`Mαякɗσωη` *Ƥσѕтιηg Iѕ AƖяєαɗу Lσcкєɗ*⚠️♻️"
elseif lang then
return "ارسال پیام های دارای فونت در گروه هم اکنون ممنوع است⚠️♻️"
end
else
data[tostring(target)]["settings"]["lock_markdown"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "`Mαякɗσωη` *Ƥσѕтιηg Hαѕ Ɓєєη Lσcкєɗ*🔒\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "ارسال پیام های دارای فونت در گروه ممنوع شد🔒\n*توسط :* `"..msg.from.id.."`"
end
end
end
local function unlock_markdown(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_markdown = data[tostring(target)]["settings"]["lock_markdown"]
if lock_markdown == "no" then
if not lang then
return "`Mαякɗσωη` *Ƥσѕтιηg Iѕ Ɲσт Lσcкєɗ*⚠️🚫"
elseif lang then
return "ارسال پیام های دارای فونت در گروه ممنوع نمیباشد⚠️🚫"
end
else
data[tostring(target)]["settings"]["lock_markdown"] = "no" save_data(_config.moderation.data, data)
if not lang then
return "`Mαякɗσωη` *Ƥσѕтιηg Hαѕ Ɓєєη UηƖσcкєɗ*🔓\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "ارسال پیام های دارای فونت در گروه آزاد شد🔓\n*توسط :* `"..msg.from.id.."`"
end
end
end
---------------Lock Webpage-------------------
local function lock_webpage(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_webpage = data[tostring(target)]["settings"]["lock_webpage"]
if lock_webpage == "yes" then
if not lang then
return "`Ɯєвραgє` *Iѕ AƖяєαɗу Lσcкєɗ*⚠️♻️"
elseif lang then
return "ارسال صفحات وب در گروه هم اکنون ممنوع است⚠️♻️"
end
else
data[tostring(target)]["settings"]["lock_webpage"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "`Ɯєвραgє` *Hαѕ Ɓєєη Lσcкєɗ*🔒\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "ارسال صفحات وب در گروه ممنوع شد🔒\n*توسط :* `"..msg.from.id.."`"
end
end
end
local function unlock_webpage(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_webpage = data[tostring(target)]["settings"]["lock_webpage"]
if lock_webpage == "no" then
if not lang then
return "`Ɯєвραgє` *Iѕ Ɲσт Lσcкєɗ*⚠️🚫"
elseif lang then
return "ارسال صفحات وب در گروه ممنوع نمیباشد⚠️🚫"
end
else
data[tostring(target)]["settings"]["lock_webpage"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "`Ɯєвραgє` *Hαѕ Ɓєєη UηƖσcкєɗ*🔓\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "ارسال صفحات وب در گروه آزاد شد🔓\n*توسط :* `"..msg.from.id.."`"
end
end
end
---------------Lock English-------------------
local function lock_english(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_badword = data[tostring(target)]["settings"]["lock_english"]
if lock_english == "yes" then
if not lang then
return "`ƐηgƖιѕн` *Ƥσѕтιηg Iѕ AƖяєαɗу Lσcкєɗ*⚠️♻️"
elseif lang then
return "انگلیسی در گروه هم اکنون ممنوع است⚠️♻️"
end
else
data[tostring(target)]["settings"]["lock_english"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "`ƐηgƖιѕн` *Ƥσѕтιηg Hαѕ Ɓєєη Lσcкєɗ*🔒\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "انگلیسی در گروه ممنوع شد🔒\n*توسط :* `"..msg.from.id.."`"
end
end
end
local function unlock_english(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_english = data[tostring(target)]["settings"]["lock_english"]
if lock_english == "no" then
if not lang then
return "`ƐηgƖιѕн` *Ƥσѕтιηg Iѕ Ɲσт Lσcкєɗ*⚠️🚫"
elseif lang then
return "انگلیسی در گروه ممنوع نمیباشد⚠️🚫"
end
else
data[tostring(target)]["settings"]["lock_english"] = "no" save_data(_config.moderation.data, data)
if not lang then
return "`ƐηgƖιѕн` *Ƥσѕтιηg Hαѕ Ɓєєη UηƖσcкєɗ*🔓\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "انگلیسی در گروه آزاد شد🔓\n*توسط :* `"..msg.from.id.."`"
end
end
end
---------------Lock Pin-------------------
local function lock_pin(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_pin = data[tostring(target)]["settings"]["lock_pin"]
if lock_pin == "yes" then
if not lang then
return "`Ƥιηηєɗ Mєѕѕαgє` *Iѕ AƖяєαɗу Lσcкєɗ*⚠️♻️"
elseif lang then
return "سنجاق کردن پیام در گروه هم اکنون ممنوع است⚠️♻️"
end
else
data[tostring(target)]["settings"]["lock_pin"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "`Ƥιηηєɗ Mєѕѕαgє` *Hαѕ Ɓєєη Lσcкєɗ*🔒\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "سنجاق کردن پیام در گروه ممنوع شد🔒\n*توسط :* `"..msg.from.id.."`"
end
end
end
local function unlock_pin(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local lock_pin = data[tostring(target)]["settings"]["lock_pin"]
if lock_pin == "no" then
if not lang then
return "`Ƥιηηєɗ Mєѕѕαgє` *Iѕ Ɲσт Lσcкєɗ*⚠️🚫"
elseif lang then
return "سنجاق کردن پیام در گروه ممنوع نمیباشد⚠️🚫"
end
else
data[tostring(target)]["settings"]["lock_pin"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "`Ƥιηηєɗ Mєѕѕαgє` *Hαѕ Ɓєєη UηƖσcкєɗ*🔓\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "سنجاق کردن پیام در گروه آزاد شد🔓\n*توسط :* `"..msg.from.id.."`"
end
end
end
--------settings---------
---------------Mute Gif-------------------
local function mute_gif(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_gif = data[tostring(target)]["settings"]["mute_gif"]
if mute_gif == "yes" then
if not lang then
return "`Mυтє Ɠιf` *Iѕ AƖяєαɗу ƐηαвƖєɗ*⚠️♻️"
elseif lang then
return "بیصدا کردن تصاویر متحرک فعال است⚠️♻️"
end
else
data[tostring(target)]["settings"]["mute_gif"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "`Mυтє Ɠιf` *Hαѕ Ɓєєη ƐηαвƖєɗ*🔇\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "بیصدا کردن تصاویر متحرک فعال شد🔇\n*توسط :* `"..msg.from.id.."`"
end
end
end
local function unmute_gif(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_gif = data[tostring(target)]["settings"]["mute_gif"]
if mute_gif == "no" then
if not lang then
return "`Mυтє Ɠιf` *Iѕ AƖяєαɗу ƊιѕαвƖєɗ*⚠️🚫"
elseif lang then
return "بیصدا کردن تصاویر متحرک غیر فعال بود⚠️🚫"
end
else
data[tostring(target)]["settings"]["mute_gif"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "`Mυтє Ɠιf` *Hαѕ Ɓєєη ƊιѕαвƖєɗ*🔊\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "بیصدا کردن تصاویر متحرک غیر فعال شد🔊\n*توسط :* `"..msg.from.id.."`"
end
end
end
---------------Mute Game-------------------
local function mute_game(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_game = data[tostring(target)]["settings"]["mute_game"]
if mute_game == "yes" then
if not lang then
return "`Mυтє Ɠαмє` *Iѕ AƖяєαɗу ƐηαвƖєɗ*⚠️♻️"
elseif lang then
return "بیصدا کردن بازی های تحت وب فعال است⚠️♻️"
end
else
data[tostring(target)]["settings"]["mute_game"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "`Mυтє Ɠαмє` *Hαѕ Ɓєєη ƐηαвƖєɗ*🔇\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "بیصدا کردن بازی های تحت وب فعال شد🔇\n*توسط :* `"..msg.from.id.."`"
end
end
end
local function unmute_game(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_game = data[tostring(target)]["settings"]["mute_game"]
if mute_game == "no" then
if not lang then
return "`Mυтє Ɠαмє` *Iѕ AƖяєαɗу ƊιѕαвƖєɗ*⚠️🚫"
elseif lang then
return "بیصدا کردن بازی های تحت وب غیر فعال است⚠️🚫"
end
else
data[tostring(target)]["settings"]["mute_game"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "`Mυтє Ɠαмє` *Hαѕ Ɓєєη ƊιѕαвƖєɗ*🔊\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "بیصدا کردن بازی های تحت وب غیر فعال شد🔊\n*توسط :* `"..msg.from.id.."`"
end
end
end
---------------Mute Inline-------------------
local function mute_inline(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_inline = data[tostring(target)]["settings"]["mute_inline"]
if mute_inline == "yes" then
if not lang then
return "`Mυтє IηƖιηє` *Iѕ AƖяєαɗу ƐηαвƖєɗ*⚠️♻️"
elseif lang then
return "بیصدا کردن کیبورد شیشه ای فعال است⚠️♻️"
end
else
data[tostring(target)]["settings"]["mute_inline"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "`Mυтє IηƖιηє` *Hαѕ Ɓєєη ƐηαвƖєɗ*🔇\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "بیصدا کردن کیبورد شیشه ای فعال شد🔇\n*توسط :* `"..msg.from.id.."`"
end
end
end
local function unmute_inline(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_inline = data[tostring(target)]["settings"]["mute_inline"]
if mute_inline == "no" then
if not lang then
return "`Mυтє IηƖιηє` *Iѕ AƖяєαɗу ƊιѕαвƖєɗ*⚠️🚫"
elseif lang then
return "بیصدا کردن کیبورد شیشه ای غیر فعال است⚠️🚫"
end
else
data[tostring(target)]["settings"]["mute_inline"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "`Mυтє IηƖιηє` *Hαѕ Ɓєєη ƊιѕαвƖєɗ*🔊\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "بیصدا کردن کیبورد شیشه ای غیر فعال شد🔊\n*توسط :* `"..msg.from.id.."`"
end
end
end
---------------Mute Text-------------------
local function mute_text(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_text = data[tostring(target)]["settings"]["mute_text"]
if mute_text == "yes" then
if not lang then
return "`Mυтє Ƭєxт` *Iѕ AƖяєαɗу ƐηαвƖєɗ*⚠️♻️"
elseif lang then
return "بیصدا کردن متن فعال است⚠️♻️"
end
else
data[tostring(target)]["settings"]["mute_text"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "`Mυтє Ƭєxт` *Hαѕ Ɓєєη ƐηαвƖєɗ*🔇\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "بیصدا کردن متن فعال شد🔇\n*توسط :* `"..msg.from.id.."`"
end
end
end
local function unmute_text(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_text = data[tostring(target)]["settings"]["mute_text"]
if mute_text == "no" then
if not lang then
return "`Mυтє Ƭєxт` *Iѕ AƖяєαɗу ƊιѕαвƖєɗ*⚠️🚫"
elseif lang then
return "بیصدا کردن متن غیر فعال است⚠️🚫"
end
else
data[tostring(target)]["settings"]["mute_text"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "`Mυтє Ƭєxт` *Hαѕ Ɓєєη ƊιѕαвƖєɗ*🔊\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "بیصدا کردن متن غیر فعال شد🔊\n*توسط :* `"..msg.from.id.."`"
end
end
end
---------------Mute photo-------------------
local function mute_photo(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_photo = data[tostring(target)]["settings"]["mute_photo"]
if mute_photo == "yes" then
if not lang then
return "`Mυтє Ƥнσтσ` *Iѕ AƖяєαɗу ƐηαвƖєɗ*⚠️♻️"
elseif lang then
return "بیصدا کردن عکس فعال است⚠️♻️"
end
else
data[tostring(target)]["settings"]["mute_photo"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "`Mυтє Ƥнσтσ` *Hαѕ Ɓєєη ƐηαвƖєɗ*🔇\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "بیصدا کردن عکس فعال شد🔇\n*توسط :* `"..msg.from.id.."`"
end
end
end
local function unmute_photo(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_photo = data[tostring(target)]["settings"]["mute_photo"]
if mute_photo == "no" then
if not lang then
return "`Mυтє Ƥнσтσ` *Iѕ AƖяєαɗу ƊιѕαвƖєɗ*⚠️🚫"
elseif lang then
return "بیصدا کردن عکس غیر فعال است⚠️🚫"
end
else
data[tostring(target)]["settings"]["mute_photo"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "`Mυтє Ƥнσтσ` *Hαѕ Ɓєєη ƊιѕαвƖєɗ*🔊\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "بیصدا کردن عکس غیر فعال شد🔊\n*توسط :* `"..msg.from.id.."`"
end
end
end
---------------Mute Video-------------------
local function mute_video(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_video = data[tostring(target)]["settings"]["mute_video"]
if mute_video == "yes" then
if not lang then
return "`Mυтє Ʋιɗєσ` *Iѕ AƖяєαɗу ƐηαвƖєɗ*⚠️♻️"
elseif lang then
return "بیصدا کردن فیلم فعال است⚠️♻️"
end
else
data[tostring(target)]["settings"]["mute_video"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "`Mυтє Ʋιɗєσ` *Hαѕ Ɓєєη ƐηαвƖєɗ*🔇\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "بیصدا کردن فیلم فعال شد🔇\n*توسط :* `"..msg.from.id.."`"
end
end
end
local function unmute_video(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_video = data[tostring(target)]["settings"]["mute_video"]
if mute_video == "no" then
if not lang then
return "`Mυтє Ʋιɗєσ` *Iѕ AƖяєαɗу ƊιѕαвƖєɗ*⚠️🚫"
elseif lang then
return "بیصدا کردن فیلم غیر فعال است⚠️🚫"
end
else
data[tostring(target)]["settings"]["mute_video"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "`Mυтє Ʋιɗєσ` *Hαѕ Ɓєєη ƊιѕαвƖєɗ*🔊\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "بیصدا کردن فیلم غیر فعال شد🔊\n*توسط :* `"..msg.from.id.."`"
end
end
end
---------------Mute Audio-------------------
local function mute_audio(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_audio = data[tostring(target)]["settings"]["mute_audio"]
if mute_audio == "yes" then
if not lang then
return "`Mυтє Aυɗισ` *Iѕ AƖяєαɗу ƐηαвƖєɗ*⚠️♻️"
elseif lang then
return "بیصدا کردن آهنگ فعال است⚠️♻️"
end
else
data[tostring(target)]["settings"]["mute_audio"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "`Mυтє Aυɗισ` *Hαѕ Ɓєєη ƐηαвƖєɗ*🔇\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "بیصدا کردن آهنگ فعال شد🔇\n*توسط :* `"..msg.from.id.."`"
end
end
end
local function unmute_audio(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_audio = data[tostring(target)]["settings"]["mute_audio"]
if mute_audio == "no" then
if not lang then
return "`Mυтє Aυɗισ` *Iѕ AƖяєαɗу ƊιѕαвƖєɗ*⚠️🚫"
elseif lang then
return "بیصدا کردن آهنک غیر فعال است⚠️🚫"
end
else
data[tostring(target)]["settings"]["mute_audio"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "`Mυтє Aυɗισ` *Hαѕ Ɓєєη ƊιѕαвƖєɗ*🔊\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "بیصدا کردن آهنگ غیر فعال شد🔊\n*توسط :* `"..msg.from.id.."`"
end
end
end
---------------Mute Voice-------------------
local function mute_voice(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_voice = data[tostring(target)]["settings"]["mute_voice"]
if mute_voice == "yes" then
if not lang then
return "`Mυтє Ʋσιcє` *Iѕ AƖяєαɗу ƐηαвƖєɗ*⚠️♻️"
elseif lang then
return "بیصدا کردن صدا فعال است⚠️♻️"
end
else
data[tostring(target)]["settings"]["mute_voice"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "`Mυтє Ʋσιcє` *Hαѕ Ɓєєη ƐηαвƖєɗ*🔇\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "بیصدا کردن صدا فعال شد🔇\n*توسط :* `"..msg.from.id.."`"
end
end
end
local function unmute_voice(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_voice = data[tostring(target)]["settings"]["mute_voice"]
if mute_voice == "no" then
if not lang then
return "`Mυтє Ʋσιcє` *Iѕ AƖяєαɗу ƊιѕαвƖєɗ*⚠️🚫"
elseif lang then
return "بیصدا کردن صدا غیر فعال است⚠️🚫"
end
else
data[tostring(target)]["settings"]["mute_voice"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "`Mυтє Ʋσιcє` *Hαѕ Ɓєєη ƊιѕαвƖєɗ*🔊\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "بیصدا کردن صدا غیر فعال شد🔊\n*توسط :* `"..msg.from.id.."`"
end
end
end
---------------Mute Sticker-------------------
local function mute_sticker(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_sticker = data[tostring(target)]["settings"]["mute_sticker"]
if mute_sticker == "yes" then
if not lang then
return "`Mυтє Sтιcкєя` *Iѕ AƖяєαɗу ƐηαвƖєɗ*⚠️♻️"
elseif lang then
return "بیصدا کردن برچسب فعال است⚠️♻️"
end
else
data[tostring(target)]["settings"]["mute_sticker"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "`Mυтє Sтιcкєя` *Hαѕ Ɓєєη ƐηαвƖєɗ*🔇\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "بیصدا کردن برچسب فعال شد🔇\n*توسط :* `"..msg.from.id.."`"
end
end
end
local function unmute_sticker(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_sticker = data[tostring(target)]["settings"]["mute_sticker"]
if mute_sticker == "no" then
if not lang then
return "`Mυтє Sтιcкєя` *Iѕ AƖяєαɗу ƊιѕαвƖєɗ*⚠️🚫"
elseif lang then
return "بیصدا کردن برچسب غیر فعال است⚠️🚫"
end
else
data[tostring(target)]["settings"]["mute_sticker"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "`Mυтє Sтιcкєя` *Hαѕ Ɓєєη ƊιѕαвƖєɗ*🔊\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "بیصدا کردن برچسب غیر فعال شد🔊\n*توسط :* `"..msg.from.id.."`"
end
end
end
---------------Mute Contact-------------------
local function mute_contact(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_contact = data[tostring(target)]["settings"]["mute_contact"]
if mute_contact == "yes" then
if not lang then
return "`Mυтє Ƈσηтαcт` *Iѕ AƖяєαɗу ƐηαвƖєɗ*⚠️♻️"
elseif lang then
return "بیصدا کردن مخاطب فعال است⚠️♻️"
end
else
data[tostring(target)]["settings"]["mute_contact"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "`Mυтє Ƈσηтαcт` *Hαѕ Ɓєєη ƐηαвƖєɗ*🔇\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "بیصدا کردن مخاطب فعال شد🔇\n*توسط :* `"..msg.from.id.."`"
end
end
end
local function unmute_contact(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_contact = data[tostring(target)]["settings"]["mute_contact"]
if mute_contact == "no" then
if not lang then
return "`Mυтє Ƈσηтαcт` *Iѕ AƖяєαɗу ƊιѕαвƖєɗ*⚠️🚫"
elseif lang then
return "بیصدا کردن مخاطب غیر فعال است⚠️🚫"
end
else
data[tostring(target)]["settings"]["mute_contact"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "`Mυтє Ƈσηтαcт` *Hαѕ Ɓєєη ƊιѕαвƖєɗ*🔊\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "بیصدا کردن مخاطب غیر فعال شد🔊\n*توسط :* `"..msg.from.id.."`"
end
end
end
---------------Mute Forward-------------------
local function mute_forward(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_forward = data[tostring(target)]["settings"]["mute_forward"]
if mute_forward == "yes" then
if not lang then
return "`Mυтє Ƒσяωαяɗ` *Iѕ AƖяєαɗу ƐηαвƖєɗ*⚠️♻️"
elseif lang then
return "بیصدا کردن نقل قول فعال است⚠️♻️"
end
else
data[tostring(target)]["settings"]["mute_forward"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "`Mυтє Ƒσяωαяɗ` *Hαѕ Ɓєєη ƐηαвƖєɗ*🔇\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "بیصدا کردن نقل قول فعال شد🔇\n*توسط :* `"..msg.from.id.."`"
end
end
end
local function unmute_forward(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_forward = data[tostring(target)]["settings"]["mute_forward"]
if mute_forward == "no" then
if not lang then
return "`Mυтє Ƒσяωαяɗ` *Iѕ AƖяєαɗу ƊιѕαвƖєɗ*⚠️🚫"
elseif lang then
return "بیصدا کردن نقل قول غیر فعال است⚠️🚫"
end
else
data[tostring(target)]["settings"]["mute_forward"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "`Mυтє Ƒσяωαяɗ` *Hαѕ Ɓєєη ƊιѕαвƖєɗ*🔊\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "بیصدا کردن نقل قول غیر فعال شد🔊\n*توسط :* `"..msg.from.id.."`"
end
end
end
---------------Mute Location-------------------
local function mute_location(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_location = data[tostring(target)]["settings"]["mute_location"]
if mute_location == "yes" then
if not lang then
return "`Mυтє Lσcαтιση` *Iѕ AƖяєαɗу ƐηαвƖєɗ*⚠️♻️"
elseif lang then
return "بیصدا کردن موقعیت فعال است⚠️♻️"
end
else
data[tostring(target)]["settings"]["mute_location"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "`Mυтє Lσcαтιση` *Hαѕ Ɓєєη ƐηαвƖєɗ*🔇\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "بیصدا کردن موقعیت فعال شد🔇\n*توسط :* `"..msg.from.id.."`"
end
end
end
local function unmute_location(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_location = data[tostring(target)]["settings"]["mute_location"]
if mute_location == "no" then
if not lang then
return "`Mυтє Lσcαтιση` *Iѕ AƖяєαɗу ƊιѕαвƖєɗ*⚠️🚫"
elseif lang then
return "بیصدا کردن موقعیت غیر فعال است⚠️🚫"
end
else
data[tostring(target)]["settings"]["mute_location"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "`Mυтє Lσcαтιση` *Hαѕ Ɓєєη ƊιѕαвƖєɗ*🔊\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "بیصدا کردن موقعیت غیر فعال شد🔊\n*توسط :* `"..msg.from.id.."`"
end
end
end
---------------Mute Document-------------------
local function mute_document(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_document = data[tostring(target)]["settings"]["mute_document"]
if mute_document == "yes" then
if not lang then
return "`Mυтє Ɗσcυмєηт` *Iѕ AƖяєαɗу ƐηαвƖєɗ*⚠️♻️"
elseif lang then
return "بیصدا کردن اسناد فعال لست⚠️♻️"
end
else
data[tostring(target)]["settings"]["mute_document"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "`Mυтє Ɗσcυмєηт` *Hαѕ Ɓєєη ƐηαвƖєɗ*🔇\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "بیصدا کردن اسناد فعال شد🔇\n*توسط :* `"..msg.from.id.."`"
end
end
end
local function unmute_document(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_document = data[tostring(target)]["settings"]["mute_document"]
if mute_document == "no" then
if not lang then
return "`Mυтє Ɗσcυмєηт` *Iѕ AƖяєαɗу ƊιѕαвƖєɗ*⚠️🚫"
elseif lang then
return "بیصدا کردن اسناد غیر فعال است⚠️🚫"
end
else
data[tostring(target)]["settings"]["mute_document"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "`Mυтє Ɗσcυмєηт` *Hαѕ Ɓєєη ƊιѕαвƖєɗ*🔊\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "بیصدا کردن اسناد غیر فعال شد🔊\n*توسط :* `"..msg.from.id.."`"
end
end
end
---------------Mute TgService-------------------
local function mute_tgservice(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_tgservice = data[tostring(target)]["settings"]["mute_tgservice"]
if mute_tgservice == "yes" then
if not lang then
return "`Mυтє ƬgSєяνιcє` *Iѕ AƖяєαɗу ƐηαвƖєɗ*⚠️♻️"
elseif lang then
return "بیصدا کردن خدمات تلگرام فعال است⚠️♻️"
end
else
data[tostring(target)]["settings"]["mute_tgservice"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "`Mυтє ƬgSєяνιcє` *Hαѕ Ɓєєη ƐηαвƖєɗ*🔇\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "بیصدا کردن خدمات تلگرام فعال شد🔇\n*توسط :* `"..msg.from.id.."`"
end
end
end
local function unmute_tgservice(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نیستید"
end
end
local mute_tgservice = data[tostring(target)]["settings"]["mute_tgservice"]
if mute_tgservice == "no" then
if not lang then
return "`Mυтє ƬgSєяνιcє` *Iѕ AƖяєαɗу ƊιѕαвƖєɗ*⚠️🚫"
elseif lang then
return "بیصدا کردن خدمات تلگرام غیر فعال است⚠️🚫"
end
else
data[tostring(target)]["settings"]["mute_tgservice"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "`Mυтє ƬgSєяνιcє` *Hαѕ Ɓєєη ƊιѕαвƖєɗ*🔊\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "بیصدا کردن خدمات تلگرام غیر فعال شد🔊\n*توسط :* `"..msg.from.id.."`"
end
end
end
---------------Mute Keyboard-------------------
local function mute_keyboard(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local mute_keyboard = data[tostring(target)]["settings"]["mute_keyboard"]
if mute_keyboard == "yes" then
if not lang then
return "`Mυтє Ƙєувσαяɗ` *Iѕ AƖяєαɗу ƐηαвƖєɗ*⚠️♻️"
elseif lang then
return "بیصدا کردن صفحه کلید فعال است⚠️♻️"
end
else
data[tostring(target)]["settings"]["mute_keyboard"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "`Mυтє Ƙєувσαяɗ` *Hαѕ Ɓєєη ƐηαвƖєɗ*🔇\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "بیصدا کردن صفحه کلید فعال شد🔇\n*توسط :* `"..msg.from.id.."`"
end
end
end
local function unmute_keyboard(msg, data, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نیستید"
end
end
local mute_keyboard = data[tostring(target)]["settings"]["mute_keyboard"]
if mute_keyboard == "no" then
if not lang then
return "`Mυтє Ƙєувσαяɗ` *Iѕ AƖяєαɗу ƊιѕαвƖєɗ*⚠️🚫"
elseif lang then
return "بیصدا کردن صفحه کلید غیرفعال است⚠️🚫"
end
else
data[tostring(target)]["settings"]["mute_keyboard"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "`Mυтє Ƙєувσαяɗ` *Hαѕ Ɓєєη ƊιѕαвƖєɗ*🔊\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
else
return "بیصدا کردن صفحه کلید غیرفعال شد🔊\n*توسط :* `"..msg.from.id.."`"
end
end
end
function group_settings(msg, target)
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
local data = load_data(_config.moderation.data)
local target = msg.to.id
if not is_mod(msg) then
if not lang then
return "_You're Not_ *Moderator*"
else
return "شما مدیر گروه نمیباشید"
end
end
local data = load_data(_config.moderation.data)
local target = msg.to.id
if data[tostring(target)] then
if data[tostring(target)]["settings"]["num_msg_max"] then
NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['num_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
if data[tostring(target)]["settings"]["set_char"] then
SETCHAR = tonumber(data[tostring(target)]['settings']['set_char'])
print('custom'..SETCHAR)
else
SETCHAR = 40
end
if data[tostring(target)]["settings"]["time_check"] then
TIME_CHECK = tonumber(data[tostring(target)]['settings']['time_check'])
print('custom'..TIME_CHECK)
else
TIME_CHECK = 2
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_link"] then
data[tostring(target)]["settings"]["lock_link"] = "yes"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_tag"] then
data[tostring(target)]["settings"]["lock_tag"] = "yes"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_username"] then
data[tostring(target)]["settings"]["lock_username"] = "yes"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_mention"] then
data[tostring(target)]["settings"]["lock_mention"] = "no"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_arabic"] then
data[tostring(target)]["settings"]["lock_arabic"] = "no"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_edit"] then
data[tostring(target)]["settings"]["lock_edit"] = "no"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_spam"] then
data[tostring(target)]["settings"]["lock_spam"] = "yes"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_english"] then
data[tostring(target)]["settings"]["lock_english"] = "no"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_flood"] then
data[tostring(target)]["settings"]["lock_flood"] = "yes"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_bots"] then
data[tostring(target)]["settings"]["lock_bots"] = "yes"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_markdown"] then
data[tostring(target)]["settings"]["lock_markdown"] = "no"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_badword"] then
data[tostring(target)]["settings"]["lock_badword"] = "no"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_webpage"] then
data[tostring(target)]["settings"]["lock_webpage"] = "no"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_tabchi"] then
data[tostring(target)]["settings"]["lock_tabchi"] = "no"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["welcome"] then
data[tostring(target)]["settings"]["welcome"] = "no"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_pin"] then
data[tostring(target)]["settings"]["lock_pin"] = "no"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_join"] then
data[tostring(target)]["settings"]["lock_join"] = "no"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["mute_gif"] then
data[tostring(target)]["settings"]["mute_gif"] = "no"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["mute_text"] then
data[tostring(target)]["settings"]["mute_text"] = "no"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["mute_photo"] then
data[tostring(target)]["settings"]["mute_photo"] = "no"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["mute_video"] then
data[tostring(target)]["settings"]["mute_video"] = "no"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["mute_audio"] then
data[tostring(target)]["settings"]["mute_audio"] = "no"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["mute_voice"] then
data[tostring(target)]["settings"]["mute_voice"] = "no"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["mute_sticker"] then
data[tostring(target)]["settings"]["mute_sticker"] = "no"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["mute_contact"] then
data[tostring(target)]["settings"]["mute_contact"] = "no"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["mute_forward"] then
data[tostring(target)]["settings"]["mute_forward"] = "no"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["mute_location"] then
data[tostring(target)]["settings"]["mute_location"] = "no"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["mute_document"] then
data[tostring(target)]["settings"]["mute_document"] = "no"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["mute_tgservice"] then
data[tostring(target)]["settings"]["mute_tgservice"] = "no"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["mute_inline"] then
data[tostring(target)]["settings"]["mute_inline"] = "no"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["mute_game"] then
data[tostring(target)]["settings"]["mute_game"] = "no"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["mute_keyboard"] then
data[tostring(target)]["settings"]["mute_keyboard"] = "no"
end
end
local expire_date = ''
local expi = redis:ttl('ExpireDate:'..msg.to.id)
if expi == -1 then
if lang then
expire_date = 'نامحدود!'
else
expire_date = 'Unlimited!'
end
else
local day = math.floor(expi / 86400) + 1
if lang then
expire_date = day..' روز'
else
expire_date = day..' Days'
end
end
local cmdss = redis:hget('group:'..msg.to.id..':cmd', 'bot')
local cmdsss = ''
if lang then
if cmdss == 'owner' then
cmdsss = cmdsss..'اونر و بالاتر'
elseif cmdss == 'moderator' then
cmdsss = cmdsss..'مدیر و بالاتر'
else
cmdsss = cmdsss..'کاربر و بالاتر'
end
else
if cmdss == 'owner' then
cmdsss = cmdsss..'Owner or higher'
elseif cmdss == 'moderator' then
cmdsss = cmdsss..'Moderator or higher'
else
cmdsss = cmdsss..'Member or higher'
end
end
local hash = "muteall:"..msg.to.id
local check_time = redis:ttl(hash)
day = math.floor(check_time / 86400)
bday = check_time % 86400
hours = math.floor( bday / 3600)
bhours = bday % 3600
min = math.floor(bhours / 60)
sec = math.floor(bhours % 60)
if not lang then
if not redis:get(hash) or check_time == -1 then
mute_all1 = 'no'
elseif tonumber(check_time) > 1 and check_time < 60 then
mute_all1 = '_enable for_ *'..sec..'* _sec_'
elseif tonumber(check_time) > 60 and check_time < 3600 then
mute_all1 = '_enable for_ '..min..' _min_ *'..sec..'* _sec_'
elseif tonumber(check_time) > 3600 and tonumber(check_time) < 86400 then
mute_all1 = '_enable for_ *'..hours..'* _hour_ *'..min..'* _min_ *'..sec..'* _sec_'
elseif tonumber(check_time) > 86400 then
mute_all1 = '_enable for_ *'..day..'* _day_ *'..hours..'* _hour_ *'..min..'* _min_ *'..sec..'* _sec_'
end
elseif lang then
if not redis:get(hash) or check_time == -1 then
mute_all2 = '*no*'
elseif tonumber(check_time) > 1 and check_time < 60 then
mute_all2 = '_فعال برای_ *'..sec..'* _ثانیه_'
elseif tonumber(check_time) > 60 and check_time < 3600 then
mute_all2 = '_فعال برای_ *'..min..'* _دقیقه و_ *'..sec..'* _ثانیه_'
elseif tonumber(check_time) > 3600 and tonumber(check_time) < 86400 then
mute_all2 = '_فعال برای_ *'..hours..'* _ساعت و_ *'..min..'* _دقیقه و_ *'..sec..'* _ثانیه_'
elseif tonumber(check_time) > 86400 then
mute_all2 = '_فعال برای_ *'..day..'* _روز و_ *'..hours..'* _ساعت و_ *'..min..'* _دقیقه و_ *'..sec..'* _ثانیه_'
end
end
if not lang then
local settings = data[tostring(target)]["settings"]
text = "*̅G̅ʀ̅օ̅ʊ̅ք̅ ̅S̅ɛ̅ȶ̅ȶ̅ɨ̅ռ̅ɢ̅ֆ:*\n*̅ʟ̅օ̅ƈ̅ӄ̅ ̅ɛ̅ɖ̅ɨ̅ȶ:* "..settings.lock_edit.."\n*̅ʟ̅օ̅ƈ̅ӄ̅ ̅ʟ̅ɨ̅ռ̅ӄ̅ֆ :* "..settings.lock_link.."\n*̅ʟ̅օ̅ƈ̅ӄ̅ ̅ȶ̅ǟ̅ɢ̅ֆ :* "..settings.lock_tag.."\n*̅ʟ̅օ̅ƈ̅ӄ̅ ̅ʝ̅օ̅ɨ̅ռ :* "..settings.lock_join.."\n*̅ʟ̅օ̅ƈ̅ӄ̅ ̅ʄ̅ʟ̅օ̅օ̅ɖ :* "..settings.lock_flood.."\n*̅ʟ̅օ̅ƈ̅ӄ̅ ̅ʊ̅ֆ̅ɛ̅ʀ̅ռ̅ǟ̅ʍ̅ɛ :* "..settings.lock_username.."\n*̅ʟ̅օ̅ƈ̅ӄ̅ ̅ֆ̅ք̅ǟ̅ʍ :* "..settings.lock_spam.."\n*̅ʟ̅օ̅ƈ̅ӄ̅ ̅ʍ̅ɛ̅ռ̅ȶ̅ɨ̅օ̅ռ :* "..settings.lock_mention.."\n*̅ʟ̅օ̅ƈ̅ӄ̅ ̅ɛ̅ռ̅ɢ̅ʟ̅ɨ̅ֆ̅ɦ :* "..settings.lock_english.."\n*̅ʟ̅օ̅ƈ̅ӄ̅ ̅ǟ̅ʀ̅ǟ̅ɮ̅ɨ̅ƈ: :* "..settings.lock_arabic.."\n*̅ʟ̅օ̅ƈ̅ӄ̅ ̅ա̅ɛ̅ɮ̅ք̅ǟ̅ɢ̅ɛ :* "..settings.lock_webpage.."\n*̅ʟ̅օ̅ƈ̅ӄ̅ ̅ɮ̅ǟ̅ɖ̅ա̅օ̅ʀ̅ɖ :* "..settings.lock_badword.."\n*̅ʟ̅օ̅ƈ̅ӄ̅ ̅ʍ̅ǟ̅ʀ̅ӄ̅ɖ̅օ̅ա̅ռ :* "..settings.lock_markdown.."\n*̅ʟ̅օ̅ƈ̅ӄ̅ ̅ȶ̅ǟ̅ɮ̅ƈ̅ɦ̅ɨ :* "..settings.lock_tabchi.."\n*̅G̅ʀ̅օ̅ʊ̅ք̅ ̅ա̅ɛ̅ʟ̅ƈ̅օ̅ʍ̅ɛ :* "..settings.welcome.."\n*̅L̅օ̅ƈ̅ӄ̅ ̅ք̅ɨ̅ռ̅ ̅ʍ̅ɛ̅ֆ̅ֆ̅ǟ̅ɢ̅ɛ :* "..settings.lock_pin.."\n*̅B̅օ̅ȶ̅ֆ̅ ̅ք̅ʀ̅օ̅ȶ̅ɛ̅ƈ̅ȶ̅ɨ̅օ̅ռ :* "..settings.lock_bots.."\n*̅F̅ʟ̅օ̅օ̅ɖ̅ ̅ֆ̅ɛ̅ռ̅ֆ̅ɨ̅ȶ̅ɨ̅ʋ̅ɨ̅ȶ̅ʏ :* *"..NUM_MSG_MAX.."*\n*̅C̅ɦ̅ǟ̅ʀ̅ǟ̅ƈ̅ȶ̅ɛ̅ʀ̅ ̅ֆ̅ɛ̅ռ̅ֆ̅ɨ̅ȶ̅ɨ̅ʋ̅ɨ̅ȶ̅ʏ :* *"..SETCHAR.."*\n*̅F̅ℓ̅σ̅σ̅đ̅ ̅ƈ̅ɧ̅ε̅ƈ̅ҡ̅ ̅ŧ̅ï̅ɱ̅ε :* *"..TIME_CHECK.."*\n➖➖➖➖➖➖➖➖➖\n*̅G̅ŗ̅σ̅ų̅þ̅ ̅M̅ų̅ŧ̅ε̅ ̅L̅ï̅ş̅ŧ* : \n*̅M̅ų̅ŧ̅ε̅ ̅ɠ̅ï̅∱ :* "..settings.mute_gif.."\n*̅M̅ų̅ŧ̅ε̅ ̅ŧ̅ε̅х̅ŧ :* "..settings.mute_text.."\n*̅M̅ų̅ŧ̅ε̅ ̅ï̅ŋ̅ℓ̅ï̅ŋ̅ε :* "..settings.mute_inline.."\n*̅M̅ų̅ŧ̅ε̅ ̅ɠ̅ą̅ɱ̅ε :* "..settings.mute_game.."\n*̅M̅ų̅ŧ̅ε̅ ̅þ̅ɧ̅σ̅ŧ̅σ :* "..settings.mute_photo.."\n*̅M̅ų̅ŧ̅ε̅ ̅√̅ï̅đ̅ε̅σ :* "..settings.mute_video.."\n*̅M̅ų̅ŧ̅ε̅ ̅ą̅ų̅đ̅ï̅σ :* "..settings.mute_audio.."\n*̅M̅ų̅ŧ̅ε̅ ̅√̅σ̅ï̅ƈ̅ε :* "..settings.mute_voice.."\n*̅M̅ų̅ŧ̅ε̅ ̅ş̅ŧ̅ï̅ƈ̅ҡ̅ε̅ŗ :* "..settings.mute_sticker.."\n*̅M̅ų̅ŧ̅ε̅ ̅ƈ̅σ̅ŋ̅ŧ̅ą̅ƈ̅ŧ :* "..settings.mute_contact.."\n*̅M̅ų̅ŧ̅ε̅ ̅∱̅σ̅ŗ̅щ̅ą̅ŗ̅đ :* "..settings.mute_forward.."\n*̅M̅ų̅ŧ̅ε̅ ̅ℓ̅σ̅ƈ̅ą̅ŧ̅ï̅σ̅ŋ :* "..settings.mute_location.."\n*̅M̅ų̅ŧ̅ε̅ ̅đ̅σ̅ƈ̅ų̅ɱ̅ε̅ŋ̅ŧ :* "..settings.mute_document.."\n*̅M̅ų̅ŧ̅ε̅ ̅T̅ɠ̅S̅ε̅ŗ̅√̅ï̅ƈ̅ε :* "..settings.mute_tgservice.."\n*̅M̅ų̅ŧ̅ε̅ ̅K̅ε̅γ̅ɓ̅σ̅ą̅ŗ̅đ :* "..settings.mute_keyboard.."\n*̅M̅ų̅ŧ̅ε̅ ̅A̅ℓ̅ℓ :* "..mute_all1.."\n➖➖➖➖➖➖➖➖➖\n*̅E̅х̅þ̅ï̅ŗ̅ε̅ ̅D̅ą̅ŧ̅ε :* *"..expire_date.."*\n*̅B̅σ̅ŧ̅ ̅C̅σ̅ɱ̅ɱ̅ą̅ŋ̅đ̅ş :* *"..cmdsss.."*\n*̅B̅σ̅ŧ̅ ̅ƈ̅ɧ̅ą̅ŋ̅ŋ̅ε̅ℓ:* @ProtectionTeam\n*̅G̅ŗ̅σ̅ų̅þ̅ ̅L̅ą̅ŋ̅ɠ̅ų̅ą̅ɠ̅ε:* *̅E̅N*"
else
local settings = data[tostring(target)]["settings"]
text = "*تنظیمات گروه:*\n_قفل ویرایش پیام :_ "..settings.lock_edit.."\n_قفل لینک :_ "..settings.lock_link.."\n_قفل ورود :_ "..settings.lock_join.."\n_قفل تگ :_ "..settings.lock_tag.."\n_قفل پیام مکرر :_ "..settings.lock_flood.."\n_قفل یوزرنیم :_ "..settings.lock_username.."\n_قفل هرزنامه :_ "..settings.lock_spam.."\n_قفل فراخوانی :_ "..settings.lock_mention.."\n_قفل انگلیسی :_ "..settings.lock_english.."\n_قفل عربی :_ "..settings.lock_arabic.."\n_قفل صفحات وب :_ "..settings.lock_webpage.."\n_قفل فحش :_ "..settings.lock_badword.."\n_قفل فونت :_ "..settings.lock_markdown.."\n_قفل تبچی :_ "..settings.lock_tabchi.."\n_پیام خوشآمد گویی :_ "..settings.welcome.."\n_قفل سنجاق کردن :_ "..settings.lock_pin.."\n_محافظت در برابر ربات ها :_ "..settings.lock_bots.."\n_حداکثر پیام مکرر :_ *"..NUM_MSG_MAX.."*\n_حداکثر حروف مجاز :_ *"..SETCHAR.."*\n_زمان بررسی پیام های مکرر :_ *"..TIME_CHECK.."*\n➖➖➖➖➖➖➖➖➖\n*لیست بیصدا ها* : \n_بیصدا تصاویر متحرک :_ "..settings.mute_gif.."\n_بیصدا متن :_ "..settings.mute_text.."\n_بیصدا کیبورد شیشه ای :_ "..settings.mute_inline.."\n_بیصدا بازی های تحت وب :_ "..settings.mute_game.."\n_بیصدا عکس :_ "..settings.mute_photo.."\n_بیصدا فیلم :_ "..settings.mute_video.."\n_بیصدا آهنگ :_ "..settings.mute_audio.."\n_بیصدا صدا :_ "..settings.mute_voice.."\n_بیصدا برچسب :_ "..settings.mute_sticker.."\n_بیصدا مخاطب :_ "..settings.mute_contact.."\n_بیصدا نقل قول :_ "..settings.mute_forward.."\n_بیصدا موقعیت :_ "..settings.mute_location.."\n_بیصدا اسناد :_ "..settings.mute_document.."\n_بیصدا خدمات تلگرام :_ "..settings.mute_tgservice.."\n_بیصدا صفحه کلید :_ "..settings.mute_keyboard.."\n_بیصدا همه پیام ها :_ "..mute_all2.."\n*____________________*\n_دستورات ربات :_ *"..cmdsss.."*\n_تاریخ انقضا :_ *"..expire_date.."*\n*کانال ربات*: @ProtectionTeam\n_زبان سوپر گروه :_ `فارسی`"
end
text = string.gsub(text, 'yes', '🔒')
text = string.gsub(text, 'no', '🔓')
return text
end
local function run(msg, matches)
if is_banned(msg.from.id, msg.to.id) or is_gbanned(msg.from.id, msg.to.id) or is_silent_user(msg.from.id, msg.to.id) then
return false
end
local cmd = redis:hget('group:'..msg.to.id..':cmd', 'bot')
local mutealll = redis:get('group:'..msg.to.id..':muteall')
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
local data = load_data(_config.moderation.data)
local chat = msg.to.id
local user = msg.from.id
if cmd == 'moderator' and not is_mod(msg) or cmd == 'owner' and not is_owner(msg) or mutealll and not is_mod(msg) then
return
else
if msg.to.type ~= 'pv' then
if matches[1]:lower() == "id" or matches[1] == 'ایدی' then
if not matches[2] and not msg.reply_id then
local function getpro(arg, data)
if data.photos_[0] then
if not lang then
tdcli.sendPhoto(msg.chat_id_, msg.id_, 0, 1, nil, data.photos_[0].sizes_[1].photo_.persistent_id_,'Chat ID : '..msg.to.id..'\nUser ID : '..msg.from.id,dl_cb,nil)
elseif lang then
tdcli.sendPhoto(msg.chat_id_, msg.id_, 0, 1, nil, data.photos_[0].sizes_[1].photo_.persistent_id_,'شناسه گروه : '..msg.to.id..'\nشناسه شما : '..msg.from.id,dl_cb,nil)
end
else
if not lang then
tdcli.sendMessage(msg.to.id, msg.id_, 1, "`You Have Not Profile Photo...!`\n\n> *Chat ID :* `"..msg.to.id.."`\n*User ID :* `"..msg.from.id.."`", 1, 'md')
elseif lang then
tdcli.sendMessage(msg.to.id, msg.id_, 1, "_شما هیچ عکسی ندارید...!_\n\n> _شناسه گروه :_ `"..msg.to.id.."`\n_شناسه شما :_ `"..msg.from.id.."`", 1, 'md')
end
end
end
tdcli_function ({
ID = "GetUserProfilePhotos",
user_id_ = msg.from.id,
offset_ = 0,
limit_ = 1
}, getpro, nil)
end
if msg.reply_id and not matches[2] then
tdcli.getMessage(msg.to.id, msg.reply_id, action_by_reply, {chat_id=msg.to.id,cmd="id"})
end
if matches[2] and #matches[2] > 3 and not matches[3] then
tdcli_function ({
ID = "SearchPublicChat",
username_ = matches[2]
}, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="id"})
end
end
if (matches[1]:lower() == "pin" or matches[1] == 'سنجاق') and is_mod(msg) and msg.reply_id then
local lock_pin = data[tostring(msg.to.id)]["settings"]["lock_pin"]
if lock_pin == 'yes' then
if is_owner(msg) then
data[tostring(chat)]['pin'] = msg.reply_id
save_data(_config.moderation.data, data)
tdcli.pinChannelMessage(msg.to.id, msg.reply_id, 1)
if not lang then
return "*Message Has Been Pinned*"
elseif lang then
return "پیام سجاق شد"
end
elseif not is_owner(msg) then
return
end
elseif lock_pin == 'no' then
data[tostring(chat)]['pin'] = msg.reply_id
save_data(_config.moderation.data, data)
tdcli.pinChannelMessage(msg.to.id, msg.reply_id, 1)
if not lang then
return "*Message Has Been Pinned*"
elseif lang then
return "پیام سجاق شد"
end
end
end
if (matches[1]:lower() == 'unpin' or matches[1] == 'حذف سنجاق') and is_mod(msg) then
local lock_pin = data[tostring(msg.to.id)]["settings"]["lock_pin"]
if lock_pin == 'yes' then
if is_owner(msg) then
tdcli.unpinChannelMessage(msg.to.id)
if not lang then
return "*Pin message has been unpinned*"
elseif lang then
return "پیام سنجاق شده پاک شد"
end
elseif not is_owner(msg) then
return
end
elseif lock_pin == 'no' then
tdcli.unpinChannelMessage(msg.to.id)
if not lang then
return "*Pin message has been unpinned*"
elseif lang then
return "پیام سنجاق شده پاک شد"
end
end
end
if matches[1]:lower() == "add" or matches[1] == 'افزودن' then
return modadd(msg)
end
if matches[1]:lower() == "rem" or matches[1] == 'حذف گروه' then
return modrem(msg)
end
if (matches[1]:lower() == "setmanager" or matches[1] == 'ادمین گروه') and is_owner(msg) then
if not matches[2] and msg.reply_id then
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.to.id,
message_id_ = msg.reply_id
}, action_by_reply, {chat_id=msg.to.id,cmd="setmanager"})
end
if matches[2] and string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "GetUser",
user_id_ = matches[2],
}, action_by_id, {chat_id=msg.to.id,user_id=matches[2],cmd="setmanager"})
end
if matches[2] and not string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "SearchPublicChat",
username_ = matches[2]
}, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="setmanager"})
end
end
if (matches[1]:lower() == "remmanager" or matches[1] == 'حذف ادمین گروه') and is_owner(msg) then
if not matches[2] and msg.reply_id then
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.to.id,
message_id_ = msg.reply_id
}, action_by_reply, {chat_id=msg.to.id,cmd="remmanager"})
end
if matches[2] and string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "GetUser",
user_id_ = matches[2],
}, action_by_id, {chat_id=msg.to.id,user_id=matches[2],cmd="remmanager"})
end
if matches[2] and not string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "SearchPublicChat",
username_ = matches[2]
}, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="remmanager"})
end
end
if (matches[1]:lower() == "whitelist" or matches[1] == 'لیست سفید') and matches[2] == "+" and is_mod(msg) then
if not matches[3] and msg.reply_id then
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.to.id,
message_id_ = msg.reply_id
}, action_by_reply, {chat_id=msg.to.id,cmd="setwhitelist"})
end
if matches[3] and string.match(matches[3], '^%d+$') then
tdcli_function ({
ID = "GetUser",
user_id_ = matches[3],
}, action_by_id, {chat_id=msg.to.id,user_id=matches[3],cmd="setwhitelist"})
end
if matches[3] and not string.match(matches[3], '^%d+$') then
tdcli_function ({
ID = "SearchPublicChat",
username_ = matches[3]
}, action_by_username, {chat_id=msg.to.id,username=matches[3],cmd="setwhitelist"})
end
end
if (matches[1]:lower() == "whitelist" or matches[1] == 'لیست سفید') and matches[2] == "-" and is_mod(msg) then
if not matches[3] and msg.reply_id then
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.to.id,
message_id_ = msg.reply_id
}, action_by_reply, {chat_id=msg.to.id,cmd="remwhitelist"})
end
if matches[3] and string.match(matches[3], '^%d+$') then
tdcli_function ({
ID = "GetUser",
user_id_ = matches[3],
}, action_by_id, {chat_id=msg.to.id,user_id=matches[3],cmd="remwhitelist"})
end
if matches[3] and not string.match(matches[3], '^%d+$') then
tdcli_function ({
ID = "SearchPublicChat",
username_ = matches[3]
}, action_by_username, {chat_id=msg.to.id,username=matches[3],cmd="remwhitelist"})
end
end
if (matches[1]:lower() == "setowner" or matches[1] == 'مالک') and is_admin(msg) then
if not matches[2] and msg.reply_id then
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.to.id,
message_id_ = msg.reply_id
}, action_by_reply, {chat_id=msg.to.id,cmd="setowner"})
end
if matches[2] and string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "GetUser",
user_id_ = matches[2],
}, action_by_id, {chat_id=msg.to.id,user_id=matches[2],cmd="setowner"})
end
if matches[2] and not string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "SearchPublicChat",
username_ = matches[2]
}, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="setowner"})
end
end
if (matches[1]:lower() == "remowner" or matches[1] == 'حذف مالک') and is_admin(msg) then
if not matches[2] and msg.reply_id then
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.to.id,
message_id_ = msg.reply_id
}, action_by_reply, {chat_id=msg.to.id,cmd="remowner"})
end
if matches[2] and string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "GetUser",
user_id_ = matches[2],
}, action_by_id, {chat_id=msg.to.id,user_id=matches[2],cmd="remowner"})
end
if matches[2] and not string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "SearchPublicChat",
username_ = matches[2]
}, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="remowner"})
end
end
if (matches[1]:lower() == "promote" or matches[1] == 'مدیر') and is_owner(msg) then
if not matches[2] and msg.reply_id then
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.to.id,
message_id_ = msg.reply_id
}, action_by_reply, {chat_id=msg.to.id,cmd="promote"})
end
if matches[2] and string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "GetUser",
user_id_ = matches[2],
}, action_by_id, {chat_id=msg.to.id,user_id=matches[2],cmd="promote"})
end
if matches[2] and not string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "SearchPublicChat",
username_ = matches[2]
}, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="promote"})
end
end
if (matches[1]:lower() == "demote" or matches[1] == 'حذف مدیر') and is_owner(msg) then
if not matches[2] and msg.reply_id then
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.to.id,
message_id_ = msg.reply_id
}, action_by_reply, {chat_id=msg.to.id,cmd="demote"})
end
if matches[2] and string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "GetUser",
user_id_ = matches[2],
}, action_by_id, {chat_id=msg.to.id,user_id=matches[2],cmd="demote"})
end
if matches[2] and not string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "SearchPublicChat",
username_ = matches[2]
}, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="demote"})
end
end
if (matches[1]:lower() == "lock" or matches[1] == 'قفل') and is_mod(msg) then
local target = msg.to.id
if not lang then
if matches[2] == "link" then
return lock_link(msg, data, target)
end
if matches[2] == "tag" then
return lock_tag(msg, data, target)
end
if matches[2] == 'username' then
return lock_username(msg, data, target)
end
if matches[2] == "mention" then
return lock_mention(msg, data, target)
end
if matches[2] == "arabic" then
return lock_arabic(msg, data, target)
end
if matches[2] == 'english' then
return lock_english(msg, data, target)
end
if matches[2] == "edit" then
return lock_edit(msg, data, target)
end
if matches[2] == "spam" then
return lock_spam(msg, data, target)
end
if matches[2] == "flood" then
return lock_flood(msg, data, target)
end
if matches[2] == 'tabchi' then
return lock_tabchi(msg, data, target)
end
if matches[2] == "bots" then
return lock_bots(msg, data, target)
end
if matches[2] == "markdown" then
return lock_markdown(msg, data, target)
end
if matches[2] == "webpage" then
return lock_webpage(msg, data, target)
end
if matches[2] == 'badword' then
return lock_badword(msg, data, target)
end
if matches[2] == "pin" and is_owner(msg) then
return lock_pin(msg, data, target)
end
if matches[2] == "join" then
return lock_join(msg, data, target)
end
if matches[2] == 'cmds' then
redis:hset('group:'..msg.to.id..':cmd', 'bot', 'moderator')
return 'cmds has been locked for member'
end
else
if matches[2] == 'لینک' then
return lock_link(msg, data, target)
end
if matches[2] == 'تگ' then
return lock_tag(msg, data, target)
end
if matches[2] == 'یوزرنیم' then
return lock_username(msg, data, target)
end
if matches[2] == 'فراخوانی' then
return lock_mention(msg, data, target)
end
if matches[2] == 'عربی' then
return lock_arabic(msg, data, target)
end
if matches[2] == 'انگلیسی' then
return lock_english(msg, data, target)
end
if matches[2] == 'ویرایش' then
return lock_edit(msg, data, target)
end
if matches[2] == 'هرزنامه' then
return lock_spam(msg, data, target)
end
if matches[2] == 'پیام مکرر' then
return lock_flood(msg, data, target)
end
if matches[2] == 'تبچی' then
return lock_tabchi(msg, data, target)
end
if matches[2] == 'ربات' then
return lock_bots(msg, data, target)
end
if matches[2] == 'فونت' then
return lock_markdown(msg, data, target)
end
if matches[2] == 'وب' then
return lock_webpage(msg, data, target)
end
if matches[2] == 'فحش' then
return lock_badword(msg, data, target)
end
if matches[2] == 'سنجاق' and is_owner(msg) then
return lock_pin(msg, data, target)
end
if matches[2] == "ورود" then
return lock_join(msg, data, target)
end
if matches[2] == 'دستورات' then
redis:hset('group:'..msg.to.id..':cmd', 'bot', 'moderator')
return 'دستورات برای کاربر عادی قفل شد'
end
end
end
if (matches[1]:lower() == "unlock" or matches[1] == 'باز') and is_mod(msg) then
local target = msg.to.id
if not lang then
if matches[2] == "link" then
return unlock_link(msg, data, target)
end
if matches[2] == "tag" then
return unlock_tag(msg, data, target)
end
if matches[2] == 'username' then
return unlock_username(msg, data, target)
end
if matches[2] == "mention" then
return unlock_mention(msg, data, target)
end
if matches[2] == "arabic" then
return unlock_arabic(msg, data, target)
end
if matches[2] == 'english' then
return unlock_english(msg, data, target)
end
if matches[2] == "edit" then
return unlock_edit(msg, data, target)
end
if matches[2] == "spam" then
return unlock_spam(msg, data, target)
end
if matches[2] == "flood" then
return unlock_flood(msg, data, target)
end
if matches[2] == 'tabchi' then
return unlock_tabchi(msg, data, target)
end
if matches[2] == "bots" then
return unlock_bots(msg, data, target)
end
if matches[2] == "markdown" then
return unlock_markdown(msg, data, target)
end
if matches[2] == "webpage" then
return unlock_webpage(msg, data, target)
end
if matches[2] == 'badword' then
return unlock_badword(msg, data, target)
end
if matches[2] == "pin" and is_owner(msg) then
return unlock_pin(msg, data, target)
end
if matches[2] == "join" then
return unlock_join(msg, data, target)
end
if matches[2] == 'cmds' then
redis:del('group:'..msg.to.id..':cmd')
return 'cmds has been unlocked for member'
end
else
if matches[2] == 'لینک' then
return unlock_link(msg, data, target)
end
if matches[2] == 'تگ' then
return unlock_tag(msg, data, target)
end
if matches[2] == 'یوزرنیم' then
return unlock_username(msg, data, target)
end
if matches[2] == 'فراخوانی' then
return unlock_mention(msg, data, target)
end
if matches[2] == 'عربی' then
return unlock_arabic(msg, data, target)
end
if matches[2] == 'انگلیسی' then
return unlock_english(msg, data, target)
end
if matches[2] == 'ویرایش' then
return unlock_edit(msg, data, target)
end
if matches[2] == 'هرزنامه' then
return unlock_spam(msg, data, target)
end
if matches[2] == 'پیام مکرر' then
return unlock_flood(msg, data, target)
end
if matches[2] == 'تبچی' then
return unlock_tabchi(msg, data, target)
end
if matches[2] == 'ربات' then
return unlock_bots(msg, data, target)
end
if matches[2] == 'فونت' then
return unlock_markdown(msg, data, target)
end
if matches[2] == 'وب' then
return unlock_webpage(msg, data, target)
end
if matches[2] == 'فحش' then
return unlock_badword(msg, data, target)
end
if matches[2] == 'سنجاق' and is_owner(msg) then
return unlock_pin(msg, data, target)
end
if matches[2] == "ورود" then
return unlock_join(msg, data, target)
end
if matches[2] == 'دستورات' then
redis:del('group:'..msg.to.id..':cmd')
return 'دستورات برای کاربر عادی باز شد'
end
end
end
if (matches[1]:lower() == "mute" or matches[1] == 'بیصدا') and is_mod(msg) then
local target = msg.to.id
if not lang then
if matches[2] == "gif" then
return mute_gif(msg, data, target)
end
if matches[2] == "text" then
return mute_text(msg ,data, target)
end
if matches[2] == "photo" then
return mute_photo(msg ,data, target)
end
if matches[2] == "video" then
return mute_video(msg ,data, target)
end
if matches[2] == "audio" then
return mute_audio(msg ,data, target)
end
if matches[2] == "voice" then
return mute_voice(msg ,data, target)
end
if matches[2] == "sticker" then
return mute_sticker(msg ,data, target)
end
if matches[2] == "contact" then
return mute_contact(msg ,data, target)
end
if matches[2] == "forward" then
return mute_forward(msg ,data, target)
end
if matches[2] == "location" then
return mute_location(msg ,data, target)
end
if matches[2] == "document" then
return mute_document(msg ,data, target)
end
if matches[2] == "tgservice" then
return mute_tgservice(msg ,data, target)
end
if matches[2] == "inline" then
return mute_inline(msg ,data, target)
end
if matches[2] == "game" then
return mute_game(msg ,data, target)
end
if matches[2] == "keyboard" then
return mute_keyboard(msg ,data, target)
end
if matches[2] == 'all' then
local hash = 'muteall:'..msg.to.id
redis:set(hash, true)
return "*Mute All* *Hαѕ Ɓєєη ƐηαвƖєɗ*🔇\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
end
else
if matches[2] == 'تصاویر متحرک' then
return mute_gif(msg, data, target)
end
if matches[2] == 'متن' then
return mute_text(msg ,data, target)
end
if matches[2] == 'عکس' then
return mute_photo(msg ,data, target)
end
if matches[2] == 'فیلم' then
return mute_video(msg ,data, target)
end
if matches[2] == 'اهنگ' then
return mute_audio(msg ,data, target)
end
if matches[2] == 'صدا' then
return mute_voice(msg ,data, target)
end
if matches[2] == 'برچسب' then
return mute_sticker(msg ,data, target)
end
if matches[2] == 'مخاطب' then
return mute_contact(msg ,data, target)
end
if matches[2] == 'نقل قول' then
return mute_forward(msg ,data, target)
end
if matches[2] == 'موقعیت' then
return mute_location(msg ,data, target)
end
if matches[2] == 'اسناد' then
return mute_document(msg ,data, target)
end
if matches[2] == 'خدمات تلگرام' then
return mute_tgservice(msg ,data, target)
end
if matches[2] == 'کیبورد شیشه ای' then
return mute_inline(msg ,data, target)
end
if matches[2] == 'بازی' then
return mute_game(msg ,data, target)
end
if matches[2] == 'صفحه کلید' then
return mute_keyboard(msg ,data, target)
end
if matches[2]== 'همه' then
local hash = 'muteall:'..msg.to.id
redis:set(hash, true)
return "بیصدا کردن گروه فعال شد"
end
end
end
if (matches[1]:lower() == "unmute" or matches[1] == 'باصدا') and is_mod(msg) then
local target = msg.to.id
if not lang then
if matches[2] == "gif" then
return unmute_gif(msg, data, target)
end
if matches[2] == "text" then
return unmute_text(msg, data, target)
end
if matches[2] == "photo" then
return unmute_photo(msg ,data, target)
end
if matches[2] == "video" then
return unmute_video(msg ,data, target)
end
if matches[2] == "audio" then
return unmute_audio(msg ,data, target)
end
if matches[2] == "voice" then
return unmute_voice(msg ,data, target)
end
if matches[2] == "sticker" then
return unmute_sticker(msg ,data, target)
end
if matches[2] == "contact" then
return unmute_contact(msg ,data, target)
end
if matches[2] == "forward" then
return unmute_forward(msg ,data, target)
end
if matches[2] == "location" then
return unmute_location(msg ,data, target)
end
if matches[2] == "document" then
return unmute_document(msg ,data, target)
end
if matches[2] == "tgservice" then
return unmute_tgservice(msg ,data, target)
end
if matches[2] == "inline" then
return unmute_inline(msg ,data, target)
end
if matches[2] == "game" then
return unmute_game(msg ,data, target)
end
if matches[2] == "keyboard" then
return unmute_keyboard(msg ,data, target)
end
if matches[2] == 'all' then
local hash = 'muteall:'..msg.to.id
redis:del(hash)
return "*Mute All* *Hαѕ Ɓєєη ƊιѕαвƖєɗ*🔊\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
end
else
if matches[2] == 'تصاویر متحرک' then
return unmute_gif(msg, data, target)
end
if matches[2] == 'متن' then
return unmute_text(msg, data, target)
end
if matches[2] == 'عکس' then
return unmute_photo(msg ,data, target)
end
if matches[2] == 'فیلم' then
return unmute_video(msg ,data, target)
end
if matches[2] == 'اهنگ' then
return unmute_audio(msg ,data, target)
end
if matches[2] == 'صدا' then
return unmute_voice(msg ,data, target)
end
if matches[2] == 'برچسب' then
return unmute_sticker(msg ,data, target)
end
if matches[2] == 'مخاطب' then
return unmute_contact(msg ,data, target)
end
if matches[2] == 'نقل قول' then
return unmute_forward(msg ,data, target)
end
if matches[2] == 'موقعیت' then
return unmute_location(msg ,data, target)
end
if matches[2] == 'اسناد' then
return unmute_document(msg ,data, target)
end
if matches[2] == 'خدمات تلگرام' then
return unmute_tgservice(msg ,data, target)
end
if matches[2] == 'کیبورد شیشه ای' then
return unmute_inline(msg ,data, target)
end
if matches[2] == 'بازی' then
return unmute_game(msg ,data, target)
end
if matches[2] == 'صفحه کلید' then
return unmute_keyboard(msg ,data, target)
end
if matches[2]=='همه' and is_mod(msg) then
local hash = 'muteall:'..msg.to.id
redis:del(hash)
return "گروه ازاد شد و افراد می توانند دوباره پست بگذارند"
end
end
end
if (matches[1]:lower() == 'cmds' or matches[1] == 'دستورات') and is_owner(msg) then
if not lang then
if matches[2]:lower() == 'owner' then
redis:hset('group:'..msg.to.id..':cmd', 'bot', 'owner')
return 'cmds set for owner or higher'
end
if matches[2]:lower() == 'moderator' then
redis:hset('group:'..msg.to.id..':cmd', 'bot', 'moderator')
return 'cmds set for moderator or higher'
end
if matches[2]:lower() == 'member' then
redis:hset('group:'..msg.to.id..':cmd', 'bot', 'member')
return 'cmds set for member or higher'
end
else
if matches[2] == 'مالک' then
redis:hset('group:'..msg.to.id..':cmd', 'bot', 'owner')
return 'دستورات برای مدیرکل به بالا دیگر جواب می دهد'
end
if matches[2] == 'مدیر' then
redis:hset('group:'..msg.to.id..':cmd', 'bot', 'moderator')
return 'دستورات برای مدیر به بالا دیگر جواب می دهد'
end
if matches[2] == 'کاربر' then
redis:hset('group:'..msg.to.id..':cmd', 'bot', 'member')
return 'دستورات برای کاربر عادی به بالا دیگر جواب می دهد'
end
end
end
if (matches[1]:lower() == "gpinfo" or matches[1] == 'اطلاعات گروه') and is_mod(msg) and msg.to.type == "channel" then
local function group_info(arg, data)
if not lang then
ginfo = "*Group Info :*\n_Admin Count :_ *"..data.administrator_count_.."*\n_Member Count :_ *"..data.member_count_.."*\n_Kicked Count :_ *"..data.kicked_count_.."*\n_Group ID :_ *"..data.channel_.id_.."*"
elseif lang then
ginfo = "*اطلاعات گروه :*\n_تعداد مدیران :_ *"..data.administrator_count_.."*\n_تعداد اعضا :_ *"..data.member_count_.."*\n_تعداد اعضای حذف شده :_ *"..data.kicked_count_.."*\n_شناسه گروه :_ *"..data.channel_.id_.."*"
end
tdcli.sendMessage(arg.chat_id, arg.msg_id, 1, ginfo, 1, 'md')
end
tdcli.getChannelFull(msg.to.id, group_info, {chat_id=msg.to.id,msg_id=msg.id})
end
if (matches[1]:lower() == 'newlink' or matches[1] == 'لینک جدید') and is_mod(msg) and not matches[2] then
local function callback_link (arg, data)
local administration = load_data(_config.moderation.data)
if not data.invite_link_ then
administration[tostring(msg.to.id)]['settings']['linkgp'] = nil
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(msg.to.id, msg.id, 1, "_Bot is not group creator_\n_set a link for group with using_ /setlink", 1, 'md')
elseif lang then
return tdcli.sendMessage(msg.to.id, msg.id, 1, "_ربات سازنده گروه نیست_\n_با دستور_ setlink/ _لینک جدیدی برای گروه ثبت کنید_", 1, 'md')
end
else
administration[tostring(msg.to.id)]['settings']['linkgp'] = data.invite_link_
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(msg.to.id, msg.id, 1, "*Newlink Created*", 1, 'md')
elseif lang then
return tdcli.sendMessage(msg.to.id, msg.id, 1, "_لینک جدید ساخته شد_", 1, 'md')
end
end
end
tdcli.exportChatInviteLink(msg.to.id, callback_link, nil)
end
if (matches[1]:lower() == 'newlink' or matches[1] == 'لینک جدید') and is_mod(msg) and (matches[2] == 'pv' or matches[2] == 'خصوصی') then
local function callback_link (arg, data)
local result = data.invite_link_
local administration = load_data(_config.moderation.data)
if not result then
administration[tostring(msg.to.id)]['settings']['linkgp'] = nil
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(msg.to.id, msg.id, 1, "_Bot is not group creator_\n_set a link for group with using_ /setlink", 1, 'md')
elseif lang then
return tdcli.sendMessage(msg.to.id, msg.id, 1, "_ربات سازنده گروه نیست_\n_با دستور_ setlink/ _لینک جدیدی برای گروه ثبت کنید_", 1, 'md')
end
else
administration[tostring(msg.to.id)]['settings']['linkgp'] = result
save_data(_config.moderation.data, administration)
if not lang then
tdcli.sendMessage(user, msg.id, 1, "*Newlink Group* _:_ `"..msg.to.id.."`\n"..result, 1, 'md')
return tdcli.sendMessage(msg.to.id, msg.id, 1, "*New link Was Send In Your Private Message*", 1, 'md')
elseif lang then
tdcli.sendMessage(user, msg.id, 1, "*لینک جدید گروه* _:_ `"..msg.to.id.."`\n"..result, 1, 'md')
return tdcli.sendMessage(msg.to.id, msg.id, 1, "_لینک جدید ساخته شد و در پیوی شما ارسال شد_", 1, 'md')
end
end
end
tdcli.exportChatInviteLink(msg.to.id, callback_link, nil)
end
if (matches[1]:lower() == 'setlink' or matches[1] == 'تنظیم لینک') and is_owner(msg) then
if not matches[2] then
data[tostring(chat)]['settings']['linkgp'] = 'waiting'
save_data(_config.moderation.data, data)
if not lang then
return '_Please send the new group_ *link* _now_'
else
return 'لطفا لینک گروه خود را ارسال کنید'
end
end
data[tostring(chat)]['settings']['linkgp'] = matches[2]
save_data(_config.moderation.data, data)
if not lang then
return '_Group Link Was Saved Successfully._'
else
return 'لینک گروه شما با موفقیت ذخیره شد'
end
end
if msg.text then
local is_link = msg.text:match("^([https?://w]*.?telegram.me/joinchat/%S+)$") or msg.text:match("^([https?://w]*.?t.me/joinchat/%S+)$")
if is_link and data[tostring(chat)]['settings']['linkgp'] == 'waiting' and is_owner(msg) then
data[tostring(chat)]['settings']['linkgp'] = msg.text
save_data(_config.moderation.data, data)
if not lang then
return "*Newlink* _has been set_"
else
return "لینک جدید ذخیره شد"
end
end
end
if (matches[1]:lower() == 'link' or matches[1] == 'لینک') and is_mod(msg) and not matches[2] then
local linkgp = data[tostring(chat)]['settings']['linkgp']
if not linkgp then
if not lang then
return "_First create a link for group with using_ /newlink\n_If bot not group creator set a link with using_ /setlink"
else
return "ابتدا با دستور newlink/ لینک جدیدی برای گروه بسازید\nو اگر ربات سازنده گروه نیس با دستور setlink/ لینک جدیدی برای گروه ثبت کنید"
end
end
if not lang then
text = "<b>Group Link :</b>\n"..linkgp
else
text = "<b>لینک گروه :</b>\n"..linkgp
end
return tdcli.sendMessage(chat, msg.id, 1, text, 1, 'html')
end
if (matches[1]:lower() == 'link' or matches[1] == 'لینک') and (matches[2] == 'pv' or matches[2] == 'خصوصی') then
if is_mod(msg) then
local linkgp = data[tostring(chat)]['settings']['linkgp']
if not linkgp then
if not lang then
return "_First create a link for group with using_ /newlink\n_If bot not group creator set a link with using_ /setlink"
else
return "ابتدا با دستور newlink/ لینک جدیدی برای گروه بسازید\nو اگر ربات سازنده گروه نیس با دستور setlink/ لینک جدیدی برای گروه ثبت کنید"
end
end
if not lang then
tdcli.sendMessage(chat, msg.id, 1, "<b>link Was Send In Your Private Message</b>", 1, 'html')
tdcli.sendMessage(user, "", 1, "<b>Group Link "..msg.to.title.." :</b>\n"..linkgp, 1, 'html')
else
tdcli.sendMessage(chat, msg.id, 1, "<b>لینک گروه در پیوی شما ارسال شد</b>", 1, 'html')
tdcli.sendMessage(user, "", 1, "<b>لینک گروه "..msg.to.title.." :</b>\n"..linkgp, 1, 'html')
end
end
end
if (matches[1]:lower() == "setrules" or matches[1] == 'تنظیم قوانین') and matches[2] and is_mod(msg) then
data[tostring(chat)]['rules'] = matches[2]
save_data(_config.moderation.data, data)
if not lang then
return "*Group rules* _has been set_"
else
return "قوانین گروه ثبت شد"
end
end
if matches[1]:lower() == "rules" or matches[1] == 'قوانین' then
if not data[tostring(chat)]['rules'] then
if not lang then
rules = "ℹ️ The Default Rules :\n1⃣ No Flood.\n2⃣ No Spam.\n3⃣ No Advertising.\n4⃣ Try to stay on topic.\n5⃣ Forbidden any racist, sexual, homophobic or gore content.\n➡️ Repeated failure to comply with these rules will cause ban.\n@ProtectionTeam"
elseif lang then
rules = "ℹ️ قوانین پپیشفرض:\n1⃣ ارسال پیام مکرر ممنوع.\n2⃣ اسپم ممنوع.\n3⃣ تبلیغ ممنوع.\n4⃣ سعی کنید از موضوع خارج نشید.\n5⃣ هرنوع نژاد پرستی, شاخ بازی و پورنوگرافی ممنوع .\n➡️ از قوانین پیروی کنید, در صورت عدم رعایت قوانین اول اخطار و در صورت تکرار مسدود.\n@ProtectionTeam"
end
else
rules = "*Group Rules :*\n"..data[tostring(chat)]['rules']
end
return rules
end
if (matches[1]:lower() == "res" or matches[1] == 'کاربری') and matches[2] and is_mod(msg) then
tdcli_function ({
ID = "SearchPublicChat",
username_ = matches[2]
}, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="res"})
end
if (matches[1]:lower() == "whois" or matches[1] == 'شناسه') and matches[2] and string.match(matches[2], '^%d+$') and is_mod(msg) then
tdcli_function ({
ID = "GetUser",
user_id_ = matches[2],
}, action_by_id, {chat_id=msg.to.id,user_id=matches[2],cmd="whois"})
end
if matches[1]:lower() == 'setchar' or matches[1]:lower() == 'حداکثر حروف مجاز' then
if not is_mod(msg) then
return
end
local chars_max = matches[2]
data[tostring(msg.to.id)]['settings']['set_char'] = chars_max
save_data(_config.moderation.data, data)
if not lang then
return "*Character sensitivity* _has been set to :_ *[ "..matches[2].." ]*"
else
return "_حداکثر حروف مجاز در پیام تنظیم شد به :_ *[ "..matches[2].." ]*"
end
end
if (matches[1]:lower() == 'setflood' or matches[1] == 'تنظیم پیام مکرر') and is_mod(msg) then
if tonumber(matches[2]) < 1 or tonumber(matches[2]) > 50 then
return "_Wrong number, range is_ *[2-50]*"
end
local flood_max = matches[2]
data[tostring(chat)]['settings']['num_msg_max'] = flood_max
save_data(_config.moderation.data, data)
if not lang then
return "_Group_ *flood* _sensitivity has been set to :_ *[ "..matches[2].." ]*"
else
return '_محدودیت پیام مکرر به_ *'..tonumber(matches[2])..'* _تنظیم شد._'
end
end
if (matches[1]:lower() == 'setfloodtime' or matches[1] == 'تنظیم زمان بررسی') and is_mod(msg) then
if tonumber(matches[2]) < 2 or tonumber(matches[2]) > 10 then
return "_Wrong number, range is_ *[2-10]*"
end
local time_max = matches[2]
data[tostring(chat)]['settings']['time_check'] = time_max
save_data(_config.moderation.data, data)
if not lang then
return "_Group_ *flood* _check time has been set to :_ *[ "..matches[2].." ]*"
else
return "_حداکثر زمان بررسی پیام های مکرر تنظیم شد به :_ *[ "..matches[2].." ]*"
end
end
if (matches[1]:lower() == 'clean' or matches[1] == 'پاک کردن') and is_owner(msg) then
if not lang then
if matches[2] == 'mods' then
if next(data[tostring(chat)]['mods']) == nil then
return "_No_ *moderators* _in this group_"
end
for k,v in pairs(data[tostring(chat)]['mods']) do
data[tostring(chat)]['mods'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
return "_All_ *moderators* _has been demoted_"
end
if matches[2] == 'filterlist' then
if next(data[tostring(chat)]['filterlist']) == nil then
return "*Filtered words list* _is empty_"
end
for k,v in pairs(data[tostring(chat)]['filterlist']) do
data[tostring(chat)]['filterlist'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
return "*Filtered words list* _has been cleaned_"
end
if matches[2] == 'rules' then
if not data[tostring(chat)]['rules'] then
return "_No_ *rules* _available_"
end
data[tostring(chat)]['rules'] = nil
save_data(_config.moderation.data, data)
return "*Group rules* _has been cleaned_"
end
if matches[2] == 'welcome' then
if not data[tostring(chat)]['setwelcome'] then
return "*Welcome Message not set*"
end
data[tostring(chat)]['setwelcome'] = nil
save_data(_config.moderation.data, data)
return "*Welcome message* _has been cleaned_"
end
if matches[2] == 'about' then
if msg.to.type == "chat" then
if not data[tostring(chat)]['about'] then
return "_No_ *description* _available_"
end
data[tostring(chat)]['about'] = nil
save_data(_config.moderation.data, data)
elseif msg.to.type == "channel" then
tdcli.changeChannelAbout(chat, "", dl_cb, nil)
end
return "*Group description* _has been cleaned_"
end
else
if matches[2] == 'مدیران' then
if next(data[tostring(chat)]['mods']) == nil then
return "هیچ مدیری برای گروه انتخاب نشده است"
end
for k,v in pairs(data[tostring(chat)]['mods']) do
data[tostring(chat)]['mods'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
return "تمام مدیران گروه تنزیل مقام شدند"
end
if matches[2] == 'لیست فیلتر' then
if next(data[tostring(chat)]['filterlist']) == nil then
return "_لیست کلمات فیلتر شده خالی است_"
end
for k,v in pairs(data[tostring(chat)]['filterlist']) do
data[tostring(chat)]['filterlist'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
return "_لیست کلمات فیلتر شده پاک شد_"
end
if matches[2] == 'قوانین' then
if not data[tostring(chat)]['rules'] then
return "قوانین برای گروه ثبت نشده است"
end
data[tostring(chat)]['rules'] = nil
save_data(_config.moderation.data, data)
return "قوانین گروه پاک شد"
end
if matches[2] == 'خوشآمد' then
if not data[tostring(chat)]['setwelcome'] then
return "پیام خوشآمد گویی ثبت نشده است"
end
data[tostring(chat)]['setwelcome'] = nil
save_data(_config.moderation.data, data)
return "پیام خوشآمد گویی پاک شد"
end
if matches[2] == 'درباره' then
if msg.to.type == "chat" then
if not data[tostring(chat)]['about'] then
return "پیامی مبنی بر درباره گروه ثبت نشده است"
end
data[tostring(chat)]['about'] = nil
save_data(_config.moderation.data, data)
elseif msg.to.type == "channel" then
tdcli.changeChannelAbout(chat, "", dl_cb, nil)
end
return "پیام مبنی بر درباره گروه پاک شد"
end
end
end
if (matches[1]:lower() == 'clean' or matches[1] == 'پاک کردن') and is_admin(msg) then
if not lang then
if matches[2] == 'owners' then
if next(data[tostring(chat)]['owners']) == nil then
return "_No_ *owners* _in this group_"
end
for k,v in pairs(data[tostring(chat)]['owners']) do
data[tostring(chat)]['owners'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
return "_All_ *owners* _has been demoted_"
end
else
if matches[2] == 'مالکان' then
if next(data[tostring(chat)]['owners']) == nil then
return "مالکی برای گروه انتخاب نشده است"
end
for k,v in pairs(data[tostring(chat)]['owners']) do
data[tostring(chat)]['owners'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
return "تمامی مالکان گروه تنزیل مقام شدند"
end
end
end
if (matches[1]:lower() == "setname" or matches[1] == 'تنظیم نام') and matches[2] and is_mod(msg) then
local gp_name = matches[2]
tdcli.changeChatTitle(chat, gp_name, dl_cb, nil)
end
if (matches[1]:lower() == "setabout" or matches[1] == 'تنظیم درباره') and matches[2] and is_mod(msg) then
if msg.to.type == "channel" then
tdcli.changeChannelAbout(chat, matches[2], dl_cb, nil)
elseif msg.to.type == "chat" then
data[tostring(chat)]['about'] = matches[2]
save_data(_config.moderation.data, data)
end
if not lang then
return "*Group description* _has been set_"
else
return "پیام مبنی بر درباره گروه ثبت شد"
end
end
if matches[1]:lower() == "about" or matches[1] == 'درباره' and msg.to.type == "chat" then
if not data[tostring(chat)]['about'] then
if not lang then
about = "_No_ *description* _available_"
elseif lang then
about = "پیامی مبنی بر درباره گروه ثبت نشده است"
end
else
about = "*Group Description :*\n"..data[tostring(chat)]['about']
end
return about
end
if (matches[1]:lower() == 'filter' or matches[1] == 'فیلتر') and is_mod(msg) then
return filter_word(msg, matches[2])
end
if (matches[1]:lower() == 'unfilter' or matches[1] == 'حذف فیلتر') and is_mod(msg) then
return unfilter_word(msg, matches[2])
end
if (matches[1]:lower() == 'config' or matches[1] == 'پیکربندی') and is_admin(msg) then
tdcli.getChannelMembers(msg.to.id, 0, 'Administrators', 200, config_cb, {chat_id=msg.to.id})
end
if (matches[1]:lower() == 'filterlist' or matches[1] == 'لیست فیلتر') and is_mod(msg) then
return filter_list(msg)
end
if (matches[1]:lower() == "modlist" or matches[1] == 'لیست مدیران') and is_mod(msg) then
return modlist(msg)
end
if (matches[1]:lower() == "whitelist" or matches[1] == 'لیست سفید') and not matches[2] and is_mod(msg) then
return whitelist(msg.to.id)
end
if (matches[1]:lower() == "ownerlist" or matches[1] == 'لیست مالکان') and is_owner(msg) then
return ownerlist(msg)
end
if (matches[1]:lower() == "settings" or matches[1] == 'تنظیمات') and is_mod(msg) then
return group_settings(msg, target)
end
if matches[1]:lower() == "setlang" and is_owner(msg) then
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if matches[2] == "fa" then
redis:set(hash, true)
return "*زبان گروه تنظیم شد به : فارسی*"..BDRpm
end
end
if matches[1] == 'زبان انگلیسی' then
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
redis:del(hash)
return "_Group Language Set To:_ EN"..BDRpm
end
if (matches[1] == 'mutetime' or matches[1] == 'زمان بیصدا') and is_mod(msg) then
local hash = 'muteall:'..msg.to.id
local hour = tonumber(matches[2])
local num1 = (tonumber(hour) * 3600)
local minutes = tonumber(matches[3])
local num2 = (tonumber(minutes) * 60)
local second = tonumber(matches[4])
local num3 = tonumber(second)
local num4 = tonumber(num1 + num2 + num3)
redis:setex(hash, num4, true)
if not lang then
return "_Mute all has been enabled for_ \n⏺ *hours :* `"..matches[2].."`\n⏺ *minutes :* `"..matches[3].."`\n⏺ *seconds :* `"..matches[4].."`"..BDRpm
elseif lang then
return "بی صدا کردن فعال شد در \n⏺ ساعت : "..matches[2].."\n⏺ دقیقه : "..matches[3].."\n⏺ ثانیه : "..matches[4]..BDRpm
end
end
if (matches[1] == 'mutehours' or matches[1]== 'ساعت بیصدا') and is_mod(msg) then
local hash = 'muteall:'..msg.to.id
local hour = matches[2]
local num1 = tonumber(hour) * 3600
local num4 = tonumber(num1)
redis:setex(hash, num4, true)
if not lang then
return "Mute all has been enabled for \n⏺ hours : "..matches[2]..BDRpm
elseif lang then
return "بی صدا کردن فعال شد در \n⏺ ساعت : "..matches[2]..BDRpm
end
end
if (matches[1] == 'muteminutes' or matches[1]== 'دقیقه بیصدا') and is_mod(msg) then
local hash = 'muteall:'..msg.to.id
local minutes = matches[2]
local num2 = tonumber(minutes) * 60
local num4 = tonumber(num2)
redis:setex(hash, num4, true)
if not lang then
return "Mute all has been enabled for \n⏺ minutes : "..matches[2]..BDRpm
elseif lang then
return "بی صدا کردن فعال شد در \n⏺ دقیقه : "..matches[2]..BDRpm
end
end
if (matches[1] == 'settingseconds' or matches[1] == 'ثانیه بیصدا') and is_mod(msg) then
local hash = 'muteall:'..msg.to.id
local second = matches[2]
local num3 = tonumber(second)
local num4 = tonumber(num3)
redis:setex(hash, num3, true)
if not lang then
return "Mute all has been enabled for \n⏺ seconds : "..matches[2]..BDRpm
elseif lang then
return "بی صدا کردن فعال شد در \n⏺ ثانیه : "..matches[2]..BDRpm
end
end
if (matches[1] == 'muteall' or matches[1] == 'موقعیت') and (matches[2] == 'status' or matches[2] == 'بیصدا') and is_mod(msg) then
local hash = 'muteall:'..msg.to.id
local mute_time = redis:ttl(hash)
if tonumber(mute_time) < 0 then
if not lang then
return '_Mute All is Disable._'
else
return '_بیصدا بودن گروه غیر فعال است._'
end
else
if not lang then
return mute_time.." Sec"
elseif lang then
return mute_time.."ثانیه"
end
end
end
-------------Edit--------------
if matches[1] == 'edit' or matches[1] == 'ادیت' and msg.reply_to_message_id_ ~= 0 and is_sudo(msg) then
local text = matches[2]
tdcli.editMessageText(msg.to.id, msg.reply_to_message_id_, nil, text, 1, 'md')
end
if matches[1] == 'edit' or matches[1] == 'ادیت' and msg.reply_to_message_id_ ~= 0 and is_sudo(msg) then
local tExt = matches[2]
tdcli.editMessageCaption(msg.to.id, msg.reply_to_message_id_, nil, tExt)
end
--------------Plugin----------------
local function plugin_enabled( name )
for k,v in pairs(_config.enabled_plugins) do
if name == v then
return k
end
end
-- If not found
return false
end
-- Returns true if file exists in plugins folder
local function plugin_exists( name )
for k,v in pairs(plugins_names()) do
if name..'.lua' == v then
return true
end
end
return false
end
local function list_all_plugins(only_enabled, msg)
local tmp = '\nt.me/ProtectionTeam'
local text = ''
local nsum = 0
for k, v in pairs( plugins_names( )) do
-- ✔ enabled, ❌ disabled
local status = '➖-»'
nsum = nsum+1
nact = 0
-- Check if is enabled
for k2, v2 in pairs(_config.enabled_plugins) do
if v == v2..'.lua' then
status = '➕-»'
end
nact = nact+1
end
if not only_enabled or status == '➕-»'then
-- get the name
v = string.match (v, "(.*)%.lua")
text = text..nsum..'.'..status..' '..v..' \n'
end
end
text = '<code>'..text..'</code>\n\n'..nsum..' <b>📂plugins installed</b>\n\n'..nact..' <i>➕️plugins enabled</i>\n\n'..nsum-nact..' <i>➖plugins disabled</i>'..tmp
tdcli.sendMessage(msg.to.id, msg.id_, 1, text, 1, 'html')
end
local function list_plugins(only_enabled, msg)
local text = ''
local nsum = 0
for k, v in pairs( plugins_names( )) do
-- ✔ enabled, ❌ disabled
local status = '*➖-»*'
nsum = nsum+1
nact = 0
-- Check if is enabled
for k2, v2 in pairs(_config.enabled_plugins) do
if v == v2..'.lua' then
status = '*|➕|-»*'
end
nact = nact+1
end
if not only_enabled or status == '*➕-»*'then
-- get the name
v = string.match (v, "(.*)%.lua")
-- text = text..v..' '..status..'\n'
end
end
text = "*BotReloaded :|*"
tdcli.sendMessage(msg.to.id, msg.id_, 1, text, 1, 'md')
end
local function reload_plugins(checks, msg)
plugins = {}
load_plugins()
return list_plugins(true, msg)
end
local function enable_plugin( plugin_name, msg )
print('checking if '..plugin_name..' exists')
-- Check if plugin is enabled
if plugin_enabled(plugin_name) then
local text = '<b>'..plugin_name..'</b> <i>is enabled.</i>'
tdcli.sendMessage(msg.to.id, msg.id_, 1, text, 1, 'html')
return
end
-- Checks if plugin exists
if plugin_exists(plugin_name) then
-- Add to the config table
table.insert(_config.enabled_plugins, plugin_name)
print(plugin_name..' added to _config table')
save_config()
-- Reload the plugins
return reload_plugins(true, msg)
else
local text = '<b>'..plugin_name..'</b> <i>does not exists.</i>'
tdcli.sendMessage(msg.to.id, msg.id_, 1, text, 1, 'html')
end
end
local function disable_plugin( name, msg )
local k = plugin_enabled(name)
-- Check if plugin is enabled
if not k then
local text = '<b>'..name..'</b> <i>not enabled.</i>'
tdcli.sendMessage(msg.to.id, msg.id_, 1, text, 1, 'html')
return
end
-- Check if plugins exists
if not plugin_exists(name) then
local text = '<b>'..name..'</b> <i>does not exists.</i>'
tdcli.sendMessage(msg.to.id, msg.id_, 1, text, 1, 'html')
else
-- Disable and reload
table.remove(_config.enabled_plugins, k)
save_config( )
return reload_plugins(true, msg)
end
end
local function disable_plugin_on_chat(receiver, plugin, msg)
if not plugin_exists(plugin) then
return "_Plugin doesn't exists_"
end
if not _config.disabled_plugin_on_chat then
_config.disabled_plugin_on_chat = {}
end
if not _config.disabled_plugin_on_chat[receiver] then
_config.disabled_plugin_on_chat[receiver] = {}
end
_config.disabled_plugin_on_chat[receiver][plugin] = true
save_config()
local text = '<b>'..plugin..'</b> <i>disabled on this chat.</i>'
tdcli.sendMessage(msg.to.id, msg.id_, 1, text, 1, 'html')
end
local function reenable_plugin_on_chat(receiver, plugin, msg)
if not _config.disabled_plugin_on_chat then
return 'There aren\'t any disabled plugins'
end
if not _config.disabled_plugin_on_chat[receiver] then
return 'There aren\'t any disabled plugins for this chat'
end
if not _config.disabled_plugin_on_chat[receiver][plugin] then
return '_This plugin is not disabled_'
end
_config.disabled_plugin_on_chat[receiver][plugin] = false
save_config()
local text = '<b>'..plugin..'</b> <i>is enabled again.</i>'
tdcli.sendMessage(msg.to.id, msg.id_, 1, text, 1, 'html')
end
-- Show the available plugins
if is_sudo(msg) then
if (matches[1]:lower() == 'plugin' or matches[1] == 'لیست پلاگین') then --after changed to moderator mode, set only sudo
return list_all_plugins(false, msg)
end
-- Re-enable a plugin for this chat
if matches[1]:lower() == 'pl' or matches[1] == 'پلاگین' then
if matches[2] == '+' and matches[4] == 'chat' or matches[4] == 'گروه' then
if is_mod(msg) then
local receiver = msg.chat_id_
local plugin = matches[3]
print("enable "..plugin..' on this chat')
return reenable_plugin_on_chat(receiver, plugin, msg)
end
end
-- Enable a plugin
if matches[2] == '+' and is_sudo(msg) then --after changed to moderator mode, set only sudo
local plugin_name = matches[3]
print("enable: "..matches[3])
return enable_plugin(plugin_name, msg)
end
-- Disable a plugin on a chat
if matches[2] == '-' and matches[4] == 'chat' or matches[4] == 'گروه' then
if is_mod(msg) then
local plugin = matches[3]
local receiver = msg.chat_id_
print("disable "..plugin..' on this chat')
return disable_plugin_on_chat(receiver, plugin, msg)
end
end
-- Disable a plugin
if matches[2] == '-' and is_sudo(msg) then --after changed to moderator mode, set only sudo
if matches[3] == 'plugins' then
return 'This plugin can\'t be disabled'
end
print("disable: "..matches[3])
return disable_plugin(matches[3], msg)
end
-- Reload all the plugins!
if matches[2] == '*' and is_sudo(msg) then --after changed to moderator mode, set only sudo
return reload_plugins(true, msg)
end
end
if (matches[1]:lower() == 'reload' or matches[1] == 'بارگذاری') and is_sudo(msg) then --after changed to moderator mode, set only sudo
return reload_plugins(true, msg)
end
end
--------------------Me---------------------
local function setrank(msg, user_id, value,chat_id)
local hash = nil
hash = 'rank:'..msg.to.id..':variables'
if hash then
redis:hset(hash, user_id, value)
return tdcli.sendMessage(chat_id, '', 0, '_set_ *Rank* _for_ *[ '..user_id..' ]* _To :_ *'..value..'*', 0, "md")
end
end
local function info_by_reply(arg, data)
if tonumber(data.sender_user_id_) then
local function info_cb(arg, data)
if data.username_ then
username = "@"..check_markdown(data.username_)
else
username = ""
end
if data.first_name_ then
firstname = check_markdown(data.first_name_)
else
firstname = ""
end
if data.last_name_ then
lastname = check_markdown(data.last_name_)
else
lastname = ""
end
local hash = 'rank:'..arg.chat_id..':variables'
local text = "_First name :_ *"..firstname.."*\n_Last name :_ *"..lastname.."*\n_Username :_ "..username.."\n_ID :_ *"..data.id_.."*\n"
if data.id_ == tonumber(MRlucas) then
text = text..'_Rank :_ *Executive Admin*\n'
elseif is_sudo1(data.id_) then
text = text..'_Rank :_ *Full Access Admin*\n'
elseif is_admin1(data.id_) then
text = text..'_Rank :_ *Bot Admin*\n'
elseif is_owner1(arg.chat_id, data.id_) then
text = text..'_Rank :_ *Group Owner*\n'
elseif is_mod1(arg.chat_id, data.id_) then
text = text..'_Rank :_ *Group Moderator*\n'
else
text = text..'_Rank :_ *Group Member*\n'
end
local user_info = {}
local uhash = 'user:'..data.id_
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..data.id_..':'..arg.chat_id
user_info_msgs = tonumber(redis:get(um_hash) or 0)
text = text..'Total messages : '..user_info_msgs..'\n'
text = text..BDRpm
tdcli.sendMessage(arg.chat_id, arg.msgid, 0, text, 0, "md")
end
tdcli_function ({
ID = "GetUser",
user_id_ = data.sender_user_id_
}, info_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_,msgid=data.id_})
else
tdcli.sendMessage(data.chat_id_, "", 0, "*User not found*", 0, "md")
end
end
local function info_by_username(arg, data)
if tonumber(data.id_) then
if data.type_.user_.username_ then
username = "@"..check_markdown(data.type_.user_.username_)
else
username = ""
end
if data.type_.user_.first_name_ then
firstname = check_markdown(data.type_.user_.first_name_)
else
firstname = ""
end
if data.type_.user_.last_name_ then
lastname = check_markdown(data.type_.user_.last_name_)
else
lastname = ""
end
local hash = 'rank:'..arg.chat_id..':variables'
local text = "_First name :_ *"..firstname.."*\n_Last name :_ *"..lastname.."*\n_Username :_ "..username.."\n_ID :_ *"..data.id_.."*\n"
if data.id_ == tonumber(MRlucas) then
text = text..'_Rank :_ *Executive Admin*\n'
elseif is_sudo1(data.id_) then
text = text..'_Rank :_ *Full Access Admin*\n'
elseif is_admin1(data.id_) then
text = text..'_Rank :_ *Bot Admin*\n'
elseif is_owner1(arg.chat_id, data.id_) then
text = text..'_Rank :_ *Group Owner*\n'
elseif is_mod1(arg.chat_id, data.id_) then
text = text..'_Rank :_ *Group Moderator*\n'
else
text = text..'_Rank :_ *Group Member*\n'
end
local user_info = {}
local uhash = 'user:'..data.id_
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..data.id_..':'..arg.chat_id
user_info_msgs = tonumber(redis:get(um_hash) or 0)
text = text..'Total messages : '..user_info_msgs..'\n'
text = text..BDRpm
tdcli.sendMessage(arg.chat_id, arg.msgid, 0, text, 0, "md")
else
tdcli.sendMessage(arg.chat_id, "", 0, "*User not found*", 0, "md")
end
end
local function info_by_id(arg, data)
if tonumber(data.id_) then
if data.username_ then
username = "@"..check_markdown(data.username_)
else
username = ""
end
if data.first_name_ then
firstname = check_markdown(data.first_name_)
else
firstname = ""
end
if data.last_name_ then
lastname = check_markdown(data.last_name_)
else
lastname = ""
end
local hash = 'rank:'..arg.chat_id..':variables'
local text = "_First name :_ *"..firstname.."*\n_Last name :_ *"..lastname.."*\n_Username :_ "..username.."\n_ID :_ *"..data.id_.."*\n"
if data.id_ == tonumber(MRlucas) then
text = text..'_Rank :_ *Executive Admin*\n'
elseif is_sudo1(data.id_) then
text = text..'_Rank :_ *Full Access Admin*\n'
elseif is_admin1(data.id_) then
text = text..'_Rank :_ *Bot Admin*\n'
elseif is_owner1(arg.chat_id, data.id_) then
text = text..'_Rank :_ *Group Owner*\n'
elseif is_mod1(arg.chat_id, data.id_) then
text = text..'_Rank :_ *Group Moderator*\n'
else
text = text..'_Rank :_ *Group Member*\n'
end
local user_info = {}
local uhash = 'user:'..data.id_
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..data.id_..':'..arg.chat_id
user_info_msgs = tonumber(redis:get(um_hash) or 0)
text = text..'Total messages : '..user_info_msgs..'\n'
text = text..BDRpm
tdcli.sendMessage(arg.chat_id, arg.msgid, 0, text, 0, "md")
else
tdcli.sendMessage(arg.chat_id, "", 0, "*User not found*", 0, "md")
end
end
local function setrank_by_reply(arg, data)
end
if matches[1]:lower() == "me" or matches[1] == "من" then
if not matches[2] and tonumber(msg.reply_to_message_id_) ~= 0 then
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.chat_id_,
message_id_ = msg.reply_to_message_id_
}, info_by_reply, {chat_id=msg.chat_id_})
end
if matches[2] and string.match(matches[2], '^%d+$') and tonumber(msg.reply_to_message_id_) == 0 then
tdcli_function ({
ID = "GetUser",
user_id_ = matches[2],
}, info_by_id, {chat_id=msg.chat_id_,user_id=matches[2],msgid=msg.id_})
end
if matches[2] and not string.match(matches[2], '^%d+$') and tonumber(msg.reply_to_message_id_) == 0 then
tdcli_function ({
ID = "SearchPublicChat",
username_ = matches[2]
}, info_by_username, {chat_id=msg.chat_id_,username=matches[2],msgid=msg.id_})
end
if not matches[2] and tonumber(msg.reply_to_message_id_) == 0 then
local function info2_cb(arg, data)
if tonumber(data.id_) then
if data.username_ then
username = "@"..check_markdown(data.username_)
else
username = ""
end
if data.first_name_ then
firstname = check_markdown(data.first_name_)
else
firstname = ""
end
if data.last_name_ then
lastname = check_markdown(data.last_name_)
else
lastname = ""
end
local hash = 'rank:'..arg.chat_id..':variables'
local text = "_First name :_ *"..firstname.."*\n_Last name :_ *"..lastname.."*\n_Username :_ "..username.."\n_ID :_ *"..data.id_.."*\n"
if data.id_ == tonumber(MRlucas) then
text = text..'_Rank :_ *Executive Admin*\n'
elseif is_sudo1(data.id_) then
text = text..'_Rank :_ *Full Access Admin*\n'
elseif is_admin1(data.id_) then
text = text..'_Rank :_ *Bot Admin*\n'
elseif is_owner1(arg.chat_id, data.id_) then
text = text..'_Rank :_ *Group Owner*\n'
elseif is_mod1(arg.chat_id, data.id_) then
text = text..'_Rank :_ *Group Moderator*\n'
else
text = text..'_Rank :_ *Group Member*\n'
end
local user_info = {}
local uhash = 'user:'..data.id_
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..data.id_..':'..arg.chat_id
user_info_msgs = tonumber(redis:get(um_hash) or 0)
text = text..'Total messages : '..user_info_msgs..'\n'
text = text..BDRpm
tdcli.sendMessage(arg.chat_id, arg.msgid, 0, text, 0, "md")
end
end
tdcli_function ({
ID = "GetUser",
user_id_ = msg.from.id,
}, info_by_id, {chat_id=msg.chat_id_,user_id=msg.from.id,msgid=msg.id_})
end
end
-------------Echo--------------
if matches[1] == 'echo' or matches[1] == 'اکو' then
local pext = matches[2]
tdcli.sendMessage(msg.to.id, 0,1, pext,1,'html')
end
-----------cleanbot----------
if matches[1] == 'cleanbot' or matches[1] == 'پاک کردن ربات' then
function clbot(arg, data)
for k, v in pairs(data.members_) do
kick_user(v.user_id_, msg.to.id)
end
tdcli.sendMessage(msg.to.id, msg.id, 1, '_All Bots was cleared._', 1, 'md')
end
tdcli.getChannelMembers(msg.to.id, 0, 'Bots', 200, clbot, nil)
end
--------------Delete Message----------------
local function delmsg (i,naji)
msgs = i.msgs
for k,v in pairs(naji.messages_) do
msgs = msgs - 1
tdcli.deleteMessages(v.chat_id_,{[0] = v.id_}, dl_cb, cmd)
if msgs == 1 then
tdcli.deleteMessages(naji.messages_[0].chat_id_,{[0] = naji.messages_[0].id_}, dl_cb, cmd)
return false
end
end
tdcli.getChatHistory(naji.messages_[0].chat_id_, naji.messages_[0].id_,0 , 100, delmsg, {msgs=msgs})
end
if matches[1] == 'del' or matches[1] == 'حذف' and is_owner(msg) then
if tostring(msg.to.id):match("^-100") then
if tonumber(matches[2]) > 1000 or tonumber(matches[2]) < 1 then
return '🚫 *1000*> _تعداد پیام های قابل پاک سازی در هر دفعه_ >*1* 🚫'
else
tdcli.getChatHistory(msg.to.id, msg.id,0 , 100, delmsg, {msgs=matches[2]})
return ""..matches[2].." _پیام اخیر با موفقیت پاکسازی شدند_ 🚮"
end
else
return '⚠️ _این قابلیت فقط در سوپرگروه ممکن است_ ⚠️'
end
end
--------------------------------
if matches[1]:lower() == 'clean' or matches[1] == 'پاک کردن' and matches[2]:lower() == 'blacklist' or matches[2] == 'بلک لیست' then
if not is_mod(msg) then
return -- «Mods allowed»
end
local function cleanbl(ext, res)
if tonumber(res.total_count_) == 0 then -- «Blocklist is empty or maybe Bot is not group's admin»
return tdcli.sendMessage(ext.chat_id, ext.msg_id, 0, '⚠️ _لیست مسدودی های گروه خالی است_ !', 1, 'md')
end
local x = 0
for x,y in pairs(res.members_) do
x = x + 1
tdcli.changeChatMemberStatus(ext.chat_id, y.user_id_, 'Left', dl_cb, nil) -- «Changing user status to left, removes user from blocklist»
end
return tdcli.sendMessage(ext.chat_id, ext.msg_id, 0, '✅ _ کاربر از لیست مسدودی های گروه آزاد شدند_ !', 1, 'md')
end
return tdcli.getChannelMembers(msg.to.id, 0, 'Kicked', 200, cleanbl, {chat_id = msg.to.id, msg_id = msg.id}) -- «Gets channel blocklist»
end
--------------------------------
if matches[1] == 'addkick' or matches[1] == 'افزودن ریمو' and is_owner(msg) then
if gp_type(msg.to.id) == "channel" then
tdcli.getChannelMembers(msg.to.id, 0, "Kicked", 200, function (i, naji)
for k,v in pairs(naji.members_) do
tdcli.addChatMember(i.chat_id, v.user_id_, 50, dl_cb, nil)
end
end, {chat_id=msg.to.id})
return "*>Banned User has been added Again Sussecfully✅*"
end
return "*Just in the super group may be :(*"
end
--------------------------------
if matches[1] == 'ping'or matches[1] == 'ربات' then
tdcli.sendDocument(msg.chat_id_, msg.id_, 0, 1, nil, './data/ping.webp', '', dl_cb,msg.reply_id, nil)
end
--------------------------------
if matches [1] == 'setnerkh' or matches[1] == 'تنظیم نرخ' then
if not is_admin(msg) then
return '_You are Not_ *Moderator*'
end
local nerkh = matches[2]
redis:set('bot:nerkh',nerkh)
return 'نرخ باموفقیت ثبت گردید😐❤️'
end
if matches[1] == 'nerkh' or matches[1] == 'نرخ' then
if not is_mod(msg) then
return
end
local hash = ('bot:nerkh')
local nerkh = redis:get(hash)
if not nerkh then
return 'نرخ ثبت نشده📛'
else
tdcli.sendMessage(msg.chat_id_, 0, 1, nerkh, 1, 'html')
end
end
if matches[1]== "delnerkh" or matches[1] == 'پاک کردن نرخ' then
if not is_admin(msg) then
return '_You are Not_ *Moderator*'
end
local hash = ('bot:nerkh')
redis:del(hash)
return 'نرخ پاک شد🗑'
end
------------------Invite---------------------
function getMessage(chat_id, message_id,cb)
tdcli_function ({
ID = "GetMessage",
chat_id_ = chat_id,
message_id_ = message_id
}, cb, nil)
end
-------------------------------------------------------------------------------------------------------------------
function from_username(msg)
function gfrom_user(extra,result,success)
if result.username_ then
F = result.username_
else
F = 'nil'
end
return F
end
local username = getUser(msg.sender_user_id_,gfrom_user)
return username
end
--Start Function
if matches[1] == "invite" and matches[2] and is_owner(msg) then
if string.match(matches[2], '^%d+$') then
tdcli.addChatMember(msg.to.id, matches[2], 0)
end
------------------------Username------------------------------------------------------------------------------------
if matches[1] == "invite" and matches[2] and is_owner(msg) then
if string.match(matches[2], '^.*$') then
function invite_by_username(extra, result, success)
if result.id_ then
tdcli.addChatMember(msg.to.id, result.id_, 5)
end
end
resolve_username(matches[2],invite_by_username)
end
end
------------------------Reply---------------------------------------------------------------------------------------
if matches[1] == "invite" and msg.reply_to_message_id_ ~= 0 and is_owner(msg) then
function inv_reply(extra, result, success)
tdcli.addChatMember(msg.to.id, result.sender_user_id_, 5)
end
getMessage(msg.chat_id_, msg.reply_to_message_id_,inv_reply)
end
end
-----------------------------------------
if matches[1]:lower() == "help" or matches[1] == 'راهنما' and is_mod(msg) then
if not lang then
text = [[
*▪️PCT Bot Commands: *
*🔹!helplock*
🔻Show locks Help
*🔹!helpmute*
🔻Show mutes Help
*🔹!helptools*
🔻Show Tools Help
*🔹!helpfun*
🔻Show Fun Help
*🔹!helpmanag*
🔻Show manag Help
—---------------------------------------------------------------------
⚠️This Help List Only For *Moderators/Owners!*
🔺Its Means, Only Group *Moderators/Owners* Can Use It!
*Good luck ;)*
—---------------------------------------------------------------------—
®PCT BOT
]]
elseif lang then
text = [[
*▪️راهنمای عملکرد ربات: *
_🔹راهنما قفل_
🔻برای مشاهده دستورات قفل
_🔹راهنما بیصدا_
🔻برای مشاهده دستورات بیصدا
_🔹راهنما ابزار_
🔻برای مشاهده دستورات سودو ها
_🔹!راهنمای سرگرمی_
🔻برای مشاهده دستورات سرگرمی
_🔹راهنما مدیریتی_
🔻برای مشاهده دستورات مدیریتی گروه
—---------------------------------------------------------------------
⚠️_این راهنما فقط برای مدیران/مالکان گروه میباشد!
این به این معناست که فقط مدیران/مالکان گروه میتوانند از دستورات بالا استفاده کنند!_
*موفق باشید ;)*
—---------------------------------------------------------------------—
®PCT BOT
]]
end
return text
end
-----------------------------------------
if matches[1]:lower() == "helplock" or matches[1] == 'راهنما قفل' and is_mod(msg) then
if not lang then
lock = [[
*PCT Bot Commands:*
`!lock🔒`
*link ~ join ~ tag ~ edit ~ arabic ~ webpage ~ bots ~ spam ~ flood ~ markdown ~ mention ~ pin ~ cmds ~ badword ~ username ~ english*
_If This Actions Lock, Bot Check Actions And Delete Them_
`!unlock🔓`
*link ~ join ~ tag ~ edit ~ arabic ~ webpage ~ bots ~ spam ~ flood ~ markdown ~ mention ~ pin ~ cmds ~ badword ~ username ~ english*
_If This Actions Unlock, Bot Not Delete Them_
_You Can Use_ *[!/#]* _To Run The Commands_
_This Help List Only For_ *Moderators/Owners!*
_Its Means, Only Group_ *Moderators/Owners* _Can Use It!_
*Good luck ;)*]]
elseif lang then
lock = [[
*دستورات ربات پروتکشن:*
*قفل🔒*
`لینک ~ ویرایش ~ تگ ~ یوزرنیم ~ انگلیسی ~ عربی ~ وب ~ ربات ~ هرزنامه ~ پیام مکرر ~ فراخوانی ~ سنجاق ~ دستورات ~ ورود ~ فونت ~ تبچی`
_در صورت قفل بودن فعالیت ها, ربات آنهارا حذف خواهد کرد_
*باز🔓*
`لینک ~ ویرایش ~ تگ ~ یوزرنیم ~ انگلیسی ~ عربی ~ وب ~ ربات ~ هرزنامه ~ پیام مکرر ~ فراخوانی ~ سنجاق ~ دستورات ~ ورود ~ فونت ~ تبچی`
_در صورت باز نبودن فعالیت ها, ربات آنهارا حذف نخواهد کرد_
_این راهنما فقط برای مدیران/مالکان گروه میباشد!
این به این معناست که فقط مدیران/مالکان گروه میتوانند از دستورات بالا استفاده کنند!_
]]
end
return lock
end
-----------------------------------------
if matches[1]:lower() == "helpmute" or matches[1] == 'راهنما بیصدا' and is_mod(msg) then
if not lang then
mute = [[
*PCT Bot Commands:*
`!mute🔇`
*gif ~ photo ~ document ~ sticker ~ keyboard ~ video ~ text ~ forward ~ location ~ audio ~ voice ~ contact ~ all*
_If This Actions Lock, Bot Check Actions And Delete Them_
*!unmute🔊*
*gif ~ photo ~ document ~ sticker ~ keyboard ~ video ~ text ~ forward ~ location ~ audio ~ voice ~ contact ~ all*
_If This Actions Unlock, Bot Not Delete Them_
*!mutetime*
`(hour) (minute) (seconds)`
_Mute group at this time_
*!mutehours*
`(number)`
_Mute group at this time_
*!muteminutes*
`(number)`
_Mute group at this time_
_You Can Use_ *[!/#]* _To Run The Commands_
_This Help List Only For_ *Moderators/Owners!*
_Its Means, Only Group_ *Moderators/Owners* _Can Use It!_
*Good luck ;)*]]
elseif lang then
mute = [[
*دستورات ربات پروتکشن:*
*بیصدا🔇*
`همه ~ تصاویر متحرک ~ عکس ~ اسناد ~ برچسب ~ صفحه کلید ~ فیلم ~ متن ~ نقل قول ~ موقعیت ~ اهنگ ~ صدا ~ مخاطب ~ کیبورد شیشه ای ~ بازی ~ خدمات تلگرام`
_در صورت بیصدا بودن فعالیت ها, ربات آنهارا حذف خواهد کرد_
*باصدا🔊*
`همه ~ تصاویر متحرک ~ عکس ~ اسناد ~ برچسب ~ صفحه کلید ~ فیلم ~ متن ~ نقل قول ~ موقعیت ~ اهنگ ~ صدا ~ مخاطب ~ کیبورد شیشه ای ~ بازی ~ خدمات تلگرام`
_در صورت بیصدا نبودن فعالیت ها, ربات آنهارا حذف نخواهد کرد_
*زمان بیصدا* `(ساعت) (دقیقه) (ثانیه)`
_بیصدا کردن گروه با ساعت و دقیقه و ثانیه_
*ساعت بیصدا* `(عدد)`
_بیصدا کردن گروه در ساعت_
*دقیقه بیصدا* `(عدد)`
_بیصدا کردن گروه در دقیقه_
*ثانیه بیصدا* `(عدد)`
_بیصدا کردن گروه در ثانیه_
_این راهنما فقط برای مدیران/مالکان گروه میباشد!
این به این معناست که فقط مدیران/مالکان گروه میتوانند از دستورات بالا استفاده کنند!_
*موفق باشید ;)*]]
end
return mute
end
-----------------------------------------
if matches[1]:lower() == "helpmanag" or matches[1] == 'راهنما مدیریتی' and is_mod(msg) then
if not lang then
Management = [[
*PCT Bot Management:*
*!setmanager* `[username|id|reply]`
_Add User To Group Admins(CreatorBot)_
*!Remmanager* `[username|id|reply]`
_Remove User From Owner List(CreatorBot)_
*!setowner* `[username|id|reply]`
_Set Group Owner(Multi Owner)_
*!remowner* `[username|id|reply]`
_Remove User From Owner List_
*!promote* `[username|id|reply]`
_Promote User To Group Admin_
*!demote* `[username|id|reply]`
_Demote User From Group Admins List_
*!setflood* `[2-50]`
_Set Flooding Number_
*!silent* `[username|id|reply]`
_Silent User From Group_
*!unsilent* `[username|id|reply]`
_Unsilent User From Group_
*!kick* `[username|id|reply]`
_Kick User From Group_
*!ban* `[username|id|reply]`
_Ban User From Group_
*!unban* `[username|id|reply]`
_UnBan User From Group_
*!res* `[username]`
_Show User ID_
*!id* `[reply]`
_Show User ID_
*!whois* `[id]`
_Show User's Username And Name_
*!clean* `[bans | mods | bots | rules | about | silentlist | filtelist | welcome]`
_Bot Clean Them_
*!filter* `[word]`
_Word filter_
*!unfilter* `[word]`
_Word unfilter_
*!pin* `[reply]`
_Pin Your Message_
*!unpin*
_Unpin Pinned Message_
*!welcome enable/disable*
_Enable Or Disable Group Welcome_
*!settings*
_Show Group Settings_
*!cmds* `[member | moderator | owner]`
_set cmd_
*!whitelist* `[+ | -]`
_Add User To White List_
*!silentlist*
_Show Silented Users List_
*!filterlist*
_Show Filtered Words List_
*!banlist*
_Show Banned Users List_
*!ownerlist*
_Show Group Owners List_
*!whitelist*
_Show Group whitelist List_
*!modlist*
_Show Group Moderators List_
*!rules*
_Show Group Rules_
*!about*
_Show Group Description_
*!id*
_Show Your And Chat ID_
*!gpinfo*
_Show Group Information_
*!newlink*
_Create A New Link_
*!newlink pv*
_Create A New Link The Pv_
*!link*
_Show Group Link_
*!link pv*
_Send Group Link In Your Private Message_
*!setlang fa*
_Set Persian Language_
*!setwelcome [text]*
_set Welcome Message_
_You Can Use_ *[!/#]* _To Run The Commands_
_This Help List Only For_ *Moderators/Owners!*
_Its Means, Only Group_ *Moderators/Owners* _Can Use It!_
*Good luck ;)*]]
elseif lang then
Management = [[
*دستورات ربات پروتکشن:*
*ادمین گروه* `[username|id|reply]`
_افزودن ادمین گروه(درصورت اینکه ربات سازنده گروه)_
*حذف ادمین گروه* `[username|id|reply]`
_حذف ادمین گروه(درصورت اینکه ربات سازنده گروه)_
*مالک* `[username|id|reply]`
_انتخاب مالک گروه(قابل انتخاب چند مالک)_
*حذف مالک* `[username|id|reply]`
_حذف کردن فرد از فهرست مالکان گروه_
*مدیر* `[username|id|reply]`
_ارتقا مقام کاربر به مدیر گروه_
*حذف مدیر* `[username|id|reply]`
_تنزیل مقام مدیر به کاربر_
*تنظیم پیام مکرر* `[2-50]`
_تنظیم حداکثر تعداد پیام مکرر_
*سکوت* `[username|id|reply]`
_بیصدا کردن کاربر در گروه_
*!حذف سکوت* `[username|id|reply]`
_در آوردن کاربر از حالت بیصدا در گروه_
*!اخراج* `[username|id|reply]`
_حذف کاربر از گروه_
*!بن* `[username|id|reply]`
_مسدود کردن کاربر از گروه_
*!حذف بن* `[username|id|reply]`
_در آوردن از حالت مسدودیت کاربر از گروه_
*کاربری* `[username]`
_نمایش شناسه کاربر_
*ایدی* `[reply]`
_نمایش شناسه کاربر_
*شناسه* `[id]`
_نمایش نام کاربر, نام کاربری و اطلاعات حساب_
*تنظیم*`[قوانین | نام | لینک | درباره | خوشآمد]`
_ربات آنهارا ثبت خواهد کرد_
*پاک کردن* `[بن | مدیران | ربات | قوانین | درباره | لیست سکوت | خوشآمد]`
_ربات آنهارا پاک خواهد کرد_
*لیست سفید* `[+|-]`
_افزودن افراد به لیست سفید_
*فیلتر* `[کلمه]`
_فیلترکلمه مورد نظر_
*حذف فیلتر* `[کلمه]`
_ازاد کردن کلمه مورد نظر_
*سنجاق* `[reply]`
_ربات پیام شمارا در گروه سنجاق خواهد کرد_
*حذف سنجاق*
_ربات پیام سنجاق شده در گروه را حذف خواهد کرد_
*!خوشآمد فعال/غیرفعال*
_فعال یا غیرفعال کردن خوشآمد گویی_
*تنظیمات*
_نمایش تنظیمات گروه_
*دستورات* `[کاربر | مدیر | مالک]`
_نتخاب کردن قفل cmd بر چه مدیریتی_
*لیست سکوت*
_نمایش فهرست افراد بیصدا_
*فیلتر لیست*
_نمایش لیست کلمات فیلتر شده_
*لیست سفید*
_نمایش افراد سفید شده از گروه_
*لیست بن*
_نمایش افراد مسدود شده از گروه_
*لیست مالکان*
_نمایش فهرست مالکان گروه_
*لیست مدیران*
_نمایش فهرست مدیران گروه_
*قوانین*
_نمایش قوانین گروه_
*درباره*
_نمایش درباره گروه_
*ایدی*
_نمایش شناسه شما و گروه_
*اطلاعات گروه*
_نمایش اطلاعات گروه_
*لینک جدید*
_ساخت لینک جدید_
*لینک جدید خصوصی*
_ساخت لینک جدید در پیوی_
*لینک*
_نمایش لینک گروه_
*لینک خصوصی*
_ارسال لینک گروه به چت خصوصی شما_
*زبان انگلیسی*
_تنظیم زبان انگلیسی_
*!تنظیم خوشآمد [متن]*
_ثبت پیام خوش آمد گویی_
_این راهنما فقط برای مدیران/مالکان گروه میباشد!
این به این معناست که فقط مدیران/مالکان گروه میتوانند از دستورات بالا استفاده کنند!_
*موفق باشید ;)*]]
end
return Management
end
-----------------------------------------
if matches[1]:lower() == "helpfun" or matches[1] == "راهنما سرگرمی" and is_mod(msg) then
if not lang then
helpfun = [[
_PCT Reborn Fun Help Commands:_
*!time*
_Get time in a sticker_
*!short* `[link]`
_Make short url_
*!voice* `[text]`
_Convert text to voice_
*!tr* `[lang] [word]`
_Translates FA to EN and EN to FA_
_Example:_
*!tr fa hi*
*!sticker* `[word]`
_Convert text to sticker_
*!photo* `[word]`
_Convert text to photo_
*!azan* `[city]`
_Get Azan time for your city_
*!calc* `[number]`
Calculator
*!praytime* `[city]`
_Get Patent (Pray Time)_
*!tosticker* `[reply]`
_Convert photo to sticker_
*!tophoto* `[reply]`
_Convert text to photo_
*!weather* `[city]`
_Get weather_
_You can use_ *[!/#]* _at the beginning of commands._
*Good luck ;)*]]
tdcli.sendMessage(msg.chat_id_, 0, 1, helpfun, 1, 'md')
else
helpfun = [[
_راهنمای سرگرمی ربات پروتکشن:_
*ساعت*
_دریافت ساعت به صورت استیکر_
*لینک کوتاه* `[لینک]`
_کوتاه کننده لینک_
*تبدیل به صدا* `[متن]`
_تبدیل متن به صدا_
*ترجمه* `[زبان]` `[کلمه]`
_ترجمه متن فارسی به انگلیسی وبرعکس_
_مثال:_
_ترجمه زبان سلام_
*استیکر* `[کلمه]`
_تبدیل متن به استیکر_
*عکس* `[کلمه]`
_تبدیل متن به عکس_
*اذان* `[شهر]`
_دریافت اذان_
*حساب کن* `[عدد]`
_ماشین حساب_
*ساعات شرعی* `[شهر]`
_اعلام ساعات شرعی_
*تبدیل به استیکر* `[ریپلی]`
_تبدیل عکس به استیکر_
*تبدیل به عکس* `[ریپلی]`
_تبدیل استیکربه عکس_
*اب هوا* `[شهر]`
_دریافت اب وهوا_
*شما میتوانید از [!/#] در اول دستورات برای اجرای آنها بهره بگیرید*
موفق باشید ;)]]
tdcli.sendMessage(msg.chat_id_, 0, 1, helpfun, 1, 'md')
end
end
-----------------------------------------
if matches[1] == "helptools" or matches[1] == "راهنما ابزار" and is_mod(msg) then
if not lang then
text = [[
_Sudoer And Admins PCT Bot Help :_
*!visudo* `[username|id|reply]`
_Add Sudo_
*!desudo* `[username|id|reply]`
_Demote Sudo_
*!sudolist *
_Sudo(s) list_
*!adminprom* `[username|id|reply]`
_Add admin for bot_
*!admindem* `[username|id|reply]`
_Demote bot admin_
*!adminlist *
_Admin(s) list_
*!leave *
_Leave current group_
*!autoleave* `[disable/enable]`
_Automatically leaves group_
*!creategroup* `[text]`
_Create normal group_
*!createsuper* `[text]`
_Create supergroup_
*!tosuper *
_Convert to supergroup_
*!chats*
_List of added groups_
*!join* `[id]`
_Adds you to the group_
*!rem* `[id]`
_Remove a group from Database_
*!import* `[link]`
_Bot joins via link_
*!setbotname* `[text]`
_Change bot's name_
*!setbotusername* `[text]`
_Change bot's username_
*!delbotusername *
_Delete bot's username_
*!markread* `[off/on]`
_Second mark_
*!broadcast* `[text]`
_Send message to all added groups_
*!bc* `[text] [gpid]`
_Send message to a specific group_
*!sendfile* `[folder] [file]`
_Send file from folder_
*!sendplug* `[plug]`
_Send plugin_
*!del* `[Reply]`
_Remove message Person you are_
*!save* `[plugin name] [reply]`
_Save plugin by reply_
*!savefile* `[address/filename] [reply]`
_Save File by reply to specific folder_
*!clear cache*
_Clear All Cache Of .telegram-cli/data_
*!check*
_Stated Expiration Date_
*!check* `[GroupID]`
_Stated Expiration Date Of Specific Group_
*!charge* `[GroupID]` `[Number Of Days]`
_Set Expire Time For Specific Group_
*!charge* `[Number Of Days]`
_Set Expire Time For Group_
*!jointo* `[GroupID]`
_Invite You To Specific Group_
*!leave* `[GroupID]`
_Leave Bot From Specific Group_
_You can use_ *[!/#]* _at the beginning of commands._
`This help is only for sudoers/bot admins.`
*This means only the sudoers and its bot admins can use mentioned commands.*
*Good luck ;)*]]
tdcli.sendMessage(msg.chat_id_, 0, 1, text, 1, 'md')
else
text = [[
_راهنمای ادمین و سودو های ربات پروتکشن:_
*سودو* `[username|id|reply]`
_اضافه کردن سودو_
*حذف سودو* `[username|id|reply]`
_حذف کردن سودو_
*لیست سودو*
_لیست سودوهای ربات_
*ادمین* `[username|id|reply]`
_اضافه کردن ادمین به ربات_
*حذف ادمین* `[username|id|reply]`
_حذف فرد از ادمینی ربات_
*لیست ادمین*
_لیست ادمین ها_
*خروج*
_خارج شدن ربات از گروه_
*خروج خودکار* `[غیرفعال/فعال | موقعیت]`
_خروج خودکار_
*ساخت گروه* `[اسم انتخابی]`
_ساخت گروه ریلم_
*ساخت سوپر گروه* `[اسم انتخابی]`
_ساخت سوپر گروه_
*تبدیل به سوپر*
_تبدیل به سوپر گروه_
*لیست گروه ها*
_لیست گروه های مدیریتی ربات_
*افزودن* `[ایدی گروه]`
_جوین شدن توسط ربات_
*حذف گروه* `[ایدی گروه]`
_حذف گروه ازطریق پنل مدیریتی_
*ورود لینک* `[لینک_]`
_جوین شدن ربات توسط لینک_
*تغییر نام ربات* `[text]`
_تغییر اسم ربات_
*تغییر یوزرنیم ربات* `[text]`
_تغییر یوزرنیم ربات_
*حذف یوزرنیم ربات*
_پاک کردن یوزرنیم ربات_
*تیک دوم* `[فعال/غیرفعال]`
_تیک دوم_
*ارسال به همه* `[متن]`
_فرستادن پیام به تمام گروه های مدیریتی ربات_
*ارسال* `[متن]` `[ایدی گروه]`
_ارسال پیام مورد نظر به گروه خاص_
*ارسال فایل* `[cd]` `[file]`
_ارسال فایل موردنظر از پوشه خاص_
*ارسال پلاگین* `[اسم پلاگین]`
_ارسال پلاگ مورد نظر_
* ذخیره پلاگین* `[اسم پلاگین] [reply]`
_ذخیره کردن پلاگین_
*ذخیره فایل* `[address/filename] [reply]`
_ذخیره کردن فایل در پوشه مورد نظر_
*پاک کردن حافظه*
_پاک کردن کش مسیر .telegram-cli/data_
*اعتبار*
_اعلام تاریخ انقضای گروه_
*اعتبار* `[ایدی گروه]`
_اعلام تاریخ انقضای گروه مورد نظر_
*شارژ* `[ایدی گروه]` `[تعداد روز]`
_تنظیم تاریخ انقضای گروه مورد نظر_
*شارژ* `[تعداد روز]`
_تنظیم تاریخ انقضای گروه_
*ورود به* `[ایدی گروه]`
_دعوت شدن شما توسط ربات به گروه مورد نظر_
*خروج* `[ایدی گروه]`
_خارج شدن ربات از گروه مورد نظر_
*شما میتوانید از [!/#] در اول دستورات برای اجرای آنها بهره بگیرید*
_این راهنما فقط برای سودو ها/ادمین های ربات میباشد!_
`این به این معناست که فقط سودو ها/ادمین های ربات میتوانند از دستورات بالا استفاده کنند!`
*موفق باشید ;)*]]
tdcli.sendMessage(msg.chat_id_, 0, 1, text, 1, 'md')
end
end
--------------------- Welcome -----------------------
if (matches[1]:lower() == "welcome" or matches[1] == 'خوشآمد') and is_mod(msg) then
if not lang then
if matches[2] == "enable" then
welcome = data[tostring(chat)]['settings']['welcome']
if welcome == "yes" then
return "_Group_ *welcome* *Iѕ AƖяєαɗу ƐηαвƖєɗ*⚠️♻️"
else
data[tostring(chat)]['settings']['welcome'] = "yes"
save_data(_config.moderation.data, data)
return "_Group_ *welcome* *Hαѕ Ɓєєη ƐηαвƖєɗ*🔇\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
end
end
if matches[2] == "disable" then
welcome = data[tostring(chat)]['settings']['welcome']
if welcome == "no" then
return "_Group_ *Welcome* *Iѕ AƖяєαɗу ƊιѕαвƖєɗ*⚠️🚫"
else
data[tostring(chat)]['settings']['welcome'] = "no"
save_data(_config.moderation.data, data)
return "_Group_ *welcome* *Hαѕ Ɓєєη ƊιѕαвƖєɗ*🔊\n*OяƊєя Ɓу :* `"..msg.from.id.."`"
end
end
else
if matches[2] == "فعال" then
welcome = data[tostring(chat)]['settings']['welcome']
if welcome == "yes" then
return "_خوشآمد گویی از قبل فعال بود_"
else
data[tostring(chat)]['settings']['welcome'] = "yes"
save_data(_config.moderation.data, data)
return "_خوشآمد گویی فعال شد_"
end
end
if matches[2] == "غیرفعال" then
welcome = data[tostring(chat)]['settings']['welcome']
if welcome == "no" then
return "_خوشآمد گویی از قبل فعال نبود_"
else
data[tostring(chat)]['settings']['welcome'] = "no"
save_data(_config.moderation.data, data)
return "_خوشآمد گویی غیرفعال شد_"
end
end
end
end
if (matches[1]:lower() == "setwelcome" or matches[1] == 'تنظیم خوشآمد') and matches[2] and is_mod(msg) then
data[tostring(chat)]['setwelcome'] = matches[2]
save_data(_config.moderation.data, data)
if not lang then
return "_Welcome Message Has Been Set To :_\n*"..matches[2].."*\n\n*You can use :*\n_{gpname} Group Name_\n_{rules} ➣ Show Group Rules_\n_{time} ➣ Show time english _\n_{date} ➣ Show date english _\n_{timefa} ➣ Show time persian _\n_{datefa} ➣ show date persian _\n_{name} ➣ New Member First Name_\n_{username} ➣ New Member Username_"
else
return "_پیام خوشآمد گویی تنظیم شد به :_\n*"..matches[2].."*\n\n*شما میتوانید از*\n_{gpname} نام گروه_\n_{rules} ➣ نمایش قوانین گروه_\n_{time} ➣ ساعت به زبان انگلیسی _\n_{date} ➣ تاریخ به زبان انگلیسی _\n_{timefa} ➣ ساعت به زبان فارسی _\n_{datefa} ➣ تاریخ به زبان فارسی _\n_{name} ➣ نام کاربر جدید_\n_{username} ➣ نام کاربری کاربر جدید_\n_استفاده کنید_"
end
end
end
end
if msg.to.type ~= 'pv' then
if (matches[1]:lower() == "kick" or matches[1] == "اخراج") and is_mod(msg) then
if not matches[2] and msg.reply_id then
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.to.id,
message_id_ = msg.reply_id
}, action_by_reply, {chat_id=msg.to.id,cmd="kick"})
end
if matches[2] and string.match(matches[2], '^%d+$') then
if is_mod1(msg.to.id, userid) then
if not lang then
tdcli.sendMessage(msg.to.id, "", 0, "_You can't kick mods,owners or bot admins_", 0, "md")
elseif lang then
tdcli.sendMessage(msg.to.id, "", 0, "*شما نمیتوانید مدیران،صاحبان گروه و ادمین های ربات رو اخراج کنید*", 0, "md")
end
else
kick_user(matches[2], msg.to.id)
end
end
if matches[2] and not string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "SearchPublicChat",
username_ = matches[2]
}, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="kick"})
end
end
if (matches[1]:lower() == "delall" or matches[1] == "حذف پیام") and is_mod(msg) then
if not matches[2] and msg.reply_id then
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.to.id,
message_id_ = msg.reply_id
}, action_by_reply, {chat_id=msg.to.id,cmd="delall"})
end
if matches[2] and string.match(matches[2], '^%d+$') then
if is_mod1(msg.to.id, userid) then
if not lang then
return tdcli.sendMessage(msg.to.id, "", 0, "_You can't delete messages mods,owners or bot admins_", 0, "md")
elseif lang then
return tdcli.sendMessage(msg.to.id, "", 0, "*شما نمیتوانید پیام های مدیران،صاحبان گروه و ادمین های ربات رو پاک کنید*", 0, "md")
end
else
tdcli.deleteMessagesFromUser(msg.to.id, matches[2], dl_cb, nil)
if not lang then
return tdcli.sendMessage(msg.to.id, "", 0, "_All_ *messages* _of_ *[ "..matches[2].." ]* _has been_ *deleted*", 0, "md")
elseif lang then
return tdcli.sendMessage(msg.to.id, "", 0, "*تمامی پیام های* *[ "..matches[2].." ]* *پاک شد*", 0, "md")
end
end
end
if matches[2] and not string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "SearchPublicChat",
username_ = matches[2]
}, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="delall"})
end
end
end
if (matches[1]:lower() == "banall" or matches[1] == "سوپر بن") and is_admin(msg) then
if not matches[2] and msg.reply_id then
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.to.id,
message_id_ = msg.reply_id
}, action_by_reply, {chat_id=msg.to.id,cmd="banall"})
end
if matches[2] and string.match(matches[2], '^%d+$') then
if is_admin1(userid) then
if not lang then
return tdcli.sendMessage(msg.to.id, "", 0, "_You can't globally ban other admins_", 0, "md")
else
return tdcli.sendMessage(msg.to.id, "", 0, "*شما نمیتوانید ادمین های ربات رو از گروه های ربات محروم کنید*", 0, "md")
end
end
if is_gbanned(matches[2]) then
if not lang then
return tdcli.sendMessage(msg.to.id, "", 0, "*User "..matches[2].." is already globally banned*", 0, "md")
else
return tdcli.sendMessage(msg.to.id, "", 0, "*کاربر "..matches[2].." از گروه های ربات محروم بود*", 0, "md")
end
end
data['gban_users'][tostring(matches[2])] = ""
save_data(_config.moderation.data, data)
kick_user(matches[2], msg.to.id)
if not lang then
return tdcli.sendMessage(msg.to.id, msg.id, 0, "*User "..matches[2].." has been globally banned*", 0, "md")
else
return tdcli.sendMessage(msg.to.id, msg.id, 0, "*کاربر "..matches[2].." از تمام گروه هار ربات محروم شد*", 0, "md")
end
end
if matches[2] and not string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "SearchPublicChat",
username_ = matches[2]
}, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="banall"})
end
end
if (matches[1]:lower() == "unbanall" or matches[1] == "حذف سوپر بن") and is_admin(msg) then
if not matches[2] and msg.reply_id then
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.to.id,
message_id_ = msg.reply_id
}, action_by_reply, {chat_id=msg.to.id,cmd="unbanall"})
end
if matches[2] and string.match(matches[2], '^%d+$') then
if not is_gbanned(matches[2]) then
if not lang then
return tdcli.sendMessage(msg.to.id, "", 0, "*User "..matches[2].." is not globally banned*", 0, "md")
else
return tdcli.sendMessage(msg.to.id, "", 0, "*کاربر "..matches[2].." از گروه های ربات محروم نبود*", 0, "md")
end
end
data['gban_users'][tostring(matches[2])] = nil
save_data(_config.moderation.data, data)
if not lang then
return tdcli.sendMessage(msg.to.id, msg.id, 0, "*User "..matches[2].." has been globally unbanned*", 0, "md")
else
return tdcli.sendMessage(msg.to.id, msg.id, 0, "*کاربر "..matches[2].." از محرومیت گروه های ربات خارج شد*", 0, "md")
end
end
if matches[2] and not string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "SearchPublicChat",
username_ = matches[2]
}, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="unbanall"})
end
end
if msg.to.type ~= 'pv' then
if matches[1]:lower() == "ban" or matches[1] == "بن" and is_mod(msg) then
if not matches[2] and msg.reply_id then
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.to.id,
message_id_ = msg.reply_id
}, action_by_reply, {chat_id=msg.to.id,cmd="ban"})
end
if matches[2] and string.match(matches[2], '^%d+$') then
if is_mod1(msg.to.id, userid) then
if not lang then
return tdcli.sendMessage(msg.to.id, "", 0, "_You can't ban mods,owners or bot admins_", 0, "md")
else
return tdcli.sendMessage(msg.to.id, "", 0, "*شما نمیتوانید مدیران،صاحبان گروه و ادمین های ربات رو از گروه محروم کنید*", 0, "md")
end
end
if is_banned(matches[2], msg.to.id) then
if not lang then
return tdcli.sendMessage(msg.to.id, "", 0, "_User "..matches[2].." is already banned_", 0, "md")
else
return tdcli.sendMessage(msg.to.id, "", 0, "*کاربر "..matches[2].." از گروه محروم بود*", 0, "md")
end
end
data[tostring(chat)]['banned'][tostring(matches[2])] = ""
save_data(_config.moderation.data, data)
kick_user(matches[2], msg.to.id)
if not lang then
return tdcli.sendMessage(msg.to.id, msg.id, 0, "_User "..matches[2].." has been banned_", 0, "md")
else
return tdcli.sendMessage(msg.to.id, msg.id, 0, "*کاربر "..matches[2].." از گروه محروم شد*", 0, "md")
end
end
if matches[2] and not string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "SearchPublicChat",
username_ = matches[2]
}, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="ban"})
end
end
if (matches[1]:lower() == "unban" or matches[1] == "حذف بن") and is_mod(msg) then
if not matches[2] and msg.reply_id then
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.to.id,
message_id_ = msg.reply_id
}, action_by_reply, {chat_id=msg.to.id,cmd="unban"})
end
if matches[2] and string.match(matches[2], '^%d+$') then
if not is_banned(matches[2], msg.to.id) then
if not lang then
return tdcli.sendMessage(msg.to.id, "", 0, "_User "..matches[2].." is not banned_", 0, "md")
else
return tdcli.sendMessage(msg.to.id, "", 0, "*کاربر "..matches[2].." از گروه محروم نبود*", 0, "md")
end
end
data[tostring(chat)]['banned'][tostring(matches[2])] = nil
save_data(_config.moderation.data, data)
if not lang then
return tdcli.sendMessage(msg.to.id, msg.id, 0, "_User "..matches[2].." has been unbanned_", 0, "md")
else
return tdcli.sendMessage(msg.to.id, msg.id, 0, "*کاربر "..matches[2].." از محرومیت گروه خارج شد*", 0, "md")
end
end
if matches[2] and not string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "SearchPublicChat",
username_ = matches[2]
}, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="unban"})
end
end
if (matches[1]:lower() == "silent" or matches[1] == "سکوت") and is_mod(msg) then
if not matches[2] and msg.reply_id then
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.to.id,
message_id_ = msg.reply_id
}, action_by_reply, {chat_id=msg.to.id,cmd="silent"})
end
if matches[2] and string.match(matches[2], '^%d+$') then
if is_mod1(msg.to.id, userid) then
if not lang then
return tdcli.sendMessage(msg.to.id, "", 0, "_You can't silent mods,leaders or bot admins_", 0, "md")
else
return tdcli.sendMessage(msg.to.id, "", 0, "*شما نمیتوانید توانایی چت کردن رو از مدیران،صاحبان گروه و ادمین های ربات بگیرید*", 0, "md")
end
end
if is_silent_user(matches[2], chat) then
if not lang then
return tdcli.sendMessage(msg.to.id, "", 0, "_User "..matches[2].." is already silent_", 0, "md")
else
return tdcli.sendMessage(msg.to.id, "", 0, "*کاربر "..matches[2].." از قبل توانایی چت کردن رو نداشت*", 0, "md")
end
end
data[tostring(chat)]['is_silent_users'][tostring(matches[2])] = ""
save_data(_config.moderation.data, data)
if not lang then
return tdcli.sendMessage(msg.to.id, msg.id, 0, "_User "..matches[2].." added to silent users list_", 0, "md")
else
return tdcli.sendMessage(msg.to.id, msg.id, 0, "*کاربر "..matches[2].." توانایی چت کردن رو از دست داد*", 0, "md")
end
end
if matches[2] and not string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "SearchPublicChat",
username_ = matches[2]
}, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="silent"})
end
end
if (matches[1]:lower() == "unsilent" or matches[1] == "حذف سکوت") and is_mod(msg) then
if not matches[2] and msg.reply_id then
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.to.id,
message_id_ = msg.reply_id
}, action_by_reply, {chat_id=msg.to.id,cmd="unsilent"})
end
if matches[2] and string.match(matches[2], '^%d+$') then
if not is_silent_user(matches[2], chat) then
if not lang then
return tdcli.sendMessage(msg.to.id, "", 0, "_User "..matches[2].." is not silent_", 0, "md")
else
return tdcli.sendMessage(msg.to.id, "", 0, "*کاربر "..matches[2].." از قبل توانایی چت کردن رو داشت*", 0, "md")
end
end
data[tostring(chat)]['is_silent_users'][tostring(matches[2])] = nil
save_data(_config.moderation.data, data)
if not lang then
return tdcli.sendMessage(msg.to.id, msg.id, 0, "_User "..matches[2].." removed from silent users list_", 0, "md")
else
return tdcli.sendMessage(msg.to.id, msg.id, 0, "*کاربر "..matches[2].." توانایی چت کردن رو به دست آورد*", 0, "md")
end
end
if matches[2] and not string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "SearchPublicChat",
username_ = matches[2]
}, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="unsilent"})
end
end
if (matches[1]:lower() == 'clean' or matches[1] == "پاک کردن") and is_owner(msg) then
if not lang then
if matches[2]:lower() == 'bans' then
if next(data[tostring(chat)]['banned']) == nil then
return "_No_ *banned* _users in this group_"
end
for k,v in pairs(data[tostring(chat)]['banned']) do
data[tostring(chat)]['banned'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
return "_All_ *banned* _users has been unbanned_"
end
if matches[2]:lower() == 'silentlist' then
if next(data[tostring(chat)]['is_silent_users']) == nil then
return "_No_ *silent* _users in this group_"
end
for k,v in pairs(data[tostring(chat)]['is_silent_users']) do
data[tostring(chat)]['is_silent_users'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
return "*Silent list* _has been cleaned_"
end
else
if matches[2] == 'بن لیست' then
if next(data[tostring(chat)]['banned']) == nil then
return "*هیچ کاربری از این گروه محروم نشده*"
end
for k,v in pairs(data[tostring(chat)]['banned']) do
data[tostring(chat)]['banned'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
return "*تمام کاربران محروم شده از گروه از محرومیت خارج شدند*"
end
if matches[2] == 'لیست سکوت' then
if next(data[tostring(chat)]['is_silent_users']) == nil then
return "*لیست کاربران سایلنت شده خالی است*"
end
for k,v in pairs(data[tostring(chat)]['is_silent_users']) do
data[tostring(chat)]['is_silent_users'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
return "*لیست کاربران سایلنت شده پاک شد*"
end
end
end
end
if (matches[1]:lower() == 'clean' or matches[1]:lower() == 'پاک کردن') and is_sudo(msg) then
if not lang then
if matches[2]:lower() == 'gbans' then
if next(data['gban_users']) == nil then
return "_No_ *globally banned* _users available_"
end
for k,v in pairs(data['gban_users']) do
data['gban_users'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
return "_All_ *globally banned* _users has been unbanned_"
end
else
if matches[2] == 'لیست سوپر بن' then
if next(data['gban_users']) == nil then
return "*هیچ کاربری از گروه های ربات محروم نشده*"
end
for k,v in pairs(data['gban_users']) do
data['gban_users'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
return "*تمام کاربرانی که از گروه های ربات محروم بودند از محرومیت خارج شدند*"
end
end
end
if matches[1]:lower() == "gbanlist" and is_admin(msg) or matches[1] == "لیست سوپر بن" and is_admin(msg) then
return gbanned_list(msg)
end
if msg.to.type ~= 'pv' then
if matches[1]:lower() == "silentlist" and is_mod(msg) or matches[1] == "لیست سکوت" and is_mod(msg) then
return silent_users_list(chat)
end
if matches[1]:lower() == "banlist" and is_mod(msg) or matches[1] == "لیست بن" and is_mod(msg) then
return banned_list(chat)
end
end
end
local checkmod = true
-----------------------------------------
local function pre_process(msg)
local chat = msg.to.id
local user = msg.from.id
local hash = "gp_lang:"..chat
local lang = redis:get(hash)
local data = load_data(_config.moderation.data)
if checkmod and msg.text and msg.to.type == 'channel' then
tdcli.getChannelMembers(msg.to.id, 0, 'Administrators', 200, function(a, b)
local secchk = true
checkmod = false
for k,v in pairs(b.members_) do
if v.user_id_ == tonumber(our_id) then
secchk = false
end
end
if secchk then
checkmod = false
if not lang then
return tdcli.sendMessage(msg.to.id, 0, 1, '_Robot isn\'t Administrator, Please promote to Admin!_', 1, "md")
else
return tdcli.sendMessage(msg.to.id, 0, 1, '_لطفا برای کارکرد کامل دستورات، ربات را به مدیر گروه ارتقا دهید._', 1, "md")
end
end
end, nil)
end
local function welcome_cb(arg, data)
local url , res = http.request('http://irapi.ir/time/')
if res ~= 200 then return "No connection" end
local jdat = json:decode(url)
administration = load_data(_config.moderation.data)
if administration[arg.chat_id]['setwelcome'] then
welcome = administration[arg.chat_id]['setwelcome']
else
if not lang then
welcome = "*Welcome Dude*"
elseif lang then
welcome = "_خوش آمدید_"
end
end
if administration[tostring(arg.chat_id)]['rules'] then
rules = administration[arg.chat_id]['rules']
else
if not lang then
rules = "ℹ️ The Default Rules :\n1⃣ No Flood.\n2⃣ No Spam.\n3⃣ No Advertising.\n4⃣ Try to stay on topic.\n5⃣ Forbidden any racist, sexual, homophobic or gore content.\n➡️ Repeated failure to comply with these rules will cause ban.\n@ProtectionTeam"
elseif lang then
rules = "ℹ️ قوانین پپیشفرض:\n1⃣ ارسال پیام مکرر ممنوع.\n2⃣ اسپم ممنوع.\n3⃣ تبلیغ ممنوع.\n4⃣ سعی کنید از موضوع خارج نشید.\n5⃣ هرنوع نژاد پرستی, شاخ بازی و پورنوگرافی ممنوع .\n➡️ از قوانین پیروی کنید, در صورت عدم رعایت قوانین اول اخطار و در صورت تکرار مسدود.\n@ProtectionTeam"
end
end
if data.username_ then
user_name = "@"..check_markdown(data.username_)
else
user_name = ""
end
local welcome = welcome:gsub("{rules}", rules)
local welcome = welcome:gsub("{name}", check_markdown(data.first_name_..' '..(data.last_name_ or '')))
local welcome = welcome:gsub("{username}", user_name)
local welcome = welcome:gsub("{time}", jdat.ENtime)
local welcome = welcome:gsub("{date}", jdat.ENdate)
local welcome = welcome:gsub("{timefa}", jdat.FAtime)
local welcome = welcome:gsub("{datefa}", jdat.FAdate)
local welcome = welcome:gsub("{gpname}", arg.gp_name)
tdcli.sendMessage(arg.chat_id, arg.msg_id, 0, welcome, 0, "md")
end
if data[tostring(chat)] and data[tostring(chat)]['settings'] then
if msg.adduser then
welcome = data[tostring(msg.to.id)]['settings']['welcome']
if welcome == "yes" then
tdcli.getUser(msg.adduser, welcome_cb, {chat_id=chat,msg_id=msg.id_,gp_name=msg.to.title})
else
return false
end
end
if msg.joinuser then
welcome = data[tostring(msg.to.id)]['settings']['welcome']
if welcome == "yes" then
tdcli.getUser(msg.sender_user_id_, welcome_cb, {chat_id=chat,msg_id=msg.id_,gp_name=msg.to.title})
else
return false
end
end
end
if msg.to.type ~= 'pv' then
chat = msg.to.id
user = msg.from.id
local function check_newmember(arg, data)
test = load_data(_config.moderation.data)
lock_bots = test[arg.chat_id]['settings']['lock_bots']
local hash = "gp_lang:"..arg.chat_id
local lang = redis:get(hash)
if data.type_.ID == "UserTypeBot" then
if not is_owner(arg.msg) and lock_bots == 'yes' then
kick_user(data.id_, arg.chat_id)
end
end
if data.username_ then
user_name = '@'..check_markdown(data.username_)
else
user_name = check_markdown(data.first_name_)
end
if is_banned(data.id_, arg.chat_id) then
if not lang then
tdcli.sendMessage(arg.chat_id, arg.msg_id, 0, "_User_ "..user_name.." *[ "..data.id_.." ]* _is banned_", 0, "md")
else
tdcli.sendMessage(arg.chat_id, arg.msg_id, 0, "_کاربر_ "..user_name.." *[ "..data.id.."]*_banned_", 0, "md")
end
kick_user(data.id_, arg.chat_id)
end
if is_gbanned(data.id_) then
if not lang then
tdcli.sendMessage(arg.chat_id, arg.msg_id, 0, "_User_ "..user_name.." *[ "..data.id_.." ]* _is globally banned_", 0, "md")
else
tdcli.sendMessage(arg.chat_id, arg.msg_id, 0, "_کاربر_ "..user_name.." *[ "..data.id_.." ]* _از تمام گروه های ربات محروم است_", 0, "md")
end
kick_user(data.id_, arg.chat_id)
end
end
if msg.adduser then
tdcli_function ({
ID = "GetUser",
user_id_ = msg.adduser
}, check_newmember, {chat_id=chat,msg_id=msg.id,user_id=user,msg=msg})
end
if msg.joinuser then
tdcli_function ({
ID = "GetUser",
user_id_ = msg.joinuser
}, check_newmember, {chat_id=chat,msg_id=msg.id,user_id=user,msg=msg})
end
if is_silent_user(msg.from.id, msg.to.id) then
del_msg(msg.to.id, msg.id)
return false
end
if is_banned(msg.from.id, msg.to.id) then
del_msg(msg.to.id, tonumber(msg.id))
kick_user(msg.from.id, msg.to.id)
return false
end
if is_gbanned(msg.from.id) then
del_msg(msg.to.id, tonumber(msg.id))
kick_user(msg.from.id, msg.to.id)
return false
end
end
return msg
end
return {
description = "Plugin to manage other plugins. Enable, disable or reload.",
usage = {
moderator = {
"!pl - [plugin] chat : disable plugin only this chat.",
"!pl + [plugin] chat : enable plugin only this chat.",
},
sudo = {
"!plist : list all plugins.",
"!pl + [plugin] : enable plugin.",
"!pl - [plugin] : disable plugin.",
"!pl * : reloads all plugins." },
},
patterns ={
command .. "([Ii]d)$",
command .. "([Aa]dd)$",
command .. "([Pp]lugin)$",
command .. "([Pp]l) (+) ([%w_%.%-]+)$",
command .. "([Pp]l) (-) ([%w_%.%-]+)$",
command .. "([Pp]l) (+) ([%w_%.%-]+) (chat)$",
command .. "([Pp]l) (-) ([%w_%.%-]+) (chat)$",
command .. "([Pp]l) (*)$",
command .. "([Rr]eload)$",
command .. "([Rr]em)$",
command .. "([Ii]d) (.*)$",
command .. "([Pp]in)$",
command .. "([Uu]npin)$",
command .. "([Gg]pinfo)$",
command .. "([Ss]etmanager)$",
command .. "([Ss]etmanager) (.*)$",
command .. "([Rr]emmanager)$",
command .. "([Rr]emmanager) (.*)$",
command .. "([Ww]hitelist) ([+-])$",
command .. "([Ww]hitelist) ([+-]) (.*)$",
command .. "([Ww]hitelist)$",
command .. "([Ss]etowner)$",
command .. "([Ss]etowner) (.*)$",
command .. "([Rr]emowner)$",
command .. "([Rr]emowner) (.*)$",
command .. "([Pp]romote)$",
command .. "([Pp]romote) (.*)$",
command .. "([Dd]emote)$",
command .. "([Dd]emote) (.*)$",
command .. "([Mm]odlist)$",
command .. "([Oo]wnerlist)$",
command .. "([Ll]ock) (.*)$",
command .. "([Uu]nlock) (.*)$",
command .. "([Mm]ute) (.*)$",
command .. "([Uu]nmute) (.*)$",
command .. "([Ll]ink)$",
command .. "([Ll]ink) (pv)$",
command .. "([Ss]etlink)$",
command .. "([Ss]etlink) ([https?://w]*.?telegram.me/joinchat/%S+)$",
command .. "([Ss]etlink) ([https?://w]*.?t.me/joinchat/%S+)$",
command .. "([Nn]ewlink)$",
command .. "([Nn]ewlink) (pv)$",
command .. "([Rr]ules)$",
command .. "([Ss]ettings)$",
command .. "([Ss]etrules) (.*)$",
command .. "([Aa]bout)$",
command .. "([Ss]etabout) (.*)$",
command .. "([Ss]etname) (.*)$",
command .. "([Cc]lean) (.*)$",
command .. "([Ss]etflood) (%d+)$",
command .. "([Ss]etchar) (%d+)$",
command .. "([Ss]etfloodtime) (%d+)$",
command .. "([Rr]es) (.*)$",
command .. "([Cc]mds) (.*)$",
command .. "([Ww]hois) (%d+)$",
command .. "([Hh]elp)$",
command .. "([Ss]etlang) (fa)$",
command .. "([Ff]ilter) (.*)$",
command .. "([Uu]nfilter) (.*)$",
command .. "([Ff]ilterlist)$",
command .. "([Cc]onfig)$",
command .. "([Ss]etwelcome) (.*)",
command .. "([Ww]elcome) (.*)$",
command .. '([Mm]uteall) (status)$',
command .. '([Hh]elpmute)$',
command .. '([Mm]utetime) (%d+) (%d+) (%d+)$',
command .. '([Mm]utehours) (%d+)$',
command .. '([Mm]uteminutes) (%d+)$',
command .. '([Mm]uteseconds) (%d+)$',
command .. "([Hh]elplock)$",
command .. "([Hh]elpmanag)$",
command .. "([Hh]elpfun)$",
command .. "([Hh]elptools)$",
command .. "([Ii]nvite) @(.*)$",
command .. "([Ii]nvite) (.*)$",
command .. "([Ii]nvite)$",
command .. "([Ee]dit) (.*)$",
command .. "([Ee]dit) (.*)$",
command .. "([Cc]lean) ([Bb]lacklist)$",
command .. "([Aa]ddkick)$",
command .. "([Cc]leanbot)$",
command .. "([Pp]ing)$",
command .. "([Ss]etnerkh) (.*)$",
command .. "([Dd]elnerkh)$",
command .. "([Nn]erkh)$",
command .. "([Ee]cho) (.*)$",
command .. "([Dd][Ee][Ll]) (%d+)$",
command .. "([Bb]anall)$",
command .. "([Bb]anall) (.*)$",
command .. "([Uu]nbanall)$",
command .. "([Uu]nbanall) (.*)$",
command .. "([Gg]banlist)$",
command .. "([Bb]an)$",
command .. "([Bb]an) (.*)$",
command .. "([Uu]nban)$",
command .. "([Uu]nban) (.*)$",
command .. "([Bb]anlist)$",
command .. "([Ss]ilent)$",
command .. "([Ss]ilent) (.*)$",
command .. "([Uu]nsilent)$",
command .. "([Uu]nsilent) (.*)$",
command .. "([Ss]ilentlist)$",
command .. "([Kk]ick)$",
command .. "([Kk]ick) (.*)$",
command .. "([Dd]elall)$",
command .. "([Dd]elall) (.*)$",
command .. "([Cc]lean) (.*)$",
"^([https?://w]*.?telegram.me/joinchat/%S+)$",
"^([https?://w]*.?t.me/joinchat/%S+)$",
"^([Ii][Dd])$",
"^([Aa][Dd][Dd])$",
"^([Rr][Ee][Mm])$",
"^([Ii][Dd]) (.*)$",
"^([Pp][Ii][Nn])$",
"^([Uu][Nn][Pp][Ii][Nn])$",
"^([Gg][Pp][Ii][Nn][Ff][Oo])$",
"^([Ss][Ee][Tt][Mm][Aa][Nn][Aa][Gg][Ee][Rr])$",
"^([Ss][Ee][Tt][Mm][Aa][Nn][Aa][Gg][Ee][Rr]) (.*)$",
"^([Rr][Ee][Mm][Mm][Aa][Nn][Aa][Gg][Ee][Rr])$",
"^([Rr][Ee][Mm][Mm][Aa][Nn][Aa][Gg][Ee][Rr]) (.*)$",
"^([Ww][Hh][Ii][Tt][Ee][Ll][Ii][Ss][Tt]) ([+-])$",
"^([Ww][Hh][Ii][Tt][Ee][Ll][Ii][Ss][Tt]) ([+-]) (.*)$",
"^([Ww][Hh][Ii][Tt][Ee][Ll][Ii][Ss][Tt])$",
"^([Ss][Ee][Tt][Oo][Ww][Nn][Ee][Rr])$",
"^([Ss][Ee][Tt][Oo][Ww][Nn][Ee][Rr]) (.*)$",
"^([Rr][Ee][Mm][Oo][Ww][Nn][Ee][Rr])$",
"^([Rr][Ee][Mm][Oo][Ww][Nn][Ee][Rr]) (.*)$",
"^([Pp][Rr][Oo][Mm][Oo][Tt][Ee])$",
"^([Pp][Rr][Oo][Mm][Oo][Tt][Ee]) (.*)$",
"^([Dd][Ee][Mm][Oo][Tt][Ee])$",
"^([Dd][Ee][Mm][Oo][Tt][Ee]) (.*)$",
"^([Mm][Oo][Dd][Ll][Ii][Ss][Tt])$",
"^([Oo][Ww][Nn][Ee][Rr][Ll][Ii][Ss][Tt])$",
"^([Ll][Oo][Cc][Kk]) (.*)$",
"^([Uu][Nn][Ll][Oo][Cc][Kk]) (.*)$",
"^([Mm][Uu][Tt][Ee]) (.*)$",
"^([Uu][Nn][Mm][Uu][Tt][Ee]) (.*)$",
"^([Ll][Ii][Nn][Kk])$",
"^([Ll][Ii][Nn][Kk]) (pv)$",
"^([Ss][Ee][Tt][Ll][Ii][Nn][Kk])$",
"^([Ss][Ee][Tt][Ll][Ii][Nn][Kk]) ([https?://w]*.?telegram.me/joinchat/%S+)$",
"^([Ss][Ee][Tt][Ll][Ii][Nn][Kk]) ([https?://w]*.?[Tt].me/joinchat/%S+)$",
"^([Nn][Ee][Ww][Ll][Ii][Nn][Kk])$",
"^([Nn][Ee][Ww][Ll][Ii][Nn][Kk]) (pv)$",
"^([Rr][Uu][Ll][Ee][Ss])$",
"^([Ss][Ee][Tt][Tt][Ii][Nn][Gg][Ss])$",
"^([Mm][Uu][Tt][Ee][Ll][Ii][Ss][Tt])$",
"^([Ss][Ee][Tt][Rr][Uu][Ll][Ee][Ss]) (.*)$",
"^([Bb][Oo][Uu][Tt])$",
"^([Ss][Ee][Tt][Aa][Bb][Oo][Uu][Tt]) (.*)$",
"^([Ss][Ee][Tt][Nn][Aa][Mm][Ee]) (.*)$",
"^([Cc][Ll][Ee][Aa][Nn]) (.*)$",
"^([Ss][Ee][Tt][Ff][Ll][Oo][Oo][Dd]) (%d+)$",
"^([Ss][Ee][Tt][Cc][Hh][Aa][Rr]) (%d+)$",
"^([Ss][Ee][Tt][Ff][Ll][Oo][Oo][Dd][Tt][Ii][Mm][Ee]) (%d+)$",
"^([Rr][Ee][Ss]) (.*)$",
"^([Cc][Mm][Dd][Ss]) (.*)$",
"^([Ww][Hh][Oo][Ii][Ss]) (%d+)$",
"^([Hh][Ee][Ll][Pp])$",
"^([Ss][Ee][Tt][Ll][Aa][Nn][Gg]) (fa)$",
"^([Ff][Ii][Ll][Tt][Ee][Rr]) (.*)$",
"^([Uu][Nn][Ff][Ii][Ll][Tt][Ee][Rr]) (.*)$",
"^([Ff][Ii][Ll][Tt][Ee][Rr][Ll][Ii][Ss][Tt])$",
"^([Cc][Oo][Nn][Ff][Ii][Gg])$",
"^([Ss][Ee][Tt][Ww][Ee][Ll][Cc][Oo][Mm][Ee]) (.*)",
"^([Ww][Ee][Ll][Cc][Oo][Mm][Ee]) (.*)",
'^([Mm][Uu][Tt][Ee][Aa][Ll][Ll]) ([Ss][Tt][Aa][Tt][Uu][Ss])$',
'^([Hh][Ee][Ll][Pp][Mm][Uu][Tt][Ee])$',
'^([Mm][Uu][Tt][Ee][Tt][Ii][Mm][Ee]) (%d+) (%d+) (%d+)$',
'^([Mm][Uu][Tt][Ee][Hh][Oo][Uu][Rr][Ss]) (%d+)$',
'^([Mm][Uu][Tt][Ee][Mm][Ii][Nn][Uu][Tt][Ee][Ss]) (%d+)$',
'^([Mm][Uu][Tt][Ee][Ss][Ee][Cc][Oo][Nn][Dd][Ss]) (%d+)$',
"^([Hh][Ee][Ll][Pp][Ll][Oo][Cc][Kk])$",
"^([Hh][Ee][Ll][Pp][Mm][Aa][Nn][Aa][Gg])$",
"^([Hh][Ee][Ll][Pp][Ff][Uu][Nn])$",
"^([Hh][Ee][Ll][Pp][Tt][Oo][Oo][Ll][Ss])$",
"^([Pp]lugin)$",
"^([Pp]l) (+) ([%w_%.%-]+)$",
"^([Pp]l) (-) ([%w_%.%-]+)$",
"^([Pp]l) (+) ([%w_%.%-]+) (chat)$",
"^([Pp]l) (-) ([%w_%.%-]+) (chat)$",
"^([Pp]l) (*)$",
"^([Rr]eload)$",
"^([Cc]lean) ([Bb]lacklist)$",
"^([Aa]ddkick)$",
"^([Pp]ing)$",
"^([Dd]elnerkh)$",
"^([Ss]etnerkh) (.*)$",
"^([Ee]dit) (.*)$",
"^([Ee]dit) (.*)$",
"^([Ee]cho) (.*)$",
"^([Nn]erkh)$",
"^([Cc]leanbot)$",
"^([Ii]nvite)$",
"^([Ii]nvite) @(.*)$",
"^([Ii]nvite) (.*)$",
"^([Bb]anall)$",
"^([Bb]anall) (.*)$",
"^([Uu]nbanall)$",
"^([Uu]nbanall) (.*)$",
"^([Gg]banlist)$",
"^([Bb]an)$",
"^([Bb]an) (.*)$",
"^([Uu]nban)$",
"^([Uu]nban) (.*)$",
"^([Bb]anlist)$",
"^([Ss]ilent)$",
"^([Ss]ilent) (.*)$",
"^([Uu]nsilent)$",
"^([Uu]nsilent) (.*)$",
"^([Ss]ilentlist)$",
"^([Kk]ick)$",
"^([Kk]ick) (.*)$",
"^([Dd]elall)$",
"^([Dd]elall) (.*)$",
"^([Cc]lean) (.*)$",
"^([Mm][Ee])$"
},
patterns_fa = {
'^(ایدی)$',
'^(ایدی) (.*)$',
'^(تنظیمات)$',
'^(سنجاق)$',
'^(حذف سنجاق)$',
'^(افزودن)$',
'^(حذف گروه)$',
'^(ادمین گروه)$',
'^(ادمین گروه) (.*)$',
'^(حذف ادمین گروه) (.*)$',
'^(حذف ادمین گروه)$',
'^(لیست سفید) ([+-]) (.*)$',
'^(لیست سفید) ([+-])$',
'^(لیست سفید)$',
'^(مالک)$',
'^(مالک) (.*)$',
'^(حذف مالک) (.*)$',
'^(حذف مالک)$',
'^(مدیر)$',
'^(مدیر) (.*)$',
'^(حذف مدیر)$',
'^(حذف مدیر) (.*)$',
'^(قفل) (.*)$',
'^(باز) (.*)$',
'^(بیصدا) (.*)$',
'^(باصدا) (.*)$',
'^(لینک جدید)$',
'^(لینک جدید) (خصوصی)$',
'^(اطلاعات گروه)$',
'^(دستورات) (.*)$',
'^(قوانین)$',
'^(لینک)$',
'^(تنظیم لینک)$',
'^(تنظیم لینک) ([https?://w]*.?telegram.me/joinchat/%S+)$',
'^(تنظیم لینک) ([https?://w]*.?t.me/joinchat/%S+)$',
'^(تنظیم قوانین) (.*)$',
'^(لینک) (خصوصی)$',
'^(کاربری) (.*)$',
'^(شناسه) (%d+)$',
'^(تنظیم پیام مکرر) (%d+)$',
'^(تنظیم زمان بررسی) (%d+)$',
'^(حداکثر حروف مجاز) (%d+)$',
'^(پاک کردن) (.*)$',
'^(درباره)$',
'^(تنظیم نام) (.*)$',
'^(تنظیم درباره) (.*)$',
'^(لیست فیلتر)$',
'^(لیست مالکان)$',
'^(لیست مدیران)$',
'^(راهنما)$',
'^(پیکربندی)$',
'^(فیلتر) (.*)$',
'^(حذف فیلتر) (.*)$',
'^(خوشآمد) (.*)$',
'^(تنظیم خوشآمد) (.*)$',
'^(ساعت بیصدا) (%d+)$',
'^(دقیقه بیصدا) (%d+)$',
'^(ثانیه بیصدا) (%d+)$',
'^(موقعیت) (بیصدا)$',
'^(زمان بیصدا) (%d+) (%d+) (%d+)$',
'^(زبان انگلیسی)$',
'^([https?://w]*.?telegram.me/joinchat/%S+)$',
'^([https?://w]*.?t.me/joinchat/%S+)$',
"^(راهنما قفل)$",
"^(راهنما مدیریتی)$",
"^(راهنما سرگرمی)$",
"^(راهنما ابزار)$",
"^(راهنما بیصدا)$",
"^(بارگذاری)$",
"^(لیست پلاگین)$",
"^(پلاگین) (+) ([%w_%.%-]+)$",
"^(پلاگین) (-) ([%w_%.%-]+)$",
"^(پلاگین) (+) ([%w_%.%-]+) (گروه)$",
"^(پلاگین) (-) ([%w_%.%-]+) (گروه)$",
"^(پاک کردن) (بلک لیست)$",
"^(ربات)$",
"^(افزودن ریمو)$",
"^(نرخ)$",
"^(تنظیم نرخ) (.*)$",
"^(پاک کردن نرخ)$",
"^(من)$",
"^(پاک کردن ربات) (.*)$",
"^(اکو) (.*)$",
"^( ادیت) (.*)$",
"^(سوپر بن)$",
"^(سوپر بن) (.*)$",
"^(حذف سوپر بن)$",
"^(حذف سوپر بن) (.*)$",
"^(لیست سوپر بن)$",
"^(بن)$",
"^(بن) (.*)$",
"^(حذف بن)$",
"^(حذف بن) (.*)$",
"^(لیست بن)$",
"^(سکوت)$",
"^(سکوت) (.*)$",
"^(حذف سکوت)$",
"^(حذف سکوت) (.*)$",
"^(لیست سکوت)$",
"^(اخراج)$",
"^(اخراج) (.*)$",
"^(حذف پیام)$",
"^(حذف پیام) (.*)$",
"^(پاک کردن) (.*)$",
"^(ادیت) (.*)$"
},
run=run,
pre_process = pre_process
}
-- ## @BeyondTeam
| gpl-3.0 |
mamaddeveloper/uzz | plugins/channels.lua | 356 | 1732 | -- Checks if bot was disabled on specific chat
local function is_channel_disabled( receiver )
if not _config.disabled_channels then
return false
end
if _config.disabled_channels[receiver] == nil then
return false
end
return _config.disabled_channels[receiver]
end
local function enable_channel(receiver)
if not _config.disabled_channels then
_config.disabled_channels = {}
end
if _config.disabled_channels[receiver] == nil then
return 'Channel isn\'t disabled'
end
_config.disabled_channels[receiver] = false
save_config()
return "Channel re-enabled"
end
local function disable_channel( receiver )
if not _config.disabled_channels then
_config.disabled_channels = {}
end
_config.disabled_channels[receiver] = true
save_config()
return "Channel disabled"
end
local function pre_process(msg)
local receiver = get_receiver(msg)
-- If sender is moderator then re-enable the channel
--if is_sudo(msg) then
if is_momod(msg) then
if msg.text == "!channel enable" then
enable_channel(receiver)
end
end
if is_channel_disabled(receiver) then
msg.text = ""
end
return msg
end
local function run(msg, matches)
local receiver = get_receiver(msg)
-- Enable a channel
if matches[1] == 'enable' then
return enable_channel(receiver)
end
-- Disable a channel
if matches[1] == 'disable' then
return disable_channel(receiver)
end
end
return {
description = "Plugin to manage channels. Enable or disable channel.",
usage = {
"!channel enable: enable current channel",
"!channel disable: disable current channel" },
patterns = {
"^!channel? (enable)",
"^!channel? (disable)" },
run = run,
--privileged = true,
moderated = true,
pre_process = pre_process
}
| gpl-2.0 |
MmxBoy/mmxanti2 | plugins/channels.lua | 356 | 1732 | -- Checks if bot was disabled on specific chat
local function is_channel_disabled( receiver )
if not _config.disabled_channels then
return false
end
if _config.disabled_channels[receiver] == nil then
return false
end
return _config.disabled_channels[receiver]
end
local function enable_channel(receiver)
if not _config.disabled_channels then
_config.disabled_channels = {}
end
if _config.disabled_channels[receiver] == nil then
return 'Channel isn\'t disabled'
end
_config.disabled_channels[receiver] = false
save_config()
return "Channel re-enabled"
end
local function disable_channel( receiver )
if not _config.disabled_channels then
_config.disabled_channels = {}
end
_config.disabled_channels[receiver] = true
save_config()
return "Channel disabled"
end
local function pre_process(msg)
local receiver = get_receiver(msg)
-- If sender is moderator then re-enable the channel
--if is_sudo(msg) then
if is_momod(msg) then
if msg.text == "!channel enable" then
enable_channel(receiver)
end
end
if is_channel_disabled(receiver) then
msg.text = ""
end
return msg
end
local function run(msg, matches)
local receiver = get_receiver(msg)
-- Enable a channel
if matches[1] == 'enable' then
return enable_channel(receiver)
end
-- Disable a channel
if matches[1] == 'disable' then
return disable_channel(receiver)
end
end
return {
description = "Plugin to manage channels. Enable or disable channel.",
usage = {
"!channel enable: enable current channel",
"!channel disable: disable current channel" },
patterns = {
"^!channel? (enable)",
"^!channel? (disable)" },
run = run,
--privileged = true,
moderated = true,
pre_process = pre_process
}
| gpl-2.0 |
Murfalo/game-off-2016 | hump/signal.lua | 15 | 2736 | --[[
Copyright (c) 2012-2013 Matthias Richter
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
Except as contained in this notice, the name(s) of the above copyright holders
shall not be used in advertising or otherwise to promote the sale, use or
other dealings in this Software without prior written authorization.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
]]--
local Registry = {}
Registry.__index = function(self, key)
return Registry[key] or (function()
local t = {}
rawset(self, key, t)
return t
end)()
end
function Registry:register(s, f)
self[s][f] = f
return f
end
function Registry:emit(s, ...)
for f in pairs(self[s]) do
f(...)
end
end
function Registry:remove(s, ...)
local f = {...}
for i = 1,select('#', ...) do
self[s][f[i]] = nil
end
end
function Registry:clear(...)
local s = {...}
for i = 1,select('#', ...) do
self[s[i]] = {}
end
end
function Registry:emit_pattern(p, ...)
for s in pairs(self) do
if s:match(p) then self:emit(s, ...) end
end
end
function Registry:remove_pattern(p, ...)
for s in pairs(self) do
if s:match(p) then self:remove(s, ...) end
end
end
function Registry:clear_pattern(p)
for s in pairs(self) do
if s:match(p) then self[s] = {} end
end
end
local function new()
return setmetatable({}, Registry)
end
local default = new()
return setmetatable({
new = new,
register = function(...) return default:register(...) end,
emit = function(...) default:emit(...) end,
remove = function(...) default:remove(...) end,
clear = function(...) default:clear(...) end,
emit_pattern = function(...) default:emit_pattern(...) end,
remove_pattern = function(...) default:remove_pattern(...) end,
clear_pattern = function(...) default:clear_pattern(...) end,
}, {__call = new})
| mit |
osgcc/ryzom | ryzom/common/data_common/r2/r2_ui_features_tree.lua | 3 | 8690 |
r2.FeatureTree =
{
Path = "ui:interface:r2ed_palette:content:feature_tree_panel:feature_enclosing:tree_list",
}
local featureTree = r2.FeatureTree
function featureTree.buildFeatureTreeUI()
local tree = getUI(r2.FeatureTree.Path)
if not tree then return end
local rootNode = SNode()
rootNode.Text = "Features"
rootNode.Opened = false
--rootNode.Bitmap = "r2ed_icon_macro_components.tga"
tree:setRootNode(rootNode)
featureTree.addAllFeatures()
tree:forceRebuild()
end
function featureTree.getCategoryPicture(category)
local categories = r2.getCategories()
local k, v = next(categories, nil)
while k do
if v then
if v[1] == category then
return v[2]
end
end
k, v = next(categories, k)
end
return "r2ed_icon_macro_components.tga"
end
function featureTree.getFatherNode(category)
local categories = r2.getCategories()
local k, v = next(categories, nil)
while k do
if v then
if v[1] == category then
return v[3]
end
end
k, v = next(categories, k)
end
return "root"
end
function featureTree.createParentNode(parentCategory)
local tree = getUI(r2.FeatureTree.Path)
if not tree then return end
local root = tree:getRootNode()
if not root then return end
categoryNode = SNode()
local text = i18n.hasTranslation(parentCategory)
if not text then text = parentCategory else text = i18n.get(parentCategory) end
categoryNode.Text = text
categoryNode.Id = parentCategory
categoryNode.Opened = false
--categoryNode.Bitmap = featureTree.getCategoryPicture(parentCategory)
root:addChild(categoryNode)
return categoryNode
end
function featureTree.addNodeWithId(featureName, category)
local tree = getUI(r2.FeatureTree.Path)
if not tree then return end
local root = tree:getRootNode()
if not root then return end
local categoryNode = root:getNodeFromId(category)
if not categoryNode then
categoryNode = SNode()
local text = i18n.hasTranslation(category)
if not text then text = category else text = i18n.get(category) end
categoryNode.Text = text
categoryNode.Id = category
categoryNode.Opened = false
local catFather = featureTree.getFatherNode(category)
if catFather == "root" then
--categoryNode.Bitmap = featureTree.getCategoryPicture(category)
root:addChild(categoryNode)
else
local fatherNode = root:getNodeFromId(catFather)
if not fatherNode then --if the parent node doesn't exist, attach new category to root anyway
fatherNode = featureTree.createParentNode(catFather)
end
fatherNode:addChild(categoryNode)
end
end
local featureNode = SNode()
local componentName = featureName
--special case: chat sequence is not a feature like the others
if featureName == "ChatSequence" then
featureNode.Text = i18n.get("uiR2EDChatSequence")
featureNode.AHName = "lua"
featureNode.AHParams = "r2.Features['ActivitySequence'].Components.ChatSequence:createProtected()"
categoryNode:addChild(featureNode)
return
end
if string.find(componentName, "Feature") ~= nil then
componentName = string.sub(componentName, 1, string.len(componentName) - 7)
end
featureNode.Text = i18n.get("uiR2Ed"..featureName.. "Node")
featureNode.AHName = "lua"
featureNode.AHParams = "r2.Features['".. featureName.."'].Components." ..componentName.. ":createProtected()"
categoryNode:addChild(featureNode)
end
function featureTree.addUserComponentNode(userComponentName)
local tree = getUI(r2.FeatureTree.Path)
if not tree then return false end
local root = tree:getRootNode()
if not root then return false end
local userComponentsBranch = root:getNodeFromId("uiR2EdUserComponentCategory")
if not userComponentsBranch then return end
local presentNode = root:getNodeFromId(userComponentName)
if presentNode ~= nil then
messageBox("The user component '"..userComponentName.."' is already loaded. Please unload it before loading a user component with the same name.")
return false
end
local categoryNode = root:getNodeFromId("uiR2EdLoadedUserComponentCategory")
if not categoryNode then
categoryNode = SNode()
categoryNode.Text = i18n.get("uiR2EdLoadedUserComponentCategory")
categoryNode.Id = "uiR2EdLoadedUserComponentCategory"
categoryNode.Opened = false
userComponentsBranch:addChild(categoryNode)
end
local featureNode = SNode()
featureNode.Id = userComponentName
featureNode.Text = userComponentName
featureNode.AHName = "lua"
featureNode.AHParams = "r2.Translator.CreateUserComponent('"..userComponentName.."')"
categoryNode:addChild(featureNode)
tree:forceRebuild()
return true
end
function featureTree.getUserComponentList()
local tree = getUI(r2.FeatureTree.Path)
if not tree then return false end
local root = tree:getRootNode()
if not root then return false end
local featureNameTable = {}
local userComponentCategoryNode = root:getNodeFromId("uiR2EdLoadedUserComponentCategory")
if not userComponentCategoryNode then
return {}
end
local nodeSize = userComponentCategoryNode:getNumChildren()
local i = 0
while i < nodeSize do
local node = userComponentCategoryNode:getChild(i)
table.insert(featureNameTable, node.Id)
i = i + 1
end
return featureNameTable
end
function featureTree.addAllFeatures()
local loadedFeatures = r2.getLoadedFeaturesStatic()
local k, v = next(loadedFeatures, nil)
while k do
if v then
featureTree.addNodeWithId(v[2], v[3])
end
k, v = next(loadedFeatures, k)
end
if config.R2EDLoadDynamicFeatures == 1 then
local loadBt = getUI("ui:interface:r2ed_palette:content:feature_tree_panel:user_component_buttons:load")
local unloadBt = getUI("ui:interface:r2ed_palette:content:feature_tree_panel:user_component_buttons:unload")
--loadBt.active = true
--unloadBt = true
featureTree.addLoadedUserComponents()
local btPanel = getUI("ui:interface:r2ed_palette:content:feature_tree_panel:user_component_buttons")
btPanel.active = true
local loadedFeatures = r2.getLoadedFeaturesDynamic()
local k, v = next(loadedFeatures, nil)
while k do
if v then
featureTree.addNodeWithId(v[2], v[3])
end
k, v = next(loadedFeatures, k)
end
end
end
function featureTree.addLoadedUserComponents()
local tree = getUI(r2.FeatureTree.Path)
if not tree then return end
local root = tree:getRootNode()
if not root then return end
categoryNode = SNode()
categoryNode.Text = i18n.get("uiR2EdUserComponentCategory")
categoryNode.Id = "uiR2EdUserComponentCategory"
categoryNode.Opened = false
--categoryNode.Bitmap = "r2ed_icon_macro_components.tga"
root:addChild(categoryNode)
local featureNode = SNode()
featureNode.Id = "NewComponent"
featureNode.Text = "New Component"
featureNode.AHName = "lua"
featureNode.AHParams = "r2.Features['DefaultFeature'].Components.UserComponentHolder.create()"
categoryNode:addChild(featureNode)
local loadedUserComponentTable = r2_core.UserComponentTable
if table.getn(loadedUserComponentTable) == 0 then
debugInfo("No UserComponent were previously loaded")
return
end
local k, v = next(loadedUserComponentTable, nil)
while k do
local userComponentName = v[1]
featureTree.addUserComponentNode(userComponentName)
k, v = next(loadedUserComponentTable, k)
end
end
function featureTree.removeUCFromTree(featureName)
local tree = getUI(r2.FeatureTree.Path)
if not tree then return end
local root = tree:getRootNode()
if not root then return end
local featureNode = root:getNodeFromId(featureName)
if featureNode:getFather() then
featureNode:getFather():deleteChild(featureNode)
end
local categoryNode = root:getNodeFromId("uiR2EdLoadedUserComponentCategory")
local num = categoryNode:getNumChildren()
if num == 0 then
root:deleteChild(categoryNode)
end
tree:forceRebuild()
categoryNode:addChild(featureNode)
local loadedUserComponentTable = r2_core.UserComponentTable
if table.getn(loadedUserComponentTable) == 0 then
debugInfo("No UserComponent were previously loaded")
return
end
local k, v = next(loadedUserComponentTable, nil)
while k do
local userComponentName = v[1]
featureTree.addUserComponentNode(userComponentName)
k, v = next(loadedUserComponentTable, k)
end
end
function featureTree.removeUCFromTree(featureName)
local tree = getUI(r2.FeatureTree.Path)
if not tree then return end
local root = tree:getRootNode()
if not root then return end
local featureNode = root:getNodeFromId(featureName)
if featureNode:getFather() then
featureNode:getFather():deleteChild(featureNode)
end
local categoryNode = root:getNodeFromId("uiR2EdLoadedUserComponentCategory")
local num = categoryNode:getNumChildren()
if num == 0 then
root:deleteChild(categoryNode)
end
tree:forceRebuild()
end
| agpl-3.0 |
paulmarsy/Console | Libraries/nmap/App/nselib/upnp.lua | 5 | 11442 | --- A UPNP library based on code from upnp-info initially written by
-- Thomas Buchanan. The code was factored out from upnp-info and partly
-- re-written by Patrik Karlsson <patrik@cqure.net> in order to support
-- multicast requests.
--
-- The library supports sending UPnP requests and decoding the responses
--
-- The library contains the following classes
-- * <code>Comm</code>
-- ** A class that handles communication with the UPnP service
-- * <code>Helper</code>
-- ** The helper class wraps the <code>Comm</code> class using functions with a more descriptive name.
-- * <code>Util</code>
-- ** The <code>Util</code> class contains a number of static functions mainly used to convert and sort data.
--
-- The following code snippet queries all UPnP services on the network:
-- <code>
-- local helper = upnp.Helper:new()
-- helper:setMulticast(true)
-- return stdnse.format_output(helper:queryServices())
-- </code>
--
-- This next snippet queries a specific host for the same information:
-- <code>
-- local helper = upnp.Helper:new(host, port)
-- return stdnse.format_output(helper:queryServices())
-- </code>
--
--
-- @author "Thomas Buchanan, Patrik Karlsson <patrik@cqure.net>"
--
-- Version 0.1
--
local http = require "http"
local ipOps = require "ipOps"
local nmap = require "nmap"
local stdnse = require "stdnse"
local string = require "string"
local table = require "table"
local target = require "target"
_ENV = stdnse.module("upnp", stdnse.seeall)
Util = {
--- Compare function used for sorting IP-addresses
--
-- @param a table containing first item
-- @param b table containing second item
-- @return true if a is less than b
ipCompare = function(a, b)
return ipOps.compare_ip(a, "lt", b)
end,
}
Comm = {
--- Creates a new Comm instance
--
-- @param host string containing the host name or ip
-- @param port number containing the port to connect to
-- @return o a new instance of Comm
new = function( self, host, port )
local o = {}
setmetatable(o, self)
self.__index = self
o.host = host
o.port = port
o.mcast = false
return o
end,
--- Connect to the server
--
-- @return status true on success, false on failure
connect = function( self )
if ( self.mcast ) then
self.socket = nmap.new_socket("udp")
self.socket:set_timeout(5000)
else
self.socket = nmap.new_socket()
self.socket:set_timeout(5000)
local status, err = self.socket:connect(self.host, self.port, "udp" )
if ( not(status) ) then return false, err end
end
return true
end,
--- Send the UPNP discovery request to the server
--
-- @return status true on success, false on failure
sendRequest = function( self )
-- for details about the UPnP message format, see http://upnp.org/resources/documents.asp
local payload = 'M-SEARCH * HTTP/1.1\r\n\z
Host:239.255.255.250:1900\r\n\z
ST:upnp:rootdevice\r\n\z
Man:"ssdp:discover"\r\n\z
MX:3\r\n\r\n'
local status, err
if ( self.mcast ) then
status, err = self.socket:sendto( self.host, self.port, payload )
else
status, err = self.socket:send( payload )
end
if ( not(status) ) then return false, err end
return true
end,
--- Receives one or multiple UPNP responses depending on whether
-- <code>setBroadcast</code> was enabled or not.
--
-- The function returns the
-- status and a response containing:
-- * an array (table) of responses if broadcast is used
-- * a single response if broadcast is not in use
-- * an error message if status was false
--
-- @return status true on success, false on failure
-- @return result table or string containing results or error message
-- on failure.
receiveResponse = function( self )
local status, response
local result = {}
local host_responses = {}
repeat
status, response = self.socket:receive()
if ( not(status) and #response == 0 ) then
return false, response
elseif( not(status) ) then
break
end
local status, _, _, ip, _ = self.socket:get_info()
if ( not(status) ) then
return false, "Failed to retrieve socket information"
end
if target.ALLOW_NEW_TARGETS then target.add(ip) end
if ( not(host_responses[ip]) ) then
local status, output = self:decodeResponse( response )
if ( not(status) ) then
return false, "Failed to decode UPNP response"
end
output = { output }
output.name = ip
table.insert( result, output )
host_responses[ip] = true
end
until ( not( self.mcast ) )
if ( self.mcast ) then
table.sort(result, Util.ipCompare)
return true, result
end
if ( status and #result > 0 ) then
return true, result[1]
else
return false, "Received no responses"
end
end,
--- Processes a response from a upnp device
--
-- @param response as received over the socket
-- @return status boolean true on success, false on failure
-- @return response table or string suitable for output or error message if status is false
decodeResponse = function( self, response )
local output = {}
if response ~= nil then
-- We should get a response back that has contains one line for the server, and one line for the xml file location
-- these match any combination of upper and lower case responses
local server, location
server = string.match(response, "[Ss][Ee][Rr][Vv][Ee][Rr]:%s*(.-)\r?\n")
if server ~= nil then table.insert(output, "Server: " .. server ) end
location = string.match(response, "[Ll][Oo][Cc][Aa][Tt][Ii][Oo][Nn]:%s*(.-)\r?\n")
if location ~= nil then
table.insert(output, "Location: " .. location )
local v = nmap.verbosity()
-- the following check can output quite a lot of information, so we require at least one -v flag
if v > 0 then
local status, result = self:retrieveXML( location )
if status then
table.insert(output, result)
end
end
end
if #output > 0 then
return true, output
else
return false, "Could not decode response"
end
end
end,
--- Retrieves the XML file that describes the UPNP device
--
-- @param location string containing the location of the XML file from the UPNP response
-- @return status boolean true on success, false on failure
-- @return response table or string suitable for output or error message if status is false
retrieveXML = function( self, location )
local response
local options = {}
options['header'] = {}
options['header']['Accept'] = "text/xml, application/xml, text/html"
-- if we're in multicast mode, or if the user doesn't want us to override the IP address,
-- just use the HTTP library to grab the XML file
if ( self.mcast or ( not self.override ) ) then
response = http.get_url( location, options )
else
-- otherwise, split the location into an IP address, port, and path name for the xml file
local xhost, xport, xfile
xhost = string.match(location, "http://(.-)/")
-- check to see if the host portion of the location specifies a port
-- if not, use port 80 as a standard web server port
if xhost ~= nil and string.match(xhost, ":") then
xport = string.match(xhost, ":(.*)")
xhost = string.match(xhost, "(.*):")
end
-- check to see if the IP address returned matches the IP address we scanned
if xhost ~= self.host.ip then
stdnse.debug1("IP addresses did not match! Found %s, using %s instead.", xhost, self.host.ip)
xhost = self.host.ip
end
if xport == nil then
xport = 80
end
-- extract the path name from the location field, but strip off the \r that HTTP servers return
xfile = string.match(location, "http://.-(/.-)\013")
if xfile ~= nil then
response = http.get( xhost, xport, xfile, options )
end
end
if response ~= nil then
local output = {}
-- extract information about the webserver that is handling responses for the UPnP system
local webserver = response['header']['server']
if webserver ~= nil then table.insert(output, "Webserver: " .. webserver) end
-- the schema for UPnP includes a number of <device> entries, which can a number of interesting fields
for device in string.gmatch(response['body'], "<deviceType>(.-)</UDN>") do
local fn, mnf, mdl, nm, ver
fn = string.match(device, "<friendlyName>(.-)</friendlyName>")
mnf = string.match(device, "<manufacturer>(.-)</manufacturer>")
mdl = string.match(device, "<modelDescription>(.-)</modelDescription>")
nm = string.match(device, "<modelName>(.-)</modelName>")
ver = string.match(device, "<modelNumber>(.-)</modelNumber>")
if fn ~= nil then table.insert(output, "Name: " .. fn) end
if mnf ~= nil then table.insert(output,"Manufacturer: " .. mnf) end
if mdl ~= nil then table.insert(output,"Model Descr: " .. mdl) end
if nm ~= nil then table.insert(output,"Model Name: " .. nm) end
if ver ~= nil then table.insert(output,"Model Version: " .. ver) end
end
return true, output
else
return false, "Could not retrieve XML file"
end
end,
--- Enables or disables multicast support
--
-- @param mcast boolean true if multicast is to be used, false otherwise
setMulticast = function( self, mcast )
assert( type(mcast)=="boolean", "mcast has to be either true or false")
self.mcast = mcast
local family = nmap.address_family()
self.host = (family=="inet6" and "FF02::C" or "239.255.255.250")
self.port = 1900
end,
--- Closes the socket
close = function( self ) self.socket:close() end
}
Helper = {
--- Creates a new helper instance
--
-- @param host string containing the host name or ip
-- @param port number containing the port to connect to
-- @return o a new instance of Helper
new = function( self, host, port )
local o = {}
setmetatable(o, self)
self.__index = self
o.comm = Comm:new( host, port )
return o
end,
--- Enables or disables multicast support
--
-- @param mcast boolean true if multicast is to be used, false otherwise
setMulticast = function( self, mcast ) self.comm:setMulticast(mcast) end,
--- Enables or disables whether the script will override the IP address is the Location URL
--
-- @param override boolean true if override is to be enabled, false otherwise
setOverride = function( self, override )
assert( type(override)=="boolean", "override has to be either true or false")
self.comm.override = override
end,
--- Sends a UPnP queries and collects a single or multiple responses
--
-- @return status true on success, false on failure
-- @return result table or string containing results or error message
-- on failure.
queryServices = function( self )
local status, err = self.comm:connect()
local response
if ( not(status) ) then return false, err end
status, err = self.comm:sendRequest()
if ( not(status) ) then return false, err end
status, response = self.comm:receiveResponse()
self.comm:close()
return status, response
end,
}
return _ENV;
| mit |
deepak78/new-luci | protocols/luci-proto-ipv6/luasrc/model/network/proto_6x4.lua | 63 | 1066 | -- Copyright 2011 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
local netmod = luci.model.network
local _, p
for _, p in ipairs({"6in4", "6to4", "6rd"}) do
local proto = netmod:register_protocol(p)
function proto.get_i18n(self)
if p == "6in4" then
return luci.i18n.translate("IPv6-in-IPv4 (RFC4213)")
elseif p == "6to4" then
return luci.i18n.translate("IPv6-over-IPv4 (6to4)")
elseif p == "6rd" then
return luci.i18n.translate("IPv6-over-IPv4 (6rd)")
end
end
function proto.ifname(self)
return p .. "-" .. self.sid
end
function proto.opkg_package(self)
return p
end
function proto.is_installed(self)
return nixio.fs.access("/lib/netifd/proto/" .. p .. ".sh")
end
function proto.is_floating(self)
return true
end
function proto.is_virtual(self)
return true
end
function proto.get_interfaces(self)
return nil
end
function proto.contains_interface(self, ifname)
return (netmod:ifnameof(ifc) == self:ifname())
end
netmod:register_pattern_virtual("^%s-%%w" % p)
end
| apache-2.0 |
xinjuncoding/skynet | service/service_mgr.lua | 19 | 3853 | local skynet = require "skynet"
require "skynet.manager" -- import skynet.register
local snax = require "snax"
local cmd = {}
local service = {}
local function request(name, func, ...)
local ok, handle = pcall(func, ...)
local s = service[name]
assert(type(s) == "table")
if ok then
service[name] = handle
else
service[name] = tostring(handle)
end
for _,v in ipairs(s) do
skynet.wakeup(v)
end
if ok then
return handle
else
error(tostring(handle))
end
end
local function waitfor(name , func, ...)
local s = service[name]
if type(s) == "number" then
return s
end
local co = coroutine.running()
if s == nil then
s = {}
service[name] = s
elseif type(s) == "string" then
error(s)
end
assert(type(s) == "table")
if not s.launch and func then
s.launch = true
return request(name, func, ...)
end
table.insert(s, co)
skynet.wait()
s = service[name]
if type(s) == "string" then
error(s)
end
assert(type(s) == "number")
return s
end
local function read_name(service_name)
if string.byte(service_name) == 64 then -- '@'
return string.sub(service_name , 2)
else
return service_name
end
end
function cmd.LAUNCH(service_name, subname, ...)
local realname = read_name(service_name)
if realname == "snaxd" then
return waitfor(service_name.."."..subname, snax.rawnewservice, subname, ...)
else
return waitfor(service_name, skynet.newservice, realname, subname, ...)
end
end
function cmd.QUERY(service_name, subname)
local realname = read_name(service_name)
if realname == "snaxd" then
return waitfor(service_name.."."..subname)
else
return waitfor(service_name)
end
end
local function list_service()
local result = {}
for k,v in pairs(service) do
if type(v) == "string" then
v = "Error: " .. v
elseif type(v) == "table" then
v = "Querying"
else
v = skynet.address(v)
end
result[k] = v
end
return result
end
local function register_global()
function cmd.GLAUNCH(name, ...)
local global_name = "@" .. name
return cmd.LAUNCH(global_name, ...)
end
function cmd.GQUERY(name, ...)
local global_name = "@" .. name
return cmd.QUERY(global_name, ...)
end
local mgr = {}
function cmd.REPORT(m)
mgr[m] = true
end
local function add_list(all, m)
local harbor = "@" .. skynet.harbor(m)
local result = skynet.call(m, "lua", "LIST")
for k,v in pairs(result) do
all[k .. harbor] = v
end
end
function cmd.LIST()
local result = {}
for k in pairs(mgr) do
pcall(add_list, result, k)
end
local l = list_service()
for k, v in pairs(l) do
result[k] = v
end
return result
end
end
local function register_local()
local function waitfor_remote(cmd, name, ...)
local global_name = "@" .. name
local local_name
if name == "snaxd" then
local_name = global_name .. "." .. (...)
else
local_name = global_name
end
return waitfor(local_name, skynet.call, "SERVICE", "lua", cmd, global_name, ...)
end
function cmd.GLAUNCH(...)
return waitfor_remote("LAUNCH", ...)
end
function cmd.GQUERY(...)
return waitfor_remote("QUERY", ...)
end
function cmd.LIST()
return list_service()
end
skynet.call("SERVICE", "lua", "REPORT", skynet.self())
end
skynet.start(function()
skynet.dispatch("lua", function(session, address, command, ...)
local f = cmd[command]
if f == nil then
skynet.ret(skynet.pack(nil, "Invalid command " .. command))
return
end
local ok, r = pcall(f, ...)
if ok then
skynet.ret(skynet.pack(r))
else
skynet.ret(skynet.pack(nil, r))
end
end)
local handle = skynet.localname ".service"
if handle then
skynet.error(".service is already register by ", skynet.address(handle))
skynet.exit()
else
skynet.register(".service")
end
if skynet.getenv "standalone" then
skynet.register("SERVICE")
register_global()
else
register_local()
end
end)
| mit |
Murfalo/game-off-2016 | state/Dialog.lua | 1 | 3552 |
local Gamestate = require "hump.gamestate"
local TextEngine = require "xl.TextEngine"
local Keymap = require "xl.Keymap"
local TextBox = require "xl.TextBox"
local EMPTY = {}
local Dialog = {
fgcolor = { 100, 100, 100 },
selcolor = { 0, 0, 0 },
}
local font = xl.getFont( 20 )
local TB_Size
do
local inset = 5
TB_Size = {
x = inset,
y = inset,
w = GAME_SIZE.w - inset,
h = (GAME_SIZE.h / 4) - inset,
}
end
function Dialog:enter( previous, items , bkgState)
assert(type(items)=="table", "'items' must be a table")
self.items = items
self.index = 1
self.bkgState = bkgState or Game
--Gamestate.pop()
Game.dialogState = self
self:_processOptions( items )
end
function Dialog:_processOptions( items )
-- deal with the title
if items.title then
local title = items.title
if type(title) ~= "table" then
title = { title }
end
self.textbox = TextBox( title, TB_Size.w, TB_Size.h, font , "center")
self.textbox.x = TB_Size.x
self.textbox.y = TB_Size.y
else
self.textbox = nil
end
-- now for the exit option
self.exit = nil
if items.exit then
local ty = type( items.exit )
if ty == "number" and items[items.exit] then
self.exit = items[items.exit]
elseif ty == "function" then
self.exit = { action = items.exit }
elseif ty == "table" and items.exit.action then
self.exit = items.exit
end
end
-- deal with the dialog body
local height = font:getHeight() * ( #items + 2 )
local width = 0
for k,v in ipairs(items) do
local w = font:getWidth( v.text )
if w > width then
width = w
end
end
width = width + 20
self.box = {
x = (GAME_SIZE.w / 2) - (width / 2),
y = (GAME_SIZE.h / 2) - (height / 2),
w = width,
h = height,
}
self.boxData = TextBox.BuildBackgroundData( width, height )
end
function Dialog:update( dt )
end
function Dialog:draw( )
self.bkgState:draw()
if self.textbox then
self.textbox:draw()
end
love.graphics.setFont( font )
local height = font:getHeight()
local midX = GAME_SIZE.w / 2
local y = GAME_SIZE.h / 2 - (height * #self.items / 2)
Game:nocamera( true )
love.graphics.push()
love.graphics.translate( self.box.x, self.box.y )
love.graphics.setColor(0,0,0,150)
TextBox.drawBackgroundData( self.boxData )
love.graphics.pop()
for k,v in ipairs(self.items) do
local text = v.text
local width = font:getWidth( text )
local x = midX - (width / 2)
love.graphics.setColor( k == self.index and self.selcolor or self.fgcolor )
love.graphics.printf( text, x, y, width, "center" )
y = y + height
end
love.graphics.setColor( 255,255,255 )
Game:nocamera( false )
end
function Dialog:keypressed( key, isrepeat )
if Keymap.check( "menuUp", key ) then
self.index = self.index > 1 and self.index - 1 or #self.items
end
if Keymap.check( "menuDown", key ) then
self.index = self.index < #self.items and self.index + 1 or 1
end
if Keymap.check( "menuEnter", key ) then
self:_tryUse( self.items[ self.index ] )
end
if Keymap.check( "exit", key ) and self.exit then
self:_tryUse( self.exit )
end
end
function Dialog:_tryUse( item )
-- if the action returns true we don't pop
if item.action then
if not item.action( unpack( item.args or EMPTY ) ) then
Gamestate.pop()
end
else
Log.warn( "action = nil for option \"" .. item.text .. "\"" )
Gamestate.pop()
end
end
function Dialog:setText( text )
lume.trace(text)
self.textbox:setText( text )
self.textbox:update()
end
function Dialog.display( items , bkgState)
Gamestate.push( Dialog, items, bkgState)
--coroutine.yield( true )
end
return Dialog
| mit |
benignoc/ear-training-chord-creation | Classes/Class - Checklist.lua | 1 | 6455 | --[[ Lokasenna_GUI - Checklist class
Adapted from eugen2777's simple GUI template.
---- User parameters ----
(name, z, x, y, w, h, caption, opts[, dir, pad])
Required:
z Element depth, used for hiding and disabling layers. 1 is the highest.
x, y Coordinates of top-left corner
caption Checklist title. Feel free to just use a blank string: ""
opts Comma-separated string of checklist options
Options can be skipped to create a gap in the list by using "__":
opts = "Alice,Bob,Charlie,__,Edward,Francine"
->
Alice
Bob
Charlie
Edward
Francine
Optional:
dir *** Currently does nothing, dir will always be 'v'***
"h" Boxes will extend to the right, with labels above them
"v" Boxes will extend downward, with labels to their right
pad Separation in px between boxes
Additional:
bg Color to be drawn underneath the label. Defaults to "wnd_bg"
chk_w Size of each checkbox in px. Defaults to 20.
* Changing this might screw with the spacing of your check boxes *
col_txt Text color
col_fill Checked box color
font_a List title font
font_b List option font
frame Boolean. Draw a frame around the options? Defaults to true.
shadow Boolean. Draw a shadow under the text? Defaults to true.
swap If dir = "h", draws the option labels below the boxes rather than above
"v", draws the option labels to the left of the boxes rather than right
optarray[i] Options' labels are stored here. Indexed from 1.
optsel[i] Boolean. Options' checked states are stored here. Indexed from 1.
Extra methods:
GUI.Val() Returns self.optsel as a table of boolean values for each option. Indexed from 1.
GUI.Val(new) Accepts a table of boolean values for each option. Indexed from 1.
]]--
if not GUI then
reaper.ShowMessageBox("Couldn't access GUI functions.\n\nLokasenna_GUI - Core.lua must be loaded prior to any classes.", "Library Error", 0)
missing_lib = true
return 0
end
-- Checklist - New
GUI.Checklist = GUI.Element:new()
function GUI.Checklist:new(name, z, x, y, w, h, caption, opts, dir, pad)
local chk = {}
chk.name = name
chk.type = "Checklist"
chk.z = z
GUI.redraw_z[z] = true
chk.x, chk.y, chk.w, chk.h = x, y, w, h
-- constant for the square size
chk.chk_w = 20
chk.caption = caption
chk.bg = "wnd_bg"
chk.dir = dir or "v"
chk.pad = pad or 4
chk.col_txt = "txt"
chk.col_fill = "elm_fill"
chk.font_a = 2
chk.font_b = 3
chk.frame = true
chk.shadow = true
chk.swap = false
-- Parse the string of options into a table
chk.optarray, chk.optsel = {}, {}
local tempidx = 1
for word in string.gmatch(opts, '([^,]+)') do
chk.optarray[tempidx] = word
chk.optsel[tempidx] = false
tempidx = tempidx + 1
end
chk.retval = chk.optsel
setmetatable(chk, self)
self.__index = self
return chk
end
function GUI.Checklist:init()
self.buff = self.buff or GUI.GetBuffer()
local w = self.chk_w
gfx.dest = self.buff
gfx.setimgdim(self.buff, -1, -1)
gfx.setimgdim(self.buff, 2*w + 4, w + 2)
GUI.color("elm_frame")
gfx.rect(1, 1, w, w, 0)
GUI.color(self.col_fill)
gfx.rect(w + 3 + 0.25*w, 1 + 0.25*w, 0.5*w, 0.5*w, 1)
if self.caption ~= "" then
GUI.font(self.font_a)
local str_w, str_h = gfx.measurestr(self.caption)
self.cap_h = 0.5*str_h
self.cap_x = self.x + (self.w - str_w) / 2
else
self.cap_h = 0
self.cap_x = 0
end
end
-- Checklist - Draw
function GUI.Checklist:draw()
local x, y, w, h = self.x, self.y, self.w, self.h
local dir = self.dir
local pad = self.pad
local f_color = self.col_fill
-- Draw the element frame
if self.frame then
GUI.color("elm_frame")
gfx.rect(x, y, w, h, 0)
end
if self.caption ~= "" then
GUI.font(self.font_a)
gfx.x = self.cap_x
gfx.y = y - self.cap_h
GUI.text_bg(self.caption, self.bg)
GUI.shadow(self.caption, self.col_txt, "shadow")
y = y + self.cap_h + pad
end
-- Draw the options
GUI.color("txt")
local size = self.chk_w
-- Set the options slightly into the frame
x, y = x + 0.5*pad, y + 0.5*pad
-- If horizontal, leave some extra space for labels
if dir == "h" and self.caption ~= "" and not self.swap then y = y + self.cap_h + 2*pad end
local x_adj, y_adj = table.unpack(dir == "h" and { (size + pad), 0 } or { 0, (size + pad) })
GUI.font(self.font_b)
for i = 1, #self.optarray do
local str = self.optarray[i]
if str ~= "__" then
local opt_x, opt_y = x + (i - 1) * x_adj, y + (i - 1) * y_adj
-- Draw the option frame
--GUI.color("elm_frame")
--gfx.rect(opt_x, opt_y, size, size, 0)
gfx.blit(self.buff, 1, 0, 1, 1, size, size, opt_x, opt_y)
-- Fill in if selected
if self.optsel[i] == true then
--GUI.color(f_color)
--gfx.rect(opt_x + size * 0.25, opt_y + size * 0.25, size / 2, size / 2, 1)
gfx.blit(self.buff, 1, 0, size + 3, 1, size, size, opt_x, opt_y)
end
local str_w, str_h = gfx.measurestr(self.optarray[i])
local swap = self.swap
if dir == "h" then
if not swap then
gfx.x, gfx.y = opt_x + (size - str_w) / 2, opt_y - size
else
gfx.x, gfx.y = opt_x + (size - str_w) / 2, opt_y + size + 4
end
else
if not swap then
gfx.x, gfx.y = opt_x + 1.5 * size, opt_y + (size - str_h) / 2
else
gfx.x, gfx.y = opt_x - str_w - 8, opt_y + (size - str_h) / 2
end
end
GUI.text_bg(self.optarray[i], self.bg)
if #self.optarray == 1 or self.shadow then
GUI.shadow(self.optarray[i], self.col_txt, "shadow")
else
GUI.color(self.col_txt)
gfx.drawstr(self.optarray[i])
end
end
end
end
-- Checklist - Get/set value. Returns a table of boolean values for each option.
function GUI.Checklist:val(new)
if new then
if type(new) == "table" then
for i = 1, #new do
self.optsel[i] = new[i]
end
GUI.redraw_z[self.z] = true
end
else
return self.optsel
end
end
-- Checklist - Mouse down
function GUI.Checklist:onmouseup()
-- See which option it's on
local mouseopt = self.dir == "h" and (GUI.mouse.x - (self.x + 0.5*self.chk_w))
or (GUI.mouse.y - (self.y + self.cap_h) )
mouseopt = mouseopt / ((self.chk_w + self.pad) * #self.optarray)
mouseopt = GUI.clamp( math.floor(mouseopt * #self.optarray) + 1 , 1, #self.optarray )
-- Toggle that option
self.optsel[mouseopt] = not self.optsel[mouseopt]
GUI.redraw_z[self.z] = true
--self:val()
end
| mit |
fegimanam/a | plugins/Robot.lua | 292 | 1641 | -- Checks if bot was disabled on specific chat
local function is_channel_disabled( receiver )
if not _config.disabled_channels then
return false
end
if _config.disabled_channels[receiver] == nil then
return false
end
return _config.disabled_channels[receiver]
end
local function enable_channel(receiver)
if not _config.disabled_channels then
_config.disabled_channels = {}
end
if _config.disabled_channels[receiver] == nil then
return 'Robot is Online'
end
_config.disabled_channels[receiver] = false
save_config()
return "Robot is Online"
end
local function disable_channel( receiver )
if not _config.disabled_channels then
_config.disabled_channels = {}
end
_config.disabled_channels[receiver] = true
save_config()
return "Robot is Offline"
end
local function pre_process(msg)
local receiver = get_receiver(msg)
-- If sender is moderator then re-enable the channel
--if is_sudo(msg) then
if is_momod(msg) then
if msg.text == "[!/]bot on" then
enable_channel(receiver)
end
end
if is_channel_disabled(receiver) then
msg.text = ""
end
return msg
end
local function run(msg, matches)
local receiver = get_receiver(msg)
-- Enable a channel
if matches[1] == 'on' then
return enable_channel(receiver)
end
-- Disable a channel
if matches[1] == 'off' then
return disable_channel(receiver)
end
end
return {
description = "Robot Switch",
usage = {
"/bot on : enable robot in group",
"/bot off : disable robot in group" },
patterns = {
"^[!/]bot? (on)",
"^[!/]bot? (off)" },
run = run,
privileged = true,
--moderated = true,
pre_process = pre_process
}
| gpl-2.0 |
emptyrivers/WeakAuras2 | WeakAurasOptions/AceGUI-Widgets/AceGUIWidget-WeakAurasMultiLineEditBox.lua | 1 | 12124 | if not WeakAuras.IsCorrectVersion() then return end
local Type, Version = "WeakAurasMultiLineEditBox", 35
local AceGUI = LibStub and LibStub("AceGUI-3.0", true)
if not AceGUI or (AceGUI:GetWidgetVersion(Type) or 0) >= Version then return end
-- Lua APIs
local pairs = pairs
-- WoW APIs
local GetCursorInfo, GetSpellInfo, ClearCursor = GetCursorInfo, GetSpellInfo, ClearCursor
local CreateFrame, UIParent = CreateFrame, UIParent
local _G = _G
--[[-----------------------------------------------------------------------------
Support functions
-------------------------------------------------------------------------------]]
if not AceGUIWeakAurasMultiLineEditBoxInsertLink then
-- upgradeable hook
hooksecurefunc("ChatEdit_InsertLink", function(...) return _G.AceGUIWeakAurasMultiLineEditBoxInsertLink(...) end)
end
function _G.AceGUIWeakAurasMultiLineEditBoxInsertLink(text)
for i = 1, AceGUI:GetWidgetCount(Type) do
local editbox = _G[("WeakAurasMultiLineEditBox%uEdit"):format(i)]
if editbox and editbox:IsVisible() and editbox:HasFocus() then
editbox:Insert(text)
return true
end
end
end
local function Layout(self)
self:SetHeight(self.numlines * 14 + (self.disablebutton and 19 or 41) + self.labelHeight)
if self.labelHeight == 0 then
self.scrollBar:SetPoint("TOP", self.frame, "TOP", 0, -23)
else
self.scrollBar:SetPoint("TOP", self.label, "BOTTOM", 0, -19)
end
if self.disablebutton then
self.scrollBar:SetPoint("BOTTOM", self.frame, "BOTTOM", 0, 21)
self.scrollBG:SetPoint("BOTTOMLEFT", 0, 4)
else
self.scrollBar:SetPoint("BOTTOM", self.button, "TOP", 0, 18)
self.scrollBG:SetPoint("BOTTOMLEFT", self.button, "TOPLEFT")
end
end
--[[-----------------------------------------------------------------------------
Scripts
-------------------------------------------------------------------------------]]
local function OnClick(self) -- Button
self = self.obj
self.editBox:ClearFocus()
if not self:Fire("OnEnterPressed", IndentationLib.decode(self.editBox:GetText())) then
self.button:Disable()
end
end
local function OnCursorChanged(self, _, y, _, cursorHeight) -- EditBox
self, y = self.obj.scrollFrame, -y
local offset = self:GetVerticalScroll()
if y < offset then
self:SetVerticalScroll(y)
else
y = y + cursorHeight - self:GetHeight()
if y > offset then
self:SetVerticalScroll(y)
end
end
end
local function OnEditFocusLost(self) -- EditBox
self:HighlightText(0, 0)
self.obj:Fire("OnEditFocusLost")
self.obj.scrollFrame:EnableMouseWheel(false);
end
local function OnEnter(self) -- EditBox / ScrollFrame
self = self.obj
if not self.entered then
self.entered = true
self:Fire("OnEnter")
end
end
local function OnLeave(self) -- EditBox / ScrollFrame
self = self.obj
if self.entered then
self.entered = nil
self:Fire("OnLeave")
end
end
local function OnMouseUp(self) -- ScrollFrame
self = self.obj.editBox
self:SetFocus()
self:SetCursorPosition(self:GetNumLetters())
end
local function OnReceiveDrag(self) -- EditBox / ScrollFrame
local type, id, info = GetCursorInfo()
if type == "spell" then
info = GetSpellInfo(id, info)
elseif type ~= "item" then
return
end
ClearCursor()
self = self.obj
local editBox = self.editBox
if not editBox:HasFocus() then
editBox:SetFocus()
editBox:SetCursorPosition(editBox:GetNumLetters())
end
editBox:Insert(info)
self.button:Enable()
end
local function OnSizeChanged(self, width, height) -- ScrollFrame
self.obj.editBox:SetWidth(width)
end
local function OnTextChanged(self, userInput) -- EditBox
if userInput then
self = self.obj
self:Fire("OnTextChanged", IndentationLib.decode(self.editBox:GetText()))
self.button:Enable()
end
end
local function OnTextSet(self) -- EditBox
self:HighlightText(0, 0)
self:SetCursorPosition(self:GetNumLetters())
self:SetCursorPosition(0)
self.obj.button:Disable()
end
local function OnVerticalScroll(self, offset) -- ScrollFrame
local editBox = self.obj.editBox
editBox:SetHitRectInsets(0, 0, offset, editBox:GetHeight() - offset - self:GetHeight())
end
local function OnFrameShow(frame)
if (frame.focusOnShow) then
frame.obj.editBox:SetFocus()
frame.focusOnShow = nil;
end
local self = frame.obj;
local option = self.userdata.option;
local numExtraButtons = 0;
if (option and option.arg and option.arg.extraFunctions) then
numExtraButtons = #option.arg.extraFunctions;
for index, data in ipairs(option.arg.extraFunctions) do
if (not self.extraButtons[index]) then
local extraButton = CreateFrame("Button", ("%s%dExpandButton%d"):format(Type, self.widgetNum, index), frame, "UIPanelButtonTemplate")
extraButton:SetPoint("LEFT", self.extraButtons[index - 1], "RIGHT");
extraButton:SetHeight(22)
extraButton:SetWidth(100);
self.extraButtons[index] = extraButton;
end
local extraButton = self.extraButtons[index];
extraButton:SetText(data.buttonLabel);
extraButton:SetScript("OnClick", data.func);
extraButton:Show();
end
end
for i = numExtraButtons + 1, #self.extraButtons do
self.extraButtons[i]:Hide();
end
end
local function OnEditFocusGained(frame)
AceGUI:SetFocus(frame.obj)
frame.obj:Fire("OnEditFocusGained")
frame.obj.scrollFrame:EnableMouseWheel(true);
end
--[[-----------------------------------------------------------------------------
Methods
-------------------------------------------------------------------------------]]
local methods = {
["OnAcquire"] = function(self)
self.editBox:SetText("")
self:SetDisabled(false)
self:SetWidth(200)
self:DisableButton(false)
self:SetNumLines()
self.entered = nil
self:SetMaxLetters(0)
end,
["OnRelease"] = function(self)
self:ClearFocus()
end,
["SetDisabled"] = function(self, disabled)
local editBox = self.editBox
if disabled then
editBox:ClearFocus()
editBox:EnableMouse(false)
editBox:SetTextColor(0.5, 0.5, 0.5)
self.label:SetTextColor(0.5, 0.5, 0.5)
self.scrollFrame:EnableMouse(false)
self.button:Disable()
else
editBox:EnableMouse(true)
editBox:SetTextColor(1, 1, 1)
self.label:SetTextColor(1, 0.82, 0)
self.scrollFrame:EnableMouse(true)
end
end,
["SetLabel"] = function(self, text)
if text and text ~= "" then
self.label:SetText(text)
if self.labelHeight ~= 10 then
self.labelHeight = 10
self.label:Show()
end
elseif self.labelHeight ~= 0 then
self.labelHeight = 0
self.label:Hide()
end
Layout(self)
end,
["SetNumLines"] = function(self, value)
if not value or value < 4 then
value = 4
end
self.numlines = value
Layout(self)
end,
["SetText"] = function(self, text)
self.editBox:SetText(IndentationLib.encode(text))
end,
["GetText"] = function(self)
return IndentationLib.decode(self.editBox:GetText())
end,
["SetMaxLetters"] = function (self, num)
self.editBox:SetMaxLetters(num or 0)
end,
["DisableButton"] = function(self, disabled)
self.disablebutton = disabled
if disabled then
self.button:Hide()
else
self.button:Show()
end
Layout(self)
end,
["ClearFocus"] = function(self)
self.editBox:ClearFocus()
self.frame.focusOnShow = nil;
end,
["SetFocus"] = function(self)
self.editBox:SetFocus()
if not self.frame:IsShown() then
self.frame.focusOnShow = true;
end
end,
["HighlightText"] = function(self, from, to)
self.editBox:HighlightText(from, to)
end,
["GetCursorPosition"] = function(self)
return self.editBox:GetCursorPosition()
end,
["SetCursorPosition"] = function(self, ...)
return self.editBox:SetCursorPosition(...)
end,
}
--[[-----------------------------------------------------------------------------
Constructor
-------------------------------------------------------------------------------]]
local backdrop = {
bgFile = [[Interface\Tooltips\UI-Tooltip-Background]],
edgeFile = [[Interface\Tooltips\UI-Tooltip-Border]], edgeSize = 16,
insets = { left = 4, right = 3, top = 4, bottom = 3 }
}
local function Constructor()
local frame = CreateFrame("Frame", nil, UIParent)
frame:Hide()
frame:SetScript("OnShow", OnFrameShow);
local widgetNum = AceGUI:GetNextWidgetNum(Type)
local label = frame:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
label:SetPoint("TOPLEFT", frame, "TOPLEFT", 0, -4)
label:SetPoint("TOPRIGHT", frame, "TOPRIGHT", 0, -4)
label:SetJustifyH("LEFT")
label:SetText(ACCEPT)
label:SetHeight(10)
local button = CreateFrame("Button", ("%s%dButton"):format(Type, widgetNum), frame, "UIPanelButtonTemplate")
button:SetPoint("BOTTOMLEFT", 0, 4)
button:SetHeight(22)
button:SetWidth(100)
button:SetText(ACCEPT)
button:SetScript("OnClick", OnClick)
button:Disable()
local extraButtons = {};
extraButtons[0] = button;
local scrollBG = CreateFrame("Frame", nil, frame, BackdropTemplateMixin and "BackdropTemplate")
scrollBG:SetBackdrop(backdrop)
scrollBG:SetBackdropColor(0, 0, 0)
scrollBG:SetBackdropBorderColor(0.4, 0.4, 0.4)
local scrollFrame = CreateFrame("ScrollFrame", ("%s%dScrollFrame"):format(Type, widgetNum), frame, "UIPanelScrollFrameTemplate")
scrollFrame:EnableMouseWheel(false);
local scrollBar = _G[scrollFrame:GetName() .. "ScrollBar"]
scrollBar:ClearAllPoints()
scrollBar:SetPoint("TOP", label, "BOTTOM", 0, -19)
scrollBar:SetPoint("BOTTOM", button, "TOP", 0, 18)
scrollBar:SetPoint("RIGHT", frame, "RIGHT")
scrollBG:SetPoint("TOPRIGHT", scrollBar, "TOPLEFT", 0, 19)
scrollBG:SetPoint("BOTTOMLEFT", button, "TOPLEFT")
scrollFrame:SetPoint("TOPLEFT", scrollBG, "TOPLEFT", 5, -6)
scrollFrame:SetPoint("BOTTOMRIGHT", scrollBG, "BOTTOMRIGHT", -4, 4)
scrollFrame:SetScript("OnEnter", OnEnter)
scrollFrame:SetScript("OnLeave", OnLeave)
scrollFrame:SetScript("OnMouseUp", OnMouseUp)
scrollFrame:SetScript("OnReceiveDrag", OnReceiveDrag)
scrollFrame:SetScript("OnSizeChanged", OnSizeChanged)
scrollFrame:HookScript("OnVerticalScroll", OnVerticalScroll)
local editBox = CreateFrame("EditBox", ("%s%dEdit"):format(Type, widgetNum), scrollFrame)
editBox:SetAllPoints()
editBox:SetFontObject(ChatFontNormal)
editBox:SetMultiLine(true)
editBox:EnableMouse(true)
editBox:SetAutoFocus(false)
editBox:SetCountInvisibleLetters(false)
editBox:SetScript("OnCursorChanged", OnCursorChanged)
editBox:SetScript("OnEditFocusLost", OnEditFocusLost)
editBox:SetScript("OnEnter", OnEnter)
editBox:SetScript("OnEscapePressed", editBox.ClearFocus)
editBox:SetScript("OnLeave", OnLeave)
editBox:SetScript("OnMouseDown", OnReceiveDrag)
editBox:SetScript("OnReceiveDrag", OnReceiveDrag)
editBox:SetScript("OnTextChanged", OnTextChanged)
editBox:SetScript("OnTextSet", OnTextSet)
editBox:SetScript("OnEditFocusGained", OnEditFocusGained)
scrollFrame:SetScrollChild(editBox)
local widget = {
button = button,
extraButtons = extraButtons,
editBox = editBox,
frame = frame,
label = label,
labelHeight = 10,
numlines = 4,
scrollBar = scrollBar,
scrollBG = scrollBG,
scrollFrame = scrollFrame,
type = Type,
widgetNum = widgetNum,
}
for method, func in pairs(methods) do
widget[method] = func
end
button.obj, editBox.obj, scrollFrame.obj = widget, widget, widget
return AceGUI:RegisterAsWidget(widget)
end
AceGUI:RegisterWidgetType(Type, Constructor, Version)
| gpl-2.0 |
Multi01/Arducopter-clone | Tools/CHDK-Scripts/Cannon SX260/3DR_EAI_SX260.lua | 182 | 29665 |
--[[
KAP UAV Exposure Control Script v3.1
-- Released under GPL by waterwingz and wayback/peabody
http://chdk.wikia.com/wiki/KAP_%26_UAV_Exposure_Control_Script
3DR EAI 1.0 is a fork of KAP 3.1 with settings specific to Canon cameras triggered off the Pixhawk autopilot.
Changelog:
-Modified Tv, Av, and ISO settings for the Canon SX260
-Added an option to turn the GPS on and off
-Added control of GPS settings in Main Loop
-Changed USB OneShot mode to listen for 100ms command pulse from Pixhawk
@title 3DR EAI 1.0 - Lets Map!
@param i Shot Interval (sec)
@default i 2
@range i 2 120
@param s Total Shots (0=infinite)
@default s 0
@range s 0 10000
@param j Power off when done?
@default j 0
@range j 0 1
@param e Exposure Comp (stops)
@default e 6
@values e -2.0 -1.66 -1.33 -1.0 -0.66 -0.33 0.0 0.33 0.66 1.00 1.33 1.66 2.00
@param d Start Delay Time (sec)
@default d 0
@range d 0 10000
@param y Tv Min (sec)
@default y 5
@values y None 1/60 1/100 1/200 1/400 1/640
@param t Target Tv (sec)
@default t 7
@values t 1/100 1/200 1/400 1/640 1/800 1/1000 1/1250 1/1600 1/2000
@param x Tv Max (sec)
@default x 4
@values x 1/1000 1/1250 1/1600 1/2000 1/3200 1/5000 1/10000
@param f Av Low(f-stop)
@default f 6
@values f 1.8 2.0 2.2 2.6 2.8 3.2 3.5 4.0 4.5 5.0 5.6 6.3 7.1 8.0
@param a Av Target (f-stop)
@default a 7
@values a 1.8 2.0 2.2 2.6 2.8 3.2 3.5 4.0 4.5 5.0 5.6 6.3 7.1 8.0
@param m Av Max (f-stop)
@default m 13
@values m 1.8 2.0 2.2 2.6 2.8 3.2 3.5 4.0 4.5 5.0 5.6 6.3 7.1 8.0
@param p ISO Min
@default p 0
@values p 80 100 200 400 800 1250 1600
@param q ISO Max1
@default q 1
@values q 100 200 400 800 1250 1600
@param r ISO Max2
@default r 3
@values r 100 200 400 800 1250 1600
@param n Allow use of ND filter?
@default n 0
@values n No Yes
@param z Zoom position
@default z 0
@values z Off 0% 10% 20% 30% 40% 50% 60% 70% 80% 90% 100%
@param c Focus @ Infinity Mode
@default c 3
@values c None @Shot AFL MF
@param v Video Interleave (shots)
@default v 0
@values v Off 1 5 10 25 50 100
@param w Video Duration (sec)
@default w 10
@range w 5 300
@param u Trigger Type
@default u 2
@values u Interval Cont. USB PWM
@param g GPS On
@default g 1
@range g 0 1
@param b Backlight Off?
@default b 1
@range b 0 1
@param l Logging
@default l 3
@values l Off Screen SDCard Both
--]]
props=require("propcase")
capmode=require("capmode")
-- convert user parameter to usable variable names and values
tv_table = { -320, 576, 640, 736, 832, 896, 928, 960, 992, 1024, 1056, 1113, 1180, 1276}
tv96target = tv_table[t+3]
tv96max = tv_table[x+8]
tv96min = tv_table[y+1]
sv_table = { 381, 411, 507, 603, 699, 761, 795 }
sv96min = sv_table[p+1]
sv96max1 = sv_table[q+2]
sv96max2 = sv_table[r+2]
av_table = { 171, 192, 218, 265, 285, 322, 347, 384, 417, 446, 477, 510, 543, 576 }
av96target = av_table[a+1]
av96minimum = av_table[f+1]
av96max = av_table[m+1]
ec96adjust = (e - 6)*32
video_table = { 0, 1, 5, 10, 25, 50, 100 }
video_mode = video_table[v+1]
video_duration = w
interval = i*1000
max_shots = s
poff_if_done = j
start_delay = d
backlight = b
log_mode= l
focus_mode = c
usb_mode = u
gps = g
if ( z==0 ) then zoom_setpoint = nil else zoom_setpoint = (z-1)*10 end
-- initial configuration values
nd96offset=3*96 -- ND filter's number of equivalent f-stops (f * 96)
infx = 50000 -- focus lock distance in mm (approximately 55 yards)
shot_count = 0 -- shot counter
blite_timer = 300 -- backlight off delay in 100mSec increments
old_console_timeout = get_config_value( 297 )
shot_request = false -- pwm mode flag to request a shot be taken
-- check camera Av configuration ( variable aperture and/or ND filter )
if n==0 then -- use of nd filter allowed?
if get_nd_present()==1 then -- check for ND filter only
Av_mode = 0 -- 0 = ND disabled and no iris available
else
Av_mode = 1 -- 1 = ND disabled and iris available
end
else
Av_mode = get_nd_present()+1 -- 1 = iris only , 2=ND filter only, 3= both ND & iris
end
function printf(...)
if ( log_mode == 0) then return end
local str=string.format(...)
if (( log_mode == 1) or (log_mode == 3)) then print(str) end
if ( log_mode > 1 ) then
local logname="A/3DR_EAI_log.log"
log=io.open(logname,"a")
log:write(os.date("%Y%b%d %X ")..string.format(...),"\n")
log:close()
end
end
tv_ref = { -- note : tv_ref values set 1/2 way between shutter speed values
-608, -560, -528, -496, -464, -432, -400, -368, -336, -304,
-272, -240, -208, -176, -144, -112, -80, -48, -16, 16,
48, 80, 112, 144, 176, 208, 240, 272, 304, 336,
368, 400, 432, 464, 496, 528, 560, 592, 624, 656,
688, 720, 752, 784, 816, 848, 880, 912, 944, 976,
1008, 1040, 1072, 1096, 1129, 1169, 1192, 1225, 1265, 1376 }
tv_str = {
">64",
"64", "50", "40", "32", "25", "20", "16", "12", "10", "8.0",
"6.0", "5.0", "4.0", "3.2", "2.5", "2.0", "1.6", "1.3", "1.0", "0.8",
"0.6", "0.5", "0.4", "0.3", "1/4", "1/5", "1/6", "1/8", "1/10", "1/13",
"1/15", "1/20", "1/25", "1/30", "1/40", "1/50", "1/60", "1/80", "1/100", "1/125",
"1/160", "1/200", "1/250", "1/320", "1/400", "1/500", "1/640", "1/800", "1/1000","1/1250",
"1/1600","1/2000","1/2500","1/3200","1/4000","1/5000","1/6400","1/8000","1/10000","hi" }
function print_tv(val)
if ( val == nil ) then return("-") end
local i = 1
while (i <= #tv_ref) and (val > tv_ref[i]) do i=i+1 end
return tv_str[i]
end
av_ref = { 160, 176, 208, 243, 275, 304, 336, 368, 400, 432, 464, 480, 496, 512, 544, 592, 624, 656, 688, 720, 752, 784 }
av_str = {"n/a","1.8", "2.0","2.2","2.6","2.8","3.2","3.5","4.0","4.5","5.0","5.6","5.9","6.3","7.1","8.0","9.0","10.0","11.0","13.0","14.0","16.0","hi"}
function print_av(val)
if ( val == nil ) then return("-") end
local i = 1
while (i <= #av_ref) and (val > av_ref[i]) do i=i+1 end
return av_str[i]
end
sv_ref = { 370, 397, 424, 456, 492, 523, 555, 588, 619, 651, 684, 731, 779, 843, 907 }
sv_str = {"n/a","80","100","120","160","200","250","320","400","500","640","800","1250","1600","3200","hi"}
function print_sv(val)
if ( val == nil ) then return("-") end
local i = 1
while (i <= #sv_ref) and (val > sv_ref[i]) do i=i+1 end
return sv_str[i]
end
function pline(message, line) -- print line function
fg = 258 bg=259
end
-- switch between shooting and playback modes
function switch_mode( m )
if ( m == 1 ) then
if ( get_mode() == false ) then
set_record(1) -- switch to shooting mode
while ( get_mode() == false ) do
sleep(100)
end
sleep(1000)
end
else
if ( get_mode() == true ) then
set_record(0) -- switch to playback mode
while ( get_mode() == true ) do
sleep(100)
end
sleep(1000)
end
end
end
-- focus lock and unlock
function lock_focus()
if (focus_mode > 1) then -- focus mode requested ?
if ( focus_mode == 2 ) then -- method 1 : set_aflock() command enables MF
if (chdk_version==120) then
set_aflock(1)
set_prop(props.AF_LOCK,1)
else
set_aflock(1)
end
if (get_prop(props.AF_LOCK) == 1) then printf(" AFL enabled") else printf(" AFL failed ***") end
else -- mf mode requested
if (chdk_version==120) then -- CHDK 1.2.0 : call event proc or levents to try and enable MF mode
if call_event_proc("SS.Create") ~= -1 then
if call_event_proc("SS.MFOn") == -1 then
call_event_proc("PT_MFOn")
end
elseif call_event_proc("RegisterShootSeqEvent") ~= -1 then
if call_event_proc("PT_MFOn") == -1 then
call_event_proc("MFOn")
end
end
if (get_prop(props.FOCUS_MODE) == 0 ) then -- MF not set - try levent PressSw1AndMF
post_levent_for_npt("PressSw1AndMF")
sleep(500)
end
elseif (chdk_version >= 130) then -- CHDK 1.3.0 : set_mf()
if ( set_mf(1) == 0 ) then set_aflock(1) end -- as a fall back, try setting AFL is set_mf fails
end
if (get_prop(props.FOCUS_MODE) == 1) then printf(" MF enabled") else printf(" MF enable failed ***") end
end
sleep(1000)
set_focus(infx)
sleep(1000)
end
end
function unlock_focus()
if (focus_mode > 1) then -- focus mode requested ?
if (focus_mode == 2 ) then -- method 1 : AFL
if (chdk_version==120) then
set_aflock(0)
set_prop(props.AF_LOCK,0)
else
set_aflock(0)
end
if (get_prop(props.AF_LOCK) == 0) then printf(" AFL unlocked") else printf(" AFL unlock failed") end
else -- mf mode requested
if (chdk_version==120) then -- CHDK 1.2.0 : call event proc or levents to try and enable MF mode
if call_event_proc("SS.Create") ~= -1 then
if call_event_proc("SS.MFOff") == -1 then
call_event_proc("PT_MFOff")
end
elseif call_event_proc("RegisterShootSeqEvent") ~= -1 then
if call_event_proc("PT_MFOff") == -1 then
call_event_proc("MFOff")
end
end
if (get_prop(props.FOCUS_MODE) == 1 ) then -- MF not reset - try levent PressSw1AndMF
post_levent_for_npt("PressSw1AndMF")
sleep(500)
end
elseif (chdk_version >= 130) then -- CHDK 1.3.0 : set_mf()
if ( set_mf(0) == 0 ) then set_aflock(0) end -- fall back so reset AFL is set_mf fails
end
if (get_prop(props.FOCUS_MODE) == 0) then printf(" MF disabled") else printf(" MF disable failed") end
end
sleep(100)
end
end
-- zoom position
function update_zoom(zpos)
local count = 0
if(zpos ~= nil) then
zstep=((get_zoom_steps()-1)*zpos)/100
printf("setting zoom to "..zpos.." percent step="..zstep)
sleep(200)
set_zoom(zstep)
sleep(2000)
press("shoot_half")
repeat
sleep(100)
count = count + 1
until (get_shooting() == true ) or (count > 40 )
release("shoot_half")
end
end
-- restore camera settings on shutdown
function restore()
set_config_value(121,0) -- USB remote disable
set_config_value(297,old_console_timeout) -- restore console timeout value
if (backlight==1) then set_lcd_display(1) end -- display on
unlock_focus()
if( zoom_setpoint ~= nil ) then update_zoom(0) end
if( shot_count >= max_shots) and ( max_shots > 1) then
if ( poff_if_done == 1 ) then -- did script ending because # of shots done ?
printf("power off - shot count at limit") -- complete power down
sleep(2000)
post_levent_to_ui('PressPowerButton')
else
set_record(0) end -- just retract lens
end
end
-- Video mode
function check_video(shot)
local capture_mode
if ((video_mode>0) and(shot>0) and (shot%video_mode == 0)) then
unlock_focus()
printf("Video mode started. Button:"..tostring(video_button))
if( video_button ) then
click "video"
else
capture_mode=capmode.get()
capmode.set('VIDEO_STD')
press("shoot_full")
sleep(300)
release("shoot_full")
end
local end_second = get_day_seconds() + video_duration
repeat
wait_click(500)
until (is_key("menu")) or (get_day_seconds() > end_second)
if( video_button ) then
click "video"
else
press("shoot_full")
sleep(300)
release("shoot_full")
capmode.set(capture_mode)
end
printf("Video mode finished.")
sleep(1000)
lock_focus()
return(true)
else
return(false)
end
end
-- PWM USB pulse functions
function ch1up()
printf(" * usb pulse = ch1up")
shot_request = true
end
function ch1mid()
printf(" * usb pulse = ch1mid")
if ( get_mode() == false ) then
switch_mode(1)
lock_focus()
end
end
function ch1down()
printf(" * usb pulse = ch1down")
switch_mode(0)
end
function ch2up()
printf(" * usb pulse = ch2up")
update_zoom(100)
end
function ch2mid()
printf(" * usb pulse = ch2mid")
if ( zoom_setpoint ~= nil ) then update_zoom(zoom_setpoint) else update_zoom(50) end
end
function ch2down()
printf(" * usb pulse = ch2down")
update_zoom(0)
end
function pwm_mode(pulse_width)
if pulse_width > 0 then
if pulse_width < 5 then ch1up()
elseif pulse_width < 8 then ch1mid()
elseif pulse_width < 11 then ch1down()
elseif pulse_width < 14 then ch2up()
elseif pulse_width < 17 then ch2mid()
elseif pulse_width < 20 then ch2down()
else printf(" * usb pulse width error") end
end
end
-- Basic exposure calculation using shutter speed and ISO only
-- called for Tv-only and ND-only cameras (cameras without an iris)
function basic_tv_calc()
tv96setpoint = tv96target
av96setpoint = nil
local min_av = get_prop(props.MIN_AV)
-- calculate required ISO setting
sv96setpoint = tv96setpoint + min_av - bv96meter
-- low ambient light ?
if (sv96setpoint > sv96max2 ) then -- check if required ISO setting is too high
sv96setpoint = sv96max2 -- clamp at max2 ISO if so
tv96setpoint = math.max(bv96meter+sv96setpoint-min_av,tv96min) -- recalculate required shutter speed down to Tv min
-- high ambient light ?
elseif (sv96setpoint < sv96min ) then -- check if required ISO setting is too low
sv96setpoint = sv96min -- clamp at minimum ISO setting if so
tv96setpoint = bv96meter + sv96setpoint - min_av -- recalculate required shutter speed and hope for the best
end
end
-- Basic exposure calculation using shutter speed, iris and ISO
-- called for iris-only and "both" cameras (cameras with an iris & ND filter)
function basic_iris_calc()
tv96setpoint = tv96target
av96setpoint = av96target
-- calculate required ISO setting
sv96setpoint = tv96setpoint + av96setpoint - bv96meter
-- low ambient light ?
if (sv96setpoint > sv96max1 ) then -- check if required ISO setting is too high
sv96setpoint = sv96max1 -- clamp at first ISO limit
av96setpoint = bv96meter + sv96setpoint - tv96setpoint -- calculate new aperture setting
if ( av96setpoint < av96min ) then -- check if new setting is goes below lowest f-stop
av96setpoint = av96min -- clamp at lowest f-stop
sv96setpoint = tv96setpoint + av96setpoint - bv96meter -- recalculate ISO setting
if (sv96setpoint > sv96max2 ) then -- check if the result is above max2 ISO
sv96setpoint = sv96max2 -- clamp at highest ISO setting if so
tv96setpoint = math.max(bv96meter+sv96setpoint-av96setpoint,tv96min) -- recalculate required shutter speed down to tv minimum
end
end
-- high ambient light ?
elseif (sv96setpoint < sv96min ) then -- check if required ISO setting is too low
sv96setpoint = sv96min -- clamp at minimum ISO setting if so
tv96setpoint = bv96meter + sv96setpoint - av96setpoint -- recalculate required shutter speed
if (tv96setpoint > tv96max ) then -- check if shutter speed now too fast
tv96setpoint = tv96max -- clamp at maximum shutter speed if so
av96setpoint = bv96meter + sv96setpoint - tv96setpoint -- calculate new aperture setting
if ( av96setpoint > av96max ) then -- check if new setting is goes above highest f-stop
av96setpoint = av96max -- clamp at highest f-stop
tv96setpoint = bv96meter + sv96setpoint - av96setpoint -- recalculate shutter speed needed and hope for the best
end
end
end
end
-- calculate exposure for cams without adjustable iris or ND filter
function exposure_Tv_only()
insert_ND_filter = nil
basic_tv_calc()
end
-- calculate exposure for cams with ND filter only
function exposure_NDfilter()
insert_ND_filter = false
basic_tv_calc()
if (tv96setpoint > tv96max ) then -- check if shutter speed now too fast
insert_ND_filter = true -- flag the ND filter to be inserted
bv96meter = bv96meter - nd96offset -- adjust meter for ND offset
basic_tv_calc() -- start over, but with new meter value
bv96meter = bv96meter + nd96offset -- restore meter for later logging
end
end
-- calculate exposure for cams with adjustable iris only
function exposure_iris()
insert_ND_filter = nil
basic_iris_calc()
end
-- calculate exposure for cams with both adjustable iris and ND filter
function exposure_both()
insert_ND_filter = false -- NOTE : assume ND filter never used automatically by Canon firmware
basic_iris_calc()
if (tv96setpoint > tv96max ) then -- check if shutter speed now too fast
insert_ND_filter = true -- flag the ND filter to be inserted
bv96meter = bv96meter - nd96offset -- adjust meter for ND offset
basic_iris_calc() -- start over, but with new meter value
bv96meter = bv96meter + nd96offset -- restore meter for later logging
end
end
-- ========================== Main Program =================================
set_console_layout(1 ,1, 45, 14 )
--printf("KAP 3.1 started - press MENU to exit")
printf("3DR EAI 1.0 Canon SX260 - Lets Map!")
printf("Based On KAP 3.1")
printf("Press the shutter button to pause")
bi=get_buildinfo()
printf("%s %s-%s %s %s %s", bi.version, bi.build_number, bi.build_revision, bi.platform, bi.platsub, bi.build_date)
chdk_version= tonumber(string.sub(bi.build_number,1,1))*100 + tonumber(string.sub(bi.build_number,3,3))*10 + tonumber(string.sub(bi.build_number,5,5))
if ( tonumber(bi.build_revision) > 0 ) then
build = tonumber(bi.build_revision)
else
build = tonumber(string.match(bi.build_number,'-(%d+)$'))
end
if ((chdk_version<120) or ((chdk_version==120)and(build<3276)) or ((chdk_version==130)and(build<3383))) then
printf("CHDK 1.2.0 build 3276 or higher required")
else
if( props.CONTINUOUS_AF == nil ) then caf=-999 else caf = get_prop(props.CONTINUOUS_AF) end
if( props.SERVO_AF == nil ) then saf=-999 else saf = get_prop(props.SERVO_AF) end
cmode = capmode.get_name()
printf("Mode:%s,Continuous_AF:%d,Servo_AF:%d", cmode,caf,saf)
printf(" Tv:"..print_tv(tv96target).." max:"..print_tv(tv96max).." min:"..print_tv(tv96min).." ecomp:"..(ec96adjust/96).."."..(math.abs(ec96adjust*10/96)%10) )
printf(" Av:"..print_av(av96target).." minAv:"..print_av(av96minimum).." maxAv:"..print_av(av96max) )
printf(" ISOmin:"..print_sv(sv96min).." ISO1:"..print_sv(sv96max1).." ISO2:"..print_sv(sv96max2) )
printf(" MF mode:"..focus_mode.." Video:"..video_mode.." USB:"..usb_mode)
printf(" AvM:"..Av_mode.." int:"..(interval/1000).." Shts:"..max_shots.." Dly:"..start_delay.." B/L:"..backlight)
sleep(500)
if (start_delay > 0 ) then
printf("entering start delay of ".. start_delay.." seconds")
sleep( start_delay*1000 )
end
-- CAMERA CONFIGURATION -
-- FIND config table here http://subversion.assembla.com/svn/chdk/trunk/core/conf.c
set_config_value(2,0) --Save raw: off
if (gps==1) then
set_config_value(282,1) --turn GPS on
--set_config_value(278,1) --show GPS symbol
set_config_value(261,1) --wait for signal time
set_config_value(266,5) --battery shutdown percentage
end
-- enable USB remote in USB remote moded
if (usb_mode > 0 ) then
set_config_value(121,1) -- make sure USB remote is enabled
if (get_usb_power(1) == 0) then -- can we start ?
printf("waiting on USB signal")
repeat wait_click(20) until ((get_usb_power(1) == 1) or ( is_key("menu")))
--changed sleep from 1000 to 500
else sleep(500) end
printf("USB signal received")
end
-- switch to shooting mode
switch_mode(1)
-- set zoom position
update_zoom(zoom_setpoint)
-- lock focus at infinity
lock_focus()
-- disable flash and AF assist lamp
set_prop(props.FLASH_MODE, 2) -- flash off
set_prop(props.AF_ASSIST_BEAM,0) -- AF assist off if supported for this camera
set_config_value( 297, 60) -- set console timeout to 60 seconds
if (usb_mode > 2 ) then repeat until (get_usb_power(2) == 0 ) end -- flush pulse buffer
next_shot_time = get_tick_count()
script_exit = false
if( get_video_button() == 1) then video_button = true else video_button = false end
set_console_layout(2 ,0, 45, 4 )
repeat
--BB: Set get_usb_power(2) > 7 for a 70/100s pulse
--BB: Could consider a max threshold to prevent erroneous trigger events
--eg. get_usb_power(2) > 7 && get_usb_power(2) < 13
if( ( (usb_mode < 2 ) and ( next_shot_time <= get_tick_count() ) )
or ( (usb_mode == 2 ) and (get_usb_power(2) > 7 ) )
or ( (usb_mode == 3 ) and (shot_request == true ) ) ) then
-- time to insert a video sequence ?
if( check_video(shot_count) == true) then next_shot_time = get_tick_count() end
-- intervalometer timing
next_shot_time = next_shot_time + interval
-- set focus at infinity ? (maybe redundant for AFL & MF mode but makes sure its set right)
if (focus_mode > 0) then
set_focus(infx)
sleep(100)
end
-- check exposure
local count = 0
local timeout = false
press("shoot_half")
repeat
sleep(50)
count = count + 1
if (count > 40 ) then timeout = true end
until (get_shooting() == true ) or (timeout == true)
-- shoot in auto mode if meter reading invalid, else calculate new desired exposure
if ( timeout == true ) then
release("shoot_half")
repeat sleep(50) until get_shooting() == false
shoot() -- shoot in Canon auto mode if we don't have a valid meter reading
shot_count = shot_count + 1
printf(string.format('IMG_%04d.JPG',get_exp_count()).." : shot in auto mode, meter reading invalid")
else
-- get meter reading values (and add in exposure compensation)
bv96raw=get_bv96()
bv96meter=bv96raw-ec96adjust
tv96meter=get_tv96()
av96meter=get_av96()
sv96meter=get_sv96()
-- set minimum Av to larger of user input or current min for zoom setting
av96min= math.max(av96minimum,get_prop(props.MIN_AV))
if (av96target < av96min) then av96target = av96min end
-- calculate required setting for current ambient light conditions
if (Av_mode == 1) then exposure_iris()
elseif (Av_mode == 2) then exposure_NDfilter()
elseif (Av_mode == 3) then exposure_both()
else exposure_Tv_only()
end
-- set up all exposure overrides
set_tv96_direct(tv96setpoint)
set_sv96(sv96setpoint)
if( av96setpoint ~= nil) then set_av96_direct(av96setpoint) end
if(Av_mode > 1) and (insert_ND_filter == true) then -- ND filter available and needed?
set_nd_filter(1) -- activate the ND filter
nd_string="NDin"
else
set_nd_filter(2) -- make sure the ND filter does not activate
nd_string="NDout"
end
-- and finally shoot the image
press("shoot_full_only")
sleep(100)
release("shoot_full")
repeat sleep(50) until get_shooting() == false
shot_count = shot_count + 1
-- update shooting statistic and log as required
shot_focus=get_focus()
if(shot_focus ~= -1) and (shot_focus < 20000) then
focus_string=" foc:"..(shot_focus/1000).."."..(((shot_focus%1000)+50)/100).."m"
if(focus_mode>0) then
error_string=" **WARNING : focus not at infinity**"
end
else
focus_string=" foc:infinity"
error_string=nil
end
printf(string.format('%d) IMG_%04d.JPG',shot_count,get_exp_count()))
printf(" meter : Tv:".. print_tv(tv96meter) .." Av:".. print_av(av96meter) .." Sv:"..print_sv(sv96meter).." "..bv96raw ..":"..bv96meter)
printf(" actual: Tv:".. print_tv(tv96setpoint).." Av:".. print_av(av96setpoint).." Sv:"..print_sv(sv96setpoint))
printf(" AvMin:".. print_av(av96min).." NDF:"..nd_string..focus_string )
if ((max_shots>0) and (shot_count >= max_shots)) then script_exit = true end
shot_request = false -- reset shot request flag
end
collectgarbage()
end
-- check if USB remote enabled in intervalometer mode and USB power is off -> pause if so
if ((usb_mode == 1 ) and (get_usb_power(1) == 0)) then
printf("waiting on USB signal")
unlock_focus()
switch_mode(0)
repeat wait_click(20) until ((get_usb_power(1) == 1) or ( is_key("menu")))
switch_mode(1)
lock_focus()
if ( is_key("menu")) then script_exit = true end
printf("USB wait finished")
sleep(100)
end
if (usb_mode == 3 ) then pwm_mode(get_usb_power(2)) end
if (blite_timer > 0) then
blite_timer = blite_timer-1
if ((blite_timer==0) and (backlight==1)) then set_lcd_display(0) end
end
if( error_string ~= nil) then
draw_string( 16, 144, string.sub(error_string.." ",0,42), 258, 259)
end
wait_click(100)
if( not( is_key("no_key"))) then
if ((blite_timer==0) and (backlight==1)) then set_lcd_display(1) end
blite_timer=300
if ( is_key("menu") ) then script_exit = true end
end
until (script_exit==true)
printf("script halt requested")
restore()
end
--[[ end of file ]]--
| gpl-3.0 |
topkecleon/otouto | otouto/plugins/admin/filter.lua | 1 | 1476 | --[[
filter.lua
Copyright 2018 topkecleon <drew@otou.to>
This code is licensed under the GNU AGPLv3. See /LICENSE for details.
]]--
local utilities = require('otouto.utilities')
local P = {}
function P:init(bot)
self.triggers = utilities.triggers(bot.info.username, bot.config.cmd_pat)
:t('filter', true).table
self.command = 'filter [term]'
self.doc = "Adds or removes a filter, or lists all filters. Messages containing filtered terms are deleted. \z
Filters use Lua patterns."
self.privilege = 3
self.administration = true
end
function P:action(_bot, msg, group, _user)
local admin = group.data.admin
local input = utilities.input(msg.text_lower)
local output
if input then
local idx
for i = 1, #admin.filter do
if admin.filter[i] == input then
idx = i
break
end
end
if idx then
table.remove(admin.filter, idx)
output = 'That term has been removed from the filter.'
else
table.insert(admin.filter, input)
output = 'That term has been added to the filter.'
end
elseif #admin.filter == 0 then
output = 'There are currently no filtered terms.'
else
output = '<b>Filtered terms:</b>\n• ' ..
utilities.html_escape(table.concat(admin.filter, '\n• '))
end
utilities.send_reply(msg, output, 'html')
end
return P
| agpl-3.0 |
vzaramel/kong | kong/constants.lua | 5 | 1493 | local VERSION = "0.5.0"
return {
NAME = "kong",
VERSION = VERSION,
ROCK_VERSION = VERSION.."-1",
SYSLOG = {
ADDRESS = "kong-hf.mashape.com",
PORT = 61828,
API = "api"
},
CLI = {
GLOBAL_KONG_CONF = "/etc/kong/kong.yml",
NGINX_CONFIG = "nginx.conf",
NGINX_PID = "kong.pid",
DNSMASQ_PID = "dnsmasq.pid",
},
DATABASE_NULL_ID = "00000000-0000-0000-0000-000000000000",
DATABASE_ERROR_TYPES = setmetatable ({
SCHEMA = "schema",
INVALID_TYPE = "invalid_type",
DATABASE = "database",
UNIQUE = "unique",
FOREIGN = "foreign"
}, { __index = function(t, key)
local val = rawget(t, key)
if not val then
error("'"..tostring(key).."' is not a valid errortype", 2)
end
return val
end
}),
-- Non standard headers, specific to Kong
HEADERS = {
HOST_OVERRIDE = "X-Host-Override",
PROXY_TIME = "X-Kong-Proxy-Time",
API_TIME = "X-Kong-Api-Time",
CONSUMER_ID = "X-Consumer-ID",
CONSUMER_CUSTOM_ID = "X-Consumer-Custom-ID",
CONSUMER_USERNAME = "X-Consumer-Username",
RATELIMIT_LIMIT = "X-RateLimit-Limit",
RATELIMIT_REMAINING = "X-RateLimit-Remaining"
},
AUTHENTICATION = {
QUERY = "query",
BASIC = "basic",
HEADER = "header"
},
RATELIMIT = {
PERIODS = {
"second",
"minute",
"hour",
"day",
"month",
"year"
}
}
}
| apache-2.0 |
iamliqiang/prosody-modules | mod_storage_ldap/mod_storage_ldap.lua | 32 | 4728 | -- vim:sts=4 sw=4
-- Prosody IM
-- Copyright (C) 2008-2010 Matthew Wild
-- Copyright (C) 2008-2010 Waqas Hussain
-- Copyright (C) 2012 Rob Hoelz
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
----------------------------------------
-- Constants and such --
----------------------------------------
local setmetatable = setmetatable;
local ldap = module:require 'ldap';
local vcardlib = module:require 'ldap/vcard';
local st = require 'util.stanza';
local gettime = require 'socket'.gettime;
if not ldap then
return;
end
local CACHE_EXPIRY = 300;
local params = module:get_option('ldap');
----------------------------------------
-- Utility Functions --
----------------------------------------
local function ldap_record_to_vcard(record)
return vcardlib.create {
record = record,
format = params.vcard_format,
}
end
local get_alias_for_user;
do
local user_cache;
local last_fetch_time;
local function populate_user_cache()
local ld = ldap.getconnection();
local usernamefield = params.user.usernamefield;
local namefield = params.user.namefield;
user_cache = {};
for _, attrs in ld:search { base = params.user.basedn, scope = 'onelevel', filter = params.user.filter } do
user_cache[attrs[usernamefield]] = attrs[namefield];
end
last_fetch_time = gettime();
end
function get_alias_for_user(user)
if last_fetch_time and last_fetch_time + CACHE_EXPIRY < gettime() then
user_cache = nil;
end
if not user_cache then
populate_user_cache();
end
return user_cache[user];
end
end
----------------------------------------
-- General Setup --
----------------------------------------
local ldap_store = {};
ldap_store.__index = ldap_store;
local adapters = {
roster = {},
vcard = {},
}
for k, v in pairs(adapters) do
setmetatable(v, ldap_store);
v.__index = v;
v.name = k;
end
function ldap_store:get(username)
return nil, "get method unimplemented on store '" .. tostring(self.name) .. "'"
end
function ldap_store:set(username, data)
return nil, "LDAP storage is currently read-only";
end
----------------------------------------
-- Roster Storage Implementation --
----------------------------------------
function adapters.roster:get(username)
local ld = ldap.getconnection();
local contacts = {};
local memberfield = params.groups.memberfield;
local namefield = params.groups.namefield;
local filter = memberfield .. '=' .. tostring(username);
local groups = {};
for _, config in ipairs(params.groups) do
groups[ config[namefield] ] = config.name;
end
-- XXX this kind of relies on the way we do groups at INOC
for _, attrs in ld:search { base = params.groups.basedn, scope = 'onelevel', filter = filter } do
if groups[ attrs[namefield] ] then
local members = attrs[memberfield];
for _, user in ipairs(members) do
if user ~= username then
local jid = user .. '@' .. module.host;
local record = contacts[jid];
if not record then
record = {
subscription = 'both',
groups = {},
name = get_alias_for_user(user),
};
contacts[jid] = record;
end
record.groups[ groups[ attrs[namefield] ] ] = true;
end
end
end
end
return contacts;
end
----------------------------------------
-- vCard Storage Implementation --
----------------------------------------
function adapters.vcard:get(username)
if not params.vcard_format then
return nil, '';
end
local ld = ldap.getconnection();
local filter = params.user.usernamefield .. '=' .. tostring(username);
local match = ldap.singlematch {
base = params.user.basedn,
filter = filter,
};
if match then
match.jid = username .. '@' .. module.host
return st.preserialize(ldap_record_to_vcard(match));
else
return nil, 'not found';
end
end
----------------------------------------
-- Driver Definition --
----------------------------------------
local driver = {};
function driver:open(store, typ)
local adapter = adapters[store];
if adapter and not typ then
return adapter;
end
return nil, "unsupported-store";
end
module:provides("storage", driver);
| mit |
ferstar/openwrt-dreambox | feeds/luci/luci/luci/modules/admin-full/luasrc/model/cbi/admin_system/fstab.lua | 3 | 5869 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id: fstab.lua 6562 2010-11-27 04:55:38Z jow $
]]--
require("luci.tools.webadmin")
local fs = require "nixio.fs"
local util = require "nixio.util"
local devices = {}
util.consume((fs.glob("/dev/sd*")), devices)
util.consume((fs.glob("/dev/hd*")), devices)
util.consume((fs.glob("/dev/scd*")), devices)
util.consume((fs.glob("/dev/mmc*")), devices)
local size = {}
for i, dev in ipairs(devices) do
local s = tonumber((fs.readfile("/sys/class/block/%s/size" % dev:sub(6))))
size[dev] = s and math.floor(s / 2048)
end
m = Map("fstab", translate("Mount Points"),translate("Mount Points desc"))
local mounts = luci.sys.mounts()
v = m:section(Table, mounts, translate("Mounted file systems"))
fs = v:option(DummyValue, "fs", translate("Filesystem"))
mp = v:option(DummyValue, "mountpoint", translate("Mount Point"))
avail = v:option(DummyValue, "avail", translate("Available"))
function avail.cfgvalue(self, section)
return luci.tools.webadmin.byte_format(
( tonumber(mounts[section].available) or 0 ) * 1024
) .. " / " .. luci.tools.webadmin.byte_format(
( tonumber(mounts[section].blocks) or 0 ) * 1024
)
end
used = v:option(DummyValue, "used", translate("Used"))
function used.cfgvalue(self, section)
return ( mounts[section].percent or "0%" ) .. " (" ..
luci.tools.webadmin.byte_format(
( tonumber(mounts[section].used) or 0 ) * 1024
) .. ")"
end
local mounts = luci.sys.swapfree()
v = m:section(Table, mounts, translate("Mounted Swap file systems"))
fs = v:option(DummyValue, "fs", translate("Filesystem"))
total = v:option(DummyValue, "total", translate("total"))
function total.cfgvalue(self, section)
return luci.tools.webadmin.byte_format(
( tonumber(mounts[section].total) or 0 ) * 1024
)
end
used = v:option(DummyValue, "used", translate("used"))
function used.cfgvalue(self, section)
return luci.tools.webadmin.byte_format(
( tonumber(mounts[section].used) or 0 ) * 1024
)
end
free = v:option(DummyValue, "free", translate("free"))
function free.cfgvalue(self, section)
return luci.tools.webadmin.byte_format(
( tonumber(mounts[section].free) or 0 ) * 1024
)
end
mount = m:section(TypedSection, "mount", translate("Mount Points"), translate("Mount Points define at which point a memory device will be attached to the filesystem"))
mount.anonymous = true
mount.addremove = true
mount.template = "cbi/tblsection"
mount.extedit = luci.dispatcher.build_url("admin/diskapply/fstab/mount/%s")
mount.create = function(...)
local sid = TypedSection.create(...)
if sid then
luci.http.redirect(mount.extedit % sid)
return
end
end
mount:option(Flag, "enabled", translate("Enabled")).rmempty = false
dev = mount:option(DummyValue, "device", translate("Device UUID"))
dev.cfgvalue = function(self, section)
local v
v = m.uci:get("fstab", section, "uuid")
if v then return "UUID: %s" % v end
v = m.uci:get("fstab", section, "label")
if v then return "Label: %s" % v end
v = Value.cfgvalue(self, section) or "?"
return size[v] and "%s (%s MB)" % {v, size[v]} or v
end
dev2 = mount:option(DummyValue, "device", translate("Device"))
dev2.cfgvalue = function(self, section)
local v
v = Value.cfgvalue(self, section) or "?"
return size[v] and "%s (%s MB)" % {v, size[v]} or v
end
mp = mount:option(DummyValue, "target", translate("Mount Point"))
mp.cfgvalue = function(self, section)
if m.uci:get("fstab", section, "is_rootfs") == "1" then
return "/overlay"
else
return Value.cfgvalue(self, section) or "?"
end
end
fs = mount:option(DummyValue, "fstype", translate("Filesystem"))
fs.cfgvalue = function(self, section)
return Value.cfgvalue(self, section) or "?"
end
op = mount:option(DummyValue, "options", translate("Options"))
op.cfgvalue = function(self, section)
return Value.cfgvalue(self, section) or "defaults"
end
rf = mount:option(DummyValue, "is_rootfs", translate("Root"))
rf.cfgvalue = function(self, section)
return Value.cfgvalue(self, section) == "1"
and translate("yes") or translate("no")
end
ck = mount:option(DummyValue, "enabled_fsck", translate("Check"))
ck.cfgvalue = function(self, section)
return Value.cfgvalue(self, section) == "1"
and translate("yes") or translate("no")
end
swap = m:section(TypedSection, "swap", "SWAP", translate("If your physical memory is insufficient unused data can be temporarily swapped to a swap-device resulting in a higher amount of usable <abbr title=\"Random Access Memory\">RAM</abbr>. Be aware that swapping data is a very slow process as the swap-device cannot be accessed with the high datarates of the <abbr title=\"Random Access Memory\">RAM</abbr>."))
swap.anonymous = true
swap.addremove = true
swap.template = "cbi/tblsection"
swap.extedit = luci.dispatcher.build_url("admin/diskapply/fstab/swap/%s")
swap.create = function(...)
local sid = TypedSection.create(...)
if sid then
luci.http.redirect(swap.extedit % sid)
return
end
end
swap:option(Flag, "enabled", translate("Enabled")).rmempty = false
dev = swap:option(DummyValue, "device", translate("Device UUID"))
dev.cfgvalue = function(self, section)
local v
v = m.uci:get("fstab", section, "uuid")
if v then return "UUID: %s" % v end
v = m.uci:get("fstab", section, "label")
if v then return "Label: %s" % v end
v = Value.cfgvalue(self, section) or "?"
return size[v] and "%s (%s MB)" % {v, size[v]} or v
end
dev2 = swap:option(DummyValue, "device", translate("Device"))
dev2.cfgvalue = function(self, section)
local v
v = Value.cfgvalue(self, section) or "?"
return size[v] and "%s (%s MB)" % {v, size[v]} or v
end
return m
| gpl-2.0 |
loringmoore/The-Forgotten-Server | data/migrations/7.lua | 58 | 2518 | function onUpdateDatabase()
print("> Updating database to version 8 (account viplist with description, icon and notify server side)")
db.query("RENAME TABLE `player_viplist` TO `account_viplist`")
db.query("ALTER TABLE `account_viplist` DROP FOREIGN KEY `account_viplist_ibfk_1`")
db.query("UPDATE `account_viplist` SET `player_id` = (SELECT `account_id` FROM `players` WHERE `id` = `player_id`)")
db.query("ALTER TABLE `account_viplist` CHANGE `player_id` `account_id` INT( 11 ) NOT NULL COMMENT 'id of account whose viplist entry it is'")
db.query("ALTER TABLE `account_viplist` DROP FOREIGN KEY `account_viplist_ibfk_2`")
db.query("ALTER TABLE `account_viplist` CHANGE `vip_id` `player_id` INT( 11 ) NOT NULL COMMENT 'id of target player of viplist entry'")
db.query("ALTER TABLE `account_viplist` DROP INDEX `player_id`, ADD INDEX `account_id` (`account_id`)")
db.query("ALTER TABLE `account_viplist` DROP INDEX `vip_id`, ADD INDEX `player_id` (`player_id`)")
db.query("ALTER TABLE `account_viplist` ADD FOREIGN KEY (`account_id`) REFERENCES `accounts` (`id`) ON DELETE CASCADE")
db.query("ALTER TABLE `account_viplist` ADD FOREIGN KEY (`player_id`) REFERENCES `players` (`id`) ON DELETE CASCADE")
db.query("ALTER TABLE `account_viplist` ADD `description` VARCHAR(128) NOT NULL DEFAULT '', ADD `icon` TINYINT( 2 ) UNSIGNED NOT NULL DEFAULT '0', ADD `notify` TINYINT( 1 ) NOT NULL DEFAULT '0'")
-- Remove duplicates
local resultId = db.storeQuery("SELECT `account_id`, `player_id`, COUNT(*) AS `count` FROM `account_viplist` GROUP BY `account_id`, `player_id` HAVING COUNT(*) > 1")
if resultId ~= false then
repeat
db.query("DELETE FROM `account_viplist` WHERE `account_id` = " .. result.getDataInt(resultId, "account_id") .. " AND `player_id` = " .. result.getDataInt(resultId, "player_id") .. " LIMIT " .. (result.getDataInt(resultId, "count") - 1))
until not result.next(resultId)
result.free(resultId)
end
-- Remove if an account has over 200 entries
resultId = db.storeQuery("SELECT `account_id`, COUNT(*) AS `count` FROM `account_viplist` GROUP BY `account_id` HAVING COUNT(*) > 200")
if resultId ~= false then
repeat
db.query("DELETE FROM `account_viplist` WHERE `account_id` = " .. result.getDataInt(resultId, "account_id") .. " LIMIT " .. (result.getDataInt(resultId, "count") - 200))
until not result.next(resultId)
result.free(resultId)
end
db.query("ALTER TABLE `account_viplist` ADD UNIQUE `account_player_index` (`account_id`, `player_id`)")
return true
end
| gpl-2.0 |
Murfalo/game-off-2016 | hump/gamestate.lua | 1 | 3117 | --[[
Copyright (c) 2010-2013 Matthias Richter
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
Except as contained in this notice, the name(s) of the above copyright holders
shall not be used in advertising or otherwise to promote the sale, use or
other dealings in this Software without prior written authorization.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
]]--
local function __NULL__() end
-- default gamestate produces error on every callback
local state_init = setmetatable({leave = __NULL__},
{__index = function() error("Gamestate not initialized. Use Gamestate.switch()") end})
local stack = {state_init}
local GS = {}
function GS.new(t) return t or {} end -- constructor - deprecated!
function GS.switch(to, ...)
assert(to, "Missing argument: Gamestate to switch to")
local pre = stack[#stack]
;(pre.leave or __NULL__)(pre)
;(to.init or __NULL__)(to)
to.init = nil
stack[#stack] = to
return (to.enter or __NULL__)(to, pre, ...)
end
function GS.push(to, ...)
assert(to, "Missing argument: Gamestate to switch to")
local pre = stack[#stack]
;(to.init or __NULL__)(to)
to.init = nil
stack[#stack+1] = to
return (to.enter or __NULL__)(to, pre, ...)
end
function GS.pop()
assert(#stack > 1, "No more states to pop!")
local pre = stack[#stack]
stack[#stack] = nil
return (pre.leave or __NULL__)(pre)
end
function GS.current()
return stack[#stack]
end
local all_callbacks = {
'draw', 'errhand', 'focus', 'keypressed', 'keyreleased', 'mousefocus',
'mousepressed', 'mousereleased', 'quit', 'resize', 'textinput',
'threaderror', 'update', 'visible', 'gamepadaxis', 'gamepadpressed',
'gamepadreleased', 'joystickadded', 'joystickaxis', 'joystickhat',
'joystickpressed', 'joystickreleased', 'joystickremoved'
}
function GS.registerEvents(callbacks)
local registry = {}
callbacks = callbacks or all_callbacks
for _, f in ipairs(callbacks) do
registry[f] = love[f] or __NULL__
love[f] = function(...)
registry[f](...)
return GS[f](...)
end
end
end
-- forward any undefined functions
setmetatable(GS, {__index = function(_, func)
return function(...)
return (stack[#stack][func] or __NULL__)(stack[#stack], ...)
end
end})
return GS | mit |
deepak78/new-luci | modules/luci-base/luasrc/sgi/cgi.lua | 81 | 1688 | -- Copyright 2008 Steven Barth <steven@midlink.org>
-- Licensed to the public under the Apache License 2.0.
exectime = os.clock()
module("luci.sgi.cgi", package.seeall)
local ltn12 = require("luci.ltn12")
require("nixio.util")
require("luci.http")
require("luci.sys")
require("luci.dispatcher")
-- Limited source to avoid endless blocking
local function limitsource(handle, limit)
limit = limit or 0
local BLOCKSIZE = ltn12.BLOCKSIZE
return function()
if limit < 1 then
handle:close()
return nil
else
local read = (limit > BLOCKSIZE) and BLOCKSIZE or limit
limit = limit - read
local chunk = handle:read(read)
if not chunk then handle:close() end
return chunk
end
end
end
function run()
local r = luci.http.Request(
luci.sys.getenv(),
limitsource(io.stdin, tonumber(luci.sys.getenv("CONTENT_LENGTH"))),
ltn12.sink.file(io.stderr)
)
local x = coroutine.create(luci.dispatcher.httpdispatch)
local hcache = ""
local active = true
while coroutine.status(x) ~= "dead" do
local res, id, data1, data2 = coroutine.resume(x, r)
if not res then
print("Status: 500 Internal Server Error")
print("Content-Type: text/plain\n")
print(id)
break;
end
if active then
if id == 1 then
io.write("Status: " .. tostring(data1) .. " " .. data2 .. "\r\n")
elseif id == 2 then
hcache = hcache .. data1 .. ": " .. data2 .. "\r\n"
elseif id == 3 then
io.write(hcache)
io.write("\r\n")
elseif id == 4 then
io.write(tostring(data1 or ""))
elseif id == 5 then
io.flush()
io.close()
active = false
elseif id == 6 then
data1:copyz(nixio.stdout, data2)
data1:close()
end
end
end
end
| apache-2.0 |
alexd2580/igjam2016 | src/lib/suit/slider.lua | 9 | 1608 | -- This file is part of SUIT, copyright (c) 2016 Matthias Richter
local BASE = (...):match('(.-)[^%.]+$')
return function(core, info, ...)
local opt, x,y,w,h = core.getOptionsAndSize(...)
opt.id = opt.id or info
info.min = info.min or math.min(info.value, 0)
info.max = info.max or math.max(info.value, 1)
info.step = info.step or (info.max - info.min) / 10
local fraction = (info.value - info.min) / (info.max - info.min)
local value_changed = false
opt.state = core:registerHitbox(opt.id, x,y,w,h)
if core:isActive(opt.id) then
-- mouse update
local mx,my = core:getMousePosition()
if opt.vertical then
fraction = math.min(1, math.max(0, (y+h - my) / h))
else
fraction = math.min(1, math.max(0, (mx - x) / w))
end
local v = fraction * (info.max - info.min) + info.min
if v ~= info.value then
info.value = v
value_changed = true
end
-- keyboard update
local key_up = opt.vertical and 'up' or 'right'
local key_down = opt.vertical and 'down' or 'left'
if core:getPressedKey() == key_up then
info.value = math.min(info.max, info.value + info.step)
value_changed = true
elseif core:getPressedKey() == key_down then
info.value = math.max(info.min, info.value - info.step)
value_changed = true
end
end
core:registerDraw(opt.draw or core.theme.Slider, fraction, opt, x,y,w,h)
return {
id = opt.id,
hit = core:mouseReleasedOn(opt.id),
changed = value_changed,
hovered = core:isHovered(opt.id),
entered = core:isHovered(opt.id) and not core:wasHovered(opt.id),
left = not core:isHovered(opt.id) and core:wasHovered(opt.id)
}
end
| mit |
spark51/spark_robot | plugins/pokedex.lua | 626 | 1668 | do
local images_enabled = true;
local function get_sprite(path)
local url = "http://pokeapi.co/"..path
print(url)
local b,c = http.request(url)
local data = json:decode(b)
local image = data.image
return image
end
local function callback(extra)
send_msg(extra.receiver, extra.text, ok_cb, false)
end
local function send_pokemon(query, receiver)
local url = "http://pokeapi.co/api/v1/pokemon/" .. query .. "/"
local b,c = http.request(url)
local pokemon = json:decode(b)
if pokemon == nil then
return 'No pokémon found.'
end
-- api returns height and weight x10
local height = tonumber(pokemon.height)/10
local weight = tonumber(pokemon.weight)/10
local text = 'Pokédex ID: ' .. pokemon.pkdx_id
..'\nName: ' .. pokemon.name
..'\nWeight: ' .. weight.." kg"
..'\nHeight: ' .. height.." m"
..'\nSpeed: ' .. pokemon.speed
local image = nil
if images_enabled and pokemon.sprites and pokemon.sprites[1] then
local sprite = pokemon.sprites[1].resource_uri
image = get_sprite(sprite)
end
if image then
image = "http://pokeapi.co"..image
local extra = {
receiver = receiver,
text = text
}
send_photo_from_url(receiver, image, callback, extra)
else
return text
end
end
local function run(msg, matches)
local receiver = get_receiver(msg)
local query = URL.escape(matches[1])
return send_pokemon(query, receiver)
end
return {
description = "Pokedex searcher for Telegram",
usage = "!pokedex [Name/ID]: Search the pokédex for Name/ID and get info of the pokémon!",
patterns = {
"^!pokedex (.*)$",
"^!pokemon (.+)$"
},
run = run
}
end
| gpl-2.0 |
Native-Software/Krea | CoronaGameEditor/bin/Debug/lua/radar.lua | 4 | 5549 | --- This module is provided as it by Native-Software for use into a Krea project.
-- @author Frederic Raimondi
-- @copyright Native-Software 2012- All Rights Reserved.
-- @release 1.0
-- @see object
-- @description Provides a Radar Object allowing to see the position of referenced displayObject into the scene
-- <br>Changing the content of this file is at your own risk.
-- As the software Krea uses this file to auto-generate code, it can create errors during generation if you change his content.</br>
module("radar", package.seeall)
---
-- Members of the Radar Instance
-- @class table
-- @name Fields
-- @field params The table params used to create the radar instance
-- @field tabObjects The multidimensional table containing the different categories of objects to display on the radar
-- @field surface The display object used as display radar surface
-- @field sceneWidth The scene width to display on the radar
-- @field sceneHeight The scene height to display on the radar
-- @field tabEchoColors The multidimensional table containing the different echo category colors to display on the radar
-- @field echoAlpha The alpha of the radar echos
-- @field refreshInterval The refresh interval of the radar
-- @field isEnabled Indicates whether the radar is enabled or not
Radar = {}
Radar.__index = Radar
---
-- @description Create a new Radar Instance
-- @usage Usage:
-- <ul>
-- <li><code>local params = {}
-- <br>params.name = "radar"
-- <br>params.surface = displayObject
-- <br>params.sceneWidth = 230
-- <br>params.sceneHeight = 480
-- <br>params.tabObjects = {{obj1,obj2},{obj3,obj4})
-- <br>params.tabEchoColors = {{R1,G1,B1},{R2,G2,B2}
-- <br>params.echoAlpha = 0.5
-- <br>params.refreshInterval = 100 </li>
-- <li>local radar = require("radar").Radar.create(params)</code> </li>
-- </ul>
-- @param params Lua Table containing the params
-- @return Radar Instance
function Radar.create(params)
--Init attributes of instance
local radar = {}
setmetatable(radar,Radar)
radar.params = params
if(params.tabObjects) then
radar.tabObjects = params.tabObjects
else
radar.tabObjects = {}
end
radar.surface = params.surface
radar.sceneWidth = params.sceneWidth
radar.sceneHeight = params.sceneHeight
radar.tabEchoColors = params.tabEchoColors
radar.echoAlpha = params.echoAlpha
radar.refreshInterval = params.refreshInterval
radar.isEnabled = false
radar.refresh = function()
if(radar.displayGroup) then
if(radar.displayGroup.removeSelf) then
radar.displayGroup:removeSelf()
end
radar.displayGroup = nil
end
radar.displayGroup = display.newGroup()
radar.surface.displayGroupParent:insert(radar.displayGroup)
radar.surface.object:setReferencePoint(display.TopLeftReferencePoint)
radar.currentScaleX = radar.sceneWidth / radar.surface.object.contentWidth
radar.currentScaleY = radar.sceneHeight /radar.surface.object.contentHeight
local xMin = radar.surface.object.x
local yMin = radar.surface.object.y
local xMax = radar.surface.object.x + radar.surface.object.contentWidth
local yMax = radar.surface.object.y + radar.surface.object.contentHeight
for i = 1,#radar.tabObjects do
local tabIndexToRemove = {}
for j = 1,# radar.tabObjects[i] do
local obj = radar.tabObjects[i][j]
if(obj) then
if(obj.object.removeSelf) then
local radius = nil
if(obj.object.contentWidth >= obj.object.contentHeight) then
radius = obj.object.contentWidth / radar.currentScaleX
else
radius = obj.object.contentHeight / radar.currentScaleY
end
local echoX = radar.surface.object.x + obj.object.x / radar.currentScaleX
local echoY = radar.surface.object.y + obj.object.y / radar.currentScaleY
if(echoX > xMin and echoX < xMax and echoY>yMin and echoY <yMax) then
local echo = display.newCircle(0,0,radius /2)
echo:setFillColor(radar.tabEchoColors[i][1],radar.tabEchoColors[i][2],radar.tabEchoColors[i][3])
echo.alpha = radar.echoAlpha
radar.displayGroup:insert(echo)
echo.x = echoX
echo.y = echoY
end
else
table.insert(tabIndexToRemove,j)
end
else
table.insert(tabIndexToRemove,j)
end
end
for j = 1,#tabIndexToRemove do
table.remove(radar.tabObjects[i],tabIndexToRemove[j])
end
end
end
return radar
end
---
-- @description Start to refresh objects position
-- @usage Usage:
-- <ul>
-- <li><code>radar:start()</code></li>
-- </ul></br>
function Radar:start()
if(self.isEnabled ~= true) then
self.isEnabled = true
self.idTimerResfreshing = timer.performWithDelay(self.refreshInterval,self.refresh,-1)
end
end
---
-- @description Stop to refresh objects position
-- @usage Usage:
-- <ul>
-- <li><code>radar:stop()</code></li>
-- </ul></br>
function Radar:stop()
self.isEnabled = false
if(self.idTimerResfreshing) then
timer.cancel(self.idTimerResfreshing)
end
end
---
-- @description Clean the Radar instance
-- @usage Usage:
-- <ul>
-- <li><code>radar:clean()</code></li>
-- <li><code>radar = nil</code></li>
-- </ul></br>
function Radar:clean()
self.params = nil
self.tabObjects = nil
self.surface =nil
self.sceneWidth = nil
self.sceneHeight = nil
self.tabEchoColors = nil
self.echoAlpha =nil
self.refreshInterval = nil
self.refresh = nil
if(self.displayGroup) then
if(self.displayGroup.removeSelf) then
self.displayGroup:removeSelf()
end
self.displayGroup = nil
end
end
| gpl-2.0 |
KNIGHTTH0R/uzz | plugins/channels.lua | 300 | 1680 | -- Checks if bot was disabled on specific chat
local function is_channel_disabled( receiver )
if not _config.disabled_channels then
return false
end
if _config.disabled_channels[receiver] == nil then
return false
end
return _config.disabled_channels[receiver]
end
local function enable_channel(receiver)
if not _config.disabled_channels then
_config.disabled_channels = {}
end
if _config.disabled_channels[receiver] == nil then
return 'Channel isn\'t disabled'
end
_config.disabled_channels[receiver] = false
save_config()
return "Channel re-enabled"
end
local function disable_channel( receiver )
if not _config.disabled_channels then
_config.disabled_channels = {}
end
_config.disabled_channels[receiver] = true
save_config()
return "Channel disabled"
end
local function pre_process(msg)
local receiver = get_receiver(msg)
-- If sender is sudo then re-enable the channel
if is_sudo(msg) then
if msg.text == "!channel enable" then
enable_channel(receiver)
end
end
if is_channel_disabled(receiver) then
msg.text = ""
end
return msg
end
local function run(msg, matches)
local receiver = get_receiver(msg)
-- Enable a channel
if matches[1] == 'enable' then
return enable_channel(receiver)
end
-- Disable a channel
if matches[1] == 'disable' then
return disable_channel(receiver)
end
end
return {
description = "Plugin to manage channels. Enable or disable channel.",
usage = {
"!channel enable: enable current channel",
"!channel disable: disable current channel" },
patterns = {
"^!channel? (enable)",
"^!channel? (disable)" },
run = run,
privileged = true,
pre_process = pre_process
} | gpl-2.0 |
kaumanns/DeepKaspar | src/lua/deprecated/model/FastLSTM.lua | 6 | 2630 | local FastLSTM, parent = torch.class("nn.FastLSTM", "nn.LSTM")
function FastLSTM:__init(inputSize, outputSize, rho)
parent.__init(self, inputSize, outputSize, rho, false)
end
function FastLSTM:buildModel()
-- input : {input, prevOutput, prevCell}
-- output : {output, cell}
-- Calculate all four gates in one go : input, hidden, forget, output
self.i2g = nn.Linear(self.inputSize, 4*self.outputSize)
self.o2g = nn.LinearNoBias(self.outputSize, 4*self.outputSize)
local para = nn.ParallelTable():add(self.i2g):add(self.o2g)
local gates = nn.Sequential()
gates:add(nn.NarrowTable(1,2))
gates:add(para)
gates:add(nn.CAddTable())
-- Reshape to (batch_size, n_gates, hid_size)
-- Then slize the n_gates dimension, i.e dimension 2
gates:add(nn.Reshape(4,self.outputSize))
gates:add(nn.SplitTable(1,2))
local transfer = nn.ParallelTable()
transfer:add(nn.Sigmoid()):add(nn.Tanh()):add(nn.Sigmoid()):add(nn.Sigmoid())
gates:add(transfer)
local concat = nn.ConcatTable()
concat:add(gates):add(nn.SelectTable(3))
local seq = nn.Sequential()
seq:add(concat)
seq:add(nn.FlattenTable()) -- input, hidden, forget, output, cell
-- input gate * hidden state
local hidden = nn.Sequential()
hidden:add(nn.NarrowTable(1,2))
hidden:add(nn.CMulTable())
-- forget gate * cell
local cell = nn.Sequential()
local concat = nn.ConcatTable()
concat:add(nn.SelectTable(3)):add(nn.SelectTable(5))
cell:add(concat)
cell:add(nn.CMulTable())
local nextCell = nn.Sequential()
local concat = nn.ConcatTable()
concat:add(hidden):add(cell)
nextCell:add(concat)
nextCell:add(nn.CAddTable())
local concat = nn.ConcatTable()
concat:add(nextCell):add(nn.SelectTable(4))
seq:add(concat)
seq:add(nn.FlattenTable()) -- nextCell, outputGate
local cellAct = nn.Sequential()
cellAct:add(nn.SelectTable(1))
cellAct:add(nn.Tanh())
local concat = nn.ConcatTable()
concat:add(cellAct):add(nn.SelectTable(2))
local output = nn.Sequential()
output:add(concat)
output:add(nn.CMulTable())
local concat = nn.ConcatTable()
concat:add(output):add(nn.SelectTable(1))
seq:add(concat)
return seq
end
function FastLSTM:buildGate()
error"Not Implemented"
end
function FastLSTM:buildInputGate()
error"Not Implemented"
end
function FastLSTM:buildForgetGate()
error"Not Implemented"
end
function FastLSTM:buildHidden()
error"Not Implemented"
end
function FastLSTM:buildCell()
error"Not Implemented"
end
function FastLSTM:buildOutputGate()
error"Not Implemented"
end
| mit |
shadog/mdo_th_boos | plugins/plugins/zrfa_en.lua | 5 | 8133 | local function run(msg, matches)
if #matches < 2 then
return "بعد هذا الأمر، من خلال تحديد كلمة المسافة أو العبارة التي تريد إدخال الكتابة الجميلة"
end
if string.len(matches[2]) > 44 then
return "الحد الأقصى المسموح به 40 حرفاالأحرف الإنجليزية والأرقام"
end
local font_base = "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,0,9,8,7,6,5,4,3,2,1,.,_"
local font_hash = "z,y,x,w,v,u,t,s,r,q,p,o,n,m,l,k,j,i,h,g,f,e,d,c,b,a,Z,Y,X,W,V,U,T,S,R,Q,P,O,N,M,L,K,J,I,H,G,F,E,D,C,B,A,0,1,2,3,4,5,6,7,8,9,.,_"
local fonts = {
"ⓐ,ⓑ,ⓒ,ⓓ,ⓔ,ⓕ,ⓖ,ⓗ,ⓘ,ⓙ,ⓚ,ⓛ,ⓜ,ⓝ,ⓞ,ⓟ,ⓠ,ⓡ,ⓢ,ⓣ,ⓤ,ⓥ,ⓦ,ⓧ,ⓨ,ⓩ,ⓐ,ⓑ,ⓒ,ⓓ,ⓔ,ⓕ,ⓖ,ⓗ,ⓘ,ⓙ,ⓚ,ⓛ,ⓜ,ⓝ,ⓞ,ⓟ,ⓠ,ⓡ,ⓢ,ⓣ,ⓤ,ⓥ,ⓦ,ⓧ,ⓨ,ⓩ,⓪,➈,➇,➆,➅,➄,➃,➂,➁,➀,●,_",
"⒜,⒝,⒞,⒟,⒠,⒡,⒢,⒣,⒤,⒥,⒦,⒧,⒨,⒩,⒪,⒫,⒬,⒭,⒮,⒯,⒰,⒱,⒲,⒳,⒴,⒵,⒜,⒝,⒞,⒟,⒠,⒡,⒢,⒣,⒤,⒥,⒦,⒧,⒨,⒩,⒪,⒫,⒬,⒭,⒮,⒯,⒰,⒱,⒲,⒳,⒴,⒵,⓪,⑼,⑻,⑺,⑹,⑸,⑷,⑶,⑵,⑴,.,_",
"α,в,c,∂,є,ƒ,g,н,ι,נ,к,ℓ,м,η,σ,ρ,q,я,ѕ,т,υ,ν,ω,χ,у,z,α,в,c,∂,є,ƒ,g,н,ι,נ,к,ℓ,м,η,σ,ρ,q,я,ѕ,т,υ,ν,ω,χ,у,z,0,9,8,7,6,5,4,3,2,1,.,_",
"α,в,c,d,e,ғ,ɢ,н,ι,j,ĸ,l,м,ɴ,o,p,q,r,ѕ,т,υ,v,w,х,y,z,α,в,c,d,e,ғ,ɢ,н,ι,j,ĸ,l,м,ɴ,o,p,q,r,ѕ,т,υ,v,w,х,y,z,0,9,8,7,6,5,4,3,2,1,.,_",
"α,в,¢,đ,e,f,g,ħ,ı,נ,κ,ł,м,и,ø,ρ,q,я,š,т,υ,ν,ω,χ,ч,z,α,в,¢,đ,e,f,g,ħ,ı,נ,κ,ł,м,и,ø,ρ,q,я,š,т,υ,ν,ω,χ,ч,z,0,9,8,7,6,5,4,3,2,1,.,_",
"ą,ҍ,ç,ժ,ҽ,ƒ,ց,հ,ì,ʝ,ҟ,Ӏ,ʍ,ղ,օ,ք,զ,ɾ,ʂ,է,մ,ѵ,ա,×,վ,Հ,ą,ҍ,ç,ժ,ҽ,ƒ,ց,հ,ì,ʝ,ҟ,Ӏ,ʍ,ղ,օ,ք,զ,ɾ,ʂ,է,մ,ѵ,ա,×,վ,Հ,⊘,९,𝟠,7,Ϭ,Ƽ,५,Ӡ,ϩ,𝟙,.,_", "ค,ც,८,ძ,૯,Բ,૭,Һ,ɿ,ʆ,қ,Ն,ɱ,Ո,૦,ƿ,ҩ,Ր,ς,੮,υ,౮,ω,૪,ע,ઽ,ค,ც,८,ძ,૯,Բ,૭,Һ,ɿ,ʆ,қ,Ն,ɱ,Ո,૦,ƿ,ҩ,Ր,ς,੮,υ,౮,ω,૪,ע,ઽ,0,9,8,7,6,5,4,3,2,1,.,_",
"α,ß,ς,d,ε,ƒ,g,h,ï,յ,κ,レ,m,η,⊕,p,Ω,r,š,†,u,∀,ω,x,ψ,z,α,ß,ς,d,ε,ƒ,g,h,ï,յ,κ,レ,m,η,⊕,p,Ω,r,š,†,u,∀,ω,x,ψ,z,0,9,8,7,6,5,4,3,2,1,.,_",
"ค,๒,ς,๔,є,Ŧ,ɠ,ђ,เ,ן,к,l,๓,ภ,๏,թ,ợ,г,ร,t,ย,v,ฬ,x,ץ,z,ค,๒,ς,๔,є,Ŧ,ɠ,ђ,เ,ן,к,l,๓,ภ,๏,թ,ợ,г,ร,t,ย,v,ฬ,x,ץ,z,0,9,8,7,6,5,4,3,2,1,.,_",
"ム,乃,ζ,Ð,乇,キ,Ǥ,ん,ノ,フ,ズ,レ,ᄊ,刀,Ծ,ア,Q,尺,ㄎ,イ,Ц,Џ,Щ,メ,リ,乙,ム,乃,ζ,Ð,乇,キ,Ǥ,ん,ノ,フ,ズ,レ,ᄊ,刀,Ծ,ア,q,尺,ㄎ,イ,Ц,Џ,Щ,メ,リ,乙,ᅙ,9,8,ᆨ,6,5,4,3,ᆯ,1,.,_",
"α,β,c,δ,ε,Ŧ,ĝ,h,ι,j,κ,l,ʍ,π,ø,ρ,φ,Ʀ,$,†,u,υ,ω,χ,ψ,z,α,β,c,δ,ε,Ŧ,ĝ,h,ι,j,κ,l,ʍ,π,ø,ρ,φ,Ʀ,$,†,u,υ,ω,χ,ψ,z,0,9,8,7,6,5,4,3,2,1,.,_",
"ձ,ъ,ƈ,ժ,ε,բ,ց,հ,ﻨ,յ,ĸ,l,ო,ռ,օ,թ,զ,г,ร,է,ս,ν,ա,×,ყ,২,ձ,ъ,ƈ,ժ,ε,բ,ց,հ,ﻨ,յ,ĸ,l,ო,ռ,օ,թ,զ,г,ร,է,ս,ν,ա,×,ყ,২,0,9,8,7,6,5,4,3,2,1,.,_",
"Λ,ɓ,¢,Ɗ,£,ƒ,ɢ,ɦ,ĩ,ʝ,Қ,Ł,ɱ,ה,ø,Ṗ,Ҩ,Ŕ,Ş,Ŧ,Ū,Ɣ,ω,Ж,¥,Ẑ,Λ,ɓ,¢,Ɗ,£,ƒ,ɢ,ɦ,ĩ,ʝ,Қ,Ł,ɱ,ה,ø,Ṗ,Ҩ,Ŕ,Ş,Ŧ,Ū,Ɣ,ω,Ж,¥,Ẑ,0,9,8,7,6,5,4,3,2,1,.,_",
"Λ,Б,Ͼ,Ð,Ξ,Ŧ,G,H,ł,J,К,Ł,M,Л,Ф,P,Ǫ,Я,S,T,U,V,Ш,Ж,Џ,Z,Λ,Б,Ͼ,Ð,Ξ,Ŧ,g,h,ł,j,К,Ł,m,Л,Ф,p,Ǫ,Я,s,t,u,v,Ш,Ж,Џ,z,0,9,8,7,6,5,4,3,2,1,.,_",
"ɐ,q,ɔ,p,ǝ,ɟ,ɓ,ɥ,ı,ſ,ʞ,ๅ,ɯ,u,o,d,b,ɹ,s,ʇ,n,ʌ,ʍ,x,ʎ,z,ɐ,q,ɔ,p,ǝ,ɟ,ɓ,ɥ,ı,ſ,ʞ,ๅ,ɯ,u,o,d,b,ɹ,s,ʇ,n,ʌ,ʍ,x,ʎ,z,0,9,8,7,6,5,4,3,2,1,.,_",
"ɒ,d,ɔ,b,ɘ,ʇ,ϱ,н,i,į,ʞ,l,м,и,o,q,p,я,ƨ,т,υ,v,w,x,γ,z,ɒ,d,ɔ,b,ɘ,ʇ,ϱ,н,i,į,ʞ,l,м,и,o,q,p,я,ƨ,т,υ,v,w,x,γ,z,0,9,8,7,6,5,4,3,2,1,.,_",
"A̴,̴B̴,̴C̴,̴D̴,̴E̴,̴F̴,̴G̴,̴H̴,̴I̴,̴J̴,̴K̴,̴L̴,̴M̴,̴N̴,̴O̴,̴P̴,̴Q̴,̴R̴,̴S̴,̴T̴,̴U̴,̴V̴,̴W̴,̴X̴,̴Y̴,̴Z̴,̴a̴,̴b̴,̴c̴,̴d̴,̴e̴,̴f̴,̴g̴,̴h̴,̴i̴,̴j̴,̴k̴,̴l̴,̴m̴,̴n̴,̴o̴,̴p̴,̴q̴,̴r̴,̴s̴,̴t̴,̴u̴,̴v̴,̴w̴,̴x̴,̴y̴,̴z̴,̴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("A",tar_font[1])
local text = text:gsub("B",tar_font[2])
local text = text:gsub("C",tar_font[3])
local text = text:gsub("D",tar_font[4])
local text = text:gsub("E",tar_font[5])
local text = text:gsub("F",tar_font[6])
local text = text:gsub("G",tar_font[7])
local text = text:gsub("H",tar_font[8])
local text = text:gsub("I",tar_font[9])
local text = text:gsub("J",tar_font[10])
local text = text:gsub("K",tar_font[11])
local text = text:gsub("L",tar_font[12])
local text = text:gsub("M",tar_font[13])
local text = text:gsub("N",tar_font[14])
local text = text:gsub("O",tar_font[15])
local text = text:gsub("P",tar_font[16])
local text = text:gsub("Q",tar_font[17])
local text = text:gsub("R",tar_font[18])
local text = text:gsub("S",tar_font[19])
local text = text:gsub("T",tar_font[20])
local text = text:gsub("U",tar_font[21])
local text = text:gsub("V",tar_font[22])
local text = text:gsub("W",tar_font[23])
local text = text:gsub("X",tar_font[24])
local text = text:gsub("Y",tar_font[25])
local text = text:gsub("Z",tar_font[26])
local text = text:gsub("a",tar_font[27])
local text = text:gsub("b",tar_font[28])
local text = text:gsub("c",tar_font[29])
local text = text:gsub("d",tar_font[30])
local text = text:gsub("e",tar_font[31])
local text = text:gsub("f",tar_font[32])
local text = text:gsub("g",tar_font[33])
local text = text:gsub("h",tar_font[34])
local text = text:gsub("i",tar_font[35])
local text = text:gsub("j",tar_font[36])
local text = text:gsub("k",tar_font[37])
local text = text:gsub("l",tar_font[38])
local text = text:gsub("m",tar_font[39])
local text = text:gsub("n",tar_font[40])
local text = text:gsub("o",tar_font[41])
local text = text:gsub("p",tar_font[42])
local text = text:gsub("q",tar_font[43])
local text = text:gsub("r",tar_font[44])
local text = text:gsub("s",tar_font[45])
local text = text:gsub("t",tar_font[46])
local text = text:gsub("u",tar_font[47])
local text = text:gsub("v",tar_font[48])
local text = text:gsub("w",tar_font[49])
local text = text:gsub("x",tar_font[50])
local text = text:gsub("y",tar_font[51])
local text = text:gsub("z",tar_font[52])
local text = text:gsub("0",tar_font[53])
local text = text:gsub("9",tar_font[54])
local text = text:gsub("8",tar_font[55])
local text = text:gsub("7",tar_font[56])
local text = text:gsub("6",tar_font[57])
local text = text:gsub("5",tar_font[58])
local text = text:gsub("4",tar_font[59])
local text = text:gsub("3",tar_font[60])
local text = text:gsub("2",tar_font[61])
local text = text:gsub("1",tar_font[62])
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❣ #Dev @Th3_BOOS"
end
return {
description = "Fantasy Writer",
usagehtm = '<tr><td align="center">decoration متن</td><td align="right">مع هذا البرنامج المساعد يمكن النصوص الخاصة بك مع مجموعة متنوعة من الخطوط والتصميم الجميل. أحرف الحد الأقصى المسموح به هو 20 ويمكن فقط استخدام الأحرف الإنجليزية والأرقام</td></tr>',
usage = {"decoration [text] : زخرفه النص",},
patterns = {
"^(زخرف) (.*)",
"^(زخرف)$",
},
run = run
}
| gpl-2.0 |
greasydeal/darkstar | scripts/globals/abilities/pets/healing_breath_ii.lua | 3 | 1466 | ---------------------------------------------------
-- Healing Breath II
---------------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------------
function onAbilityCheck(player, target, ability)
return 0,0;
end;
function onPetAbility(target, pet, skill, master)
-- TODO:
-- Healing Breath I and II should have lower multipliers. They'll need to be corrected if the multipliers are ever found. Don't want to over-correct right now.
---------- Deep Breathing ----------
-- 0 for none
-- 50 for first merit
-- 5 for each merit after the first
-- TODO: 5 per merit for augmented AF2 (10663 *w/ augment*)
local deep = 0;
if (pet:hasStatusEffect(EFFECT_MAGIC_ATK_BOOST) == true) then
deep = 50 + (master:getMerit(MERIT_DEEP_BREATHING)-1)*5;
pet:delStatusEffect(EFFECT_MAGIC_ATK_BOOST);
end
local gear = master:getMod(MOD_WYVERN_BREATH); -- Master gear that enhances breath
local tp = math.floor(skill:getTP()/20)/1.165; -- HP only increases for every 20% TP
local base = math.floor(((45+tp+gear+deep)/256)*(pet:getMaxHP())+42);
if(target:getHP()+base > target:getMaxHP()) then
base = target:getMaxHP() - target:getHP(); --cap it
end
skill:setMsg(MSG_SELF_HEAL);
target:addHP(base);
return base;
end | gpl-3.0 |
pleonex/telegram-bot | plugins/quotes.lua | 651 | 1630 | local quotes_file = './data/quotes.lua'
local quotes_table
function read_quotes_file()
local f = io.open(quotes_file, "r+")
if f == nil then
print ('Created a new quotes file on '..quotes_file)
serialize_to_file({}, quotes_file)
else
print ('Quotes loaded: '..quotes_file)
f:close()
end
return loadfile (quotes_file)()
end
function save_quote(msg)
local to_id = tostring(msg.to.id)
if msg.text:sub(11):isempty() then
return "Usage: !addquote quote"
end
if quotes_table == nil then
quotes_table = {}
end
if quotes_table[to_id] == nil then
print ('New quote key to_id: '..to_id)
quotes_table[to_id] = {}
end
local quotes = quotes_table[to_id]
quotes[#quotes+1] = msg.text:sub(11)
serialize_to_file(quotes_table, quotes_file)
return "done!"
end
function get_quote(msg)
local to_id = tostring(msg.to.id)
local quotes_phrases
quotes_table = read_quotes_file()
quotes_phrases = quotes_table[to_id]
return quotes_phrases[math.random(1,#quotes_phrases)]
end
function run(msg, matches)
if string.match(msg.text, "!quote$") then
return get_quote(msg)
elseif string.match(msg.text, "!addquote (.+)$") then
quotes_table = read_quotes_file()
return save_quote(msg)
end
end
return {
description = "Save quote",
description = "Quote plugin, you can create and retrieve random quotes",
usage = {
"!addquote [msg]",
"!quote",
},
patterns = {
"^!addquote (.+)$",
"^!quote$",
},
run = run
}
| gpl-2.0 |
jguluarte/StoreFront | Events.lua | 1 | 1110 | -- This is where we register all of the events
-- This file should be loaded *last*
if not StoreFront then return end
-- this is to wrap the registering and unregistering
local function register_once(name, event, callback)
local handler = function(...)
callback(arg)
EVENT_MANAGER:UnregisterForEvent(name, event)
end
EVENT_MANAGER:RegisterForEvent(name, event, handler)
end
-- On add on loaded
local function onLoaded(event, name)
if name ~= StoreFront.name then return end
-- call all of my initialization functions
StoreFront:initialize()
-- init / deconstruct listeners
EVENT_MANAGER:RegisterForEvent(
StoreFront.name,
EVENT_OPEN_TRADING_HOUSE,
StoreFront.openTradingHouse
)
EVENT_MANAGER:RegisterForEvent(
StoreFront.name,
EVENT_CLOSE_TRADING_HOUSE,
StoreFront.closeTradingHouse
)
EVENT_MANAGER:UnregisterForEvent(StoreFront.name, EVENT_ADD_ON_LOADED)
end
EVENT_MANAGER:RegisterForEvent(StoreFront.name, EVENT_ADD_ON_LOADED, onLoaded)
-- local function load
-- EVENT_OPEN_TRADING_HOUSE
| mit |
naclander/tome | game/modules/example_realtime/init.lua | 3 | 1227 | -- ToME - Tales of Middle-Earth
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
name = "Realtime Example Module"
long_name = "Realtime Example Module for T-Engine4"
short_name = "example_realtime"
author = { "DarkGod", "darkgod@te4.org" }
homepage = "http://te4.org/modules:example"
version = {1,1,5}
engine = {1,1,5,"te4"}
description = [[
This is *NOT* a game, just an example/template to make your own using the T-Engine4.
]]
starter = "mod.load"
show_only_on_cheat = true -- Example modules are not shown to normal players
| gpl-3.0 |
RezaShell32/robot2 | libs/redis.lua | 32 | 1129 | local Redis = (loadfile "./libs/lua-redis.lua")()
local FakeRedis = (loadfile "./libs/fakeredis.lua")()
local params = {
host = '127.0.0.1',
port = 6379,
}
-- Overwrite HGETALL
Redis.commands.hgetall = Redis.command('hgetall', {
response = function(reply, command, ...)
local new_reply = { }
for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end
return new_reply
end
})
local redis = nil
-- Won't launch an error if fails
local ok = pcall(function()
redis = Redis.connect(params)
end)
if not ok then
local fake_func = function()
print('\27[31mCan\'t connect with Redis, install/configure it!\27[39m')
end
fake_func()
fake = FakeRedis.new()
print('\27[31mRedis addr: '..params.host..'\27[39m')
print('\27[31mRedis port: '..params.port..'\27[39m')
redis = setmetatable({fakeredis=true}, {
__index = function(a, b)
if b ~= 'data' and fake[b] then
fake_func(b)
end
return fake[b] or fake_func
end })
end
return redis
-- کد های پایین در ربات نشان داده نمیشوند
-- http://permag.ir
-- @permag_ir
-- @permag_bots
-- @permag | gpl-3.0 |
greasydeal/darkstar | scripts/zones/Bastok_Mines/npcs/Tibelda.lua | 36 | 1405 | -----------------------------------
-- Area: Bastok Mines
-- NPC: Tibelda
-- Only sells when Bastok controlls Valdeaunia Region
-----------------------------------
require("scripts/globals/shop");
require("scripts/globals/conquest");
package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil;
require("scripts/zones/Bastok_Mines/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
RegionOwner = GetRegionOwner(VALDEAUNIA);
if (RegionOwner ~= BASTOK) then
player:showText(npc,TIBELDA_CLOSED_DIALOG);
else
player:showText(npc,TIBELDA_OPEN_DIALOG);
stock = {
0x111e, 29, --Frost Turnip
0x027e, 170 --Sage
}
showShop(player,BASTOK,stock);
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 |
LegionXI/darkstar | scripts/zones/Al_Zahbi/npcs/Eumoa-Tajimoa.lua | 14 | 1039 | -----------------------------------
-- Area: Al Zahbi
-- NPC: Eumoa-Tajimoa
-- Type: Standard NPC
-- @zone 48
-- @pos 19.275 -1 55.182
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Al_Zahbi/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x00ef);
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 |
greasydeal/darkstar | scripts/globals/weaponskills/vorpal_blade.lua | 30 | 1435 | -----------------------------------
-- Vorpal Blade
-- Sword weapon skill
-- Skill Level: 200
-- Delivers a four-hit attack. Chance of params.critical varies with TP.
-- Stacks with Sneak Attack.
-- Aligned with the Soil Gorget & Thunder Gorget.
-- Aligned with the Soil Belt & Thunder Belt.
-- Element: None
-- Modifiers: STR:60%
-- 100%TP 200%TP 300%TP
-- 1.375 1.375 1.375
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 4;
params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1;
params.str_wsc = 0.3; 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.1; params.crit200 = 0.3; params.crit300 = 0.5;
params.canCrit = true;
params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0;
params.atkmulti = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.ftp100 = 1.375; params.ftp200 = 1.375; params.ftp300 = 1.375;
params.str_wsc = 0.6;
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params);
damage = damage * WEAPON_SKILL_POWER
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
naclander/tome | game/modules/tome/data/gfx/particles/dust_trail.lua | 3 | 1830 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
base_size = 32
return { generator = function()
-- Make a random palette from light brown, dark brown, green, and black.
-- This lets us avoid "weird" colors like yellow, orange, and blue, and
-- these particles should still be clearly visible over a variety of terrain.
local r1 = rng.float(0, 1)
local r2 = rng.float(0, 1)
local r3 = rng.float(0, 0.5)
local r4 = rng.float(0, 1.5)
local tot = r1 + r2 + r3 + r4
r1 = r1 / tot
r2 = r2 / tot
r3 = r3 / tot
return {
trail = 1,
life = rng.range(35, 50),
size = rng.float(2, 3), sizev = 0, sizea = 0,
x = rng.range(-12, 12), xv = rng.float(-0.3, 0.3), xa = 0,
y = rng.range(-10, 16), yv = rng.float(-0.5, -0.3), ya = 0.02,
dir = 0, dirv = 0, dira = 0,
vel = 0.0, velv = 0, vela = 0,
r = r1*0.55 + r2*0.42 + r3*0.10, rv = 0, ra = 0,
g = r1*0.45 + r2*0.26 + r3*0.55, gv = 0, ga = 0,
b = r1*0.33 + r2*0.15 + r3*0.10, bv = 0, ba = 0,
a = 1.0, av = 0, aa = -0.0006,
}
end, },
function(self)
self.nb = (self.nb or 0) + 1
if self.nb < 30 then
self.ps:emit(6)
end
end,
40
| gpl-3.0 |
ricker75/Global-Server | data/movements/scripts/gnomebase/warzone3.lua | 2 | 1525 | --- [[ Warzone 3 feito por Yuri Lagrotta ]] ---
local kickposs = {x=33000, y=31899, z=9}
local function deAbyssador()
if(getGlobalStorageValue(91159) < 1) then
TOP_LEFT_CORNER = {x = 33074, y = 31896, z = 12, stackpos=253}
BOTTOM_RIGHT_CORNER = {x = 33103, y = 31925, z = 12, stackpos=253}
for Py = TOP_LEFT_CORNER.y, BOTTOM_RIGHT_CORNER.y do
for Px = TOP_LEFT_CORNER.x, BOTTOM_RIGHT_CORNER.x do
creature = getThingfromPos({x=Px, y=Py, z=12, stackpos=253})
if isMonster(creature.uid) then
if getCreatureName(creature.uid) == "Abyssador" then
doRemoveCreature(creature.uid)
setGlobalStorageValue(91159, 1)
addEvent(setGlobalStorageValue, 5 * 60 * 1000, 91159, 0)
end
end
end
end
end
return FALSE
end
local function deSummonAbyssador()
if(getGlobalStorageValue(99159) < 1) then
addEvent(doSummonCreature, 45*1000, "abyssador", {x=33089, y=31909, z=12})
setGlobalStorageValue(99159, 1)
addEvent(setGlobalStorageValue, 10 * 60 * 1000, 99159, 0)
end
end
function onStepIn(cid, item, position, topos, frompos)
if not isPlayer(cid) then
return false
end
if item.actionid == 5161 then
doPlayerSendTextMessage(cid, 19, "You have half an hour to heroically defeat Abyssador. Otherwise you'll be teleported out by the gnomish emergency device.")
doTeleportThing(cid, {x=33082, y=31905, z=12})
deAbyssador()
deSummonAbyssador()
elseif item.actionid == 5162 then
doTeleportThing(cid, kickposs)
end
return true
end | gpl-2.0 |
xingchch/AndroLua | assets/import.lua | 1 | 18862 | local require=require
local table=require "table"
local string=require "string"
local packages = {}
local loaded = {}
luajava.package=packages
luajava.loaded=loaded
local _G=_G
local insert = table.insert
local new = luajava.new
local bindClass = luajava.bindClass
local function append(t,v)
for _,_v in ipairs(t) do
if _v==v then
return
end
end
insert(t,v)
end
local function massage_classname (classname)
if classname:find('_') then
classname = classname:gsub('_','$')
end
return classname
end
local function import_class (classname,packagename)
packagename = massage_classname(packagename)
local res,class = pcall(bindClass,packagename)
if res then
loaded[classname] = class
return class
end
--[[packagename = packagename:gsub("%.(%w+)$","$%1")
local res,class = pcall(bindClass,packagename)
if res then
loaded[classname] = class
return class
end]]
end
local globalMT = {
__index = function(T,classname)
-- classname = massage_classname(classname)
for i,p in ipairs(packages) do
local class = loaded[classname] or import_class(classname,p..classname)
if class then T[classname]=class return class end
end
return nil
end
}
--setmetatable(_G, globalMT)
local function import_require(name)
local s,r=pcall(require,name)
return s and r
end
local function env_import(env)
local _env=env
setmetatable(_env, globalMT)
return function (package)
local i = package:find('%*$')
if i then -- a wildcard; put into the package list, including the final '.'
append(packages,package:sub(1,-2))
else
local classname = package:match('([%w_]+)$')
local class =import_require(package) or import_class(classname,package)
if class then
_env[classname]=class
if class ~= true then
_env[classname]=class
end
return class
else
error("cannot find "..package)
end
end
end
end
import=env_import(_G)
append(packages,'')
function enum(e)
return function()
if e.hasMoreElements() then
return e.nextElement()
end
end
end
function each(o)
local iter=o.iterator()
return function()
if iter.hasNext() then
return iter.next()
end
end
end
function dump (t)
local _t={}
for k,v in pairs(t) do
table.insert(_t,tostring(k).."="..tostring(v))
end
t=table.concat(_t,"\n")
return t
end
local content=activity
local ViewGroup=bindClass("android.view.ViewGroup")
local String=bindClass("java.lang.String")
local Gravity=bindClass("android.view.Gravity")
local OnClickListener=bindClass("android.view.View$OnClickListener")
local TypedValue=luajava.bindClass("android.util.TypedValue")
local BitmapDrawable=luajava.bindClass("android.graphics.drawable.BitmapDrawable")
local LuaDrawable=luajava.bindClass "com.androlua.LuaDrawable"
local ArrayAdapter=bindClass("android.widget.ArrayAdapter")
local ScaleType=bindClass("android.widget.ImageView$ScaleType")
local scaleTypes=ScaleType.values()
local android_R=bindClass("android.R")
android={R=android_R}
local dm=content.getResources().getDisplayMetrics()
local id=0x7f000000
local toint={
--android:drawingCacheQuality
auto=0,
low=1,
high=2,
--android:importantForAccessibility
auto=0,
yes=1,
no=2,
--android:layerType
none=0,
software=1,
hardware=2,
--android:layoutDirection
ltr=0,
rtl=1,
inherit=2,
locale=3,
--android:scrollbarStyle
insideOverlay=0x0,
insideInset=0x01000000,
outsideOverlay=0x02000000,
outsideInset=0x03000000,
--android:visibility
visible=0,
invisible=1,
gone=2,
wrap_content=-2,
fill_parent=-1,
match_parent=-1,
wrap=-2,
fill=-1,
match=-1,
--android:autoLink
none=0x00,
web=0x01,
email=0x02,
phon=0x04,
map=0x08,
all=0x0f,
--android:orientation
vertical=1,
horizontal= 0,
--android:gravity
axis_clip = 8,
axis_pull_after = 4,
axis_pull_before = 2,
axis_specified = 1,
axis_x_shift = 0,
axis_y_shift = 4,
bottom = 80,
center = 17,
center_horizontal = 1,
center_vertical = 16,
clip_horizontal = 8,
clip_vertical = 128,
display_clip_horizontal = 16777216,
display_clip_vertical = 268435456,
--fill = 119,
fill_horizontal = 7,
fill_vertical = 112,
horizontal_gravity_mask = 7,
left = 3,
no_gravity = 0,
relative_horizontal_gravity_mask = 8388615,
relative_layout_direction = 8388608,
right = 5,
start = 8388611,
top = 48,
vertical_gravity_mask = 112,
["end"] = 8388613,
--android:textAlignment
inherit=0,
gravity=1,
textStart=2,
textEnd=3,
textCenter=4,
viewStart=5,
viewEnd=6,
--android:inputType
none=0x00000000,
text=0x00000001,
textCapCharacters=0x00001001,
textCapWords=0x00002001,
textCapSentences=0x00004001,
textAutoCorrect=0x00008001,
textAutoComplete=0x00010001,
textMultiLine=0x00020001,
textImeMultiLine=0x00040001,
textNoSuggestions=0x00080001,
textUri=0x00000011,
textEmailAddress=0x00000021,
textEmailSubject=0x00000031,
textShortMessage=0x00000041,
textLongMessage=0x00000051,
textPersonName=0x00000061,
textPostalAddress=0x00000071,
textPassword=0x00000081,
textVisiblePassword=0x00000091,
textWebEditText=0x000000a1,
textFilter=0x000000b1,
textPhonetic=0x000000c1,
textWebEmailAddress=0x000000d1,
textWebPassword=0x000000e1,
number=0x00000002,
numberSigned=0x00001002,
numberDecimal=0x00002002,
numberPassword=0x00000012,
phone=0x00000003,
datetime=0x00000004,
date=0x00000014,
time=0x00000024,
}
local scaleType={
--android:scaleType
matrix=0,
fitXY=1,
fitStart=2,
fitCenter=3,
fitEnd=4,
center=5,
centerCrop=6,
centerInside=7,
}
local rules={
layout_above=2,
layout_alignBaseline=4,
layout_alignBottom=8,
layout_alignEnd=19,
layout_alignLeft=5,
layout_alignParentBottom=12,
layout_alignParentEnd=21,
layout_alignParentLeft=9,
layout_alignParentRight=11,
layout_alignParentStart=20,
layout_alignParentTop=10,
layout_alignRight=7,
layout_alignStart=18,
layout_alignTop=6,
layout_alignWithParentIfMissing=0,
layout_below=3,
layout_centerHorizontal=14,
layout_centerInParent=13,
layout_centerVertical=15,
layout_toEndOf=17,
layout_toLeftOf=0,
layout_toRightOf=1,
layout_toStartOf=16
}
local types={
px=0,
dp=1,
sp=2,
pt=3,
["in"]=4,
mm=5
}
local function checkType(v)
local n,ty=string.match(v,"^(%d+)(%a%a)$")
return tonumber(n),types[ty]
end
local function checkNumber(var)
if type(var) == "string" then
if var=="true" then
return true
elseif var=="false" then
return false
end
local s=var:find("|")
if s then
local i1=toint[var:sub(1,s-1)]
local i2=toint[var:sub(s+1,-1)]
if i1 and i2 then
return i1 | i2
end
end
if toint[var] then
return toint[var]
end
local h=string.match(var,"^#(%x+)$")
if h then
local c=tonumber(h,16)
if c then
if #h<=6 then
return c|0xffffffffff000000
elseif #h<=8 then
c=math.modf((c<<32)/0xffffffff)
return c
end
end
end
local n,ty=checkType(var)
if ty then
return TypedValue.applyDimension(ty,n,dm)
end
end
-- return var
end
local function checkValue(var)
return tonumber(var) or checkNumber(var) or var
end
local function checkValues(...)
local vars={...}
for n=1,#vars do
vars[n]=checkValue(vars[n])
end
return unpack(vars)
end
local function getattr(s)
return android_R.attr[s]
end
local function checkattr(s)
local e,s=pcall(getattr,s)
if e then
return s
end
return nil
end
local function dump2 (t)
local _t={}
table.insert(_t,tostring(t))
table.insert(_t,"\t{")
for k,v in pairs(t) do
if type(v)=="table" then
table.insert(_t,"\t\t"..tostring(k).."={"..tostring(v[1]).." ...}")
else
table.insert(_t,"\t\t"..tostring(k).."="..tostring(v))
end
end
table.insert(_t,"\t}")
t=table.concat(_t,"\n")
return t
end
local function setattribute(view,params,k,v,ids)
if k=="layout_x" then
params.x=checkValue(v)
elseif k=="layout_y" then
params.y=checkValue(v)
elseif k=="layout_weight" then
params.weight=checkValue(v)
elseif k=="layout_gravity" then
params.gravity=checkValue(v)
elseif k=="layout_marginStart" then
params.setMarginStart(checkValue(v))
elseif k=="layout_marginEnd" then
params.setMarginEnd(checkValue(v))
elseif rules[k] and (v==true or v=="true") then
params.addRule(rules[k])
elseif rules[k] then
params.addRule(rules[k],ids[v])
elseif k=="items" and type(v)=="table" then --创建列表项目
local adapter=ArrayAdapter(content,android_R.layout.simple_list_item_1, String(v))
view.setAdapter(adapter)
elseif k=="text" then
view.setText(v)
elseif k=="textSize" then
if tonumber(v) then
view.setTextSize(tonumber(v))
elseif type(v)=="string" then
local n,ty=checkType(v)
if ty then
view.setTextSize(ty,n)
else
view.setTextSize(v)
end
else
view.setTextSize(v)
end
elseif k=="textAppearance" then
view.setTextAppearance(content,checkattr(v))
elseif k=="src" then
task([[require "import" url=... return loadbitmap(url)]],v,function(bmp)view.setImageBitmap(bmp)end)
elseif k=="scaleType" then
view.setScaleType(scaleTypes[scaleType[v]])
elseif k=="password" and (v=="true" or v==true) then
view.setInputType(0x81)
elseif type(k)=="string" and not(k:find("layout_")) and not(k:find("padding")) and k~="style" then --设置属性
k=string.gsub(k,"^(%w)",function(s)return string.upper(s)end)
view["set"..k](checkValue(v))
end
end
local function env_loadlayout(env)
local _env=env
local ids={}
local ltrs={}
return function(t,root,group)
local view,style
if t.style then
style=checkattr(t.style)
end
if style then
view = t[1](content,nil,style)
else
view = t[1](content) --创建view
end
local params=ViewGroup.LayoutParams(checkValue(t.layout_width) or -2,checkValue(t.layout_height) or -2) --设置layout属性
if group then
params=group.class.LayoutParams(params)
end
--设置layout_margin属性
if t.layout_margin or t.layout_marginStart or t.layout_marginEnd or t.layout_marginLeft or t.layout_marginTop or t.layout_marginRight or t.layout_marginBottom then
params.setMargins(checkValues( t.layout_marginLeft or t.layout_margin or 0,t.layout_marginTop or t.layout_margin or 0,t.layout_marginRight or t.layout_margin or 0,t.layout_marginBottom or t.layout_margin or 0))
end
--设置padding属性
if t.padding or t.paddingLeft or t.paddingTop or t.paddingRight or t.paddingBottom then
view.setPadding(checkValues(t.paddingLeft or t.padding or 0, t.paddingTop or t.padding or 0, t.paddingRight or t.padding or 0, t.paddingBottom or t.padding or 0))
end
if t.paddingStart or t.paddingEnd then
view.setPaddingRelative(checkValues(t.paddingStart or t.padding or 0, t.paddingTop or t.padding or 0, t.paddingEnd or t.padding or 0, t.paddingBottom or t.padding or 0))
end
for k,v in pairs(t) do
if tonumber(k) and type(v)=="table" then --创建子view
loadlayout(v,root,view)
elseif k=="id" then --创建view的全局变量
rawset(root or _env,v,view)
view.setId(id)
ids[v]=id
id=id+1
elseif k=="background" then
if type(v)=="string" then
if v:find("#") then
view.setBackgroundColor(checkNumber(v))
elseif v:find("^%w+$") then
v=rawget(_env,v)
if type(v)=="function" then
view.setBackground(LuaDrawable(v))
elseif type(v)=="userdata" then
view.setBackground(v)
end
else
task([[require "import" url=... return loadbitmap(url)]],v,function(bmp)view.setBackground(BitmapDrawable(bmp))end)
end
elseif type(v)=="userdata" then
view.setBackground(v)
elseif type(v)=="number" then
view.setBackgroundColor(v)
end
elseif k=="onClick" then --设置onClick事件接口
local listener
if type(v)=="function" then
listener=OnClickListener{onClick=v}
elseif type(v)=="userdata" then
listener=v
elseif type(v)=="string" then
if ltrs[v] then
listener=ltrs[v]
else
local l=rawget(_env,v)
if type(l)=="function" then
listener=OnClickListener{onClick=l}
elseif type(l)=="userdata" then
listener=l
end
ltrs[v]=listener
end
end
view.setOnClickListener(listener)
else
local e,s=pcall(setattribute,view,params,k,v,ids)
if not e then
local _,i=s:find(":%d+:")
s=s:sub(i,-1)
error(string.format("loadlayout error %s \n\tat %s\n\tat key=%s value=%s\n\tat %s",s,view.toString(),k,v,dump2(t)))
end
end
end
if group then
group.addView(view,params)
else
view.setLayoutParams(params)
return view
end
end
end
loadlayout=env_loadlayout(_G)
local LuaAsyncTask=luajava.bindClass("com.androlua.LuaAsyncTask")
local LuaThread=luajava.bindClass("com.androlua.LuaThread")
local LuaTimer=luajava.bindClass("com.androlua.LuaTimer")
local Object=luajava.bindClass("java.lang.Object")
function print(...)
local buf={}
for n=1,select("#",...) do
table.insert(buf,tostring(select(n,...)))
end
local msg=table.concat(buf,"\t\t")
activity.sendMsg(msg)
os.execute("log -p d -t lua "..msg)
end
local function setmetamethod(t,k,v)
getmetatable(t)[k]=v
end
local function getmetamethod(t,k,v)
return getmetatable(t)[k]
end
local getjavamethod=getmetamethod(LuaThread,"__index")
local function __call(t,k)
return function(...)
if ... then
t.call(k,Object{...})
else
t.call(k)
end
end
end
local function __index(t,k)
local s,r=pcall(getjavamethod,t,k)
if s then
return r
end
local r=__call(t,k)
setmetamethod(t,k,r)
return r
end
local function __newindex(t,k,v)
t.set(k,v)
end
local function checkPath(str)
if str:find("^[%w%.%_]+$") then
if not activity.isInAsset() then
return string.format("%s/%s.lua",activity.luaDir,str)
end
end
return str
end
function thread(src,...)
if type(src)=="string" then
src=checkPath(src)
end
local luaThread
if ... then
luaThread=LuaThread(content,src,true,Object{...})
else
luaThread=LuaThread(content,src,true)
end
luaThread.start()
--setmetamethod(luaThread,"__call",__call)
setmetamethod(luaThread,"__index",__index)
setmetamethod(luaThread,"__newindex",__newindex)
return luaThread
end
function task(src,...)
local args={...}
local callback=args[select("#",...)]
args[select("#",...)]=nil
local luaAsyncTask=LuaAsyncTask(content,src,callback)
luaAsyncTask.execute(args)
end
function timer(f,d,p,...)
local luaTimer=LuaTimer(content,f,Object{...})
if p==0 then
luaTimer.start(d)
else
luaTimer.start(d,p)
end
return luaTimer
end
local LuaBitmap=luajava.bindClass "com.androlua.LuaBitmap"
function loadbitmap(path)
if not path:find("%.") then
path=path..".png"
end
if path:find("^[%w%.%_]+$") then
if not activity.isInAsset() then
return LuaBitmap.getLoacalBitmap(string.format("%s/%s",activity.luaDir,path))
else
return LuaBitmap.getAssetBitmap(content,path)
end
elseif path:find("^https*://") then
return LuaBitmap.getHttpBitmap(path)
else
return LuaBitmap.getLoacalBitmap(path)
end
end
function utf8.sub(s,i,j)
i=utf8.offset(s,i)
j=((j or -1)==-1 and -1) or utf8.offset(s,j+1)-1
return string.sub(s,i,j)
end
import 'java.lang.*'
import 'java.util.*'
function new_env()
local _env={
activity=content,
require=require,
dump=dump,
each=each,
enum=enum,
print=print,
task=task,
timer=timer,
thread=thread,
loadbitmap=loadbitmap,
android=android,
_G=_G
}
_env.import=env_import(_env)
_env.loadlayout=env_loadlayout(_env)
return _env
end
return new_env()
| mit |
LegionXI/darkstar | scripts/zones/Bastok_Mines/npcs/Deadly_Spider.lua | 33 | 1388 | -----------------------------------
-- Area: Bastok Mines
-- NPC: Deadly Spider
-- Involved in Quest: Stamp Hunt
-----------------------------------
package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/zones/Bastok_Mines/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local StampHunt = player:getQuestStatus(BASTOK,STAMP_HUNT);
if (StampHunt == QUEST_ACCEPTED and player:getMaskBit(player:getVar("StampHunt_Mask"),0) == false) then
player:startEvent(0x0056);
else
player:startEvent(0x0011);
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 == 0x0056) then
player:setMaskBit(player:getVar("StampHunt_Mask"),"StampHunt_Mask",0,true);
end
end;
| gpl-3.0 |
LegionXI/darkstar | scripts/globals/mobskills/Sickle_Slash.lua | 34 | 1178 | ---------------------------------------------------
-- Sickle Slash
-- Deals critical damage. Chance of critical hit varies with TP.
---------------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------------
---------------------------------------------------
-- onMobSkillCheck
-- Check for Grah Family id 122,123,124
-- if not in Spider form, then ignore.
---------------------------------------------------
function onMobSkillCheck(target,mob,skill)
if ((mob:getFamily() == 122 or mob:getFamily() == 123 or mob:getFamily() == 124) and mob:AnimationSub() ~= 2) then
return 1;
else
return 0;
end
end;
function onMobWeaponSkill(target, mob, skill)
local numhits = 1;
local accmod = 1;
local dmgmod = math.random(2,4) + math.random();
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_CRIT_VARIES,1,1.5,2);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,info.hitslanded);
target:delHP(dmg);
return dmg;
end;
| gpl-3.0 |
lache/RacingKingLee | crazyclient/frameworks/cocos2d-x/cocos/scripting/lua-bindings/auto/api/AssetsManagerEx.lua | 6 | 2739 |
--------------------------------
-- @module AssetsManagerEx
-- @extend Ref
-- @parent_module cc
--------------------------------
-- @brief Gets the current update state.
-- @function [parent=#AssetsManagerEx] getState
-- @param self
-- @return int#int ret (return value: int)
--------------------------------
-- @brief Check out if there is a new version of manifest.<br>
-- You may use this method before updating, then let user determine whether<br>
-- he wants to update resources.
-- @function [parent=#AssetsManagerEx] checkUpdate
-- @param self
-- @return AssetsManagerEx#AssetsManagerEx self (return value: cc.AssetsManagerEx)
--------------------------------
-- @brief Gets storage path.
-- @function [parent=#AssetsManagerEx] getStoragePath
-- @param self
-- @return string#string ret (return value: string)
--------------------------------
-- @brief Update with the current local manifest.
-- @function [parent=#AssetsManagerEx] update
-- @param self
-- @return AssetsManagerEx#AssetsManagerEx self (return value: cc.AssetsManagerEx)
--------------------------------
-- @brief Function for retrieve the local manifest object
-- @function [parent=#AssetsManagerEx] getLocalManifest
-- @param self
-- @return Manifest#Manifest ret (return value: cc.Manifest)
--------------------------------
-- @brief Function for retrieve the remote manifest object
-- @function [parent=#AssetsManagerEx] getRemoteManifest
-- @param self
-- @return Manifest#Manifest ret (return value: cc.Manifest)
--------------------------------
-- @brief Reupdate all failed assets under the current AssetsManagerEx context
-- @function [parent=#AssetsManagerEx] downloadFailedAssets
-- @param self
-- @return AssetsManagerEx#AssetsManagerEx self (return value: cc.AssetsManagerEx)
--------------------------------
-- @brief Create function for creating a new AssetsManagerEx<br>
-- param manifestUrl The url for the local manifest file<br>
-- param storagePath The storage path for downloaded assetes<br>
-- warning The cached manifest in your storage path have higher priority and will be searched first,<br>
-- only if it doesn't exist, AssetsManagerEx will use the given manifestUrl.
-- @function [parent=#AssetsManagerEx] create
-- @param self
-- @param #string manifestUrl
-- @param #string storagePath
-- @return AssetsManagerEx#AssetsManagerEx ret (return value: cc.AssetsManagerEx)
--------------------------------
--
-- @function [parent=#AssetsManagerEx] AssetsManagerEx
-- @param self
-- @param #string manifestUrl
-- @param #string storagePath
-- @return AssetsManagerEx#AssetsManagerEx self (return value: cc.AssetsManagerEx)
return nil
| mit |
greasydeal/darkstar | scripts/zones/Ifrits_Cauldron/npcs/relic.lua | 38 | 1848 | -----------------------------------
-- Area: Ifrit's Cauldron
-- NPC: <this space intentionally left blank>
-- @pos -18 40 20 205
-----------------------------------
package.loaded["scripts/zones/Ifrits_Cauldron/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Ifrits_Cauldron/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- Working on correct relic, 4 items, Stage 4 item, Shard, Necropsyche, currencypiece
if (player:getVar("RELIC_IN_PROGRESS") == 18329 and trade:getItemCount() == 4 and trade:hasItemQty(18329,1) and
trade:hasItemQty(1582,1) and trade:hasItemQty(1589,1) and trade:hasItemQty(1451,1)) then
player:startEvent(32,18330);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
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 == 32) then
if (player:getFreeSlotsCount() < 2) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,18330);
player:messageSpecial(FULL_INVENTORY_AFTER_TRADE,1450);
else
player:tradeComplete();
player:addItem(18330);
player:addItem(1450,30);
player:messageSpecial(ITEM_OBTAINED,18330);
player:messageSpecial(ITEMS_OBTAINED,1450,30);
player:setVar("RELIC_IN_PROGRESS",0);
end
end
end; | gpl-3.0 |
ibm2431/darkstar | scripts/globals/weaponskills/nightmare_scythe.lua | 10 | 1683 | -----------------------------------
-- Nightmare Scythe
-- Scythe weapon skill
-- Skill Level: 100
-- Blinds enemy. Duration of effect varies with TP.
-- Will stack with Sneak Attack.
-- Aligned with the Shadow Gorget & Soil Gorget.
-- Aligned with the Shadow Belt & Soil Belt.
-- Element: None
-- Modifiers: STR:60% MND:60%
-- 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.3 params.dex_wsc = 0.0 params.vit_wsc = 0.0 params.agi_wsc = 0.0 params.int_wsc = 0.0 params.mnd_wsc = 0.3 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 = 0.6 params.mnd_wsc = 0.6
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, params, tp, action, primary, taChar)
if (damage > 0 and target:hasStatusEffect(dsp.effect.BLINDNESS) == false) then
local duration = (tp/1000 * 60) * applyResistanceAddEffect(player,target,dsp.magic.ele.DARK,0)
target:addStatusEffect(dsp.effect.BLINDNESS, 15, 0, duration)
end
return tpHits, extraHits, criticalHit, damage
end
| gpl-3.0 |
evrooije/beerarchy | mods/00_bt_nodes/travelnet/config.lua | 1 | 3120 |
travelnet.MAX_STATIONS_PER_NETWORK = 24;
-- set this to true if you want a simulated beam effect
travelnet.travelnet_effect_enabled = false;
-- set this to true if you want a sound to be played when the travelnet is used
travelnet.travelnet_sound_enabled = true;
-- if you set this to false, travelnets cannot be created
-- (this may be useful if you want nothing but the elevators on your server)
travelnet.travelnet_enabled = true;
-- if you set travelnet.elevator_enabled to false, you will not be able to
-- craft, place or use elevators
travelnet.elevator_enabled = true;
-- if you set this to false, doors will be disabled
travelnet.doors_enabled = true;
-- starts an abm which re-adds travelnet stations to networks in case the savefile got lost
travelnet.abm_enabled = true;
-- change these if you want other receipes for travelnet or elevator
travelnet.travelnet_recipe = {
{"default:glass", "default:steel_ingot", "default:glass", },
{"default:glass", "default:mese", "default:glass", },
{"default:glass", "default:steel_ingot", "default:glass", }
}
travelnet.elevator_recipe = {
{"default:steel_ingot", "default:glass", "default:steel_ingot", },
{"default:steel_ingot", "", "default:steel_ingot", },
{"default:steel_ingot", "default:glass", "default:steel_ingot", }
}
-- if this function returns true, the player with the name player_name is
-- allowed to add a box to the network named network_name, which is owned
-- by the player owner_name;
-- if you want to allow *everybody* to attach stations to all nets, let the
-- function always return true;
-- if the function returns false, players with the travelnet_attach priv
-- can still add stations to that network
travelnet.allow_attach = function( player_name, owner_name, network_name )
return false;
end
-- if this returns true, a player named player_name can remove a travelnet station
-- from network_name (owned by owner_name) even though he is neither the owner nor
-- has the travelnet_remove priv
travelnet.allow_dig = function( player_name, owner_name, network_name )
return false;
end
-- if this function returns false, then player player_name will not be allowed to use
-- the travelnet station_name_start on networ network_name owned by owner_name to travel to
-- the station station_name_target on the same network;
-- if this function returns true, the player will be transfered to the target station;
-- you can use this code to i.e. charge the player money for the transfer or to limit
-- usage of stations to players in the same fraction on PvP servers
travelnet.allow_travel = function( player_name, owner_name, network_name, station_name_start, station_name_target )
--minetest.chat_send_player( player_name, "Player "..tostring( player_name ).." tries to use station "..tostring( station_name_start )..
-- " on network "..tostring( network_name ).." owned by "..tostring( owner_name ).." in order to travel to "..
-- tostring( station_name_target )..".");
return true;
end
| lgpl-2.1 |
naclander/tome | game/engines/default/engine/PlayerProfile.lua | 1 | 29057 | -- TE4 - T-Engine 4
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
require "engine.class"
local http = require "socket.http"
local url = require "socket.url"
local ltn12 = require "ltn12"
local Dialog = require "engine.ui.Dialog"
local UserChat = require "engine.UserChat"
require "Json2"
------------------------------------------------------------
-- some simple serialization stuff
------------------------------------------------------------
local function basicSerialize(o)
if type(o) == "number" or type(o) == "boolean" then
return tostring(o)
elseif type(o) == "function" then
return string.format("loadstring(%q)", string.dump(o))
else -- assume it is a string
return string.format("%q", o)
end
end
local function serialize_data(outf, name, value, saved, filter, allow, savefile, force)
saved = saved or {} -- initial value
outf(name, " = ")
if type(value) == "number" or type(value) == "string" or type(value) == "boolean" or type(value) == "function" then
outf(basicSerialize(value), "\n")
elseif type(value) == "table" then
saved[value] = name -- save name for next time
outf("{}\n") -- create a new table
for k,v in pairs(value) do -- save its fields
local fieldname
fieldname = string.format("%s[%s]", name, basicSerialize(k))
serialize_data(outf, fieldname, v, saved, {new=true}, false, savefile, false)
end
else
error("cannot save a " .. type(value) .. " ("..name..")")
end
end
local function serialize(data)
local tbl = {}
local outf = function(...) for i,str in ipairs{...} do table.insert(tbl, str) end end
for k, e in pairs(data) do
serialize_data(outf, tostring(k), e)
end
return table.concat(tbl)
end
------------------------------------------------------------
--- Handles the player profile, possibly online
module(..., package.seeall, class.make)
function _M:init()
self.chat = UserChat.new()
self.dlc_files = {classes={}, files={}}
self.saved_events = {}
self.generic = {}
self.modules = {}
self.evt_cbs = {}
self.stats_fields = {}
local checkstats = function(self, field) return self.stats_fields[field] end
self.config_settings =
{
[checkstats] = { invalid = { read={online=true}, write="online" }, valid = { read={online=true}, write="online" } },
["^allow_build$"] = { invalid = { read={offline=true,online=true}, write="offline" }, valid = { read={offline=true,online=true}, write="online" } },
["^achievements$"] = { invalid = { read={offline=true,online=true}, write="offline" }, valid = { read={online=true}, write="online" } },
["^donations$"] = { invalid = { read={offline=true}, write="offline" }, valid = { read={offline=true}, write="offline" } },
}
self.auth = false
end
function _M:start()
self:funFactsGrab()
self:loadGenericProfile()
if self.generic.online and self.generic.online.login and self.generic.online.pass then
self.login = self.generic.online.login
self.pass = self.generic.online.pass
self:tryAuth()
self:waitFirstAuth()
elseif core.steam and self.generic.onlinesteam and self.generic.onlinesteam.autolog then
core.steam.sessionTicket(function(ticket) if ticket then
self.steam_token = ticket:toHex()
self:tryAuth()
self:waitFirstAuth()
end end)
end
end
function _M:addStatFields(...)
for i, f in ipairs{...} do
self.stats_fields[f] = true
end
end
function _M:loadData(f, where)
setfenv(f, where)
local ok, err = pcall(f)
if not ok and err then print("Error executing data", err) end
end
function _M:mountProfile(online, module)
-- Create the directory if needed
local restore = fs.getWritePath()
fs.setWritePath(engine.homepath)
fs.mkdir(string.format("/profiles/%s/generic/", online and "online" or "offline"))
if module then fs.mkdir(string.format("/profiles/%s/modules/%s", online and "online" or "offline", module)) end
local path = engine.homepath.."/profiles/"..(online and "online" or "offline")
fs.mount(path, "/current-profile")
print("[PROFILE] mounted ", online and "online" or "offline", "on /current-profile")
fs.setWritePath(path)
return restore
end
function _M:umountProfile(online, pop)
local path = engine.homepath.."/profiles/"..(online and "online" or "offline")
fs.umount(path)
print("[PROFILE] unmounted ", online and "online" or "offline", "from /current-profile")
if pop then fs.setWritePath(pop) end
end
-- Define the fields that are sync'ed online, and how they are sync'ed
local generic_profile_defs = {
firstrun = {nosync=true, {firstrun="number"}, receive=function(data, save) save.firstrun = data.firstrun end },
online = {nosync=true, {login="string:40", pass="string:40"}, receive=function(data, save) save.login = data.login save.pass = data.pass end },
onlinesteam = {nosync=true, {autolog="boolean"}, receive=function(data, save) save.autolog = data.autolog end },
modules_played = { {name="index:string:30"}, {time_played="number"}, receive=function(data, save) max_set(save, data.name, data, "time_played") end, export=function(env) for k, v in pairs(env) do add{name=k, time_played=v} end end },
modules_loaded = { {name="index:string:30"}, {nb="number"}, receive=function(data, save) max_set(save, data.name, data, "nb") end, export=function(env) for k, v in pairs(env) do add{name=k, nb=v} end end },
}
--- Loads profile generic profile from disk
-- Generic profile is always read from the "online" profile
function _M:loadGenericProfile()
-- Delay when we are currently saving
if savefile_pipe and savefile_pipe.saving then savefile_pipe:pushGeneric("loadGenericProfile", function() self:loadGenericProfile() end) return end
local pop = self:mountProfile(true)
local d = "/current-profile/generic/"
for i, file in ipairs(fs.list(d)) do
if file:find(".profile$") then
local f, err = loadfile(d..file)
if not f and err then
print("Error loading data profile", file, err)
else
local field = file:gsub(".profile$", "")
self.generic[field] = self.generic[field] or {}
self:loadData(f, self.generic[field])
end
end
end
self:umountProfile(true, pop)
end
--- Check if we can load this field from this profile
function _M:filterLoadData(online, field)
local ok = false
for f, conf in pairs(self.config_settings) do
local try = false
if type(f) == "string" then try = field:find(f)
elseif type(f) == "function" then try = f(self, field) end
if try then
local c
if self.hash_valid then c = conf.valid
else c = conf.invalid
end
if not c then break end
c = c.read
if not c then break end
if online and c.online then ok = true
elseif not online and c.offline then ok = true
end
break
end
end
print("[PROFILE] filtering load of ", field, " from profile ", online and "online" or "offline", "=>", ok and "allowed" or "disallowed")
return ok
end
--- Return if we should save this field in the online or offline profile
function _M:filterSaveData(field)
local online = false
for f, conf in pairs(self.config_settings) do
local try = false
if type(f) == "string" then try = field:find(f)
elseif type(f) == "function" then try = f(self, field) end
if try then
local c
if self.hash_valid then c = conf.valid
else c = conf.invalid
end
if not c then break end
c = c.write
if not c then break end
if c == "online" then online = true else online = false end
break
end
end
print("[PROFILE] filtering save of ", field, " to profile ", online and "online" or "offline")
return online
end
--- Loads profile module profile from disk
function _M:loadModuleProfile(short_name, mod_def)
if short_name == "boot" then return end
-- Delay when we are currently saving
if savefile_pipe and savefile_pipe.saving then savefile_pipe:pushGeneric("loadModuleProfile", function() self:loadModuleProfile(short_name) end) return end
local function load(online)
local pop = self:mountProfile(online, short_name)
local d = "/current-profile/modules/"..short_name.."/"
self.modules[short_name] = self.modules[short_name] or {}
for i, file in ipairs(fs.list(d)) do
if file:find(".profile$") then
local field = file:gsub(".profile$", "")
if self:filterLoadData(online, field) then
local f, err = loadfile(d..file)
if not f and err then
print("Error loading data profile", file, err)
else
self.modules[short_name][field] = self.modules[short_name][field] or {}
self:loadData(f, self.modules[short_name][field])
end
end
end
end
self:umountProfile(online, pop)
end
load(false) -- Load from offline profile
load(true) -- Load from online profile
self.mod = self.modules[short_name]
self.mod_name = short_name
self:getConfigs(short_name, nil, mod_def)
self:syncOnline(short_name, mod_def)
end
--- Saves a profile data
function _M:saveGenericProfile(name, data, nosync, nowrite)
-- Delay when we are currently saving
if not profile then return end
if savefile_pipe and savefile_pipe.saving then savefile_pipe:pushGeneric("saveGenericProfile", function() self:saveGenericProfile(name, data, nosync) end) return end
if not generic_profile_defs[name] then print("[PROFILE] refusing unknown generic data", name) return end
profile.generic[name] = profile.generic[name] or {}
local dataenv = profile.generic[name]
local f = generic_profile_defs[name].receive
setfenv(f, {
inc_set=function(dataenv, key, data, dkey)
local v = data[dkey]
if type(v) == "number" then
elseif type(v) == "table" and v[1] == "inc" then v = (dataenv[key] or 0) + v[2]
end
dataenv[key] = v
data[dkey] = v
end,
max_set=function(dataenv, key, data, dkey)
local v = data[dkey]
if type(v) == "number" then
elseif type(v) == "table" and v[1] == "inc" then v = (dataenv[key] or 0) + v[2]
end
v = math.max(v, dataenv[key] or 0)
dataenv[key] = v
data[dkey] = v
end,
})
f(data, dataenv)
if not nowrite then
local pop = self:mountProfile(true)
local f = fs.open("/generic/"..name..".profile", "w")
if f then
f:write(serialize(dataenv))
f:close()
end
self:umountProfile(true, pop)
end
if not nosync and not generic_profile_defs[name].no_sync then self:setConfigs("generic", name, data) end
end
--- Saves a module profile data
function _M:saveModuleProfile(name, data, nosync, nowrite)
if module == "boot" then return end
if not game or not game.__mod_info.profile_defs then return end
-- Delay when we are currently saving
if savefile_pipe and savefile_pipe.saving then savefile_pipe:pushGeneric("saveModuleProfile", function() self:saveModuleProfile(name, data, nosync) end) return end
local module = self.mod_name
-- Check for readability
profile.mod[name] = profile.mod[name] or {}
local dataenv = profile.mod[name]
local f = game.__mod_info.profile_defs[name].receive
setfenv(f, {
inc_set=function(dataenv, key, data, dkey)
local v = data[dkey]
if type(v) == "number" then
elseif type(v) == "table" and v[1] == "inc" then v = (dataenv[key] or 0) + v[2]
end
dataenv[key] = v
data[dkey] = v
end,
max_set=function(dataenv, key, data, dkey)
local v = data[dkey]
if type(v) == "number" then
elseif type(v) == "table" and v[1] == "inc" then v = (dataenv[key] or 0) + v[2]
end
v = math.max(v, dataenv[key] or 0)
dataenv[key] = v
data[dkey] = v
end,
})
f(data, dataenv)
if not nowrite then
local online = self:filterSaveData(name)
local pop = self:mountProfile(online, module)
local f = fs.open("/modules/"..module.."/"..name..".profile", "w")
if f then
f:write(serialize(dataenv))
f:close()
end
self:umountProfile(online, pop)
end
if not nosync and not game.__mod_info.profile_defs[name].no_sync then self:setConfigs(module, name, data) end
end
function _M:checkFirstRun()
local result = self.generic.firstrun
if not result then
self:saveGenericProfile("firstrun", {firstrun=os.time()})
end
return result
end
function _M:performlogin(login, pass)
self.login=login
self.pass=pass
print("[ONLINE PROFILE] attempting log in ", self.login)
self.auth_tried = nil
self:tryAuth()
self:waitFirstAuth()
if (profile.auth) then
self:saveGenericProfile("online", {login=login, pass=pass})
self:getConfigs("generic")
self:syncOnline("generic")
end
end
function _M:performloginSteam(token, name, email)
self.steam_token = token
self.steam_token_name = name
if email then self.steam_token_email = email end
print("[ONLINE PROFILE] attempting log in steam", token)
self.auth_tried = nil
self:tryAuth()
self:waitFirstAuth()
if (profile.auth) then
self:saveGenericProfile("onlinesteam", {autolog=true})
self:getConfigs("generic")
self:syncOnline("generic")
end
end
-----------------------------------------------------------------------
-- Events from the profile thread
-----------------------------------------------------------------------
function _M:popEvent(specific)
if not specific then
if #self.saved_events > 0 then return table.remove(self.saved_events, 1) end
return core.profile.popEvent()
else
for i, evt in ipairs(self.saved_events) do
if evt.e == specific then return table.remove(self.saved_events, i) end
end
local evt = core.profile.popEvent()
if evt then
if type(evt) == "string" then evt = evt:unserialize() end
if evt.e == specific then return evt end
self.saved_events[#self.saved_events+1] = evt
end
end
end
function _M:waitEvent(name, cb, wait_max)
-- Wait anwser, this blocks thegame but cant really be avoided :/
local stop = false
local first = true
local tries = 0
while not stop do
if not first then
if not self.waiting_event_no_redraw then core.display.forceRedraw() end
core.game.sleep(50)
end
local evt = self:popEvent(name)
while evt do
if type(game) == "table" then evt = game:handleProfileEvent(evt)
else evt = self:handleEvent(evt) end
-- print("==== waiting event", name, evt.e)
if evt.e == name then
stop = true
cb(evt)
break
end
evt = self:popEvent(name)
end
first = false
tries = tries + 1
if wait_max and tries * 50 > wait_max then break end
end
end
function _M:noMoreAuthWait()
self.no_more_wait_auth = true
end
function _M:waitFirstAuth(timeout)
if self.no_more_wait_auth then return end
if self.auth_tried and self.auth_tried >= 1 then return end
if not self.waiting_auth then return end
print("[PROFILE] waiting for first auth")
local first = true
timeout = timeout or 120
while self.waiting_auth and timeout > 0 do
if not first then
if not self.waiting_auth_no_redraw then core.display.forceRedraw() end
core.game.sleep(50)
end
local evt = self:popEvent()
while evt do
if type(game) == "table" then game:handleProfileEvent(evt)
else self:handleEvent(evt) end
if not self.waiting_auth then break end
evt = self:popEvent()
end
first = false
timeout = timeout - 1
end
end
function _M:eventAuth(e)
self.waiting_auth = false
self.auth_tried = (self.auth_tried or 0) + 1
if e.ok then
self.auth = e.ok:unserialize()
print("[PROFILE] Main thread got authed", self.auth.name)
self:getConfigs("generic", function(e) self:syncOnline(e.module) end)
else
self.auth_last_error = e.reason or "unknown"
end
end
function _M:eventGetNews(e)
if e.news and self.evt_cbs.GetNews then
self.evt_cbs.GetNews(e.news:unserialize())
self.evt_cbs.GetNews = nil
end
end
function _M:eventGetConfigs(e)
local data = zlib.decompress(e.data):unserialize()
local module = e.module
if not data then print("[ONLINE PROFILE] get configs") return end
self:setConfigsBatch(true)
for i = 1, #data do
local val = data[i]
if module == "generic" then
self:saveGenericProfile(e.kind, val, true, i < #data)
else
self:saveModuleProfile(e.kind, val, true, i < #data)
end
end
self:setConfigsBatch(false)
if self.evt_cbs.GetConfigs then self.evt_cbs.GetConfigs(e) self.evt_cbs.GetConfigs = nil end
end
function _M:eventPushCode(e)
local f, err = loadstring(e.code)
if not f then
if e.return_uuid then
core.profile.pushOrder(string.format("o='CodeReturn' uuid=%q data=%q", e.return_uuid, table.serialize{error=err}))
end
else
local ok, err = pcall(f)
if config.settings.cheat then print(ok, err) end
if e.return_uuid then
core.profile.pushOrder(string.format("o='CodeReturn' uuid=%q data=%q", e.return_uuid, table.serialize{result=ok and err, error=not ok and err}))
end
end
end
function _M:eventChat(e)
self.chat:event(e)
end
function _M:eventConnected(e)
if game and type(game) == "table" and game.log then game.log("#YELLOW#Connection to online server established.") end
end
function _M:eventDisconnected(e)
if game and type(game) == "table" and game.log then game.log("#YELLOW#Connection to online server lost, trying to reconnect.") end
end
function _M:eventFunFacts(e)
if e.data then
self.funfacts = zlib.decompress(e.data):unserialize()
end
end
--- Got an event from the profile thread
function _M:handleEvent(e)
if type(e) == "string" then e = e:unserialize() end
if not e then return end
if self["event"..e.e] then self["event"..e.e](self, e) end
return e
end
-----------------------------------------------------------------------
-- Orders for the profile thread
-----------------------------------------------------------------------
function _M:getNews(callback, steam)
print("[ONLINE PROFILE] get news")
self.evt_cbs.GetNews = callback
if not steam then core.profile.pushOrder("o='GetNews'")
else core.profile.pushOrder("o='GetNews' steam=true")
end
end
function _M:tryAuth()
print("[ONLINE PROFILE] auth")
self.auth_last_error = nil
if self.steam_token then
core.profile.pushOrder(table.serialize{o="SteamLogin", token=self.steam_token, name=self.steam_token_name, email=self.steam_token_email})
else
core.profile.pushOrder(table.serialize{o="Login", l=self.login, p=self.pass})
end
self.waiting_auth = true
end
function _M:logOut()
core.profile.pushOrder(table.serialize{o="Logoff"})
profile.generic.online = nil
profile.auth = nil
local pop = self:mountProfile(true)
fs.delete("/generic/online.profile")
fs.delete("/generic/onlinesteam.profile")
self:umountProfile(true, pop)
end
function _M:getConfigs(module, cb, mod_def)
self:waitFirstAuth()
if not self.auth then return end
self.evt_cbs.GetConfigs = cb
if module == "generic" then
for k, _ in pairs(generic_profile_defs) do
if not _.no_sync then
core.profile.pushOrder(table.serialize{o="GetConfigs", module=module, kind=k})
end
end
else
for k, _ in pairs((mod_def or game.__mod_info).profile_defs or {}) do
if not _.no_sync then
core.profile.pushOrder(table.serialize{o="GetConfigs", module=module, kind=k})
end
end
end
end
function _M:setConfigsBatch(v)
core.profile.pushOrder(table.serialize{o="SetConfigsBatch", v=v and true or false})
end
function _M:setConfigs(module, name, data)
self:waitFirstAuth()
if not self.auth then return end
if name == "online" then return end
if module ~= "generic" then
if not game.__mod_info.profile_defs then print("[PROFILE] saving config but no profile defs", module, name) return end
if not game.__mod_info.profile_defs[name] then print("[PROFILE] saving config but no profile def kind", module, name) return end
else
if not generic_profile_defs[name] then print("[PROFILE] saving config but no profile def kind", module, name) return end
end
core.profile.pushOrder(table.serialize{o="SetConfigs", module=module, kind=name, data=zlib.compress(table.serialize(data))})
end
function _M:syncOnline(module, mod_def)
self:waitFirstAuth()
if not self.auth then return end
local sync = self.generic
if module ~= "generic" then sync = self.modules[module] end
if not sync then return end
self:setConfigsBatch(true)
if module == "generic" then
for k, def in pairs(generic_profile_defs) do
if not def.no_sync and def.export and sync[k] then
local f = def.export
local ret = {}
setfenv(f, setmetatable({add=function(d) ret[#ret+1] = d end}, {__index=_G}))
f(sync[k])
for i, r in ipairs(ret) do
core.profile.pushOrder(table.serialize{o="SetConfigs", module=module, kind=k, data=zlib.compress(table.serialize(r))})
end
end
end
else
for k, def in pairs((mod_def or game.__mod_info).profile_defs or {}) do
if not def.no_sync and def.export and sync[k] then
local f = def.export
local ret = {}
setfenv(f, setmetatable({add=function(d) ret[#ret+1] = d end}, {__index=_G}))
f(sync[k])
for i, r in ipairs(ret) do
core.profile.pushOrder(table.serialize{o="SetConfigs", module=module, kind=k, data=zlib.compress(table.serialize(r))})
end
end
end
end
self:setConfigsBatch(false)
end
function _M:checkModuleHash(module, md5)
self.hash_valid = false
if not self.auth then return nil, "no online profile active" end
if config.settings.cheat then return nil, "cheat mode active" end
if game and game:isTainted() then return nil, "savefile tainted" end
core.profile.pushOrder(table.serialize{o="CheckModuleHash", module=module, md5=md5})
local ok = false
self:waitEvent("CheckModuleHash", function(e) ok = e.ok end, 10000)
if not ok then return nil, "bad game version" end
print("[ONLINE PROFILE] module hash is valid")
self.hash_valid = true
return true
end
function _M:checkAddonHash(module, addon, md5)
if not self.auth then return nil, "no online profile active" end
if config.settings.cheat then return nil, "cheat mode active" end
if game and game:isTainted() then return nil, "savefile tainted" end
core.profile.pushOrder(table.serialize{o="CheckAddonHash", module=module, addon=addon, md5=md5})
local ok = false
self:waitEvent("CheckAddonHash", function(e) ok = e.ok end, 10000)
if not ok then return nil, "bad game addon version" end
print("[ONLINE PROFILE] addon hash is valid")
return true
end
function _M:checkBatchHash(list)
if not self.auth then return nil, "no online profile active" end
if config.settings.cheat then return nil, "cheat mode active" end
if game and game:isTainted() then return nil, "savefile tainted" end
core.profile.pushOrder(table.serialize{o="CheckBatchHash", data=list})
local ok = false
local error = nil
self:waitEvent("CheckBatchHash", function(e) ok = e.ok error = e.error end, 10000)
if not ok then return nil, error or "unknown error" end
print("[ONLINE PROFILE] all hashes are valid")
self.hash_valid = true
return true
end
function _M:sendError(what, err)
print("[ONLINE PROFILE] sending error")
core.profile.pushOrder(table.serialize{o="SendError", login=self.login, what=what, err=err, module=game.__mod_info.short_name, version=game.__mod_info.version_name})
end
function _M:registerNewCharacter(module)
if not self.auth or not self.hash_valid then return end
local dialog = Dialog:simpleWaiter("Registering character", "Character is being registered on http://te4.org/")
core.display.forceRedraw()
core.profile.pushOrder(table.serialize{o="RegisterNewCharacter", module=module})
local uuid = nil
self:waitEvent("RegisterNewCharacter", function(e) uuid = e.uuid end, 10000)
dialog:done()
if not uuid then return end
print("[ONLINE PROFILE] new character UUID ", uuid)
return uuid
end
function _M:getCharball(id_profile, uuid)
if not self.auth then return end
local dialog = Dialog:simpleWaiter("Retrieving data from the server", "Retrieving...")
core.display.forceRedraw()
local data = nil
core.profile.pushOrder(table.serialize{o="GetCharball", module=game.__mod_info.short_name, uuid=uuid, id_profile=id_profile})
self:waitEvent("GetCharball", function(e) data = e.data end, 30000)
dialog:done()
if not data then return end
return data
end
function _M:getDLCD(name, version, file)
if not self.auth then return end
local data = nil
core.profile.pushOrder(table.serialize{o="GetDLCD", name=name, version=version, file=file})
self:waitEvent("GetDLCD", function(e) data = e.data end, 30000)
if not data then
print("DLCD for", name, version, file, "got a result of size0")
return ""
end
print("DLCD for", name, version, file, "got a result of size", (data or ""):len())
return (data:len() > 0) and zlib.decompress(data) or data
end
function _M:registerSaveCharball(module, uuid, data)
if not self.auth or not self.hash_valid then return end
core.profile.pushOrder(table.serialize{o="SaveCharball",
module=module,
uuid=uuid,
data=data,
})
print("[ONLINE PROFILE] saved character charball", uuid)
end
function _M:registerSaveChardump(module, uuid, title, tags, data)
if not self.auth or not self.hash_valid then return end
core.profile.pushOrder(table.serialize{o="SaveChardump",
module=module,
uuid=uuid,
data=data,
metadata=table.serialize{tags=tags, title=title},
})
print("[ONLINE PROFILE] saved character ", uuid)
end
function _M:setSaveID(module, uuid, savename, md5)
if not self.auth or not self.hash_valid or not md5 then return end
core.profile.pushOrder(table.serialize{o="SaveMD5",
module=module,
uuid=uuid,
savename=savename,
md5=md5,
})
print("[ONLINE PROFILE] saved character md5", uuid, savename, md5)
end
function _M:checkSaveID(module, uuid, savename, md5)
if not self.auth or not self.hash_valid or not md5 then return function() return false end end
core.profile.pushOrder(table.serialize{o="CheckSaveMD5",
module=module,
uuid=uuid,
savename=savename,
md5=md5,
})
print("[ONLINE PROFILE] checking character md5", uuid, savename, md5)
--[[
return function()
local ok = false
self:waitEvent("CheckSaveMD5", function(e)
if e.savename == savename and e.ok then ok = true end
end, 30000)
return ok
end
]]
return function() return true end
end
function _M:currentCharacter(module, title, uuid)
if not self.auth then return end
core.profile.pushOrder(table.serialize{o="CurrentCharacter",
module=module,
mod_short=(game and type(game)=="table") and game.__mod_info.short_name or "unknown",
title=title,
valid=self.hash_valid,
uuid=uuid,
})
print("[ONLINE PROFILE] current character ", title)
end
function _M:newProfile(Login, Name, Password, Email)
print("[ONLINE PROFILE] profile options ", Login, Email, Name)
core.profile.pushOrder(table.serialize{o="NewProfile2", login=Login, email=Email, name=Name, pass=Password})
local id = nil
local reason = nil
self:waitEvent("NewProfile2", function(e) id = e.uid reason = e.reason end)
if not id then print("[ONLINE PROFILE] could not create") return nil, reason or "unknown" end
print("[ONLINE PROFILE] profile id ", id)
self:performlogin(Login, Password)
return id
end
function _M:entityVaultPoke(module, kind, name, desc, data)
if not data then return end
if not self.auth then return end
core.profile.pushOrder(table.serialize{o="EntityPoke",
module=module,
kind=kind,
name=name,
desc=desc,
data=data,
})
print("[ONLINE PROFILE] poke entity vault", module, kind, name)
end
function _M:entityVaultPeek(module, kind, id)
if not id then return end
if not self.auth then return end
core.profile.pushOrder(table.serialize{o="EntityPeek",
module=module,
kind=kind,
id=id,
})
print("[ONLINE PROFILE] peek entity vault", module, kind, id)
end
function _M:entityVaultEmpty(module, kind, id)
if not id then return end
if not self.auth then return end
core.profile.pushOrder(table.serialize{o="EntityEmpty",
module=module,
kind=kind,
id=id,
})
print("[ONLINE PROFILE] empty entity vault", module, kind, id)
end
function _M:entityVaultInfos(module, kind)
if not self.auth then return end
core.profile.pushOrder(table.serialize{o="EntityInfos",
module=module,
kind=kind,
})
print("[ONLINE PROFILE] list entity vault", module, kind)
end
function _M:addonEnableUpload()
if not self.auth then return end
core.profile.pushOrder(table.serialize{o="AddonEnableUpload"})
print("[ONLINE PROFILE] enabling addon upload grants")
end
function _M:funFactsGrab(module)
core.profile.pushOrder(table.serialize{o="FunFactsGrab", module=module})
print("[ONLINE PROFILE] fun facts", module)
end
function _M:isDonator(s)
s = s or 1
--if core.steam then return true end
--if not self.auth or not tonumber(self.auth.donated) or tonumber(self.auth.donated) < s then return false else return true end
return true
end
function _M:allowDLC(dlc)
if core.steam then if core.steam.checkDLC(dlc[2]) then return true end end
if self.auth and self.auth.dlcs and self.auth.dlcs[dlc[1]] then return true end
return false
end
| gpl-3.0 |
LegionXI/darkstar | scripts/zones/Silver_Sea_route_to_Nashmau/Zone.lua | 17 | 1405 | -----------------------------------
--
-- Zone: Silver_Sea_route_to_Nashmau
--
-----------------------------------
package.loaded["scripts/zones/Silver_Sea_route_to_Nashmau/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Silver_Sea_route_to_Nashmau/TextIDs");
require("scripts/globals/settings");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
return cs;
end;
-----------------------------------
-- onTransportEvent
-----------------------------------
function onTransportEvent(player,transport)
player:startEvent(0x0401);
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0401) then
player:setPos(0,0,0,0,53);
end
end;
| gpl-3.0 |
greasydeal/darkstar | scripts/zones/North_Gustaberg/MobIDs.lua | 36 | 1422 | -----------------------------------
-- Area: North Gustaberg
-- Comments: -- posX, posY, posZ
--(Taken from 'mob_spawn_points' table)
-----------------------------------
-- Stinging Sophie
Stinging_Sophie=17211561;
Stinging_Sophie_PH={
[17211532] = '1', -- 352.974, -40.359, 472.914
[17211534] = '1', -- 353.313, -40.347, 463.609
[17211535] = '1', -- 237.753, -40.500, 469.738
[17211533] = '1', -- 216.150, -41.182, 445.157
[17211536] = '1', -- 197.369, -40.612, 453.688
[17211531] = '1', -- 196.873, -40.415, 500.153
[17211556] = '1', -- 210.607, -40.478, 566.096
[17211557] = '1', -- 288.447, -40.842, 634.161
[17211558] = '1', -- 295.890, -41.593, 614.738
[17211560] = '1', -- 356.544, -40.528, 570.302
[17211559] = '1', -- 363.973, -40.774, 562.355
[17211581] = '1', -- 308.116, -60.352, 550.771
[17211582] = '1', -- 308.975, -61.082, 525.690
[17211580] = '1', -- 310.309, -60.634, 521.404
[17211583] = '1', -- 285.813, -60.784, 518.539
[17211579] = '1', -- 283.958, -60.926, 530.016
};
-- Maighdean Uaine
Maighdean_Uaine=17211714;
Maighdean_Uaine_PH={
[17211698] = '1', -- 121.242, -0.500, 654.504
[17211701] = '1', -- 176.458, -0.347, 722.666
[17211697] = '1', -- 164.140, 1.981, 740.020
[17211710] = '1', -- 239.992, -0.493, 788.037
[17211700] = '1', -- 203.606, -0.607, 721.541
[17211711] = '1', -- 289.709, -0.297, 750.252
};
| gpl-3.0 |
naclander/tome | game/modules/tome/data/general/objects/egos/wands-powers.lua | 1 | 5637 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
--[[
Wands
*detection
*light
*trap destruction
*firewall
*lightning
*conjuration
]]
newEntity{
name = " of detection", addon=true, instant_resolve=true,
keywords = {detect=true},
level_range = {1, 50},
rarity = 8,
charm_power_def = {add=5, max=10, floor=true},
resolvers.charm("detect the presence of creatures around you (rad %d)", 15, function(self, who)
local rad = self:getCharmPower(who)
who:setEffect(who.EFF_SENSE, 2, {
range = rad,
actor = 1,
})
game.logSeen(who, "%s uses %s!", who.name:capitalize(), self:getName{no_count=true})
return {id=true, used=true}
end),
}
newEntity{
name = " of illumination", addon=true, instant_resolve=true,
keywords = {illuminate=true},
level_range = {1, 50},
rarity = 8,
charm_power_def = {add=4, max=15, floor=true},
resolvers.charm("light the area around you (rad %d)", 5, function(self, who)
who:project({type="ball", range=0, selffire=true, radius=self:getCharmPower(who)}, who.x, who.y, engine.DamageType.LITE, 1)
game.logSeen(who, "%s uses %s!", who.name:capitalize(), self:getName{no_count=true})
return {id=true, used=true}
end),
}
newEntity{
name = " of trap destruction", addon=true, instant_resolve=true,
keywords = {trap=true},
level_range = {1, 50},
rarity = 14,
charm_power_def = {add=resolvers.genericlast(function(e) return e.material_level * 8 end), max=100, floor=true},
resolvers.charm("try to disarm traps in a line (disarm power %d)", 15, function(self, who)
local tg = {type="beam", range=2 + who:getMag(2)}
local x, y = who:getTarget(tg)
if not x or not y then return nil end
who:project(tg, x, y, function(px, py)
local trap = game.level.map(px, py, engine.Map.TRAP)
if not trap then return end
local inc = self:getCharmPower(who)
who:attr("can_disarm", 1)
who:attr("disarm_bonus", inc)
trap:disarm(px, py, who)
who:attr("disarm_bonus", -inc)
who:attr("can_disarm", -1)
end)
game.logSeen(who, "%s uses %s!", who.name:capitalize(), self:getName{no_count=true})
return {id=true, used=true}
end),
}
newEntity{
name = " of lightning", addon=true, instant_resolve=true,
keywords = {lightning=true},
level_range = {15, 50},
rarity = 10,
charm_power_def = {add=45, max=300, floor=true},
resolvers.charm(function(self) return ("fire a beam of lightning (dam %d-%d)"):format(self:getCharmPower(who)/3, self:getCharmPower(who)) end, 6, function(self, who)
local tg = {type="beam", range=6 + who:getMag(4)}
local x, y = who:getTarget(tg)
if not x or not y then return nil end
local dam = self:getCharmPower(who)
who:project(tg, x, y, engine.DamageType.LIGHTNING, rng.avg(dam / 3, dam, 3))
local _ _, x, y = who:canProject(tg, x, y)
game.level.map:particleEmitter(who.x, who.y, math.max(math.abs(x-who.x), math.abs(y-who.y)), "lightning", {tx=x-who.x, ty=y-who.y})
game:playSoundNear(who, "talents/lightning")
game.logSeen(who, "%s uses %s!", who.name:capitalize(), self:getName{no_count=true})
return {id=true, used=true}
end),
}
newEntity{
name = " of firewall", addon=true, instant_resolve=true,
keywords = {firewall=true},
level_range = {15, 50},
rarity = 10,
charm_power_def = {add=25, max=400, floor=true},
resolvers.charm("creates a wall of flames lasting for 4 turns (dam %d overall)", 6, function(self, who)
local tg = {type="wall", range=5, halflength=3, halfmax_spots=3+1}
local x, y = who:getTarget(tg)
if not x or not y then return nil end
local dam = self:getCharmPower(who)
who:project(tg, x, y, function(px, py)
game.level.map:addEffect(who, px, py, 4, engine.DamageType.FIRE, dam / 4, 0, 5, nil, {type="inferno"}, nil, true)
end)
game:playSoundNear(who, "talents/fire")
game.logSeen(who, "%s uses %s!", who.name:capitalize(), self:getName{no_count=true})
return {id=true, used=true}
end),
}
newEntity{
name = " of conjuration", addon=true, instant_resolve=true,
keywords = {conjure=true},
level_range = {6, 50},
rarity = 6,
charm_power_def = {add=25, max=600, floor=true},
resolvers.charm(function(self) return ("fire a bolt of a random element (dam %d-%d)"):format(self:getCharmPower(who)/2, self:getCharmPower(who)) end, 6, function(self, who)
local tg = {type="bolt", range=10 + who:getMag(10)}
local x, y = who:getTarget(tg)
if not x or not y then return nil end
local dam = self:getCharmPower(who)
local elem = rng.table{
{engine.DamageType.FIRE, "flame"},
{engine.DamageType.COLD, "freeze"},
{engine.DamageType.LIGHTNING, "lightning_explosion"},
{engine.DamageType.ACID, "acid"},
{engine.DamageType.NATURE, "slime"},
{engine.DamageType.BLIGHT, "slime"},
}
who:project(tg, x, y, elem[1], rng.avg(dam / 2, dam, 3), {type=elem[2]})
game:playSoundNear(who, "talents/fire")
game.logSeen(who, "%s uses %s!", who.name:capitalize(), self:getName{no_count=true})
return {id=true, used=true}
end),
}
| gpl-3.0 |
greasydeal/darkstar | scripts/zones/The_Eldieme_Necropolis/npcs/_5f2.lua | 34 | 1104 | -----------------------------------
-- Area: The Eldieme Necropolis
-- NPC: Odin's Gate
-- @pos 180 -34 55 195
-----------------------------------
package.loaded["scripts/zones/The_Eldieme_Necropolis/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/The_Eldieme_Necropolis/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (npc:getAnimation() == 9) then
player:messageSpecial(SOLID_STONE);
end
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 |
bittorf/luci | applications/luci-app-statistics/luasrc/model/cbi/luci_statistics/exec.lua | 68 | 2536 | -- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
m = Map("luci_statistics",
translate("Exec Plugin Configuration"),
translate(
"The exec plugin starts external commands to read values " ..
"from or to notify external processes when certain threshold " ..
"values have been reached."
))
-- collectd_exec config section
s = m:section( NamedSection, "collectd_exec", "luci_statistics" )
-- collectd_exec.enable
enable = s:option( Flag, "enable", translate("Enable this plugin") )
enable.default = 0
-- collectd_exec_input config section (Exec directives)
exec = m:section( TypedSection, "collectd_exec_input",
translate("Add command for reading values"),
translate(
"Here you can define external commands which will be " ..
"started by collectd in order to read certain values. " ..
"The values will be read from stdout."
))
exec.addremove = true
exec.anonymous = true
-- collectd_exec_input.cmdline
exec_cmdline = exec:option( Value, "cmdline", translate("Script") )
exec_cmdline.default = "/usr/bin/stat-dhcpusers"
-- collectd_exec_input.cmdline
exec_cmduser = exec:option( Value, "cmduser", translate("User") )
exec_cmduser.default = "nobody"
exec_cmduser.rmempty = true
exec_cmduser.optional = true
-- collectd_exec_input.cmdline
exec_cmdgroup = exec:option( Value, "cmdgroup", translate("Group") )
exec_cmdgroup.default = "nogroup"
exec_cmdgroup.rmempty = true
exec_cmdgroup.optional = true
-- collectd_exec_notify config section (NotifyExec directives)
notify = m:section( TypedSection, "collectd_exec_notify",
translate("Add notification command"),
translate(
"Here you can define external commands which will be " ..
"started by collectd when certain threshold values have " ..
"been reached. The values leading to invokation will be " ..
"feeded to the the called programs stdin."
))
notify.addremove = true
notify.anonymous = true
-- collectd_notify_input.cmdline
notify_cmdline = notify:option( Value, "cmdline", translate("Script") )
notify_cmdline.default = "/usr/bin/stat-dhcpusers"
-- collectd_notify_input.cmdline
notify_cmduser = notify:option( Value, "cmduser", translate("User") )
notify_cmduser.default = "nobody"
notify_cmduser.rmempty = true
notify_cmduser.optional = true
-- collectd_notify_input.cmdline
notify_cmdgroup = notify:option( Value, "cmdgroup", translate("Group") )
notify_cmdgroup.default = "nogroup"
notify_cmdgroup.rmempty = true
notify_cmdgroup.optional = true
return m
| apache-2.0 |
herrbrave/RTS_Engine | RTS/RTS/Games/Delza/PlayerMoveState.lua | 1 | 1225 | include("Games/behaviors/State.lua")
BasicWASDMoveState = {}
BasicWASDMoveState.new = function(context)
local self = State.new()
self.context = context
self.context.input = Vector2f.new(0, 0)
function self.setup()
end
function self.update(dt)
step = dt / 1000.0
characterPos = getPosition(entityId)
if keys[SDLK_w] then
self.context.input:setY(-1)
elseif keys[SDLK_s] then
self.context.input:setY(1)
else
self.context.input:setY(0)
end
if keys[SDLK_a] then
self.context.input:setX(-1)
elseif keys[SDLK_d] then
self.context.input:setX(1)
else
self.context.input:setX(0)
end
self.context.input:normalize()
self.context.input:scale(self.context.speed)
if self.context.input:magnitude() > 0 then
self.context.velocity:moveToward(self.context.input:getX(), self.context.input:getY(), step * self.context.accelerate)
else
self.context.velocity:moveToward(0, 0, step * self.context.friction)
end
end
function self.onPhysics(dt)
step = dt / 1000.0
if self.context.velocity:magnitude() > 0 then
moveAndSlide(entityId, self.context.velocity:getX() * step, self.context.velocity:getY() * step)
end
end
function self.teardown()
end
return self
end | mit |
ibm2431/darkstar | scripts/globals/weaponskills/cross_reaper.lua | 10 | 1806 | -----------------------------------
-- Cross Reaper
-- Scythe weapon skill
-- Skill level: 225
-- Delivers a two-hit attack. Damage varies with TP.
-- Modifiers: STR:30% MND:30%
-- 100%TP 200%TP 300%TP
-- 2.0 2.25 2.5
-----------------------------------
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 = 2
-- ftp damage mods (for Damage Varies with TP lines are calculated in the function
params.ftp100 = 2.0 params.ftp200 = 2.25 params.ftp300 = 2.5
-- wscs are in % so 0.2=20%
params.str_wsc = 0.3 params.dex_wsc = 0.0 params.vit_wsc = 0.0 params.agi_wsc = 0.0 params.int_wsc = 0.0 params.mnd_wsc = 0.3 params.chr_wsc = 0.0
-- critical mods, again in % (ONLY USE FOR CRITICAL HIT VARIES WITH TP)
params.crit100 = 0.0 params.crit200=0.0 params.crit300=0.0
params.canCrit = false
-- params.accuracy mods (ONLY USE FOR ACCURACY VARIES WITH TP) , should be the acc at those %s NOT the penalty values. Leave 0 if acc doesnt vary with tp.
params.acc100 = 0 params.acc200=0 params.acc300=0
-- attack multiplier (only some WSes use this, this varies the actual ratio value, see Tachi: Kasha) 1 is default.
params.atk100 = 1; params.atk200 = 1; params.atk300 = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.ftp100 = 2.0 params.ftp200 = 4.0 params.ftp300 = 7.0
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)
return tpHits, extraHits, criticalHit, damage
end
| gpl-3.0 |
danjia/GameForMom | Resources/extern.lua | 14 | 2587 | function clone(object)
local lookup_table = {}
local function _copy(object)
if type(object) ~= "table" then
return object
elseif lookup_table[object] then
return lookup_table[object]
end
local new_table = {}
lookup_table[object] = new_table
for key, value in pairs(object) do
new_table[_copy(key)] = _copy(value)
end
return setmetatable(new_table, getmetatable(object))
end
return _copy(object)
end
--Create an class.
function class(classname, super)
local superType = type(super)
local cls
if superType ~= "function" and superType ~= "table" then
superType = nil
super = nil
end
if superType == "function" or (super and super.__ctype == 1) then
-- inherited from native C++ Object
cls = {}
if superType == "table" then
-- copy fields from super
for k,v in pairs(super) do cls[k] = v end
cls.__create = super.__create
cls.super = super
else
cls.__create = super
end
cls.ctor = function() end
cls.__cname = classname
cls.__ctype = 1
function cls.new(...)
local instance = cls.__create(...)
-- copy fields from class to native object
for k,v in pairs(cls) do instance[k] = v end
instance.class = cls
instance:ctor(...)
return instance
end
else
-- inherited from Lua Object
if super then
cls = clone(super)
cls.super = super
else
cls = {ctor = function() end}
end
cls.__cname = classname
cls.__ctype = 2 -- lua
cls.__index = cls
function cls.new(...)
local instance = setmetatable({}, cls)
instance.class = cls
instance:ctor(...)
return instance
end
end
return cls
end
function schedule(node, callback, delay)
local delay = CCDelayTime:create(delay)
local callfunc = CCCallFunc:create(callback)
local sequence = CCSequence:createWithTwoActions(delay, callfunc)
local action = CCRepeatForever:create(sequence)
node:runAction(action)
return action
end
function performWithDelay(node, callback, delay)
local delay = CCDelayTime:create(delay)
local callfunc = CCCallFunc:create(callback)
local sequence = CCSequence:createWithTwoActions(delay, callfunc)
node:runAction(sequence)
return sequence
end
| mit |
greasydeal/darkstar | scripts/zones/Windurst_Woods/npcs/Nikkoko.lua | 53 | 1835 | -----------------------------------
-- Area: Windurst Woods
-- NPC: Nikkoko
-- Type: Clothcraft Image Support
-- @pos -32.810 -3.25 -113.680 241
-----------------------------------
package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/crafting");
require("scripts/zones/Windurst_Woods/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local guildMember = isGuildMember(player,3);
local SkillCap = getCraftSkillCap(player,SKILL_CLOTHCRAFT);
local SkillLevel = player:getSkillLevel(SKILL_CLOTHCRAFT);
if (guildMember == 1) then
if (player:hasStatusEffect(EFFECT_CLOTHCRAFT_IMAGERY) == false) then
player:startEvent(0x271E,SkillCap,SkillLevel,1,511,player:getGil(),0,4095,0); -- p1 = skill level
else
player:startEvent(0x271E,SkillCap,SkillLevel,1,511,player:getGil(),7101,4095,0);
end
else
player:startEvent(0x271E); -- Standard Dialogue
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x271E and option == 1) then
player:messageSpecial(IMAGE_SUPPORT,0,4,1);
player:addStatusEffect(EFFECT_CLOTHCRAFT_IMAGERY,1,0,120);
end
end; | gpl-3.0 |
lbthomsen/openwrt-luci | applications/luci-app-olsr/luasrc/controller/olsr.lua | 5 | 10055 | module("luci.controller.olsr", package.seeall)
local neigh_table = nil
local ifaddr_table = nil
function index()
local ipv4,ipv6
if nixio.fs.access("/etc/config/olsrd") then
ipv4 = 1
end
if nixio.fs.access("/etc/config/olsrd6") then
ipv6 = 1
end
if not ipv4 and not ipv6 then
return
end
require("luci.model.uci")
local uci = luci.model.uci.cursor_state()
uci:foreach("olsrd", "olsrd", function(s)
if s.SmartGateway and s.SmartGateway == "yes" then has_smartgw = true end
end)
local page = node("admin", "status", "olsr")
page.target = template("status-olsr/overview")
page.title = _("OLSR")
page.subindex = true
page.acl_depends = { "luci-app-olsr" }
local page = node("admin", "status", "olsr", "json")
page.target = call("action_json")
page.title = nil
page.leaf = true
local page = node("admin", "status", "olsr", "neighbors")
page.target = call("action_neigh")
page.title = _("Neighbours")
page.subindex = true
page.order = 5
local page = node("admin", "status", "olsr", "routes")
page.target = call("action_routes")
page.title = _("Routes")
page.order = 10
local page = node("admin", "status", "olsr", "topology")
page.target = call("action_topology")
page.title = _("Topology")
page.order = 20
local page = node("admin", "status", "olsr", "hna")
page.target = call("action_hna")
page.title = _("HNA")
page.order = 30
local page = node("admin", "status", "olsr", "mid")
page.target = call("action_mid")
page.title = _("MID")
page.order = 50
if has_smartgw then
local page = node("admin", "status", "olsr", "smartgw")
page.target = call("action_smartgw")
page.title = _("SmartGW")
page.order = 60
end
local page = node("admin", "status", "olsr", "interfaces")
page.target = call("action_interfaces")
page.title = _("Interfaces")
page.order = 70
odsp = entry(
{"admin", "services", "olsrd", "display"},
cbi("olsr/olsrddisplay"), _("Display")
)
end
function action_json()
local http = require "luci.http"
local utl = require "luci.util"
local uci = require "luci.model.uci".cursor()
local jsonreq4
local jsonreq6
local v4_port = tonumber(uci:get("olsrd", "olsrd_jsoninfo", "port") or "") or 9090
local v6_port = tonumber(uci:get("olsrd6", "olsrd_jsoninfo", "port") or "") or 9090
jsonreq4 = utl.exec("(echo /all | nc 127.0.0.1 %d | sed -n '/^[}{ ]/p') 2>/dev/null" % v4_port)
jsonreq6 = utl.exec("(echo /all | nc ::1 %d | sed -n '/^[}{ ]/p') 2>/dev/null" % v6_port)
http.prepare_content("application/json")
if not jsonreq4 or jsonreq4 == "" then
jsonreq4 = "{}"
end
if not jsonreq6 or jsonreq6 == "" then
jsonreq6 = "{}"
end
http.write('{"v4":' .. jsonreq4 .. ', "v6":' .. jsonreq6 .. '}')
end
local function local_mac_lookup(ipaddr)
local _, rt
for _, rt in ipairs(luci.ip.routes({ type = 1, src = ipaddr })) do
local link = rt.dev and luci.ip.link(rt.dev)
local mac = link and luci.ip.checkmac(link.mac)
if mac then return mac end
end
end
local function remote_mac_lookup(ipaddr)
local _, n
for _, n in ipairs(luci.ip.neighbors({ dest = ipaddr })) do
local mac = luci.ip.checkmac(n.mac)
if mac then return mac end
end
end
function action_neigh(json)
local data, has_v4, has_v6, error = fetch_jsoninfo('links')
if error then
return
end
local uci = require "luci.model.uci".cursor_state()
local resolve = uci:get("luci_olsr", "general", "resolve")
local ntm = require "luci.model.network".init()
local devices = ntm:get_wifidevs()
local sys = require "luci.sys"
local assoclist = {}
local ntm = require "luci.model.network"
local ipc = require "luci.ip"
local nxo = require "nixio"
local defaultgw
ipc.routes({ family = 4, type = 1, dest_exact = "0.0.0.0/0" },
function(rt) defaultgw = rt.gw end)
local function compare(a,b)
if a.proto == b.proto then
return a.linkCost < b.linkCost
else
return a.proto < b.proto
end
end
for _, dev in ipairs(devices) do
for _, net in ipairs(dev:get_wifinets()) do
local radio = net:get_device()
assoclist[#assoclist+1] = {}
assoclist[#assoclist]['ifname'] = net:ifname()
assoclist[#assoclist]['network'] = net:network()[1]
assoclist[#assoclist]['device'] = radio and radio:name() or nil
assoclist[#assoclist]['list'] = net:assoclist()
end
end
for k, v in ipairs(data) do
local snr = 0
local signal = 0
local noise = 0
local mac = ""
local ip
local neihgt = {}
if resolve == "1" then
hostname = nixio.getnameinfo(v.remoteIP, nil, 100)
if hostname then
v.hostname = hostname
end
end
local interface = ntm:get_status_by_address(v.localIP)
local lmac = local_mac_lookup(v.localIP)
local rmac = remote_mac_lookup(v.remoteIP)
for _, val in ipairs(assoclist) do
if val.network == interface and val.list then
local assocmac, assot
for assocmac, assot in pairs(val.list) do
if rmac == luci.ip.checkmac(assocmac) then
signal = tonumber(assot.signal)
noise = tonumber(assot.noise)
snr = (noise*-1) - (signal*-1)
end
end
end
end
if interface then
v.interface = interface
end
v.snr = snr
v.signal = signal
v.noise = noise
if rmac then
v.remoteMAC = rmac
end
if lmac then
v.localMAC = lmac
end
if defaultgw == v.remoteIP then
v.defaultgw = 1
end
end
table.sort(data, compare)
luci.template.render("status-olsr/neighbors", {links=data, has_v4=has_v4, has_v6=has_v6})
end
function action_routes()
local data, has_v4, has_v6, error = fetch_jsoninfo('routes')
if error then
return
end
local uci = require "luci.model.uci".cursor_state()
local resolve = uci:get("luci_olsr", "general", "resolve")
for k, v in ipairs(data) do
if resolve == "1" then
local hostname = nixio.getnameinfo(v.gateway, nil, 100)
if hostname then
v.hostname = hostname
end
end
end
local function compare(a,b)
if a.proto == b.proto then
return a.rtpMetricCost < b.rtpMetricCost
else
return a.proto < b.proto
end
end
table.sort(data, compare)
luci.template.render("status-olsr/routes", {routes=data, has_v4=has_v4, has_v6=has_v6})
end
function action_topology()
local data, has_v4, has_v6, error = fetch_jsoninfo('topology')
if error then
return
end
local function compare(a,b)
if a.proto == b.proto then
return a.tcEdgeCost < b.tcEdgeCost
else
return a.proto < b.proto
end
end
table.sort(data, compare)
luci.template.render("status-olsr/topology", {routes=data, has_v4=has_v4, has_v6=has_v6})
end
function action_hna()
local data, has_v4, has_v6, error = fetch_jsoninfo('hna')
if error then
return
end
local uci = require "luci.model.uci".cursor_state()
local resolve = uci:get("luci_olsr", "general", "resolve")
local function compare(a,b)
if a.proto == b.proto then
return a.genmask < b.genmask
else
return a.proto < b.proto
end
end
for k, v in ipairs(data) do
if resolve == "1" then
hostname = nixio.getnameinfo(v.gateway, nil, 100)
if hostname then
v.hostname = hostname
end
end
if v.validityTime then
v.validityTime = tonumber(string.format("%.0f", v.validityTime / 1000))
end
end
table.sort(data, compare)
luci.template.render("status-olsr/hna", {hna=data, has_v4=has_v4, has_v6=has_v6})
end
function action_mid()
local data, has_v4, has_v6, error = fetch_jsoninfo('mid')
if error then
return
end
local function compare(a,b)
if a.proto == b.proto then
return a.main.ipAddress < b.main.ipAddress
else
return a.proto < b.proto
end
end
table.sort(data, compare)
luci.template.render("status-olsr/mid", {mids=data, has_v4=has_v4, has_v6=has_v6})
end
function action_smartgw()
local data, has_v4, has_v6, error = fetch_jsoninfo('gateways')
if error then
return
end
local function compare(a,b)
if a.proto == b.proto then
return a.cost < b.cost
else
return a.proto < b.proto
end
end
table.sort(data.ipv4, compare)
table.sort(data.ipv6, compare)
luci.template.render("status-olsr/smartgw", {gws=data, has_v4=has_v4, has_v6=has_v6})
end
function action_interfaces()
local data, has_v4, has_v6, error = fetch_jsoninfo('interfaces')
local ntm = require "luci.model.network".init()
if error then
return
end
local function compare(a,b)
return a.proto < b.proto
end
for k, v in ipairs(data) do
local interface = ntm:get_status_by_address(v.olsrInterface.ipAddress)
if interface then
v.interface = interface
end
end
table.sort(data, compare)
luci.template.render("status-olsr/interfaces", {iface=data, has_v4=has_v4, has_v6=has_v6})
end
-- Internal
function fetch_jsoninfo(otable)
local uci = require "luci.model.uci".cursor_state()
local utl = require "luci.util"
local json = require "luci.json"
local IpVersion = uci:get_first("olsrd", "olsrd","IpVersion")
local jsonreq4 = ""
local jsonreq6 = ""
local v4_port = tonumber(uci:get("olsrd", "olsrd_jsoninfo", "port") or "") or 9090
local v6_port = tonumber(uci:get("olsrd6", "olsrd_jsoninfo", "port") or "") or 9090
jsonreq4 = utl.exec("(echo /%s | nc 127.0.0.1 %d | sed -n '/^[}{ ]/p') 2>/dev/null" %{ otable, v4_port })
jsonreq6 = utl.exec("(echo /%s | nc ::1 %d | sed -n '/^[}{ ]/p') 2>/dev/null" %{ otable, v6_port })
local jsondata4 = {}
local jsondata6 = {}
local data4 = {}
local data6 = {}
local has_v4 = False
local has_v6 = False
if jsonreq4 == '' and jsonreq6 == '' then
luci.template.render("status-olsr/error_olsr")
return nil, 0, 0, true
end
if jsonreq4 ~= "" then
has_v4 = 1
jsondata4 = json.decode(jsonreq4) or {}
if otable == 'status' then
data4 = jsondata4
else
data4 = jsondata4[otable] or {}
end
for k, v in ipairs(data4) do
data4[k]['proto'] = '4'
end
end
if jsonreq6 ~= "" then
has_v6 = 1
jsondata6 = json.decode(jsonreq6) or {}
if otable == 'status' then
data6 = jsondata6
else
data6 = jsondata6[otable] or {}
end
for k, v in ipairs(data6) do
data6[k]['proto'] = '6'
end
end
for k, v in ipairs(data6) do
table.insert(data4, v)
end
return data4, has_v4, has_v6, false
end
| apache-2.0 |
ibm2431/darkstar | scripts/globals/items/bowl_of_witch_soup.lua | 11 | 1149 | -----------------------------------------
-- ID: 4333
-- Item: witch_soup
-- Food Effect: 4hours, All Races
-----------------------------------------
-- Magic Points 25
-- Strength -1
-- Mind 2
-- MP Recovered While Healing 1
-- Enmity -2
-----------------------------------------
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,4333)
end
function onEffectGain(target,effect)
target:addMod(dsp.mod.MP, 25)
target:addMod(dsp.mod.STR, -1)
target:addMod(dsp.mod.MND, 2)
target:addMod(dsp.mod.MPHEAL, 1)
target:addMod(dsp.mod.ENMITY, -2)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.MP, 25)
target:delMod(dsp.mod.STR, -1)
target:delMod(dsp.mod.MND, 2)
target:delMod(dsp.mod.MPHEAL, 1)
target:delMod(dsp.mod.ENMITY, -2)
end
| gpl-3.0 |
naclander/tome | game/modules/tome/data/general/objects/mindstars.lua | 3 | 3693 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
newEntity{
define_as = "BASE_MINDSTAR",
slot = "MAINHAND", offslot = "OFFHAND",
type = "weapon", subtype="mindstar",
add_name = " (#COMBAT_DAMTYPE#)",
display = "!", color=colors.LIGHT_RED, image = resolvers.image_material("mindstar", "nature"),
moddable_tile = resolvers.moddable_tile("mindstar"),
psiblade_tile = "mindstar_psiblade_%s_01",
randart_able = "/data/general/objects/random-artifacts/melee.lua",
encumber = 3,
rarity = 4,
power_source = {nature=true},
combat = {
wil_attack = true,
no_offhand_penalty = true,
talented = "mindstar",
physspeed = 1,
damrange = 1.1,
sound = {"actions/melee", pitch=0.6, vol=1.2}, sound_miss = {"actions/melee", pitch=0.6, vol=1.2},
damtype = resolvers.rngtable{DamageType.NATURE, DamageType.MIND},
},
desc = [[Mindstars are natural products. Natural gems covered in living matter, they are used to focus the mental powers of all nature defenders and psionics.
Using mindstars in the offhand does not incur the normal offhand damage penalty.]],
egos = "/data/general/objects/egos/mindstars.lua", egos_chance = { prefix=resolvers.mbonus(40, 5), suffix=resolvers.mbonus(40, 5) },
}
newEntity{ base = "BASE_MINDSTAR",
name = "mossy mindstar", short_name = "mossy",
level_range = {1, 10},
require = { stat = { wil=11 }, },
cost = 5,
material_level = 1,
combat = {
dam = resolvers.rngavg(2,3),
apr = 12,
physcrit = 2.5,
dammod = {wil=0.3, cun=0.1},
},
wielder = {
combat_mindpower = 1,
combat_mindcrit = 1,
},
}
newEntity{ base = "BASE_MINDSTAR",
name = "vined mindstar", short_name = "vined",
level_range = {10, 20},
require = { stat = { wil=16 }, },
cost = 10,
material_level = 2,
combat = {
dam = resolvers.rngavg(4,6),
apr = 18,
physcrit = 3,
dammod = {wil=0.35, cun=0.15},
},
wielder = {
combat_mindpower = 2,
combat_mindcrit = 2,
},
}
newEntity{ base = "BASE_MINDSTAR",
name = "thorny mindstar", short_name = "thorny",
level_range = {20, 30},
require = { stat = { wil=24 }, },
cost = 15,
material_level = 3,
combat = {
dam = resolvers.rngavg(7,10),
apr = 24,
physcrit = 3.5,
dammod = {wil=0.4, cun=0.2},
},
wielder = {
combat_mindpower = 3,
combat_mindcrit = 3,
},
}
newEntity{ base = "BASE_MINDSTAR",
name = "pulsing mindstar", short_name = "pulsing",
level_range = {30, 40},
require = { stat = { wil=35 }, },
cost = 25,
material_level = 4,
combat = {
dam = resolvers.rngavg(12,14),
apr = 32,
physcrit = 4.5,
dammod = {wil=0.45, cun=0.25},
},
wielder = {
combat_mindpower = 4,
combat_mindcrit = 4,
},
}
newEntity{ base = "BASE_MINDSTAR",
name = "living mindstar", short_name = "living",
level_range = {40, 50},
require = { stat = { wil=48 }, },
cost = 35,
material_level = 5,
combat = {
dam = resolvers.rngavg(15,18),
apr = 40,
physcrit = 5,
dammod = {wil=0.5, cun=0.3},
},
wielder = {
combat_mindpower = 5,
combat_mindcrit = 5,
},
}
| gpl-3.0 |
srijan/ntopng | scripts/lua/iface_ndpi_stats.lua | 1 | 1421 | --
-- (C) 2013 - ntop.org
--
dirs = ntop.getDirs()
package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path
require "lua_utils"
sendHTTPHeader('text/html')
interface.find(ifname)
if(_GET["mode"] == "sinceStartup") then
stats = interface.getStats()
elseif(_GET["host"] == nil) then
stats = interface.getNdpiStats()
else
stats = interface.getHostInfo(_GET["host"])
end
tot = 0
_ifstats = {}
for key, value in pairs(stats["ndpi"]) do
-- print("->"..key.."\n")
traffic = stats["ndpi"][key]["bytes.sent"] + stats["ndpi"][key]["bytes.rcvd"]
_ifstats[traffic] = key
--print(key.."="..traffic)
tot = tot + traffic
end
-- Print up to this number of entries
max_num_entries = 5
-- Print entries whose value >= 5% of the total
threshold = (tot * 3) / 100
print "[\n"
num = 0
accumulate = 0
for key, value in pairsByKeys(_ifstats, rev) do
if(key < threshold) then
break
end
if(num > 0) then
print ",\n"
end
print("\t { \"label\": \"" .. value .."\", \"value\": ".. key .." }")
accumulate = accumulate + key
num = num + 1
if(num == max_num_entries) then
break
end
end
if(tot == 0) then
tot = 1
end
-- In case there is some leftover do print it as "Other"
if(accumulate < tot) then
if(num > 0) then
print (",\n")
end
print("\t { \"label\": \"Other\", \"value\": ".. (tot-accumulate) .." }")
end
print "\n]"
| gpl-3.0 |
LegionXI/darkstar | scripts/zones/Ship_bound_for_Selbina/npcs/Rajmonda.lua | 14 | 1208 | -----------------------------------
-- Area: Ship bound for Selbina
-- NPC: Rajmonda
-- Type: Guild Merchant: Fishing Guild
-- @pos 1.841 -2.101 -9.000 220
-----------------------------------
package.loaded["scripts/zones/Ship_bound_for_Selbina/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/zones/Ship_bound_for_Selbina/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:sendGuild(520,1,23,5)) then
player:showText(npc,RAJMONDA_SHOP_DIALOG);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
Geigerkind/DPSMateTBC | DPSMate_DamageTaken/DPSMate_DTPS.lua | 1 | 5216 | -- Global Variables
DPSMate.Modules.DTPS = {}
DPSMate.Modules.DTPS.Hist = "DMGTaken"
DPSMate.Options.Options[1]["args"]["dtps"] = {
order = 35,
type = 'toggle',
name = DPSMate.L["dtps"],
desc = DPSMate.L["show"].." "..DPSMate.L["dtps"]..".",
get = function() return DPSMateSettings["windows"][DPSMate.Options.Dewdrop:GetOpenedParent().Key]["options"][1]["dtps"] end,
set = function() DPSMate.Options:ToggleDrewDrop(1, "dtps", DPSMate.Options.Dewdrop:GetOpenedParent()) end,
}
-- Register the moodule
DPSMate:Register("dtps", DPSMate.Modules.DTPS, DPSMate.L["dtps"])
local tinsert = table.insert
local strformat = string.format
function DPSMate.Modules.DTPS:GetSortedTable(arr,k)
local b, a, total = {}, {}, 0
for c, v in pairs(arr) do
if DPSMate:ApplyFilter(k, DPSMate:GetUserById(c)) then
local i = 1
while true do
if (not b[i]) then
tinsert(b, i, v["i"])
tinsert(a, i, c)
break
else
if b[i] < v["i"] then
tinsert(b, i, v["i"])
tinsert(a, i, c)
break
end
end
i=i+1
end
total = total + v["i"]
end
end
return b, total, a
end
function DPSMate.Modules.DTPS:EvalTable(user, k, cbt)
local a, d = {}, {}
local arr, cbet = DPSMate:GetMode(k)
cbt = cbt or cbet
if not arr[user[1]] then return end
for cat, val in pairs(arr[user[1]]) do
if cat~="i" then
local ta, tb, CV = {}, {}, 0
for ca, va in pairs(val) do
if ca~="i" then
CV = CV + va[13]
local i = 1
while true do
if (not tb[i]) then
tinsert(ta, i, ca)
tinsert(tb, i, va[13]/cbt)
break
else
if (tb[i] < va[13]/cbt) then
tinsert(ta, i, ca)
tinsert(tb, i, va[13]/cbt)
break
end
end
i = i + 1
end
end
end
local i = 1
while true do
if (not d[i]) then
tinsert(a, i, cat)
tinsert(d, i, {CV/cbt, ta, tb})
break
else
if (d[i][1] < CV/cbt) then
tinsert(a, i, cat)
tinsert(d, i, {CV/cbt, ta, tb})
break
end
end
i = i + 1
end
end
end
return a, arr[user[1]]["i"]/(cbt or 1), d
end
function DPSMate.Modules.DTPS:GetSettingValues(arr, cbt, k,ecbt)
local pt = ""
local name, value, perc, sortedTable, total, a, p, strt = {}, {}, {}, {}, 0, 0, "", {[1]="",[2]=""}
if DPSMateSettings["windows"][k]["numberformat"] == 2 or DPSMateSettings["windows"][k]["numberformat"] == 4 then p = "K"; pt="K" end
sortedTable, total, a = DPSMate.Modules.DTPS:GetSortedTable(arr,k)
for cat, val in pairs(sortedTable) do
local dmg, tot, sort, dmgr, totr, sortr = DPSMate:FormatNumbers(val, total, sortedTable[1], k)
if dmg==0 then break end; if totr<=10000 then pt="" end; if dmgr<=10000 then p="" end
local str = {[1]="",[2]="",[3]="",[4]=""}
local pname = DPSMate:GetUserById(a[cat])
if DPSMateSettings["columnsdtps"][2] then str[1] = " "..strformat("%.1f", dmg/cbt)..p; strt[2] = " "..strformat("%.1f", tot/cbt)..pt end
if DPSMateSettings["columnsdtps"][3] then str[2] = " ("..strformat("%.1f", 100*dmgr/totr).."%)" end
if DPSMateSettings["columnsdtps"][1] then str[3] = "("..DPSMate:Commas(dmg, k)..p..")"; strt[1] = "("..DPSMate:Commas(tot, k)..pt..")" end
if DPSMateSettings["columnsdtps"][4] then str[4] = " ("..strformat("%.1f", dmg/(ecbt[pname] or cbt))..p..")" end
tinsert(name, pname)
tinsert(value, str[3]..str[1]..str[4]..str[2])
tinsert(perc, 100*(dmgr/sortr))
end
return name, value, perc, strt
end
function DPSMate.Modules.DTPS:ShowTooltip(user, k)
if DPSMateSettings["informativetooltips"] then
local a,b,c = DPSMate.Modules.DTPS:EvalTable(DPSMateUser[user], k)
local ab, abn, p, i = {}, {}, 1, 1
while a[i] do
p = 1
while c[i][2][p] do
if ab[c[i][2][p]] then
ab[c[i][2][p]] = ab[c[i][2][p]] + c[i][3][p]
else
ab[c[i][2][p]] = c[i][3][p]
end
p = p + 1
end
i = i + 1
end
for cat, val in pairs(ab) do
if val>0 then
i = 1
while true do
if (not abn[i]) then
tinsert(abn, i, {cat, val})
break
else
if (abn[i][2] < val) then
tinsert(abn, i, {cat, val})
break
end
end
i = i + 1
end
end
end
ab = nil
GameTooltip:AddLine(DPSMate.L["tttop"]..DPSMateSettings["subviewrows"]..DPSMate.L["ttdamage"]..DPSMate.L["ttabilities"])
for i=1, DPSMateSettings["subviewrows"] do
if not abn[i] then break end
GameTooltip:AddDoubleLine(i..". "..DPSMate:GetAbilityById(abn[i][1]), abn[i][2].." ("..strformat("%.2f", 100*abn[i][2]/b).."%)", 1,1,1,1,1,1)
end
GameTooltip:AddLine(DPSMate.L["tttop"]..DPSMateSettings["subviewrows"]..DPSMate.L["ttattacked"])
for i=1, DPSMateSettings["subviewrows"] do
if not a[i] then break end
GameTooltip:AddDoubleLine(i..". "..DPSMate:GetUserById(a[i]),strformat("%.2f", c[i][1]).." ("..strformat("%.2f", 100*c[i][1]/b).."%)",1,1,1,1,1,1)
end
end
end
function DPSMate.Modules.DTPS:OpenDetails(obj, key, bool)
if bool then
DPSMate.Modules.DetailsDamageTaken:UpdateCompare(obj, key, bool)
else
DPSMate.Modules.DetailsDamageTaken:UpdateDetails(obj, key)
end
end
function DPSMate.Modules.DTPS:OpenTotalDetails(obj, key)
DPSMate.Modules.DetailsDamageTakenTotal:UpdateDetails(obj, key)
end
| gpl-3.0 |
wanliming11/MurlocAlgorithms | Last/OpenSource/redis-stable/deps/lua/test/sort.lua | 889 | 1494 | -- two implementations of a sort function
-- this is an example only. Lua has now a built-in function "sort"
-- extracted from Programming Pearls, page 110
function qsort(x,l,u,f)
if l<u then
local m=math.random(u-(l-1))+l-1 -- choose a random pivot in range l..u
x[l],x[m]=x[m],x[l] -- swap pivot to first position
local t=x[l] -- pivot value
m=l
local i=l+1
while i<=u do
-- invariant: x[l+1..m] < t <= x[m+1..i-1]
if f(x[i],t) then
m=m+1
x[m],x[i]=x[i],x[m] -- swap x[i] and x[m]
end
i=i+1
end
x[l],x[m]=x[m],x[l] -- swap pivot to a valid place
-- x[l+1..m-1] < x[m] <= x[m+1..u]
qsort(x,l,m-1,f)
qsort(x,m+1,u,f)
end
end
function selectionsort(x,n,f)
local i=1
while i<=n do
local m,j=i,i+1
while j<=n do
if f(x[j],x[m]) then m=j end
j=j+1
end
x[i],x[m]=x[m],x[i] -- swap x[i] and x[m]
i=i+1
end
end
function show(m,x)
io.write(m,"\n\t")
local i=1
while x[i] do
io.write(x[i])
i=i+1
if x[i] then io.write(",") end
end
io.write("\n")
end
function testsorts(x)
local n=1
while x[n] do n=n+1 end; n=n-1 -- count elements
show("original",x)
qsort(x,1,n,function (x,y) return x<y end)
show("after quicksort",x)
selectionsort(x,n,function (x,y) return x>y end)
show("after reverse selection sort",x)
qsort(x,1,n,function (x,y) return x<y end)
show("after quicksort again",x)
end
-- array to be sorted
x={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"}
testsorts(x)
| mit |
ibm2431/darkstar | scripts/globals/items/sis_kebabi.lua | 11 | 1375 | -----------------------------------------
-- ID: 5598
-- Item: sis_kebabi
-- Food Effect: 30Min, All Races
-----------------------------------------
-- Strength 6
-- Vitality -2
-- Intelligence -2
-- Attack % 20
-- Attack Cap 70
-- Ranged ATT % 20
-- Ranged ATT Cap 70
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onItemCheck(target)
local result = 0
if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then
result = dsp.msg.basic.IS_FULL
end
return result
end
function onItemUse(target)
target:addStatusEffect(dsp.effect.FOOD,0,0,1800,5598)
end
function onEffectGain(target, effect)
target:addMod(dsp.mod.STR, 6)
target:addMod(dsp.mod.VIT, -2)
target:addMod(dsp.mod.INT, -2)
target:addMod(dsp.mod.FOOD_ATTP, 20)
target:addMod(dsp.mod.FOOD_ATT_CAP, 70)
target:addMod(dsp.mod.FOOD_RATTP, 20)
target:addMod(dsp.mod.FOOD_RATT_CAP, 70)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.STR, 6)
target:delMod(dsp.mod.VIT, -2)
target:delMod(dsp.mod.INT, -2)
target:delMod(dsp.mod.FOOD_ATTP, 20)
target:delMod(dsp.mod.FOOD_ATT_CAP, 70)
target:delMod(dsp.mod.FOOD_RATTP, 20)
target:delMod(dsp.mod.FOOD_RATT_CAP, 70)
end
| gpl-3.0 |
greasydeal/darkstar | scripts/zones/Selbina/npcs/Oswald.lua | 17 | 4682 | -----------------------------------
-- Area: Selbina
-- NPC: Oswald
-- Starts and Finishes Quest: Under the sea (finish), The gift, The real gift
-- @pos 48 -15 9 248
-----------------------------------
package.loaded["scripts/zones/Selbina/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Selbina/TextIDs");
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if(player:getQuestStatus(OTHER_AREAS,THE_GIFT) == QUEST_ACCEPTED) then
if(trade:hasItemQty(4375,1) == true and trade:getGil() == 0 and trade:getItemCount() == 1) then
player:startEvent(0x0048,0,4375); -- Finish quest "The gift"
end
elseif(player:getQuestStatus(OTHER_AREAS,THE_REAL_GIFT) == QUEST_ACCEPTED) then
if(trade:hasItemQty(4484,1) == true and trade:getGil() == 0 and trade:getItemCount() == 1) then
player:startEvent(0x004b); -- Finish quest "The real gift"
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
UnderTheSea = player:getQuestStatus(OTHER_AREAS,UNDER_THE_SEA);
TheSandCharm = player:getQuestStatus(OTHER_AREAS,THE_SAND_CHARM);
TheGift = player:getQuestStatus(OTHER_AREAS,THE_GIFT);
TheRealGift = player:getQuestStatus(OTHER_AREAS,THE_REAL_GIFT);
if(player:getVar("underTheSeaVar") == 1) then
player:startEvent(0x0020); -- During quest "Under the sea" - 1st dialog
elseif(player:hasKeyItem(ETCHED_RING) == true) then
player:startEvent(0x0025); -- Finish quest "Under the sea"
elseif(UnderTheSea == QUEST_COMPLETED and TheSandCharm == QUEST_AVAILABLE) then
player:startEvent(0x0026); -- New dialog after "Under the sea"
elseif(UnderTheSea == QUEST_COMPLETED and TheSandCharm ~= QUEST_AVAILABLE and TheGift == QUEST_AVAILABLE) then
player:startEvent(0x0046,4375); -- Start quest "The gift"
elseif(TheGift == QUEST_ACCEPTED) then
player:startEvent(0x0047); -- During quest "The gift"
elseif(TheGift == QUEST_COMPLETED and TheSandCharm == QUEST_ACCEPTED) then
player:startEvent(0x004e); -- New dialog after "The gift"
elseif(TheGift == QUEST_COMPLETED and TheSandCharm == QUEST_COMPLETED and TheRealGift == QUEST_AVAILABLE) then
player:startEvent(0x0049,4484); -- Start quest "The real gift"
elseif(TheRealGift == QUEST_ACCEPTED) then
player:startEvent(0x004a,4484); -- During quest "The real gift"
elseif(TheRealGift == QUEST_COMPLETED) then
player:startEvent(0x004c); -- Final dialog after "The real gift"
else
player:startEvent(0x001e); -- Standard dialog
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if(csid == 0x0020) then
player:setVar("underTheSeaVar",2);
elseif(csid == 0x0025) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13335);
else
player:completeQuest(OTHER_AREAS,UNDER_THE_SEA);
player:addTitle(LIL_CUPID);
player:delKeyItem(ETCHED_RING);
player:setVar("underTheSeaVar",0);
player:addItem(13335);
player:messageSpecial(ITEM_OBTAINED,13335); -- Amber Earring
player:addFame(OTHER_AREAS,30);
end
elseif(csid == 0x0046 and option == 50) then
player:addQuest(OTHER_AREAS,THE_GIFT);
elseif(csid == 0x0048) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,16497);
else
player:completeQuest(OTHER_AREAS,THE_GIFT);
player:addTitle(SAVIOR_OF_LOVE);
player:addItem(16497);
player:messageSpecial(ITEM_OBTAINED,16497); -- Sleep Dagger
player:addFame(OTHER_AREAS,30);
player:tradeComplete();
end
elseif(csid == 0x0049 and option == 50) then
player:addQuest(OTHER_AREAS,THE_REAL_GIFT);
elseif(csid == 0x004b) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,17385);
else
player:completeQuest(OTHER_AREAS,THE_REAL_GIFT);
player:addTitle(THE_LOVE_DOCTOR);
player:addItem(17385);
player:messageSpecial(ITEM_OBTAINED,17385); -- Glass Fiber Fishing Rod
player:addFame(OTHER_AREAS,30);
player:tradeComplete();
end
end
end;
| gpl-3.0 |
aginor/wesnoth | data/ai/micro_ais/cas/ca_herding_sheep_runs_dog.lua | 26 | 1437 | local H = wesnoth.require "lua/helper.lua"
local AH = wesnoth.require "ai/lua/ai_helper.lua"
local function get_next_sheep(cfg)
local sheep = AH.get_units_with_moves {
side = wesnoth.current.side,
{ "and", cfg.filter_second },
{ "filter_adjacent", { side = wesnoth.current.side, { "and", cfg.filter } } }
}
return sheep[1]
end
local ca_herding_sheep_runs_dog = {}
function ca_herding_sheep_runs_dog:evaluation(ai, cfg)
-- Any sheep with moves left next to a dog runs away
if get_next_sheep(cfg) then return cfg.ca_score end
return 0
end
function ca_herding_sheep_runs_dog:execution(ai, cfg)
-- Simply get the first sheep, order does not matter
local sheep = get_next_sheep(cfg)
-- Get the first dog that the sheep is adjacent to
local dog = wesnoth.get_units { side = wesnoth.current.side, { "and", cfg.filter },
{ "filter_adjacent", { x = sheep.x, y = sheep.y } }
}[1]
local c_x, c_y = cfg.herd_x, cfg.herd_y
-- If dog is farther from center, sheep moves in, otherwise it moves out
local sign = 1
if (H.distance_between(dog.x, dog.y, c_x, c_y) >= H.distance_between(sheep.x, sheep.y, c_x, c_y)) then
sign = -1
end
local best_hex = AH.find_best_move(sheep, function(x, y)
return H.distance_between(x, y, c_x, c_y) * sign
end)
AH.movefull_stopunit(ai, sheep, best_hex)
end
return ca_herding_sheep_runs_dog
| gpl-2.0 |
TheFlyingFiddle/TIER | tier/meta.lua | 1 | 12404 | local tags = require"tier.tags"
local core = require"tier.core"
local format = require"format"
local pack = format.packvarint
local unpack = format.unpackvarint
local meta = { }
local meta_types = { }
local function newmetatype(tag)
assert(tag)
local mt = {} mt.__index = mt
mt.tag = tag
meta_types[tag] = mt
return mt
end
local simple_metatypes =
{
[tags.VOID] = true,
[tags.NULL] = true,
[tags.VARINT] = true,
[tags.VARINTZZ] = true,
[tags.CHAR] = true,
[tags.WCHAR] = true,
[tags.TYPE] = true,
[tags.DYNAMIC] = true,
[tags.FLAG] = true,
[tags.SIGN] = true,
[tags.BOOLEAN] = true,
[tags.UINT8] = true,
[tags.UINT16] = true,
[tags.UINT32] = true,
[tags.UINT64] = true,
[tags.SINT8] = true,
[tags.SINT16] = true,
[tags.SINT32] = true,
[tags.SINT64] = true,
[tags.HALF] = true,
[tags.FLOAT] = true,
[tags.DOUBLE] = true,
[tags.QUAD] = true,
[tags.STREAM] = true,
[tags.STRING] = true,
[tags.WSTRING] = true
}
for entry, _ in pairs(simple_metatypes) do
meta[tags[entry]:lower()] = { tag = entry, id = pack(entry) }
end
local function metafromtag(tag)
return meta[tags[tag]:lower()]
end
local memoized_types = setmetatable({}, { __mode = "v"})
local function canmemoize(type)
if type.recursive_protection then return true end
local isok = true
if type.tag == tags.TYPEREF then
isok = false
else
type.recursive_protection = true
for i=1, #type do
if not canmemoize(type[i]) then
isok = false
break;
end
end
type.recursive_protection = nil
end
return isok
end
local function memoize_type(type)
if canmemoize(type) then
local id = meta.getid(type)
if memoized_types[id] then
return memoized_types[id]
else
memoized_types[id] = type
end
end
return type
end
local function encodeid(encoder, type)
local writer = encoder.writer
if simple_metatypes[type.tag] then
writer:writef("V", type.tag)
elseif type.tag == tags.TYPEREF then
assert(type[1] ~= nil, "incomplete typeref")
encodeid(encoder, type[1])
else
local index = encoder.types[type]
if index == nil then
encoder.types[type] = writer:getposition()
writer:writef("V", type.tag)
type:encode(encoder)
else
local offset = writer:getposition() - index
writer:writef("V", tags.TYPEREF)
writer:writef("V", offset)
end
end
end
local outstream = format.outmemorystream
local newwriter = format.writer
local newencoder = core.encoder
function meta.getid(type)
if not type.id then
local buffer = outstream()
encoder = newencoder(newwriter(buffer))
encoder.types = { }
encodeid(encoder, type)
encoder:close()
type.id = buffer:getdata()
end
return type.id
end
function meta.encodetype(encoder, type)
meta.getid(type)
local id
--This is the encoded version of an id.
if #type.id > 1 then
local head = string.sub(type.id, 1, 1)
local body = string.sub(type.id, 2, -1)
id = head .. pack(#body) .. body
else
id = type.id
end
encoder:writef("r", id)
end
local function decodeid(decoder)
local reader = decoder.reader
local pos = reader:getposition()
local tag = reader:readf("V")
if simple_metatypes[tag] then
return metafromtag(tag)
elseif tag == tags.TYPEREF then
local typeref = pos - reader:readf("V")
return decoder.types[typeref]
else
local type = setmetatable({}, meta_types[tag])
decoder.types[pos] = type
type:decode(decoder)
local endpos = reader:getposition()
local id = string.sub(decoder.idbuffer, pos + 1, endpos + 1)
if memoized_types[id] then
type = memoized_types[id]
else
memoized_types[id] = type
type.id = id
end
return type
end
end
local instream = format.inmemorystream
local newreader = format.reader
local newdecoder = core.decoder
function meta.decodetype(decoder)
local tag = decoder:readf("V")
if simple_metatypes[tag] then
return metafromtag(tag)
else
local data = pack(tag) .. decoder:readf("s")
if memoized_types[data] then
return memoized_types[data]
end
local decoder = newdecoder(newreader(instream(data)))
decoder.types = { }
decoder.idbuffer = data
return decodeid(decoder)
end
end
do
local Array = newmetatype(tags.ARRAY)
function Array:encode(encoder)
encoder:writef("V", self.size)
encodeid(encoder, self[1])
end
function Array:decode(decoder)
self.size = decoder:readf("V")
self[1] = decodeid(decoder)
end
function meta.array(element_type, size)
local array = setmetatable({ }, Array)
array[1] = element_type
array.size = size
return memoize_type(array)
end
end
do
local List = newmetatype(tags.LIST)
function List:encode(encoder)
encoder:writef("V", self.sizebits)
encodeid(encoder, self[1])
end
function List:decode(decoder)
self.sizebits = decoder:readf("V")
self[1] = decodeid(decoder)
end
function meta.list(element_type, sizebits)
if sizebits == nil then sizebits = 0 end
local list = setmetatable({ }, List)
list[1] = element_type
list.sizebits = sizebits
return memoize_type(list)
end
end
do
local Set = newmetatype(tags.SET)
function Set:encode(encoder)
encoder:writef("V", self.sizebits)
encodeid(encoder, self[1])
end
function Set:decode(decoder)
self.sizebits = decoder:readf("V")
self[1] = decodeid(decoder)
end
function meta.set(element_type, sizebits)
if sizebits == nil then sizebits = 0 end
local set = setmetatable({}, Set)
set[1] = element_type
set.sizebits = sizebits
set.tag = tags.SET
return memoize_type(set)
end
end
do
local Map = newmetatype(tags.MAP)
function Map:encode(encoder)
encoder:writef("V", self.sizebits)
encodeid(encoder, self[1])
encodeid(encoder, self[2])
end
function Map:decode(decoder)
self.sizebits = decoder:readf("V")
self[1] = decodeid(decoder)
self[2] = decodeid(decoder)
end
function meta.map(key_type, value_type, sizebits)
if sizebits == nil then sizebits = 0 end
local map = setmetatable({ }, Map)
map[1] = key_type
map[2] = value_type
map.sizebits = sizebits
return memoize_type(map)
end
end
do
local Tuple = newmetatype(tags.TUPLE)
function Tuple:encode(encoder)
encoder:writef("V", #self)
for i=1, #self do
encodeid(encoder, self[i])
end
end
function Tuple:decode(decoder)
local size = decoder:readf("V")
for i=1, size do
self[i] = decodeid(decoder)
end
end
function meta.tuple(types)
local tuple = setmetatable({}, Tuple)
for i=1, #types do
tuple[i] = types[i]
end
return memoize_type(tuple)
end
end
do
local Union = newmetatype(tags.UNION)
function Union:encode(encoder)
encoder:writef("V", self.sizebits)
encoder:writef("V", #self)
for i=1, #self do
encodeid(encoder, self[i])
end
end
function Union:decode(decoder)
self.sizebits = decoder:readf("V")
local size = decoder:readf("V")
for i=1, size do
self[i] = decodeid(decoder)
end
end
function meta.union(types, sizebits)
if sizebits == nil then sizebits = 0 end
local union = setmetatable({}, Union)
for i=1, #types do
union[i] = types[i]
end
union.sizebits = sizebits
return memoize_type(union)
end
end
do
local Object = newmetatype(tags.OBJECT)
function Object:encode(encoder)
encodeid(encoder, self[1])
end
function Object:decode(decoder)
self[1] = decodeid(decoder)
end
function meta.object(element_type)
local obj = setmetatable({}, Object)
obj[1] = element_type
return memoize_type(obj)
end
end
do
local Embedded = newmetatype(tags.EMBEDDED)
function Embedded:encode(encoder)
encodeid(encoder, self[1])
end
function Embedded:decode(decoder)
self[1] = decodeid(decoder)
end
function Embedded:typecheck(other)
return other[1] == meta.void or
self[1] == meta.void or
meta.typecheck(other[1], self[1])
end
function meta.embedded(element_type)
local emb = setmetatable({}, Embedded)
emb[1] = element_type
return memoize_type(emb)
end
end
do
local Semantic = newmetatype(tags.SEMANTIC)
function Semantic:encode(encoder)
encoder:writef("s", self.identifier)
encodeid(encoder, self[1])
end
function Semantic:decode(decoder)
self.identifier = decoder:readf("s")
self[1] = decodeid(decoder)
end
function meta.semantic(id, element_type)
local semantic = setmetatable({}, Semantic)
semantic[1] = element_type
semantic.identifier = id
return memoize_type(semantic)
end
end
do
local Align = newmetatype(tags.ALIGN)
function Align:encode(encoder)
encoder:writef("V", self.alignof)
encodeid(encoder, self[1])
end
function Align:decode(decoder)
self.alignof = decoder:readf("V")
self[1] = decodeid(decoder)
end
local function fixedalignencode(self, encoder)
encodeid(encoder, self[1])
end
local function fixedaligndecode(self, decoder)
self.alignof = self.fixedalignof
self[1] = decodeid(decoder)
end
local function newaligntype(tag, alignof)
local type = newmetatype(tag)
type.fixedalignof = alignof
type.encode = fixedalignencode
type.decode = fixedaligndecode
return type
end
local align_tables =
{
[1] = newaligntype(tags.ALIGN1, 1),
[2] = newaligntype(tags.ALIGN2, 2),
[4] = newaligntype(tags.ALIGN4, 4),
[8] = newaligntype(tags.ALIGN8, 8)
}
function meta.align(element_type, alignof)
local align = { }
align[1] = element_type
align.alignof = alignof
if align_tables[alignof] == nil then
setmetatable(align, Align)
else
setmetatable(align, align_tables[alignof])
end
return memoize_type(align)
end
end
do
local Uint = newmetatype(tags.UINT)
function Uint:encode(encoder)
encoder:writef("V", self.bits)
end
function Uint:decode(decoder)
self.bits = decoder:readf("V")
end
function meta.uint(bits)
return memoize_type(setmetatable( { bits = bits}, Uint))
end
end
do
local Sint = newmetatype(tags.SINT)
function Sint:encode(encoder)
encoder:writef("V", self.bits)
end
function Sint:decode(decoder)
self.bits = decoder:readf("V")
end
function meta.int(bits)
return memoize_type(setmetatable({ bits = bits}, Sint))
end
end
do
local Typeref = { } Typeref.__index = Typeref
--We can do this since we know the layout of the
--meta types.
local function fixrefs(meta, ref, value)
if meta.typeref_fixing then return 0 end
--Fixing cyclic references
meta.typeref_fixing = true
local count = 0
for i=1, #meta do
if meta[i] == ref then
meta[i] = value
count = count + 1
end
count = count + fixrefs(meta[i], ref, value)
end
meta.typeref_fixing = nil
return count
end
function Typeref:encode() error("uninitialized typeref") end
function Typeref:decode() error("uninitialized typeref") end
function Typeref:setref(meta)
local numfixed = fixrefs(meta, self, meta)
if numfixed == 0 then
--IF we did not fix any references we are setting
--the typeref to something that is not a graph.
--This would indicate inproper useage of typerefs
--or that there is a structural problem with metatypes.
error("only use typerefs when constructing graphs! otherwize use normal types")
end
return memoize_type(meta)
end
function meta.typeref()
return setmetatable({tag = tags.TYPEREF}, Typeref)
end
function meta.istyperef(type)
return type.tag == tags.TYPEREF
end
end
function meta.tostring(type, level)
if level == nil then level = 0 end
type.is_writing_to_string = true
local s = string.rep(" ", level) .. tags[type.tag] .. "\n"
for i=1, #type do
if not type[i].is_writing_to_string then
s = s .. meta.tostring(type[i], level + 1)
end
end
type.is_writing_to_string = false
return s or ""
end
--Checks if two types are compatible.
function meta.typecheck(typeA, typeB)
if typeA == typeB then return true end
local mtA = getmetatable(typeA)
local mtB = getmetatable(typeB)
if mtA == mtB then
local typecheck = mtA.typecheck
if typecheck then
return typecheck(typeA, typeB)
end
if #typeA == #typeB then
local success = true
for i=1, #typeA do
if not meta.typecheck(typeA[i], typeB[i]) then
success = false
break
end
end
return success
else
return false
end
else
return false
end
end
return meta | mit |
LegionXI/darkstar | scripts/zones/Dynamis-Windurst/npcs/qm1.lua | 17 | 1325 | -----------------------------------
-- Area: Dynamis Windurst
-- NPC: qm1 (???)
-- Notes: Spawns when Megaboss is defeated
-----------------------------------
package.loaded["scripts/zones/Dynamis-Windurst/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/zones/Dynamis-Windurst/TextIDs");
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(HYDRA_CORPS_LANTERN) == false) then
player:setVar("DynaWindurst_Win",1);
player:addKeyItem(HYDRA_CORPS_LANTERN);
player:messageSpecial(KEYITEM_OBTAINED,HYDRA_CORPS_LANTERN);
else
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
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 |
greasydeal/darkstar | scripts/globals/items/serving_of_squirrels_delight.lua | 35 | 1341 | -----------------------------------------
-- ID: 5554
-- Item: serving_of_squirrels_delight
-- Food Effect: 4Hrs, All Races
-----------------------------------------
-- MP % 13 (cap 95)
-- MP Recovered While Healing 2
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,14400,5554);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_FOOD_MPP, 13);
target:addMod(MOD_FOOD_MP_CAP, 95);
target:addMod(MOD_MPHEAL, 2);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_FOOD_MPP, 13);
target:delMod(MOD_FOOD_MP_CAP, 95);
target:delMod(MOD_MPHEAL, 2);
end;
| gpl-3.0 |
Igalia/snabbswitch | src/core/lib.lua | 1 | 19599 | -- Use of this source code is governed by the Apache 2.0 license; see COPYING.
module(...,package.seeall)
local ffi = require("ffi")
local C = ffi.C
local getopt = require("lib.lua.alt_getopt")
local syscall = require("syscall")
require("core.clib_h")
local bit = require("bit")
local band, bor, bnot, lshift, rshift, bswap =
bit.band, bit.bor, bit.bnot, bit.lshift, bit.rshift, bit.bswap
local tonumber = tonumber -- Yes, this makes a performance difference.
local cast = ffi.cast
-- Returns true if x and y are structurally similar (isomorphic).
function equal (x, y)
if type(x) ~= type(y) then return false end
if type(x) == 'table' then
for k, v in pairs(x) do
if not equal(v, y[k]) then return false end
end
for k, _ in pairs(y) do
if x[k] == nil then return false end
end
return true
elseif type(x) == 'cdata' then
if x == y then return true end
if ffi.typeof(x) ~= ffi.typeof(y) then return false end
local size = ffi.sizeof(x)
if ffi.sizeof(y) ~= size then return false end
return C.memcmp(x, y, size) == 0
else
return x == y
end
end
function can_open(filename, mode)
mode = mode or 'r'
local f = io.open(filename, mode)
if f == nil then return false end
f:close()
return true
end
function can_read(filename)
return can_open(filename, 'r')
end
function can_write(filename)
return can_open(filename, 'w')
end
--- Return `command` in the Unix shell and read `what` from the result.
function readcmd (command, what)
local f = io.popen(command)
local value = f:read(what)
f:close()
return value
end
function readfile (filename, what)
local f = io.open(filename, "r")
if f == nil then error("Unable to open file: " .. filename) end
local value = f:read(what)
f:close()
return value
end
function writefile (filename, value)
local f = io.open(filename, "w")
if f == nil then error("Unable to open file: " .. filename) end
local result = f:write(value)
f:close()
return result
end
function readlink (path)
local buf = ffi.new("char[?]", 512)
local len = C.readlink(path, buf, 512)
if len < 0 then return nil, ffi.errno() end
return ffi.string(buf, len)
end
function dirname(path)
if not path then return path end
local buf = ffi.new("char[?]", #path+1)
ffi.copy(buf, path)
local ptr = C.dirname(buf)
return ffi.string(ptr)
end
function basename(path)
if not path then return path end
local buf = ffi.new("char[?]", #path+1)
ffi.copy(buf, path)
local ptr = C.basename(buf)
return ffi.string(ptr)
end
-- Return the name of the first file in `dir`.
function firstfile (dir)
return readcmd("ls -1 "..dir.." 2>/dev/null", "*l")
end
function firstline (filename) return readfile(filename, "*l") end
-- Load Lua value from string.
function load_string (string)
return loadstring("return "..string)()
end
-- Read a Lua conf from file and return value.
function load_conf (file)
return dofile(file)
end
-- Store Lua representation of value in file.
function print_object (value, stream)
stream = stream or io.stdout
local indent = 0
local function print_indent (stream)
for i = 1, indent do stream:write(" ") end
end
local function print_value (value, stream)
local type = type(value)
if type == 'table' then
indent = indent + 2
stream:write("{\n")
if #value == 0 then
for key, value in pairs(value) do
print_indent(stream)
stream:write(key, " = ")
print_value(value, stream)
stream:write(",\n")
end
else
for _, value in ipairs(value) do
print_indent(stream)
print_value(value, stream)
stream:write(",\n")
end
end
indent = indent - 2
print_indent(stream)
stream:write("}")
elseif type == 'string' then
stream:write(("%q"):format(value))
else
stream:write(("%s"):format(value))
end
end
print_value(value, stream)
stream:write("\n")
end
function store_conf (file, value)
local stream = assert(io.open(file, "w"))
stream:write("return ")
print_object(value, stream)
stream:close()
end
-- Return a bitmask using the values of `bitset' as indexes.
-- The keys of bitset are ignored (and can be used as comments).
-- Example: bits({RESET=0,ENABLE=4}, 123) => 1<<0 | 1<<4 | 123
function bits (bitset, basevalue)
local sum = basevalue or 0
for _,n in pairs(bitset) do
sum = bor(sum, lshift(1, n))
end
return sum
end
-- Return true if bit number 'n' of 'value' is set.
function bitset (value, n)
return band(value, lshift(1, n)) ~= 0
end
-- Iterator factory for splitting a string by pattern
-- (http://lua-users.org/lists/lua-l/2006-12/msg00414.html)
function string:split(pat)
local st, g = 1, self:gmatch("()("..pat..")")
local function getter(self, segs, seps, sep, cap1, ...)
st = sep and seps + #sep
return self:sub(segs, (seps or 0) - 1), cap1 or sep, ...
end
local function splitter(self)
if st then return getter(self, st, g()) end
end
return splitter, self
end
--- Hex dump and undump functions
function hexdump(s)
if #s < 1 then return '' end
local frm = ('%02X '):rep(#s-1)..'%02X'
return string.format(frm, s:byte(1, #s))
end
function hexundump(h, n)
local buf = ffi.new('char[?]', n)
local i = 0
for b in h:gmatch('%x%x') do
buf[i] = tonumber(b, 16)
i = i+1
if i >= n then break end
end
return ffi.string(buf, n)
end
function comma_value(n) -- credit http://richard.warburton.it
if type(n) == 'cdata' then
n = string.match(tostring(n), '^-?([0-9]+)U?LL$') or tonumber(n)
end
if n ~= n then return "NaN" end
local left,num,right = string.match(n,'^([^%d]*%d)(%d*)(.-)$')
return left..(num:reverse():gsub('(%d%d%d)','%1,'):reverse())..right
end
-- Return a table for bounds-checked array access.
function bounds_checked (type, base, offset, size)
type = ffi.typeof(type)
local tptr = ffi.typeof("$ *", type)
local wrap = ffi.metatype(ffi.typeof("struct { $ _ptr; }", tptr), {
__index = function(w, idx)
assert(idx < size)
return w._ptr[idx]
end,
__newindex = function(w, idx, val)
assert(idx < size)
w._ptr[idx] = val
end,
})
return wrap(ffi.cast(tptr, ffi.cast("uint8_t *", base) + offset))
end
-- Return a throttle function.
--
-- The throttle returns true at most once in any <seconds> time interval.
function throttle (seconds)
local deadline = engine.now()
return function ()
if engine.now() > deadline then
deadline = engine.now() + seconds
return true
else
return false
end
end
end
-- Return a timeout function.
--
-- The timeout function returns true only if <seconds> have elapsed
-- since it was created.
function timeout (seconds)
local deadline = engine.now() + seconds
return function () return engine.now() > deadline end
end
-- Loop until the function `condition` returns true.
function waitfor (condition)
while not condition() do C.usleep(100) end
end
function yesno (flag)
if flag then return 'yes' else return 'no' end
end
-- Increase value to be a multiple of size (if it is not already).
function align (value, size)
if value % size == 0 then
return value
else
return value + size - (value % size)
end
end
function waitfor2(name, test, attempts, interval)
io.write("Waiting for "..name..".")
for count = 1,attempts do
if test() then
print(" ok")
return
end
C.usleep(interval)
io.write(".")
io.flush()
end
print("")
error("timeout waiting for " .. name)
end
-- Return "the IP checksum" of ptr:len.
--
-- NOTE: Checksums should seldom be computed in software. Packets
-- carried over hardware ethernet (e.g. 82599) should be checksummed
-- in hardware, and packets carried over software ethernet (e.g.
-- virtio) should be flagged as not requiring checksum verification.
-- So consider it a "code smell" to call this function.
function csum (ptr, len)
return finish_csum(update_csum(ptr, len))
end
function update_csum (ptr, len, csum0)
ptr = ffi.cast("uint8_t*", ptr)
local sum = csum0 or 0LL
for i = 0, len-2, 2 do
sum = sum + lshift(ptr[i], 8) + ptr[i+1]
end
if len % 2 == 1 then sum = sum + lshift(ptr[len-1], 1) end
return sum
end
function finish_csum (sum)
while band(sum, 0xffff) ~= sum do
sum = band(sum + rshift(sum, 16), 0xffff)
end
return band(bnot(sum), 0xffff)
end
function malloc (etype)
if type(etype) == 'string' then
etype = ffi.typeof(etype)
end
local size = ffi.sizeof(etype)
local ptr = memory.dma_alloc(size)
return ffi.cast(ffi.typeof("$*", etype), ptr)
end
-- deepcopy from http://lua-users.org/wiki/CopyTable
-- with naive ctype support
function deepcopy(orig)
local orig_type = type(orig)
local copy
if orig_type == 'table' then
copy = {}
for orig_key, orig_value in next, orig, nil do
copy[deepcopy(orig_key)] = deepcopy(orig_value)
end
setmetatable(copy, deepcopy(getmetatable(orig)))
elseif orig_type == 'ctype' then
copy = ffi.new(ffi.typeof(orig))
ffi.copy(copy, orig, ffi.sizeof(orig))
else -- number, string, boolean, etc
copy = orig
end
return copy
end
-- 'orig' must be an array, not a sparse array (hash)
function array_copy(orig)
local result = {}
for i=1,#orig do
result[i] = orig[i]
end
return result
end
-- endian conversion helpers written in Lua
-- avoid C function call overhead while using C.xxxx counterparts
if ffi.abi("be") then
-- nothing to do
function htonl(b) return b end
function htons(b) return b end
else
-- htonl is unsigned, matching the C version and expectations.
-- Wrapping the return call in parenthesis avoids the compiler to do
-- a tail call optimization. In LuaJIT when the number of successive
-- tail calls is higher than the loop unroll threshold, the
-- compilation of a trace is aborted. If the trace was long that
-- can result in poor performance.
function htonl(b) return (tonumber(cast('uint32_t', bswap(b)))) end
function htons(b) return (rshift(bswap(b), 16)) end
end
ntohl = htonl
ntohs = htons
-- Manipulation of bit fields in uint{8,16,32)_t stored in network
-- byte order. Using bit fields in C structs is compiler-dependent
-- and a little awkward for handling endianness and fields that cross
-- byte boundaries. We're bound to the LuaJIT compiler, so I guess
-- this would be save, but masking and shifting is guaranteed to be
-- portable.
local bitfield_endian_conversion =
{ [16] = { ntoh = ntohs, hton = htons },
[32] = { ntoh = ntohl, hton = htonl }
}
function bitfield(size, struct, member, offset, nbits, value)
local conv = bitfield_endian_conversion[size]
local field
if conv then
field = conv.ntoh(struct[member])
else
field = struct[member]
end
local shift = size-(nbits+offset)
local mask = lshift(2^nbits-1, shift)
local imask = bnot(mask)
if value then
field = bor(band(field, imask),
band(lshift(value, shift), mask))
if conv then
struct[member] = conv.hton(field)
else
struct[member] = field
end
else
return rshift(band(field, mask), shift)
end
end
-- Process ARGS using ACTIONS with getopt OPTS/LONG_OPTS.
-- Return the remaining unprocessed arguments.
function dogetopt (args, actions, opts, long_opts)
local opts,optind,optarg = getopt.get_ordered_opts(args, opts, long_opts)
for i, v in ipairs(opts) do
if actions[v] then
actions[v](optarg[i])
else
error("unimplemented option: " .. v)
end
end
local rest = {}
for i = optind, #args do table.insert(rest, args[i]) end
return rest
end
-- based on http://stackoverflow.com/a/15434737/1523491
function have_module (name)
if package.loaded[name] then
return true
else
for _, searcher in ipairs(package.loaders) do
local loader = searcher(name)
if type(loader) == 'function' then
package.preload[name] = loader
return true
end
end
return false
end
end
-- Exit with an error if we are not running as root.
function root_check (message)
if syscall.geteuid() ~= 0 then
print(message or "error: must run as root")
main.exit(1)
end
end
-- Wrapper around os.getenv which only returns the variable's value if it
-- is non-empty.
function getenv (name)
local value = os.getenv(name)
if value and #value ~= 0 then return value
else return nil end
end
-- Wrapper around execve.
function execv(path, argv)
local env = {}
for k, v in pairs(syscall.environ()) do table.insert(env, k.."="..v) end
return syscall.execve(path, argv or {}, env)
end
-- Return an array of random bytes.
function random_bytes_from_dev_urandom (count)
local bytes = ffi.new(ffi.typeof('uint8_t[$]', count))
local f = syscall.open('/dev/urandom', 'rdonly')
local written = 0
while written < count do
written = written + assert(f:read(bytes, count-written))
end
f:close()
return bytes
end
function random_bytes_from_math_random (count)
local bytes = ffi.new(ffi.typeof('uint8_t[$]', count))
for i = 0,count-1 do bytes[i] = math.random(0, 255) end
return bytes
end
function randomseed (seed)
seed = tonumber(seed)
if seed then
local msg = 'Using deterministic random numbers, SNABB_RANDOM_SEED=%d.\n'
io.stderr:write(msg:format(seed))
-- When setting a seed, use deterministic random bytes.
random_bytes = random_bytes_from_math_random
else
-- Otherwise use /dev/urandom.
seed = ffi.cast('uint32_t*', random_bytes_from_dev_urandom(4))[0]
random_bytes = random_bytes_from_dev_urandom
end
math.randomseed(seed)
return seed
end
function random_data (length)
return ffi.string(random_bytes(length), length)
end
local lower_case = "abcdefghijklmnopqrstuvwxyz"
local upper_case = lower_case:upper()
local extra = "0123456789_-"
local alphabet = table.concat({lower_case, upper_case, extra})
assert(#alphabet == 64)
function random_printable_string (entropy)
-- 64 choices in our alphabet, so 6 bits of entropy per byte.
entropy = entropy or 160
local length = math.floor((entropy - 1) / 6) + 1
local bytes = random_data(length)
local out = {}
for i=1,length do
out[i] = alphabet:byte(bytes:byte(i) % 64 + 1)
end
return string.char(unpack(out))
end
-- Compiler barrier.
-- Prevents LuaJIT from moving load/store operations over this call.
-- Any FFI call is sufficient to achieve this, see:
-- http://www.freelists.org/post/luajit/Compiler-loadstore-barrier-volatile-pointer-barriers-in-general,3
function compiler_barrier ()
C.nop()
end
-- parse: Given ARG, a table of parameters or nil, assert that from
-- CONFIG all of the required keys are present, fill in any missing values for
-- optional keys, and error if any unknown keys are found.
--
-- ARG := { key=vaue, ... }
-- CONFIG := { key = {[required=boolean], [default=value]}, ... }
function parse (arg, config)
local ret = {}
if arg == nil then arg = {} end
for k, o in pairs(config) do
assert(arg[k] ~= nil or not o.required, "missing required parameter '"..k.."'")
end
for k, v in pairs(arg) do
assert(config[k], "unrecognized parameter '"..k.."'")
ret[k] = v
end
for k, o in pairs(config) do
if ret[k] == nil then ret[k] = o.default end
end
return ret
end
function set(...)
local ret = {}
for k, v in pairs({...}) do ret[v] = true end
return ret
end
-- Check if 'name' is a kernel network interface.
function is_iface (name)
local f = io.open('/proc/net/dev')
for line in f:lines() do
local iface = line:match("^%s*(%w+):")
if iface and iface == name then f:close() return true end
end
f:close()
return false
end
function selftest ()
print("selftest: lib")
print("Testing equal")
assert(true == equal({foo="bar"}, {foo="bar"}))
assert(false == equal({foo="bar"}, {foo="bar", baz="foo"}))
assert(false == equal({foo="bar", baz="foo"}, {foo="bar"}))
print("Testing load_string")
assert(equal(load_string("{1,2}"), {1,2}), "load_string failed.")
print("Testing load/store_conf")
local conf = { foo="1", bar=42, arr={2,"foo",4}}
local testpath = "/tmp/snabb_lib_test_conf"
store_conf(testpath, conf)
assert(equal(conf, load_conf(testpath)), "Either `store_conf' or `load_conf' failed.")
print("Testing csum")
local data = "\x45\x00\x00\x73\x00\x00\x40\x00\x40\x11\xc0\xa8\x00\x01\xc0\xa8\x00\xc7"
local cs = csum(data, string.len(data))
assert(cs == 0xb861, "bad checksum: " .. bit.tohex(cs, 4))
-- assert(readlink('/etc/rc2.d/S99rc.local') == '../init.d/rc.local', "bad readlink")
-- assert(dirname('/etc/rc2.d/S99rc.local') == '/etc/rc2.d', "wrong dirname")
-- assert(basename('/etc/rc2.d/S99rc.local') == 'S99rc.local', "wrong basename")
print("Testing hex(un)dump")
assert(hexdump('\x45\x00\xb6\x7d\x00\xFA\x40\x00\x40\x11'):upper()
:match('^45.00.B6.7D.00.FA.40.00.40.11$'), "wrong hex dump")
assert(hexundump('4500 B67D 00FA400040 11', 10)
=='\x45\x00\xb6\x7d\x00\xFA\x40\x00\x40\x11', "wrong hex undump")
print("Testing ntohl")
local raw_val = 0xf0d0b0f0
assert(ntohl(raw_val) > 0, "ntohl must be unsigned")
assert(ntohl(ntohl(raw_val)) == raw_val,
"calling ntohl twice must return the original value")
-- test parse
print("Testing parse")
local function assert_parse_equal (arg, config, expected)
assert(equal(parse(arg, config), expected))
end
local function assert_parse_error (arg, config)
assert(not pcall(parse, arg, config))
end
local req = {required=true}
local opt = {default=42}
assert_parse_equal({a=1, b=2}, {a=req, b=req, c=opt}, {a=1, b=2, c=42})
assert_parse_equal({a=1, b=2}, {a=req, b=req}, {a=1, b=2})
assert_parse_equal({a=1, b=2, c=30}, {a=req, b=req, c=opt, d=opt}, {a=1, b=2, c=30, d=42})
assert_parse_equal({a=1, b=2, d=10}, {a=req, b=req, c=opt, d=opt}, {a=1, b=2, c=42, d=10})
assert_parse_equal({d=10}, {c=opt, d=opt}, {c=42, d=10})
assert_parse_equal({}, {c=opt}, {c=42})
assert_parse_equal({d=false}, {d=opt}, {d=false})
assert_parse_equal({d=nil}, {d=opt}, {d=42})
assert_parse_equal({a=false, b=2}, {a=req, b=req}, {a=false, b=2})
assert_parse_equal(nil, {}, {})
assert_parse_error({}, {a=req, b=req, c=opt})
assert_parse_error({d=30}, {a=req, b=req, d=opt})
assert_parse_error({a=1}, {a=req, b=req})
assert_parse_error({b=1}, {a=req, b=req})
assert_parse_error({a=nil, b=2}, {a=req, b=req})
assert_parse_error({a=1, b=nil}, {a=req, b=req})
assert_parse_error({a=1, b=2, d=10, e=100}, {a=req, b=req, d=opt})
assert_parse_error({a=1, b=2, c=4}, {a=req, b=req})
assert_parse_error({a=1, b=2}, {})
assert_parse_error(nil, {a=req})
end
| apache-2.0 |
LegionXI/darkstar | scripts/globals/abilities/repair.lua | 26 | 4408 | -----------------------------------
-- Ability: Repair
-- Uses oil to restore pet's HP.
-- Obtained: Puppetmaster Level 15
-- Recast Time: 3:00
-- Duration: Instant
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/pets");
-----------------------------------
-- onAbilityCheck
-----------------------------------
function onAbilityCheck(player,target,ability)
if (player:getPet() == nil) then
return MSGBASIC_REQUIRES_A_PET,0;
else
local id = player:getEquipID(SLOT_AMMO);
if (id >= 18731 and id <= 18733 or id == 19185) then
return 0,0;
else
return MSGBASIC_UNABLE_TO_USE_JA,0;
end
end
end;
-----------------------------------
-- onUseAbility
-----------------------------------
function onUseAbility(player,target,ability)
-- 1st need to get the pet food is equipped in the range slot.
local rangeObj = player:getEquipID(SLOT_AMMO);
local totalHealing = 0;
local regenAmount = 0;
local regenTime = 0;
local pet = player:getPet();
local petCurrentHP = pet:getHP();
local petMaxHP = pet:getMaxHP();
-- Need to start to calculate the HP to restore to the pet.
-- Please note that I used this as base for the calculations:
-- http://ffxiclopedia.wikia.com/wiki/Repair
switch (rangeObj) : caseof {
[18731] = function (x) -- Automaton Oil
regenAmount = 10;
totalHealing = petMaxHP * 0.1;
regenTime = 30;
end,
[18732] = function (x) -- Automaton Oil + 1
regenAmount = 20;
totalHealing = petMaxHP * 0.2;
regenTime = 60;
end,
[18733] = function (x) -- Automaton Oil + 2
regenAmount = 30;
totalHealing = petMaxHP * 0.3;
regenTime = 90;
end,
[19185] = function (x) -- Automaton Oil + 3
regenAmount = 40;
totalHealing = petMaxHP * 0.4;
regenTime = 120;
end,
}
-- Now calculating the bonus based on gear.
local feet = player:getEquipID(SLOT_FEET);
local earring1 = player:getEquipID(SLOT_EAR1);
local earring2 = player:getEquipID(SLOT_EAR2);
if (feet == 11387 or feet == 15686 or feet == 28240 or feet == 28261) then
-- This will remove most debuffs from the automaton.
-- Checks for Puppetry Babouches, + 1, Foire Babouches, + 1
pet:delStatusEffect(EFFECT_PARALYSIS);
pet:delStatusEffect(EFFECT_POISON);
pet:delStatusEffect(EFFECT_BLINDNESS);
pet:delStatusEffect(EFFECT_BIND);
pet:delStatusEffect(EFFECT_WEIGHT);
pet:delStatusEffect(EFFECT_ADDLE);
pet:delStatusEffect(EFFECT_BURN);
pet:delStatusEffect(EFFECT_FROST);
pet:delStatusEffect(EFFECT_CHOKE);
pet:delStatusEffect(EFFECT_RASP);
pet:delStatusEffect(EFFECT_SHOCK);
pet:delStatusEffect(EFFECT_DIA);
pet:delStatusEffect(EFFECT_BIO);
pet:delStatusEffect(EFFECT_STR_DOWN);
pet:delStatusEffect(EFFECT_DEX_DOWN);
pet:delStatusEffect(EFFECT_VIT_DOWN);
pet:delStatusEffect(EFFECT_AGI_DOWN);
pet:delStatusEffect(EFFECT_INT_DOWN);
pet:delStatusEffect(EFFECT_MND_DOWN);
pet:delStatusEffect(EFFECT_CHR_DOWN);
pet:delStatusEffect(EFFECT_MAX_HP_DOWN);
pet:delStatusEffect(EFFECT_MAX_MP_DOWN);
pet:delStatusEffect(EFFECT_ATTACK_DOWN);
pet:delStatusEffect(EFFECT_EVASION_DOWN);
pet:delStatusEffect(EFFECT_DEFENSE_DOWN);
pet:delStatusEffect(EFFECT_MAGIC_DEF_DOWN);
pet:delStatusEffect(EFFECT_INHIBIT_TP);
pet:delStatusEffect(EFFECT_MAGIC_ACC_DOWN);
pet:delStatusEffect(EFFECT_MAGIC_ATK_DOWN);
end
if (earring1 == 15999 or earring2 == 15999) then --Check for Guignol Earring
regenAmount = regenAmount + 0.2 * regenAmount;
end
local diff = petMaxHP - petCurrentHP;
if (diff < totalHealing) then
totalHealing = diff;
end
pet:addHP(totalHealing);
pet:wakeUp();
-- Apply regen effect.
pet:delStatusEffect(EFFECT_REGEN);
pet:addStatusEffect(EFFECT_REGEN,regenAmount,3,regenTime); -- 3 = tick, each 3 seconds.
player:removeAmmo();
return totalHealing;
end;
| gpl-3.0 |
naclander/tome | game/modules/tome/data/zones/slime-tunnels/zone.lua | 3 | 3307 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
return {
name = "Slime Tunnels",
level_range = {45, 55},
level_scheme = "player",
max_level = 1,
decay = {300, 800},
actor_adjust_level = function(zone, level, e) return zone.base_level + e:getRankLevelAdjust() + level.level-1 + rng.range(-1,2) end,
width = 250, height = 30,
-- all_remembered = true,
-- all_lited = true,
persistent = "zone",
ambient_music = "Together We Are Strong.ogg",
no_level_connectivity = true,
max_material_level = 5,
generator = {
map = {
class = "engine.generator.map.Static",
map = "zones/slime-tunnels",
},
actor = {
class = "mod.class.generator.actor.Random",
nb_npc = {20, 30},
},
trap = {
class = "engine.generator.trap.Random",
nb_trap = {0, 0},
},
object = {
class = "engine.generator.object.Random",
nb_object = {4, 10},
},
},
post_process = function(level, zone)
-- Make sure we have all pedestals
local dragon, undead, elements, destruction = nil, nil, nil, nil
for x = 0, level.map.w - 1 do for y = 0, level.map.h - 1 do
local g = level.map(x, y, level.map.TERRAIN)
if g then
if g.define_as == "ORB_DRAGON" then dragon = g g.x, g.y = x, y
elseif g.define_as == "ORB_DESTRUCTION" then destruction = g g.x, g.y = x, y
elseif g.define_as == "ORB_ELEMENTS" then elements = g g.x, g.y = x, y
elseif g.define_as == "ORB_UNDEATH" then undead = g g.x, g.y = x, y
end
end
end end
if not dragon or not undead or not elements or not destruction then
print("Slime Tunnels generated with too few pedestals!", dragon, undead, elements, destruction)
level.force_recreate = true
return
end
local Astar = require "engine.Astar"
local a = Astar.new(level.map, game:getPlayer())
if not a:calc(level.default_up.x, level.default_up.y, dragon.x, dragon.y) then
print("Slime Tunnels generated with unreachable dragon pedestal!")
level.force_recreate = true
return
end
if not a:calc(level.default_up.x, level.default_up.y, undead.x, undead.y) then
print("Slime Tunnels generated with unreachable undead pedestal!")
level.force_recreate = true
return
end
if not a:calc(level.default_up.x, level.default_up.y, elements.x, elements.y) then
print("Slime Tunnels generated with unreachable elements pedestal!")
level.force_recreate = true
return
end
if not a:calc(level.default_up.x, level.default_up.y, destruction.x, destruction.y) then
print("Slime Tunnels generated with unreachable destruction pedestal!")
level.force_recreate = true
return
end
end,
}
| gpl-3.0 |
greasydeal/darkstar | scripts/zones/Throne_Room/mobs/Zeid.lua | 7 | 1872 | -----------------------------------
-- Area: Throne Room
-- NPC: Zeid
-- Mission 9-2 BASTOK BCNM Fight
-----------------------------------
require("scripts/globals/titles");
require("scripts/globals/status");
require("scripts/globals/missions");
require("scripts/globals/settings");
require("scripts/globals/monstertpmoves");
require("scripts/zones/Throne_Room/TextIDs");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
-----------------------------------
-- onMobFight
-----------------------------------
function onMobFight(mob, target)
printf("mobtp %u",mob:getTP());
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
killer:startEvent(0x7d04,3,3,1,3,3,3,3,3);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
printf("finishCSID: %u",csid);
printf("RESULT: %u",option);
if(csid == 0x7d04)then
if(player:getVar("bcnm_instanceid") == 1)then
SpawnMob(17453064);
local volker = player:getBattlefield():insertAlly(14182)
volker:setSpawn(-450,-167,-239,125);
volker:spawn();
player:setPos(-443,-167,-239,127);
elseif(player:getVar("bcnm_instanceid") == 2)then
SpawnMob(17453068);
local volker = player:getBattlefield():insertAlly(14182)
volker:setSpawn(-450,-167,-239,125);
volker:spawn();
elseif(player:getVar("bcnm_instanceid") == 3)then
SpawnMob(17453072);
local volker = player:getBattlefield():insertAlly(14182)
volker:setSpawn(-450,-167,-239,125);
volker:spawn();
end
end
end;
| gpl-3.0 |
greasydeal/darkstar | scripts/globals/items/kalamar.lua | 18 | 1255 | -----------------------------------------
-- ID: 5448
-- Item: Kalamar
-- Food Effect: 5Min, Mithra only
-----------------------------------------
-- Dexterity 3
-- Mind -5
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0
if (target:getRace() ~= 7) then
result = 247;
end
if(target:getMod(MOD_EAT_RAW_FISH) == 1) then
result = 0;
end
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,5448);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 3);
target:addMod(MOD_MND, -5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 3);
target:delMod(MOD_MND, -5);
end;
| gpl-3.0 |
ibm2431/darkstar | scripts/globals/items/magma_steak.lua | 11 | 1298 | -----------------------------------------
-- ID: 6071
-- Item: Magma Steak
-- Food Effect: 180 Min, All Races
-----------------------------------------
-- Strength +8
-- Attack +23% Cap 180
-- Ranged Attack +23% Cap 180
-- Vermin Killer +5
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onItemCheck(target)
local result = 0
if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then
result = dsp.msg.basic.IS_FULL
end
return result
end
function onItemUse(target)
target:addStatusEffect(dsp.effect.FOOD,0,0,10800,6071)
end
function onEffectGain(target,effect)
target:addMod(dsp.mod.STR, 8)
target:addMod(dsp.mod.FOOD_ATTP, 23)
target:addMod(dsp.mod.FOOD_ATT_CAP, 180)
target:addMod(dsp.mod.FOOD_RATTP, 23)
target:addMod(dsp.mod.FOOD_RATT_CAP, 180)
target:addMod(dsp.mod.VERMIN_KILLER, 5)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.STR, 8)
target:delMod(dsp.mod.FOOD_ATTP, 23)
target:delMod(dsp.mod.FOOD_ATT_CAP, 180)
target:delMod(dsp.mod.FOOD_RATTP, 23)
target:delMod(dsp.mod.FOOD_RATT_CAP, 180)
target:delMod(dsp.mod.VERMIN_KILLER, 5)
end
| gpl-3.0 |
naclander/tome | game/modules/tome/data/talents/psionic/focus.lua | 1 | 7445 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
--Mindlash: ranged physical rad-0 ball
--Pyrokinesis: LOS burn attack
--Reach: gem-based range improvements
--Channeling: gem-based shield and improvement
newTalent{
name = "Mindlash",
type = {"psionic/focus", 1},
require = psi_wil_req1,
points = 5,
random_ego = "attack",
cooldown = function(self, t)
local c = 5
local gem_level = getGemLevel(self)
return math.max(c - gem_level, 0)
end,
psi = function(self, t)
local eff = self:hasEffect(self.EFF_MINDLASH)
local power = eff and eff.power or 1
return 10 * power
end,
tactical = { ATTACK = function(self, t, target)
local val = { PHYSICAL = 2}
local gem_level = getGemLevel(self)
if gem_level > 0 and not target.dead and self:knowTalent(self.T_CONDUIT) and self:isTalentActive(self.T_CONDUIT) then
local c = self:getTalentFromId(self.T_CONDUIT)
local auras = self:isTalentActive(c.id)
if auras.k_aura_on then
val.PHYSICAL = val.PHYSICAL + 1
end
if auras.t_aura_on then
val.FIRE = 1
end
if auras.c_aura_on then
val.LIGHTNING = 1
end
end
return val
end },
range = function(self, t)
local r = 5
local gem_level = getGemLevel(self)
local mult = 1 + 0.01*gem_level*self:callTalent(self.T_REACH, "rangebonus")
return math.floor(r*mult)
end,
getDamage = function (self, t)
local gem_level = getGemLevel(self)
return self:combatStatTalentIntervalDamage(t, "combatMindpower", 6, 170)*(1 + 0.3*gem_level)
end,
requires_target = true,
target = function(self, t) return {type="ball", range=self:getTalentRange(t), radius=0, selffire=false, talent=t} end,
action = function(self, t)
local gem_level = getGemLevel(self)
local dam = t.getDamage(self, t)
local tg = self:getTalentTarget(t)
local x, y = self:getTarget(tg)
if not x or not y then return nil end
self:project(tg, x, y, DamageType.PHYSICAL, self:mindCrit(rng.avg(0.8*dam, dam)), {type="mindsear"})
local _ _, _, _, x, y = self:canProject(tg, x, y)
if gem_level > 0 and not tg.dead and self:knowTalent(self.T_CONDUIT) and self:isTalentActive(self.T_CONDUIT) then
local c = self:getTalentFromId(self.T_CONDUIT)
--c.do_combat(self, c, tg)
local mult = 1 + 0.2*(self:getTalentLevel(c))
local auras = self:isTalentActive(c.id)
if auras.k_aura_on then
local k_aura = self:getTalentFromId(self.T_KINETIC_AURA)
local k_dam = mult * k_aura.getAuraStrength(self, k_aura)
DamageType:get(DamageType.PHYSICAL).projector(self, x, y, DamageType.PHYSICAL, k_dam)
end
if auras.t_aura_on then
local t_aura = self:getTalentFromId(self.T_THERMAL_AURA)
local t_dam = mult * t_aura.getAuraStrength(self, t_aura)
DamageType:get(DamageType.FIRE).projector(self, x, y, DamageType.FIRE, t_dam)
end
if auras.c_aura_on then
local c_aura = self:getTalentFromId(self.T_CHARGED_AURA)
local c_dam = mult * c_aura.getAuraStrength(self, c_aura)
DamageType:get(DamageType.LIGHTNING).projector(self, x, y, DamageType.LIGHTNING, c_dam)
end
end
game:onTickEnd(function() self:setEffect(self.EFF_MINDLASH, 4, {}) end)
return true
end,
info = function(self, t)
local dam = t.getDamage(self, t)
return ([[Focus energies on a distant target to lash it with physical force, doing %d damage in addition to any Conduit damage.
Mindslayers do not do this sort of ranged attack naturally. The use of a telekinetically-wielded gem or mindstar as a focus will improve the effects considerably.]]):
format(damDesc(self, DamageType.PHYSICAL, dam))
end,
}
newTalent{
name = "Pyrokinesis",
type = {"psionic/focus", 2},
require = psi_wil_req2,
points = 5,
random_ego = "attack",
cooldown = function(self, t)
local c = 20
local gem_level = getGemLevel(self)
return c - gem_level
end,
psi = 20,
tactical = { ATTACK = { FIRE = 2 } },
range = 0,
radius = function(self, t)
local r = 5
local gem_level = getGemLevel(self)
local mult = 1 + 0.01*gem_level*self:callTalent(self.T_REACH, "rangebonus")
return math.floor(r*mult)
end,
getDamage = function (self, t)
local gem_level = getGemLevel(self)
return self:combatStatTalentIntervalDamage(t, "combatMindpower", 21, 200)*(1 + 0.3*gem_level)
end,
target = function(self, t)
return {type="ball", range=self:getTalentRange(t), radius=self:getTalentRadius(t), friendlyfire=false}
end,
action = function(self, t)
local dam = t.getDamage(self, t)
local tg = self:getTalentTarget(t)
-- self:project(tg, self.x, self.y, DamageType.FIREBURN, {dur=10, initial=0, dam=dam}, {type="ball_fire", args={radius=1}})
self:project(tg, self.x, self.y, DamageType.FIREBURN, {dur=10, initial=0, dam=dam})
game.level.map:particleEmitter(self.x, self.y, tg.radius, "ball_fire", {radius=tg.radius})
return true
end,
info = function(self, t)
local radius = self:getTalentRadius(t)
local dam = t.getDamage(self, t)
return ([[Kinetically vibrate the essence of all foes within %d squares, setting them ablaze. Does %d damage over ten turns.
Mindslayers do not do this sort of ranged attack naturally. The use of a telekinetically-wielded gem or mindstar as a focus will improve the effects considerably.]]):
format(radius, damDesc(self, DamageType.FIREBURN, dam))
end,
}
newTalent{
name = "Reach",
type = {"psionic/focus", 3},
require = psi_wil_req3,
mode = "passive",
points = 5,
rangebonus = function(self,t) return math.max(0, self:combatTalentScale(t, 3, 10)) end,
info = function(self, t)
local inc = t.rangebonus(self,t)
local gtg = self:getTalentLevel(self.T_GREATER_TELEKINETIC_GRASP) >=5 and 1 or 0
local add = getGemLevel(self)*t.rangebonus(self, t)
return ([[You can extend your mental reach beyond your natural limits using a telekinetically-wielded gemstone or mindstar as a focus. Increases the range of various abilities by %0.1f%% to %0.1f%%, depending on the quality of the gem used as a focus (currently %0.1f%%).]]):
format(inc*(1+gtg), inc*(5+gtg), add)
end,
}
newTalent{
name = "Focused Channeling",
type = {"psionic/focus", 4},
require = psi_wil_req4,
mode = "passive",
points = 5,
impfocus = function(self,t) return math.max(1, self:combatTalentScale(t, 1.2, 1.75)) end,
info = function(self, t)
local inc = t.impfocus(self,t)
local gtg = self:getTalentLevel(self.T_GREATER_TELEKINETIC_GRASP) >=5 and 1 or 0
local add = getGemLevel(self)*t.impfocus(self, t)
return ([[You can channel more energy with your auras and shields, using a telekinetically-wielded gemstone or mindstar as a focus. Increases the base strength of all auras and shields by %0.2f to %0.2f, depending on the quality of the gem or mindstar used as a focus (currently %0.2f).]]):
format(inc*(1+gtg), inc*(5+gtg), add)
end,
}
| gpl-3.0 |
gwlim/luci | applications/luci-diag-devinfo/luasrc/controller/luci_diag/netdiscover_common.lua | 76 | 3146 | --[[
Luci diag - Diagnostics controller module
(c) 2009 Daniel Dickinson
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
]]--
module("luci.controller.luci_diag.netdiscover_common", package.seeall)
require("luci.i18n")
require("luci.util")
require("luci.sys")
require("luci.cbi")
require("luci.model.uci")
local translate = luci.i18n.translate
local DummyValue = luci.cbi.DummyValue
local SimpleSection = luci.cbi.SimpleSection
function index()
return -- no-op
end
function get_params()
local netdiscover_uci = luci.model.uci.cursor()
netdiscover_uci:load("luci_devinfo")
local nettable = netdiscover_uci:get_all("luci_devinfo")
local i
local subnet
local netdout
local outnets = {}
i = next(nettable, nil)
while (i) do
if (netdiscover_uci:get("luci_devinfo", i) == "netdiscover_scannet") then
local scannet = netdiscover_uci:get_all("luci_devinfo", i)
if scannet["subnet"] and (scannet["subnet"] ~= "") and scannet["enable"] and ( scannet["enable"] == "1") then
local output = ""
local outrow = {}
outrow["interface"] = scannet["interface"]
outrow["timeout"] = 10
local timeout = tonumber(scannet["timeout"])
if timeout and ( timeout > 0 ) then
outrow["timeout"] = scannet["timeout"]
end
outrow["repeat_count"] = 1
local repcount = tonumber(scannet["repeat_count"])
if repcount and ( repcount > 0 ) then
outrow["repeat_count"] = scannet["repeat_count"]
end
outrow["sleepreq"] = 100
local repcount = tonumber(scannet["sleepreq"])
if repcount and ( repcount > 0 ) then
outrow["sleepreq"] = scannet["sleepreq"]
end
outrow["subnet"] = scannet["subnet"]
outrow["output"] = output
outnets[i] = outrow
end
end
i = next(nettable, i)
end
return outnets
end
function command_function(outnets, i)
local interface = luci.controller.luci_diag.devinfo_common.get_network_device(outnets[i]["interface"])
return "/usr/bin/netdiscover-to-devinfo " .. outnets[i]["subnet"] .. " " .. interface .. " " .. outnets[i]["timeout"] .. " -r " .. outnets[i]["repeat_count"] .. " -s " .. outnets[i]["sleepreq"] .. " </dev/null"
end
function action_links(netdiscovermap, mini)
s = netdiscovermap:section(SimpleSection, "", translate("Actions"))
b = s:option(DummyValue, "_config", translate("Configure Scans"))
b.value = ""
if (mini) then
b.titleref = luci.dispatcher.build_url("mini", "network", "netdiscover_devinfo_config")
else
b.titleref = luci.dispatcher.build_url("admin", "network", "diag_config", "netdiscover_devinfo_config")
end
b = s:option(DummyValue, "_scans", translate("Repeat Scans (this can take a few minutes)"))
b.value = ""
if (mini) then
b.titleref = luci.dispatcher.build_url("mini", "diag", "netdiscover_devinfo")
else
b.titleref = luci.dispatcher.build_url("admin", "status", "netdiscover_devinfo")
end
end
| apache-2.0 |
greasydeal/darkstar | scripts/globals/effects/teleport.lua | 23 | 2889 | -----------------------------------
--
-- EFFECT_TELEPORT
--
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/teleports");
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
end;
-----------------------------------
-- onEffectTick Action
-----------------------------------
function onEffectTick(target,effect)
end;
-----------------------------------
-- onEffectLose Action
-----------------------------------
function onEffectLose(target,effect)
local Teleport = effect:getPower();
if (Teleport == TELEPORT_DEM) then
toDem(target);
elseif (Teleport == TELEPORT_HOLLA) then
toHolla(target);
elseif (Teleport == TELEPORT_YHOAT) then
toYhoat(target);
elseif (Teleport == TELEPORT_VAHZL) then
toVahzl(target);
elseif (Teleport == TELEPORT_MEA) then
toMea(target);
elseif (Teleport == TELEPORT_ALTEP) then
toAltep(target);
elseif (Teleport == TELEPORT_WARP) then
target:warp();
elseif (Teleport == TELEPORT_ESCAPE) then
Escape(target, target:getZoneID());
elseif (Teleport == RECALL_JUGNER) then
recallJugner(target);
elseif (Teleport == RECALL_PASHH) then
recallPashh(target);
elseif (Teleport == RECALL_MERIPH) then
recallMeriph(target);
elseif (Teleport == FIREFLIES_AZOUPH) then
LeujaoamSanctumExit(target);
elseif (Teleport == FIREFLIES_BHAFLAU) then
MamoolJaTrainingExit(target);
elseif (Teleport == FIREFLIES_ZHAYOLM) then
LebrosCavernExit(target);
elseif (Teleport == FIREFLIES_DVUCCA) then
PeriqiaExit(target);
elseif (Teleport == FIREFLIES_REEF) then
IlrusiAtollExit(target);
elseif (Teleport == FIREFLIES_ALZADAAL) then
NyzulIsleExit(target);
elseif (Teleport == FIREFLIES_CUTTER) then
-- TODO
elseif (Teleport == FIREFLIES_Z_REM) then
-- TODO
elseif (Teleport == FIREFLIES_A_REM) then
-- TODO
elseif (Teleport == FIREFLIES_B_REM) then
BhaflauRemnantsExit(target);
elseif (Teleport == FIREFLIES_S_REM) then
SilverSeaRemnantsExit(target);
elseif (Teleport == TELEPORT_MAAT) then
toMaat(target);
elseif (Teleport == TELEPORT_HOMING) then
homingRing(target);
elseif (Teleport == TELEPORT_TO_LEADER) then
toLeader(target);
elseif (Teleport == TELEPORT_EXITPROMMEA) then
toExitPromMea(target);
elseif (Teleport == TELEPORT_EXITPROMHOLLA) then
toExitPromHolla(target);
elseif (Teleport == TELEPORT_EXITPROMDEM) then
toExitPromDem(target);
elseif (Teleport == TELEPORT_LUFAISE) then
toLufaise(target);
end
end; | gpl-3.0 |
greasydeal/darkstar | scripts/globals/weaponskills/victory_smite.lua | 30 | 1634 | -----------------------------------
-- Victory Smite
-- Hand-to-Hand Weapon Skill
-- Skill Level: N/A
-- Description: Delivers a fourfold attack. Chance of params.critical hit varies with TP.
-- Must have Verethragna (85)/(90)/(95)/(99)/(99-2) or Revenant Fists +1/+2/+3 equipped.
-- Aligned with the Light Gorget, Breeze Gorget & Thunder Gorget.
-- Aligned with the Light Belt, Breeze Belt & Thunder Belt.
-- Element: None
-- Skillchain Properties: Light, Fragmentation
-- Modifiers: STR:60%
-- Damage Multipliers by TP:
-- 100%TP 200%TP 300%TP
-- 2.25 2.25 2.25
-- params.critical Chance added with TP:
-- 100%TP 200%TP 300%TP
-- 10% 25% 45%
--
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 4;
params.ftp100 = 2.25; params.ftp200 = 2.25; params.ftp300 = 2.25;
params.str_wsc = 0.6; 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.1; params.crit200 = 0.25; params.crit300 = 0.45;
params.canCrit = true;
params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0;
params.atkmulti = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.str_wsc = 0.8;
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params);
damage = damage * WEAPON_SKILL_POWER
return tpHits, extraHits, criticalHit, damage;
end | gpl-3.0 |
naclander/tome | game/modules/tome/data/maps/zones/valley-moon.lua | 3 | 4063 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
quickEntity('>', {always_remember = true, type="floor", subtype="grass", show_tooltip=true, name="Passage to the caverns", desc="A dark hole in the mountain", display='>', color=colors.GREY, notice = true, change_level=2, change_zone="valley-moon-caverns", keep_old_lev=true, iamge="terrain/grass.png", add_mos={{image="terrain/stair_down.png"}}})
defineTile('.', "GRASS")
defineTile('~', "POISON_DEEP_WATER")
defineTile('"', "GRASS", nil, nil, nil, {summon_limmir=true})
defineTile('&', "PORTAL_DEMON")
defineTile('T', "TREE")
defineTile('#', "MOUNTAIN_WALL")
defineTile('M', "MOONSTONE")
addSpot({34, 1}, "portal", "demon")
addSpot({39, 7}, "portal", "demon")
addSpot({47, 11}, "portal", "demon")
startx = 45
starty = 1
return [[
##################################################
##################################&..........>####
####....T.........T~~~~~~~~T....####T....T.....###
####..........T...T~~~~~~.......######.......T.###
####................~~~TT.....#####.....T......###
####...T.....TT......~~~...............T##.....###
####.........T.......~~~.............######.TT.###
###...................~~~T.........####&.....T####
##................T...~~~~...........#####...#####
##.....TTT..........~~~~....TTTT.......###...T.###
##T............~~~~~~~.........TT........#...T.###
##T............~~~~~~......TT..................&##
###.........TT..~~~~........T.........##......####
###....TT....TT.~~~~~............T.....####.######
###............TT~~~~~~........TTTTT....######..##
###..............~~~~~~TT........TT......######.##
###......TTT....~~~~~~TTTT......TT.......T......##
###......T...~~~~~~~~~~~~~~~~~~..........TTT...###
#T#..........~~~~~~~~~~~~~~~~~~~~~.......TT....###
###........~~~~~~~~~~~~~~~~~~~~~~~~.......TT...###
###........~~~~~~~~~~~~~~~~~~~~~~~~~...........###
###........~~~~~~~~~~~"""~~~~~~~~~~~~~........T###
###..TT...~~~~~~~~~~~"""""""~~~~~~~~~~....T.T..###
###.TT...~~~~~~~~~~~~"""MMM""~~~~~.~~.......TT####
###......~~~~~~~~~~~~"""MMMM""~~~~............####
###............~~~~~~""".MM"""~~~~~....TT.....####
###.TTT.......~~~~~~~"""""""""~~~~~~~.........####
####..T......~~~~~~~~~~"""""""~~~~~~~...........##
####.........~~~~~~~~~~~""""""~~~~~~~.TTTT..TT..##
#####.........~~~~~~~~~~"""~~~~~~~~~~......TT...##
#####..........~~~~~~~~~~~~~~~~~~~~~~~~~........##
#####.....T....~~~~~~~~~~~~~~~~~~~~~~~~~........##
####......T....~~~~~~~~~~~~~~~~~~~~~~~~.......T###
####T..........~~~~~~~~~~~~~~~~~~~~~~~........T###
###.............~~~~~~~~~~~~~~~~~~~~~.....T...####
###...............~~~~~~~~~~~~~~~~~~~.........####
##...................~~~~~~~~~~~~~~~.........T####
##..T.....T...........~~~~~~~...........T..TT.####
##....................~~~~~~..........TTT...T.####
##...........T........................T........###
##.....T.....T................T................###
##....................................T.........##
##................T..........T........T....T....##
##...T................................TT......T..#
###.........T................TT...............T..#
###...................T.......T............T...###
####.........................................#####
#######.........T........T.............###########
#####################........#####################
##################################################]]
| gpl-3.0 |
ibm2431/darkstar | scripts/zones/The_Eldieme_Necropolis_[S]/npcs/Heptachiond.lua | 11 | 1771 | -----------------------------------
-- Area: The_Eldieme_Necropolis_[S]
-- NPC: Heptachiond
-- Starts and Finishes Quest: REQUIEM_FOR_THE_DEPARTED
-- !pos 256 -32 20 175
-----------------------------------
require("scripts/globals/npc_util")
require("scripts/globals/keyitems")
require("scripts/globals/quests")
-----------------------------------
function onTrade(player, npc, trade)
end;
function onTrigger(player, npc)
local Rftd = player:getQuestStatus(CRYSTAL_WAR, dsp.quest.id.crystalWar.REQUIEM_FOR_THE_DEPARTED)
-- Change to BRASS_RIBBON_OF_SERVICE later when Campaign has been added.
if Rftd == QUEST_AVAILABLE and player:hasKeyItem(dsp.ki.BRONZE_RIBBON_OF_SERVICE) and player:getMainLvl() >= 30 then
player:startEvent(105) -- Start quest "Requiem for the Departed"
elseif Rftd == QUEST_ACCEPTED then
if player:hasKeyItem(dsp.ki.SHEAF_OF_HANDMADE_INCENSE) then
player:startEvent(107) -- During quest "Requiem for the Departed" (with Handmade Incense KI)
else
player:startEvent(106) -- During quest "Requiem for the Departed" (before retrieving KI Handmade Incense)
end
elseif Rftd == QUEST_COMPLETED then
player:startEvent(108) -- New standard dialog after "Requiem for the Departed"
else
player:startEvent(104) -- Standard dialog
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
if csid == 105 then
player:addQuest(CRYSTAL_WAR, dsp.quest.id.crystalWar.REQUIEM_FOR_THE_DEPARTED)
elseif csid == 107 and npcUtil.completeQuest(player, CRYSTAL_WAR, dsp.quest.id.crystalWar.REQUIEM_FOR_THE_DEPARTED, {item = 4689}) then
player:delKeyItem(dsp.ki.SHEAF_OF_HANDMADE_INCENSE)
end
end
| gpl-3.0 |
LegionXI/darkstar | scripts/zones/Metalworks/npcs/Franziska.lua | 17 | 1138 | -----------------------------------
-- Area: Metalworks
-- NPC: Franziska
-- Type: Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Metalworks/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Metalworks/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getVar("OptionalcsCornelia") ==1) then
player:startEvent(0x0309);
else
player:startEvent(0x026C);
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 == 0x0309) then
player:setVar("OptionalcsCornelia",0);
end
end;
| gpl-3.0 |
LegionXI/darkstar | scripts/zones/Waughroon_Shrine/npcs/Burning_Circle.lua | 14 | 2281 | -----------------------------------
-- Area: Waughroon Shrine
-- NPC: Burning Circle
-- Waughroon Shrine Burning Circle
-- @pos -345 104 -260 144
-------------------------------------
package.loaded["scripts/zones/Waughroon_Shrine/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/bcnm");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/globals/missions");
require("scripts/zones/Waughroon_Shrine/TextIDs");
---- 0: Rank 2 Final Mission for Bastok "The Emissary" and Sandy "Journey Abroad"
---- 1: Worms Turn
---- 2: Grimshell Shocktroopers
---- 3: On my Way
---- 4: Thief in Norg
---- 5: 3, 2, 1
---- 6: Shattering Stars (RDM)
---- 7: Shattering Stars (THF)
---- 8: Shattering Stars (BST)
---- 9: Birds of the feather
---- 10: Crustacean Conundrum
---- 11: Grove Gardians
---- 12: The Hills are alive
---- 13: Royal Jelly
---- 14: The Final Bout
---- 15: Up in arms
---- 16: Copy Cat
---- 17: Operation Desert Swarm
---- 18: Prehistoric Pigeons
---- 19: The Palborough Project
---- 20: Shell Shocked
---- 21: Beyond infinity
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (TradeBCNM(player,player:getZoneID(),trade,npc)) then
return;
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (EventTriggerBCNM(player,npc)) then
return;
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("onUpdate CSID: %u",csid);
-- printf("onUpdate RESULT: %u",option);
if (EventUpdateBCNM(player,csid,option)) then
return;
end
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("onFinish CSID: %u",csid);
-- printf("onFinish RESULT: %u",option);
if (EventFinishBCNM(player,csid,option)) then
return;
end
end; | gpl-3.0 |
ibm2431/darkstar | scripts/zones/Quicksand_Caves/mobs/Antican_Triarius.lua | 9 | 1147 | -----------------------------------
-- Area: Quicksand Caves
-- Mob: Antican Triarius
-- Note: PH for Triarius X-XV and Hastatus XI-XII
-----------------------------------
local ID = require("scripts/zones/Quicksand_Caves/IDs")
require("scripts/globals/regimes")
require("scripts/globals/mobs")
-----------------------------------
function onMobDeath(mob, player, isKiller)
dsp.regime.checkRegime(player, mob, 812, 2, dsp.regime.type.GROUNDS)
dsp.regime.checkRegime(player, mob, 813, 2, dsp.regime.type.GROUNDS)
dsp.regime.checkRegime(player, mob, 814, 2, dsp.regime.type.GROUNDS)
dsp.regime.checkRegime(player, mob, 815, 1, dsp.regime.type.GROUNDS)
dsp.regime.checkRegime(player, mob, 816, 2, dsp.regime.type.GROUNDS)
dsp.regime.checkRegime(player, mob, 817, 2, dsp.regime.type.GROUNDS)
dsp.regime.checkRegime(player, mob, 818, 2, dsp.regime.type.GROUNDS)
dsp.regime.checkRegime(player, mob, 819, 2, dsp.regime.type.GROUNDS)
end
function onMobDespawn(mob)
dsp.mob.phOnDespawn(mob, ID.mob.TRIARIUS_X_XV_PH, 10, 7200) -- 2 hours
dsp.mob.phOnDespawn(mob, ID.mob.HASTATUS_XI_XII_PH, 10, 3600) -- 1 hour
end
| gpl-3.0 |
lbthomsen/openwrt-luci | applications/luci-app-ocserv/luasrc/controller/ocserv.lua | 5 | 1850 | -- Copyright 2014 Nikos Mavrogiannopoulos <n.mavrogiannopoulos@gmail.com>
-- Licensed to the public under the Apache License 2.0.
module("luci.controller.ocserv", package.seeall)
function index()
if not nixio.fs.access("/etc/config/ocserv") then
return
end
local page
page = entry({"admin", "vpn", "ocserv"}, alias("admin", "vpn", "ocserv", "main"),
_("OpenConnect VPN"))
page.dependent = true
page.acl_depends = { "luci-app-ocserv" }
page = entry({"admin", "vpn", "ocserv", "main"},
cbi("ocserv/main"),
_("Server Settings"), 200)
page.dependent = true
page = entry({"admin", "vpn", "ocserv", "users"},
cbi("ocserv/users"),
_("User Settings"), 300)
page.dependent = true
entry({"admin", "vpn", "ocserv", "status"},
call("ocserv_status")).leaf = true
entry({"admin", "vpn", "ocserv", "disconnect"},
post("ocserv_disconnect")).leaf = true
end
function ocserv_status()
local ipt = io.popen("/usr/bin/occtl show users");
if ipt then
local fwd = { }
while true do
local ln = ipt:read("*l")
if not ln then break end
local id, user, group, vpn_ip, ip, device, time, cipher, status =
ln:match("^%s*(%d+)%s+([-_%w]+)%s+([%(%)%.%*-_%w]+)%s+([%:%.-_%w]+)%s+([%:%.-_%w]+)%s+([%:%.-_%w]+)%s+([%:%.-_%w]+)%s+([%(%)%:%.-_%w]+)%s+([%:%.-_%w]+).*")
if id then
fwd[#fwd+1] = {
id = id,
user = user,
group = group,
vpn_ip = vpn_ip,
ip = ip,
device = device,
time = time,
cipher = cipher,
status = status
}
end
end
ipt:close()
luci.http.prepare_content("application/json")
luci.http.write_json(fwd)
end
end
function ocserv_disconnect(num)
local idx = tonumber(num)
if idx and idx > 0 then
luci.sys.call("/usr/bin/occtl disconnect id %d" % idx)
luci.http.status(200, "OK")
return
end
luci.http.status(400, "Bad request")
end
| apache-2.0 |
ibm2431/darkstar | scripts/globals/items/slice_of_buffalo_meat.lua | 11 | 1148 | -----------------------------------------
-- ID: 5152
-- Item: slice_of_buffalo_meat
-- Food Effect: 5Min, Galka only
-----------------------------------------
-- Strength 4
-- Agility -5
-- Intelligence -7
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onItemCheck(target)
local result = 0
if (target:getRace() ~= dsp.race.GALKA) then
result = dsp.msg.basic.CANNOT_EAT
end
if (target:getMod(dsp.mod.EAT_RAW_MEAT) == 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,5152)
end
function onEffectGain(target,effect)
target:addMod(dsp.mod.STR, 4)
target:addMod(dsp.mod.AGI, -5)
target:addMod(dsp.mod.INT, -7)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.STR, 4)
target:delMod(dsp.mod.AGI, -5)
target:delMod(dsp.mod.INT, -7)
end
| gpl-3.0 |
softer/prosody-modules | mod_support_contact/mod_support_contact.lua | 32 | 1757 | -- mod_support_contact.lua
--
-- Config options:
-- support_contact = "support@hostname"; -- a JID
-- support_contact_nick = "Support!"; -- roster nick
-- support_contact_group = "Users being supported!"; -- the roster group in the support contact's roster
local host = module:get_host();
local support_contact = module:get_option_string("support_contact", "support@"..host);
local support_contact_nick = module:get_option_string("support_contact_nick", "Support");
local support_contact_group = module:get_option_string("support_contact_group", "Users");
if not(support_contact and support_contact_nick) then return; end
local rostermanager = require "core.rostermanager";
local jid_split = require "util.jid".split;
local st = require "util.stanza";
module:hook("user-registered", function(event)
module:log("debug", "Adding support contact");
local groups = support_contact_group and {[support_contact_group] = true;} or {};
local node, host = event.username, event.host;
local jid = node and (node..'@'..host) or host;
local roster;
roster = rostermanager.load_roster(node, host);
if hosts[host] then
roster[support_contact] = {subscription = "both", name = support_contact_nick, groups = {}};
else
roster[support_contact] = {subscription = "from", ask = "subscribe", name = support_contact_nick, groups = {}};
end
rostermanager.save_roster(node, host, roster);
node, host = jid_split(support_contact);
if hosts[host] then
roster = rostermanager.load_roster(node, host);
roster[jid] = {subscription = "both", groups = groups};
rostermanager.save_roster(node, host, roster);
rostermanager.roster_push(node, host, jid);
else
module:send(st.presence({from=jid, to=support_contact, type="subscribe"}));
end
end);
| mit |
LegionXI/darkstar | scripts/commands/send.lua | 14 | 14235 | ---------------------------------------------------------------------------------------------------
-- func: send <player1> (<player2) or zone)
-- desc: Teleport a player to:
-- A) The given zone
-- B) another player
---------------------------------------------------------------------------------------------------
cmdprops =
{
permission = 1,
parameters = "ss"
};
---------------------------------------------------------------------------------------------------
-- desc: List of zones with their auto-translated group and message id.
-- note: The format is as follows: groupId, messageId, zoneId
---------------------------------------------------------------------------------------------------
local zone_list =
{
{ 0x14, 0xA9, 1 }, -- Phanauet Channel
{ 0x14, 0xAA, 2 }, -- Carpenters' Landing
{ 0x14, 0x84, 3 }, -- Manaclipper
{ 0x14, 0x85, 4 }, -- Bibiki Bay
{ 0x14, 0x8A, 5 }, -- Uleguerand Range
{ 0x14, 0x8B, 6 }, -- Bearclaw Pinnacle
{ 0x14, 0x86, 7 }, -- Attohwa Chasm
{ 0x14, 0x87, 8 }, -- Boneyard Gully
{ 0x14, 0x88, 9 }, -- Pso'Xja
{ 0x14, 0x89, 10 }, -- The Shrouded Maw
{ 0x14, 0x8C, 11 }, -- Oldton Movalpolos
{ 0x14, 0x8D, 12 }, -- Newton Movalpolos
{ 0x14, 0x8E, 13 }, -- Mine Shaft #2716
{ 0x14, 0xDC, 13 }, -- Mine Shaft #2716
{ 0x14, 0xAB, 14 }, -- Hall of Transference
{ 0x14, 0x9B, 16 }, -- Promyvion - Holla
{ 0x14, 0x9A, 16 }, -- Promyvion - Holla
{ 0x14, 0x9C, 17 }, -- Spire of Holla
{ 0x14, 0x9E, 18 }, -- Promyvion - Dem
{ 0x14, 0x9D, 18 }, -- Promyvion - Dem
{ 0x14, 0x9F, 19 }, -- Spire of Dem
{ 0x14, 0xA0, 20 }, -- Promyvion - Mea
{ 0x14, 0xA1, 20 }, -- Promyvion - Mea
{ 0x14, 0xA2, 21 }, -- Spire of Mea
{ 0x14, 0xA3, 22 }, -- Promyvion - Vahzl
{ 0x14, 0xA4, 22 }, -- Promyvion - Vahzl
{ 0x14, 0xA5, 22 }, -- Promyvion - Vahzl
{ 0x14, 0xA6, 22 }, -- Promyvion - Vahzl
{ 0x14, 0xA7, 23 }, -- Spire of Vahzl
{ 0x14, 0xA8, 23 }, -- Spire of Vahzl
{ 0x14, 0x90, 24 }, -- Lufaise Meadows
{ 0x14, 0x91, 25 }, -- Misareaux Coast
{ 0x14, 0x8F, 26 }, -- Tavnazian Safehold
{ 0x14, 0x93, 27 }, -- Phomiuna Aqueducts
{ 0x14, 0x94, 28 }, -- Sacrarium
{ 0x14, 0x96, 29 }, -- Riverne - Site #B01
{ 0x14, 0x95, 29 }, -- Riverne - Site #B01
{ 0x14, 0x98, 30 }, -- Riverne - Site #A01
{ 0x14, 0x97, 30 }, -- Riverne - Site #A01
{ 0x14, 0x99, 31 }, -- Monarch Linn
{ 0x14, 0x92, 32 }, -- Sealion's Den
{ 0x14, 0xAC, 33 }, -- Al'Taieu
{ 0x14, 0xAD, 34 }, -- Grand Palace of Hu'Xzoi
{ 0x14, 0xAE, 35 }, -- The Garden of Ru'Hmet
{ 0x14, 0xB0, 36 }, -- Empyreal Paradox
{ 0x14, 0xB1, 37 }, -- Temenos
{ 0x14, 0xB2, 38 }, -- Apollyon
{ 0x14, 0xB4, 39 }, -- Dynamis - Valkurm
{ 0x14, 0xB5, 40 }, -- Dynamis - Buburimu
{ 0x14, 0xB6, 41 }, -- Dynamis - Qufim
{ 0x14, 0xB7, 42 }, -- Dynamis - Tavnazia
{ 0x14, 0xAF, 43 }, -- Diorama Abdhaljs-Ghelsba
{ 0x14, 0xB8, 44 }, -- Abdhaljs Isle-Purgonorgo
{ 0x14, 0xB9, 46 }, -- Open sea route to Al Zahbi
{ 0x14, 0xBA, 47 }, -- Open sea route to Mhaura
{ 0x14, 0xBB, 48 }, -- Al Zahbi
{ 0x14, 0xDB, 50 }, -- Aht Urhgan Whitegate
{ 0x14, 0xBC, 50 }, -- Aht Urhgan Whitegate
{ 0x14, 0xBD, 51 }, -- Wajaom Woodlands
{ 0x14, 0xBE, 52 }, -- Bhaflau Thickets
{ 0x14, 0xBF, 53 }, -- Nashmau
{ 0x14, 0xC0, 54 }, -- Arrapago Reef
{ 0x14, 0xC1, 55 }, -- Ilrusi Atoll
{ 0x14, 0xC2, 56 }, -- Periqia
{ 0x14, 0xC3, 57 }, -- Talacca Cove
{ 0x14, 0xC4, 58 }, -- Silver Sea route to Nashmau
{ 0x14, 0xC5, 59 }, -- Silver Sea route to Al Zahbi
{ 0x14, 0xC6, 60 }, -- The Ashu Talif
{ 0x14, 0xC7, 61 }, -- Mount Zhayolm
{ 0x14, 0xC8, 62 }, -- Halvung
{ 0x14, 0xC9, 63 }, -- Lebros Cavern
{ 0x14, 0xCA, 64 }, -- Navukgo Execution Chamber
{ 0x14, 0xCB, 65 }, -- Mamook
{ 0x14, 0xCC, 66 }, -- Mamool Ja Training Grounds
{ 0x14, 0xCD, 67 }, -- Jade Sepulcher
{ 0x14, 0xCE, 68 }, -- Aydeewa Subterrane
{ 0x14, 0xCF, 69 }, -- Leujaoam Sanctum
{ 0x27, 0x0F, 70 }, -- Chocobo Circuit
{ 0x27, 0x10, 71 }, -- The Colosseum
{ 0x14, 0xDD, 72 }, -- Alzadaal Undersea Ruins
{ 0x14, 0xDE, 73 }, -- Zhayolm Remnants
{ 0x14, 0xDF, 74 }, -- Arrapago Remnants
{ 0x14, 0xE0, 75 }, -- Bhaflau Remnants
{ 0x14, 0xE1, 76 }, -- Silver Sea Remnants
{ 0x14, 0xE2, 77 }, -- Nyzul Isle
{ 0x14, 0xDA, 78 }, -- Hazhalm Testing Grounds
{ 0x14, 0xD0, 79 }, -- Caedarva Mire
{ 0x27, 0x11, 80 }, -- Southern San d'Oria [S]
{ 0x27, 0x13, 81 }, -- East Ronfaure [S]
{ 0x27, 0x15, 82 }, -- Jugner Forest [S]
{ 0x27, 0x23, 83 }, -- Vunkerl Inlet [S]
{ 0x27, 0x17, 84 }, -- Batallia Downs [S]
{ 0x27, 0x3E, 85 }, -- La Vaule [S]
{ 0x27, 0x40, 85 }, -- La Vaule [S]
{ 0x27, 0x19, 86 }, -- Everbloom Hollow
{ 0x27, 0x1C, 87 }, -- Bastok Markets [S]
{ 0x27, 0x1E, 88 }, -- North Gustaberg [S]
{ 0x27, 0x20, 89 }, -- Grauberg [S]
{ 0x27, 0x25, 90 }, -- Pashhow Marshlands [S]
{ 0x27, 0x27, 91 }, -- Rolanberry Fields [S]
{ 0x27, 0x42, 92 }, -- Beadeaux [S]
{ 0x27, 0x22, 93 }, -- Ruhotz Silvermines
{ 0x27, 0x2B, 94 }, -- Windurst Waters [S]
{ 0x27, 0x2D, 95 }, -- West Sarutabaruta [S]
{ 0x27, 0x2F, 96 }, -- Fort Karugo-Narugo [S]
{ 0x27, 0x32, 97 }, -- Meriphataud Mountains [S]
{ 0x27, 0x34, 98 }, -- Sauromugue Champaign [S]
{ 0x27, 0x44, 99 }, -- Castle Oztroja [S]
{ 0x14, 0x11, 100 }, -- West Ronfaure
{ 0x14, 0x0F, 101 }, -- East Ronfaure
{ 0x14, 0x51, 102 }, -- La Theine Plateau
{ 0x14, 0x60, 103 }, -- Valkurm Dunes
{ 0x14, 0x01, 104 }, -- Jugner Forest
{ 0x14, 0x02, 105 }, -- Batallia Downs
{ 0x14, 0x64, 106 }, -- North Gustaberg
{ 0x14, 0x63, 107 }, -- South Gustaberg
{ 0x14, 0x69, 108 }, -- Konschtat Highlands
{ 0x14, 0x2B, 109 }, -- Pashhow Marshlands
{ 0x14, 0x07, 110 }, -- Rolanberry Fields
{ 0x14, 0x24, 111 }, -- Beaucedine Glacier
{ 0x14, 0x4D, 112 }, -- Xarcabard
{ 0x14, 0x3D, 113 }, -- Cape Teriggan
{ 0x14, 0x3E, 114 }, -- Eastern Altepa Desert
{ 0x14, 0x18, 115 }, -- West Sarutabaruta
{ 0x14, 0x27, 116 }, -- East Sarutabaruta
{ 0x14, 0x17, 117 }, -- Tahrongi Canyon
{ 0x14, 0x16, 118 }, -- Buburimu Peninsula
{ 0x14, 0x20, 119 }, -- Meriphataud Mountains
{ 0x14, 0x2E, 120 }, -- Sauromugue Champaign
{ 0x14, 0x3F, 121 }, -- The Sanctuary of Zi'Tah
{ 0x14, 0x7D, 122 }, -- Ro'Maeve
{ 0x14, 0x7C, 122 }, -- Ro'Maeve
{ 0x14, 0x40, 123 }, -- Yuhtunga Jungle
{ 0x14, 0x41, 124 }, -- Yhoator Jungle
{ 0x14, 0x42, 125 }, -- Western Altepa Desert
{ 0x14, 0x08, 126 }, -- Qufim Island
{ 0x14, 0x0A, 127 }, -- Behemoth's Dominion
{ 0x14, 0x43, 128 }, -- Valley of Sorrows
{ 0x27, 0x31, 129 }, -- Ghoyu's Reverie
{ 0x14, 0x6F, 130 }, -- Ru'Aun Gardens
{ 0x14, 0x82, 134 }, -- Dynamis - Beaucedine
{ 0x14, 0x83, 135 }, -- Dynamis - Xarcabard
{ 0x27, 0x46, 136 }, -- Beaucedine Glacier [S]
{ 0x27, 0x48, 137 }, -- Xarcabard [S]
{ 0x14, 0x65, 139 }, -- Horlais Peak
{ 0x14, 0x6C, 140 }, -- Ghelsba Outpost
{ 0x14, 0x1F, 141 }, -- Fort Ghelsba
{ 0x14, 0x5E, 142 }, -- Yughott Grotto
{ 0x14, 0x66, 143 }, -- Palborough Mines
{ 0x14, 0x1A, 144 }, -- Waughroon Shrine
{ 0x14, 0x21, 145 }, -- Giddeus
{ 0x14, 0x19, 146 }, -- Balga's Dais
{ 0x14, 0x2A, 147 }, -- Beadeaux
{ 0x14, 0x28, 148 }, -- Qulun Dome
{ 0x14, 0x68, 149 }, -- Davoi
{ 0x14, 0x6D, 150 }, -- Monastic Cavern
{ 0x14, 0x23, 151 }, -- Castle Oztroja
{ 0x14, 0x04, 152 }, -- Altar Room
{ 0x14, 0x44, 153 }, -- The Boyahda Tree
{ 0x14, 0x37, 154 }, -- Dragon's Aery
{ 0x14, 0x0C, 157 }, -- Middle Delkfutt's Tower
{ 0x14, 0x0B, 158 }, -- Upper Delkfutt's Tower
{ 0x14, 0x36, 159 }, -- Temple of Uggalepih
{ 0x14, 0x35, 160 }, -- Den of Rancor
{ 0x14, 0x26, 161 }, -- Castle Zvahl Baileys
{ 0x14, 0x25, 161 }, -- Castle Zvahl Baileys
{ 0x14, 0x50, 162 }, -- Castle Zvahl Keep
{ 0x14, 0x4F, 162 }, -- Castle Zvahl Keep
{ 0x14, 0x39, 163 }, -- Sacrificial Chamber
{ 0x27, 0x36, 164 }, -- Garlaige Citadel [S]
{ 0x14, 0x5D, 165 }, -- Throne Room
{ 0x14, 0x2D, 166 }, -- Ranguemont Pass
{ 0x14, 0x32, 167 }, -- Bostaunieux Oubliette
{ 0x14, 0x3B, 168 }, -- Chamber of Oracles
{ 0x14, 0x1D, 169 }, -- Toraimarai Canal
{ 0x14, 0x5C, 170 }, -- Full Moon Fountain
{ 0x27, 0x29, 171 }, -- Crawlers' Nest [S]
{ 0x14, 0x61, 172 }, -- Zeruhn Mines
{ 0x14, 0x5B, 173 }, -- Korroloka Tunnel
{ 0x14, 0x5A, 174 }, -- Kuftal Tunnel
{ 0x27, 0x1A, 175 }, -- The Eldieme Necropolis [S]
{ 0x14, 0x59, 176 }, -- Sea Serpent Grotto
{ 0x14, 0x71, 177 }, -- Ve'Lugannon Palace
{ 0x14, 0x70, 177 }, -- Ve'Lugannon Palace
{ 0x14, 0x72, 178 }, -- The Shrine of Ru'Avitau
{ 0x14, 0xB3, 179 }, -- Stellar Fulcrum
{ 0x14, 0x73, 180 }, -- La'Loff Amphitheater
{ 0x14, 0x74, 181 }, -- The Celestial Nexus
{ 0x14, 0x0D, 184 }, -- Lower Delkfutt's Tower
{ 0x14, 0x7E, 185 }, -- Dynamis - San d'Oria
{ 0x14, 0x7F, 186 }, -- Dynamis - Bastok
{ 0x14, 0x80, 187 }, -- Dynamis - Windurst
{ 0x14, 0x81, 188 }, -- Dynamis - Jeuno
{ 0x14, 0x6E, 190 }, -- King Ranperre's Tomb
{ 0x14, 0x62, 191 }, -- Dangruf Wadi
{ 0x14, 0x1C, 192 }, -- Inner Horutoto Ruins
{ 0x14, 0x03, 193 }, -- Ordelle's Caves
{ 0x14, 0x1B, 194 }, -- Outer Horutoto Ruins
{ 0x14, 0x6A, 195 }, -- The Eldieme Necropolis
{ 0x14, 0x67, 196 }, -- Gusgen Mines
{ 0x14, 0x2C, 197 }, -- Crawlers' Nest
{ 0x14, 0x15, 198 }, -- Maze of Shakhrami
{ 0x14, 0x14, 200 }, -- Garlaige Citadel
{ 0x14, 0x77, 201 }, -- Cloister of Gales
{ 0x14, 0x75, 202 }, -- Cloister of Storms
{ 0x14, 0x7A, 203 }, -- Cloister of Frost
{ 0x14, 0x4A, 204 }, -- Fei'Yin
{ 0x14, 0x58, 205 }, -- Ifrit's Cauldron
{ 0x14, 0x6B, 206 }, -- Qu'Bia Arena
{ 0x14, 0x78, 207 }, -- Cloister of Flames
{ 0x14, 0x57, 208 }, -- Quicksand Caves
{ 0x14, 0x76, 209 }, -- Cloister of Tremors
{ 0x14, 0x79, 211 }, -- Cloister of Tides
{ 0x14, 0x34, 212 }, -- Gustav Tunnel
{ 0x14, 0x33, 213 }, -- Labyrinth of Onzozo
{ 0x14, 0x4C, 230 }, -- Southern San d'Oria
{ 0x14, 0x30, 231 }, -- Northern San d'Oria
{ 0x14, 0x52, 232 }, -- Port San d'Oria
{ 0x14, 0x22, 233 }, -- Chateau d'Oraguille
{ 0x14, 0x46, 234 }, -- Bastok Mines
{ 0x14, 0x56, 235 }, -- Bastok Markets
{ 0x14, 0x3C, 236 }, -- Port Bastok
{ 0x14, 0x2F, 237 }, -- Metalworks
{ 0x14, 0x3A, 238 }, -- Windurst Waters
{ 0x14, 0x54, 239 }, -- Windurst Walls
{ 0x14, 0x45, 240 }, -- Port Windurst
{ 0x14, 0x38, 241 }, -- Windurst Woods
{ 0x14, 0x55, 242 }, -- Heavens Tower
{ 0x14, 0x13, 243 }, -- Ru'Lude Gardens
{ 0x14, 0x4E, 244 }, -- Upper Jeuno
{ 0x14, 0x0E, 245 }, -- Lower Jeuno
{ 0x14, 0x06, 246 }, -- Port Jeuno
{ 0x14, 0x31, 247 }, -- Rabao
{ 0x14, 0x5F, 248 }, -- Selbina
{ 0x14, 0x1E, 249 }, -- Mhaura
{ 0x14, 0x29, 250 }, -- Kazham
{ 0x14, 0x7B, 251 }, -- Hall of the Gods
{ 0x14, 0x09, 252 }, -- Norg
{ 0x27, 0x4C, 256 }, -- Western Adoulin
{ 0x27, 0x4D, 257 }, -- Eastern Adoulin
{ 0x27, 0x4E, 259 }, -- Rala Waterways [U]
{ 0x27, 0x4F, 260 }, -- Yahse Hunting Grounds
{ 0x27, 0x50, 261 }, -- Ceizak Battlegrounds
{ 0x27, 0x51, 262 }, -- Foret de Hennetiel
{ 0x27, 0x56, 264 }, -- Yorcia Weald [U]
{ 0x27, 0x52, 265 }, -- Morimar Basalt Fields
{ 0x27, 0x57, 266 }, -- Marjami Ravine
{ 0x27, 0x5C, 267 }, -- Kamihr Drifts
{ 0x27, 0x53, 268 }, -- Sih Gates
{ 0x27, 0x54, 269 }, -- Moh Gates
{ 0x27, 0x55, 271 }, -- Cirdas Caverns [U]
{ 0x27, 0x58, 272 }, -- Dho Gates
{ 0x27, 0x5D, 273 }, -- Woh Gates
{ 0x27, 0x12, 275 }, -- Outer Ra'Kaznar [U]
{ 0x27, 0x5A, 280 }, -- Mog Garden
{ 0x27, 0x59, 284 }, -- Celennia Memorial Library
{ 0x27, 0x5B, 285 }, -- Feretory
{ 0x14, 0x09, 288 }, -- Escha - Zi'Tah
};
---------------------------------------------------------------------------------------------------
-- func: onTrigger
-- desc: Called when this command is invoked.
---------------------------------------------------------------------------------------------------
function onTrigger(player, p1, zoneId)
local word = "";
local i = 0;
local zone = zoneId;
local targ1 = GetPlayerByName(p1);
-- Not enough info..
if (p1 == nil and zone == nil) then
player:PrintToPlayer( string.format("Must specify 2 players or zone: @send <player to be sent> (<player to arrive at> or zone) ") );
return;
end
-- Ensure we have a correct combination of values..
if (p1 ~= nil) then
if (targ1 == nil) then
player:PrintToPlayer( string.format( "Player named '%s' not found!", p1 ) );
return;
end
if (zone == nil) then
player:PrintToPlayer( string.format("Must specify player to arrive at or zone.") );
return;
end
-- Was the zone auto-translated..
if (string.sub(zoneId, 1, 2) == '\253\02' and string.byte(zoneId, 5) ~= nil and string.byte(zoneId, 6) == 0xFD) then
-- Pull the group and message id from the translated string..
local groupId = string.byte(zoneId, 4);
local messageId = string.byte(zoneId, 5);
-- Attempt to lookup this zone..
for k, v in pairs(zone_list) do
if (v[1] == groupId and v[2] == messageId) then
-- Teleports player 1 to given zone.
targ1:setPos(0, 0, 0, 0, v[3], targ1);
return;
end
end
else
if (zoneId ~= nil) then
local p2 = zoneId;
local targ2 = GetPlayerByName(p2);
-- Teleports Player 1 to Player 2 coordinates and zone.
targ1:setPos( targ2:getXPos(), targ2:getYPos(), targ2:getZPos(), 0, targ2:getZoneID() );
end
end
end
end
| gpl-3.0 |
ibm2431/darkstar | scripts/zones/Port_Bastok/npcs/Yazan.lua | 11 | 1696 | -----------------------------------
-- Area: Port Bastok
-- NPC: Yazan
-- Starts Quests: Bite the Dust (100%)
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/quests");
local ID = require("scripts/zones/Port_Bastok/IDs");
-----------------------------------
function onTrade(player,npc,trade)
BiteDust = player:getQuestStatus(BASTOK,dsp.quest.id.bastok.BITE_THE_DUST);
if (BiteDust ~= QUEST_AVAILABLE and trade:hasItemQty(1015,1) and trade:getItemCount() == 1) then
player:tradeComplete();
player:startEvent(193);
end
end;
function onTrigger(player,npc)
BiteDust = player:getQuestStatus(BASTOK,dsp.quest.id.bastok.BITE_THE_DUST);
if (BiteDust == QUEST_AVAILABLE) then
player:startEvent(191);
elseif (BiteDust == QUEST_ACCEPTED) then
player:startEvent(192);
else
player:startEvent(190);
end
end;
function onEventUpdate(player,csid,option)
-- printf("CSID2: %u",csid);
-- printf("RESULT2: %u",option);
end;
function onEventFinish(player,csid,option)
if (csid == 191) then
player:addQuest(BASTOK,dsp.quest.id.bastok.BITE_THE_DUST);
elseif (csid == 193) then
if (player:getQuestStatus(BASTOK,dsp.quest.id.bastok.BITE_THE_DUST) == QUEST_ACCEPTED) then
player:addTitle(dsp.title.SAND_BLASTER)
player:addFame(BASTOK,120);
player:completeQuest(BASTOK,dsp.quest.id.bastok.BITE_THE_DUST);
else
player:addFame(BASTOK,80);
end
player:addGil(GIL_RATE*350);
player:messageSpecial(ID.text.GIL_OBTAINED,GIL_RATE*350);
end
end; | gpl-3.0 |
Geigerkind/DPSMateTBC | DPSMate/libs/GraphLib/Graph-1.0/Graph-1.0.lua | 1 | 64569 | --[[
Name: GraphLib-1.0
Revision: $Rev: 36224 $
Author(s): Cryect (cryect@gmail.com)
Website: http://www.wowace.com/
Documentation: http://www.wowace.com/wiki/GraphLib
SVN: http://svn.wowace.com/root/trunk/GraphLib/
Description: Allows for easy creation of graphs
]]
--Thanks to Nelson Minar for catching several errors where width was being used instead of height (damn copy and paste >_>)
local major, minor = "DPSGraph-1.0", "$Revision: 36224 $"
if not AceLibrary then error(major .. " requires AceLibrary.") end
if not AceLibrary:IsNewVersion(major, minor) then return end
local lib={}
local GraphFunctions={}
local gsub = gsub
local ipairs = ipairs
local pairs = pairs
local sqrt = sqrt
local table = table
local tinsert = tinsert
local tremove = tremove
local type = type
local math_max = math.max
local math_min = math.min
local math_ceil = math.ceil
local math_pi = math.pi
local math_floor = math.floor
local math_pow = math.pow
local math_random = math.random
local math_cos = math.cos
local math_sin = math.sin
local math_deg = math.deg
local math_atan = math.atan
local math_abs = math.abs
local math_fmod = math.fmod
local math_huge = math.huge
local table_remove = table.remove
local table_insert = table.insert
local string_format = string.format
local CreateFrame = CreateFrame
local GetCursorPosition = GetCursorPosition
local GetTime = GetTime
local MouseIsOver = MouseIsOver
local UnitHealth = UnitHealth
local UIParent = UIParent
local DEFAULT_CHAT_FRAME = DEFAULT_CHAT_FRAME
--Search for just Addon\\ at the front since the interface part often gets trimmed
local TextureDirectory="Interface\\AddOns\\DPSMate\\libs\\GraphLib\\GraphTextures\\"
--------------------------------------------------------------------------------
--Graph Creation Functions
--------------------------------------------------------------------------------
--Realtime Graph
function lib:CreateGraphRealtime(name,parent,relative,relativeTo,offsetX,offsetY,Width,Height)
local graph
local i
graph = CreateFrame("Frame",name,parent)
Width = math_floor(Width)
graph:SetPoint(relative,parent,relativeTo,offsetX,offsetY)
graph:SetWidth(Width)
graph:SetHeight(Height)
graph:SetResizable(true)
graph:Show()
--Create the bars
graph.Bars={}
graph.BarsUsing = {}
graph.BarNum = Width
graph.Height = Height
for i=1,Width do
local bar
bar = CreateFrame("StatusBar",name.."Bar"..i,graph)--graph:CreateTexture(nil,"ARTWORK")
bar:SetPoint("BOTTOMLEFT",graph,"BOTTOMLEFT",i-1,0)
bar:SetHeight(Height)
bar:SetWidth(1)
bar:SetOrientation("VERTICAL")
bar:SetMinMaxValues(0,1)
bar:SetStatusBarTexture("Interface\\Buttons\\WHITE8X8.blp")
local t=bar:GetStatusBarTexture()
t:SetGradientAlpha("VERTICAL",0.2,0.0,0.0,0.5,1.0,0.0,0.0,1.0)
bar:Show()
table_insert(graph.Bars,bar)
table_insert(graph.BarsUsing, bar)
end
--Set the various functions
graph.SetXAxis=GraphFunctions.SetXAxis
graph.SetYMax=GraphFunctions.SetYMax
graph.AddTimeData=GraphFunctions.AddTimeData
graph.OnUpdate=GraphFunctions.OnUpdateGraphRealtime
graph.CreateGridlines=GraphFunctions.CreateGridlines
graph.RefreshGraph=GraphFunctions.RefreshRealtimeGraph
graph.SetAxisDrawing=GraphFunctions.SetAxisDrawing
graph.SetGridSpacing=GraphFunctions.SetGridSpacing
graph.SetAxisColor=GraphFunctions.SetAxisColor
graph.SetGridColor=GraphFunctions.SetGridColor
graph.SetGridColorSecondary = GraphFunctions.SetGridColorSecondary
graph.SetGridSecondaryMultiple = GraphFunctions.SetGridSecondaryMultiple
graph.SetFilterRadius=GraphFunctions.SetFilterRadius
--graph.SetAutoscaleYAxis=GraphFunctions.SetAutoscaleYAxis
graph.SetBarColors=GraphFunctions.SetBarColors
graph.SetMode=GraphFunctions.SetMode
graph.SetAutoScale=GraphFunctions.SetAutoScale
graph.OldSetHeight = graph.SetHeight
graph.OldSetWidth = graph.SetWidth
graph.SetWidth = GraphFunctions.RealtimeSetWidth
graph.SetHeight = GraphFunctions.RealtimeSetHeight
graph.SetBarColors = GraphFunctions.RealtimeSetColors
graph.GetMaxValue = GraphFunctions.GetMaxValue
graph.GetValue = GraphFunctions.RealtimeGetValue
graph.SetUpdateLimit = GraphFunctions.SetUpdateLimit
graph.SetDecay = GraphFunctions.SetDecay
graph.SetMinMaxY = GraphFunctions.SetMinMaxY
graph.AddBar = GraphFunctions.AddBar
graph.SetYLabels = GraphFunctions.SetYLabels
graph.DrawLine=self.DrawLine
graph.HideLines=self.HideLines
graph.HideFontStrings=GraphFunctions.HideFontStrings
graph.FindFontString=GraphFunctions.FindFontString
graph.ShowFontStrings=GraphFunctions.ShowFontStrings
graph.SetBars = GraphFunctions.SetBars
--Set the update function
--Initialize Data
graph.GraphType="REALTIME"
graph.YMax=60
graph.YMin=0
graph.XMax=-0.75
graph.XMin=-10
graph.YBorder = 0
graph.XBorder = 0
graph.TimeRadius=0.5
graph.XGridInterval=0.25
graph.YGridInterval=0.25
graph.YLabelsLeft = true
graph.Mode="FAST"
graph.Filter="RECT"
graph.AxisColor={1.0,1.0,1.0,1.0}
graph.GridColor={0.5,0.5,0.5,0.5}
graph.BarColorTop = {1.0, 0.0, 0.0, 1.0}
graph.BarColorBot = {0.2, 0.0, 0.0, 0.5}
graph.AutoScale=false
graph.Data={}
graph.MinMaxY = 0
graph.CurVal = 0
graph.LastDataTime = GetTime()
graph.LimitUpdates = 0
graph.NextUpdate = 0
graph.BarHeight = {}
graph.LastShift = GetTime()
graph.BarWidth = (graph.XMax - graph.XMin) / graph.BarNum
graph.DecaySet = 0.8
graph.Decay = math_pow(graph.DecaySet, graph.BarWidth)
graph.ExpNorm = 1 / (1 - graph.Decay)
graph.FilterOverlap = math_max(math_ceil((graph.TimeRadius + graph.XMax) / graph.BarWidth), 0)
for i=1,graph.BarNum do
graph.BarHeight[i]=0
end
return graph
end
--Line Graph
--TODO: Clip lines with the bounds
function lib:CreateGraphLine(name,parent,relative,relativeTo,offsetX,offsetY,Width,Height)
local graph
local i
graph = CreateFrame("Frame",name,parent)
graph:SetPoint(relative,parent,relativeTo,offsetX,offsetY)
graph:SetWidth(Width)
graph:SetHeight(Height)
graph:Show()
--Set the various functions
graph.SetXAxis=GraphFunctions.SetXAxis
graph.SetYAxis=GraphFunctions.SetYAxis
graph.AddDataSeries=GraphFunctions.AddDataSeries
graph.ResetData=GraphFunctions.ResetData
graph.RefreshGraph=GraphFunctions.RefreshLineGraph
graph.CreateGridlines=GraphFunctions.CreateGridlines
graph.SetAxisDrawing=GraphFunctions.SetAxisDrawing
graph.SetGridSpacing=GraphFunctions.SetGridSpacing
graph.SetAxisColor=GraphFunctions.SetAxisColor
graph.SetGridColor=GraphFunctions.SetGridColor
graph.SetAutoScale=GraphFunctions.SetAutoScale
graph.SetYLabels=GraphFunctions.SetYLabels
graph.SetXLabels=GraphFunctions.SetXLabels
graph.OnUpdate=GraphFunctions.OnUpdateGraph
graph.LockXMin=GraphFunctions.LockXMin
graph.LockXMax=GraphFunctions.LockXMax
graph.LockYMin=GraphFunctions.LockYMin
graph.LockYMax=GraphFunctions.LockYMax
graph.DrawLine=self.DrawLine
graph.HideLines=self.HideLines
graph.HideFontStrings=GraphFunctions.HideFontStrings
graph.FindFontString=GraphFunctions.FindFontString
graph.ShowFontStrings=GraphFunctions.ShowFontStrings
--Set the update function
graph:SetScript("OnUpdate", graph.OnUpdate)
graph.NeedsUpdate=false
--Initialize Data
graph.GraphType="LINE"
graph.YMax=1
graph.YMin=-1
graph.XMax=1
graph.XMin=-1
graph.AxisColor={1.0,1.0,1.0,1.0}
graph.GridColor={0.5,0.5,0.5,0.5}
graph.XGridInterval=0.25
graph.YGridInterval=0.25
graph.XAxisDrawn=true
graph.YAxisDrawn=true
graph.LockOnXMin=false
graph.LockOnXMax=false
graph.LockOnYMin=false
graph.LockOnYMax=false
graph.Data={}
graph.DataPoints={}
return graph
end
--Scatter Plot
function lib:CreateGraphScatterPlot(name,parent,relative,relativeTo,offsetX,offsetY,Width,Height)
local graph
local i
graph = CreateFrame("Frame",name,parent)
graph:SetPoint(relative,parent,relativeTo,offsetX,offsetY)
graph:SetWidth(Width)
graph:SetHeight(Height)
graph:Show()
--Set the various functions
graph.SetXAxis=GraphFunctions.SetXAxis
graph.SetYAxis=GraphFunctions.SetYAxis
graph.AddDataSeries=GraphFunctions.AddDataSeries
graph.ResetData=GraphFunctions.ResetData
graph.RefreshGraph=GraphFunctions.RefreshScatterPlot
graph.CreateGridlines=GraphFunctions.CreateGridlines
--graph.OnUpdate=GraphFunctions.OnUpdateGraph
graph.LinearRegression=GraphFunctions.LinearRegression
graph.SetAxisDrawing=GraphFunctions.SetAxisDrawing
graph.SetGridSpacing=GraphFunctions.SetGridSpacing
graph.SetAxisColor=GraphFunctions.SetAxisColor
graph.SetGridColor=GraphFunctions.SetGridColor
graph.SetLinearFit=GraphFunctions.SetLinearFit
graph.SetAutoScale=GraphFunctions.SetAutoScale
graph.SetYLabels=GraphFunctions.SetYLabels
graph.LockXMin=GraphFunctions.LockXMin
graph.LockXMax=GraphFunctions.LockXMax
graph.LockYMin=GraphFunctions.LockYMin
graph.LockYMax=GraphFunctions.LockYMax
graph.DrawLine=self.DrawLine
graph.HideLines=self.HideLines
graph.HideTextures=GraphFunctions.HideTextures
graph.FindTexture=GraphFunctions.FindTexture
graph.HideFontStrings=GraphFunctions.HideFontStrings
graph.FindFontString=GraphFunctions.FindFontString
--Set the update function
--graph:SetScript("OnUpdate", graph.OnUpdate)
--graph.NeedsUpdate=false
--Initialize Data
graph.GraphType="SCATTER"
graph.YMax=1
graph.YMin=-1
graph.XMax=1
graph.XMin=-1
graph.AxisColor={1.0,1.0,1.0,1.0}
graph.GridColor={0.5,0.5,0.5,0.5}
graph.XGridInterval=0.25
graph.YGridInterval=0.25
graph.XAxisDrawn=true
graph.YAxisDrawn=true
graph.AutoScale=false
graph.LinearFit=false
graph.LockOnXMin=false
graph.LockOnXMax=false
graph.LockOnYMin=false
graph.LockOnYMax=false
graph.Data={}
return graph
end
--Pie Chart
function lib:CreateGraphPieChart(name,parent,relative,relativeTo,offsetX,offsetY,Width,Height)
local graph
local i
graph = CreateFrame("Frame",name,parent)
graph.name = name
graph:SetPoint(relative,parent,relativeTo,offsetX,offsetY)
graph:SetWidth(Width)
graph:SetHeight(Height)
graph:Show()
--Set the various functions
graph.AddPie=GraphFunctions.AddPie
graph.CompletePie=GraphFunctions.CompletePie
graph.ResetPie=GraphFunctions.ResetPie
graph.DrawLine=self.DrawLine
graph.DrawLinePie=GraphFunctions.DrawLinePie
graph.HideLines=self.HideLines
graph.HideTextures=GraphFunctions.HideTextures
graph.FindTexture=GraphFunctions.FindTexture
graph.OnUpdate=GraphFunctions.PieChart_OnUpdate
graph.SetSelectionFunc=GraphFunctions.SetSelectionFunc
graph:SetScript("OnUpdate", graph.OnUpdate)
--Initialize Data
graph.GraphType="PIE"
graph.PieUsed=0
graph.PercentOn=0
graph.Remaining=0
graph.Textures={}
graph.Ratio=Width/Height
graph.Radius=0.88*(Width/2)
graph.Radius=graph.Radius*graph.Radius
graph.Sections={}
graph.LastSection=nil
graph.onColor=1
return graph
end
-- Stacked Graphs
-- By Shino <Kronos>
-- Aka Geigerkind
-- Tom D.
-- http://legacy-logs.com
-- <shino@legacy-logs.com>
function lib:CreateStackedGraphOLD(name,parent,relative,relativeTo,offsetX,offsetY,Width,Height)
local graph
local i
graph = CreateFrame("Frame",name,parent)
graph:SetPoint(relative,parent,relativeTo,offsetX,offsetY)
graph:SetWidth(Width)
graph:SetHeight(Height)
graph:Show()
--Set the various functions
graph.SetXAxis=GraphFunctions.SetXAxis
graph.SetYAxis=GraphFunctions.SetYAxis
graph.AddDataSeries=GraphFunctions.AddDataSeries
graph.ResetData=GraphFunctions.ResetData
graph.RefreshGraph=GraphFunctions.RefreshStackedGraph
graph.CreateGridlines=GraphFunctions.CreateGridlines
graph.SetAxisDrawing=GraphFunctions.SetAxisDrawing
graph.SetGridSpacing=GraphFunctions.SetGridSpacing
graph.SetAxisColor=GraphFunctions.SetAxisColor
graph.SetGridColor=GraphFunctions.SetGridColor
graph.SetAutoScale=GraphFunctions.SetAutoScale
graph.SetYLabels=GraphFunctions.SetYLabels
graph.SetXLabels=GraphFunctions.SetXLabels
graph.OnUpdate=GraphFunctions.OnUpdateGraph
graph.LockXMin=GraphFunctions.LockXMin
graph.LockXMax=GraphFunctions.LockXMax
graph.LockYMin=GraphFunctions.LockYMin
graph.LockYMax=GraphFunctions.LockYMax
graph.FindNearValue=GraphFunctions.FindNearValue
graph.DrawLine=self.DrawLine
graph.DrawBar=self.DrawBar
graph.HideLines=self.HideLines
graph.HideBars=self.HideBars
graph.HideFontStrings=GraphFunctions.HideFontStrings
graph.FindFontString=GraphFunctions.FindFontString
graph.ShowFontStrings=GraphFunctions.ShowFontStrings
--Set the update function
graph:SetScript("OnUpdate", graph.OnUpdate)
graph.NeedsUpdate=false
--Initialize Data
graph.GraphType="STACKED"
graph.YMax=1
graph.YMin=-1
graph.XMax=1
graph.XMin=-1
graph.AxisColor={1.0,1.0,1.0,1.0}
graph.GridColor={0.5,0.5,0.5,0.5}
graph.XGridInterval=0.25
graph.YGridInterval=0.25
graph.XAxisDrawn=true
graph.YAxisDrawn=true
graph.LockOnXMin=false
graph.LockOnXMax=false
graph.LockOnYMin=false
graph.LockOnYMax=false
graph.Data={}
graph.DataPoints={}
return graph
end
-------------------------------------------------------------------------------
--Functions for Realtime Graphs
-------------------------------------------------------------------------------
--AddTimeData - Adds a data value to the realtime graph at this moment in time
function GraphFunctions:AddTimeData(value)
local t={}
t.Time=GetTime()
t.Value=value
table_insert(self.Data,t)
end
--RefreshRealtimeGraph - Refreshes the gridlines for the realtime graph
function GraphFunctions:RefreshRealtimeGraph()
self:HideLines(self)
self:CreateGridlines()
end
--SetFilterRadius - controls the radius of the filter
function GraphFunctions:SetFilterRadius(radius)
self.TimeRadius=radius
end
--SetAutoscaleYAxis - If enabled the maximum y axis is adjusted to be 25% more than the max value
function GraphFunctions:SetAutoscaleYAxis(scale)
self.AutoScale=scale
end
--SetBarColors -
function GraphFunctions:SetBarColors(BotColor,TopColor)
for i=1,self.BarNum do
local t=self.Bars[i]:GetStatusBarTexture()
t:SetGradientAlpha("VERTICAL",BotColor[1],BotColor[2],BotColor[3],BotColor[4],TopColor[1],TopColor[2],TopColor[3],TopColor[4])
end
end
function GraphFunctions:SetMode(mode)
self.Mode=mode
if mode=="FAST" then
self.LastShift=GetTime()+xmin
end
end
-------------------------------------------------------------------------------
--Functions for Line Graph Data
-------------------------------------------------------------------------------
function GraphFunctions:AddDataSeries(points,color,Dp,label)
--Make sure there is data points
if not points then
return
end
table_insert(self.Data,{Points=points;Color=color;Label=label})
table_insert(self.DataPoints, Dp)
self.NeedsUpdate=true
end
function GraphFunctions:ResetData()
self.Data={}
self.DataPoints={}
self.NeedsUpdate=true
end
function GraphFunctions:SetLinearFit(fit)
self.LinearFit=fit
self.NeedsUpdate=true
end
function GraphFunctions:HideTextures()
if not self.Textures then
self.Textures={}
end
for k, t in pairs(self.Textures) do
t:Hide()
end
end
--Make sure to show a texture after you grab it or its free for anyone else to grab
function GraphFunctions:FindTexture()
for k, t in pairs(self.Textures) do
if not t:IsShown() then
return t
end
end
local g=self:CreateTexture(nil,"BACKGROUND")
table_insert(self.Textures,g)
return g
end
function GraphFunctions:HideFontStrings()
if not self.FontStrings then
self.FontStrings={}
end
for k, t in pairs(self.FontStrings) do
t:Hide()
end
end
function GraphFunctions:ShowFontStrings()
if not self.FontStrings then
self.FontStrings={}
end
for k, t in pairs(self.FontStrings) do
t:Show()
end
end
--Make sure to show a fontstring after you grab it or its free for anyone else to grab
function GraphFunctions:FindFontString()
for k, t in pairs(self.FontStrings) do
if not t:IsShown() then
return t
end
end
local g=self:CreateFontString(nil,"OVERLAY")
table_insert(self.FontStrings,g)
return g
end
--Linear Regression via Least Squares
function GraphFunctions:LinearRegression(data)
local alpha, beta
local n, SX,SY,SXX, SXY = 0,0,0,0,0
for k,v in pairs(data) do
n=n+1
SX=SX+v[1]
SXX=SXX+v[1]*v[1]
SY=SY+v[2]
SXY=SXY+v[1]*v[2]
end
beta=(n*SXY-SX*SY)/(n*SXX-SX*SX)
alpha=(SY-beta*SX)/n
return alpha, beta
end
-------------------------------------------------------------------------------
--Functions for Pie Chart
-------------------------------------------------------------------------------
local PiePieces={"Pie\\1-2";
"Pie\\1-4";
"Pie\\1-8";
"Pie\\1-16";
"Pie\\1-32";
"Pie\\1-64";
"Pie\\1-128"}
--26 Colors
local colorByAbility = {}
local AbilityByColor = {}
local ColorTable={
{0.0,0.9,0.0},
{0.9,0.0,0.0},
{0.0,0.0,1.0},
{1.0,1.0,0.0},
{1.0,0.0,1.0},
{0.0,1.0,1.0},
{1.0,1.0,1.0},
{0.5,0.0,0.0},
{0.0,0.5,0.0},
{0.0,0.0,0.5},
{0.5,0.5,0.0},
{0.5,0.0,0.5},
{0.0,0.5,0.5},
{0.5,0.5,0.5},
{0.75,0.25,0.25},
{0.25,0.75,0.25},
{0.25,0.25,0.75},
{0.75,0.75,0.25},
{0.75,0.25,0.75},
{0.25,0.75,0.75},
{1.0,0.5,0.0},
{0.0,0.5,1.0},
{1.0,0.0,0.5},
{0.5,1.0,0.0},
{0.5,0.0,1.0},
{0.0,1.0,0.5},
{0.1,0.1,0.1},
{0.2,0.2,0.2},
{0.3,0.3,0.3},
{0.4,0.4,0.4},
{0.5,0.5,0.5},
{0.6,0.6,0.6},
{0.7,0.7,0.7},
{0.8,0.8,0.8},
{0.9,0.9,0.9},
{1.0,1.0,1.0},
{0.15,0.15,0.15},
{0.25,0.25,0.25},
{0.35,0.35,0.35},
{0.45,0.45,0.45},
{0.55,0.55,0.55},
{0.65,0.65,0.65},
{0.75,0.75,0.75},
{0.85,0.85,0.85},
{0.95,0.95,0.95},
}
function GraphFunctions:AddPie(Percent, Color, label)
local k,v
local PiePercent=self.PercentOn
local CurPiece=50
local Angle=180
local CurAngle=PiePercent*360/100
local Section={}
Section.Textures={}
if colorByAbility[label] then
Color = colorByAbility[label]
end
if type(Color) ~= "table" and ColorTable[self.onColor] then
while true do
if ColorTable[self.onColor] then
if not AbilityByColor[ColorTable[self.onColor]] then
Color = ColorTable[self.onColor]
break
end
else
break
end
self.onColor=self.onColor+1
end
end
if not ColorTable[self.onColor] and type(Color) ~= "table" then
ColorTable[self.onColor] = {0.01*math_random(0,100),0.01*math_random(0,100),0.01*math_random(0,100),1}
Color = ColorTable[self.onColor]
self.onColor=self.onColor+1
end
colorByAbility[label] = Color
AbilityByColor[Color] = label
if PiePercent==0 then
self:DrawLinePie(0)
end
Percent=Percent+self.Remaining
local LastPiece=0
for k,v in pairs(PiePieces) do
if (Percent+0.1)>CurPiece then
local t=self:FindTexture()
t:SetTexture(TextureDirectory..v)
t:ClearAllPoints()
t:SetPoint("CENTER",self,"CENTER",0,0)
t:SetHeight(self:GetHeight())
t:SetWidth(self:GetWidth())
t.name = self.name
t.label = label
t.percent = string_format("%.2f", Percent).."%"
GraphFunctions:RotateTexture(t,CurAngle)
t:Show()
t:SetVertexColor(Color[1],Color[2],Color[3],1.0)
Percent=Percent-CurPiece
PiePercent=PiePercent+CurPiece
CurAngle=CurAngle+Angle
table_insert(Section.Textures,t)
if k == 7 then
LastPiece=0.09
end
end
CurPiece=CurPiece/2
Angle=Angle/2
end
--Finish adding section data
Section.Color=Color
Section.Angle=CurAngle
table_insert(self.Sections,Section)
self:DrawLinePie((PiePercent+LastPiece)*360/100)
self.PercentOn=PiePercent
self.Remaining=Percent
return Color
end
function GraphFunctions:CompletePie(Color)
local Percent=100-self.PercentOn
local k,v
local PiePercent=self.PercentOn
local CurPiece=50
local Angle=180
local CurAngle=PiePercent*360/100
local Section={}
Section.Textures={}
if type(Color)~="table" then
if self.onColor<=26 then
Color=ColorTable[self.onColor]
else
Color={math_random(),math_random(),math_random()}
end
self.onColor=self.onColor+1
end
Percent=Percent+self.Remaining
if PiePercent~=0 then
for k,v in pairs(PiePieces) do
if (Percent+0.1)>CurPiece then
local t=self:FindTexture()
t:SetTexture(TextureDirectory..v)
t:ClearAllPoints()
t:SetPoint("CENTER",self,"CENTER",0,0)
t:SetHeight(self:GetHeight())
t:SetWidth(self:GetWidth())
GraphFunctions:RotateTexture(t,CurAngle)
t:Show()
t:SetVertexColor(Color[1],Color[2],Color[3],1.0)
Percent=Percent-CurPiece
PiePercent=PiePercent+CurPiece
CurAngle=CurAngle+Angle
table_insert(Section.Textures,t)
end
CurPiece=CurPiece/2
Angle=Angle/2
end
else--Special case if its by itself
local t=self:FindTexture()
t:SetTexture(TextureDirectory.."Pie\\1-1")
t:ClearAllPoints()
t:SetPoint("CENTER",self,"CENTER",0,0)
t:SetHeight(self:GetHeight())
t:SetWidth(self:GetWidth())
GraphFunctions:RotateTexture(t,CurAngle)
t:Show()
t:SetVertexColor(Color[1],Color[2],Color[3],1.0)
table_insert(Section.Textures,t)
end
--Finish adding section data
Section.Color=Color
Section.Angle=360
table_insert(self.Sections,Section)
self.PercentOn=PiePercent
self.Remaining=Percent
return Color
end
function GraphFunctions:ResetPie()
self:HideTextures()
self:HideLines(self)
self.PieUsed=0
self.PercentOn=0
self.Remaining=0
self.onColor=1
self.LastSection=nil
self.Sections={}
end
function GraphFunctions:DrawLinePie(angle)
local sx,sy,ex,ey
local Radian=math_pi*(90-angle)/180
local w,h
w=self:GetWidth()/2
h=self:GetHeight()/2
sx=w
sy=h
ex=sx+0.88*w*math_cos(Radian)
ey=sx+0.88*h*math_sin(Radian)
self:DrawLine(self,sx,sy,ex,ey,34,{0.0,0.0,0.0,1.0},"OVERLAY")
end
--Used to rotate the pie slices
function GraphFunctions:RotateTexture(texture,angle)
local Radian=math_pi*(45-angle)/180
local Radian2=math_pi*(45+90-angle)/180
local Radius=0.70710678118654752440084436210485
local tx,ty,tx2,ty2
tx=Radius*math_cos(Radian)
ty=Radius*math_sin(Radian)
tx2=-ty
ty2=tx
texture:SetTexCoord(0.5-tx,0.5-ty,0.5+tx2,0.5+ty2,0.5-tx2,0.5-ty2,0.5+tx,0.5+ty)
end
function GraphFunctions:SetSelectionFunc(f)
self.SelectionFunc=f
end
--TODO: Pie chart pieces need to be clickable
function GraphFunctions:PieChart_OnUpdate()
if (MouseIsOver(this)) then
local sX,sY=this:GetCenter()
local Scale=this:GetEffectiveScale()
local mX,mY=GetCursorPosition()
local dX,dY
dX=mX/Scale-sX
dY=mY/Scale-sY
local Angle=90-math_deg(math_atan(dY/dX))
dY=dY*this.Ratio
local Dist=dX*dX+dY*dY
if dX<0 then
Angle=Angle+180
end
--Are we on the Pie Chart?
if Dist<this.Radius then
--What section are we on?
for k, v in pairs(this.Sections) do
if Angle<v.Angle then
local Color
local label = AbilityByColor[v.Color]
if k~=this.LastSection then
if this.LastSection then
local Section=this.Sections[this.LastSection]
for _, t in pairs(Section.Textures) do
Color=Section.Color
--label=t.label
Percent = t.percent
t:SetVertexColor(Color[1],Color[2],Color[3],1.0)
end
end
if this.SelectionFunc then
this:SelectionFunc(k)
end
end
local ColorAdd=0.2
Color={}
Color[1]=v.Color[1]+ColorAdd
Color[2]=v.Color[2]+ColorAdd
Color[3]=v.Color[3]+ColorAdd
if label then
GameTooltip:SetOwner(this, "TOPLEFT")
GameTooltip:AddLine(label..": "..(this.Sections[k].Textures[1].percent or ""))
GameTooltip:Show()
end
for _, t in pairs(v.Textures) do
t:SetVertexColor(Color[1],Color[2],Color[3],1.0)
end
this.LastSection = k
return
end
end
end
else
if this.LastSection then
local Section=this.Sections[this.LastSection]
for _, t in pairs(Section.Textures) do
local Color=Section.Color
t:SetVertexColor(Color[1],Color[2],Color[3],1.0)
end
this.LastSection=nil
end
if this.SelectionFunc then
this:SelectionFunc(k)
end
if MouseIsOver(this:GetParent()) then
GameTooltip:Hide()
end
end
end
-------------------------------------------------------------------------------
--Axis Setting Functions
-------------------------------------------------------------------------------
function GraphFunctions:SetYMax(ymax)
self.YMax=ymax
self.NeedsUpdate=true
end
function GraphFunctions:SetYAxis(ymin,ymax)
self.YMin=ymin
self.YMax=ymax
self.NeedsUpdate=true
end
function GraphFunctions:SetXAxis(xmin,xmax)
self.XMin=xmin
self.XMax=xmax
self.NeedsUpdate=true
if self.GraphType=="REALTIME" then
self.BarWidth=(xmax-xmin)/self.BarNum
self.FilterOverlap=math_max(math_ceil((self.TimeRadius+xmax)/self.BarWidth),0)
self.LastShift=GetTime()+xmin
end
end
function GraphFunctions:SetAutoScale(auto)
self.AutoScale=auto
self.NeedsUpdate=true
end
--The various Lock Functions let you use Autoscale but holds the locked points in place
function GraphFunctions:LockXMin(state)
if state==nil then
self.LockOnXMin = not self.LockOnXMin
return
end
self.LockOnXMin = state
end
function GraphFunctions:LockXMax(state)
if state==nil then
self.LockOnXMax = not self.LockOnXMax
return
end
self.LockOnXMax = state
end
function GraphFunctions:LockYMin(state)
if state==nil then
self.LockOnYMin = not self.LockOnYMin
return
end
self.LockOnYMin = state
end
function GraphFunctions:LockYMax(state)
if state==nil then
self.LockOnYMax = not self.LockOnYMax
return
end
self.LockOnYMax = state
end
-------------------------------------------------------------------------------
--Functions for Realtime Graphs
-------------------------------------------------------------------------------
--AddTimeData - Adds a data value to the realtime graph at this moment in time
function GraphFunctions:AddTimeData(value)
if type(value) ~= "number" then
return
end
local t = {}
t.Time = GetTime()
self.LastDataTime = t.Time
t.Value = value
tinsert(self.Data, t)
end
--RefreshRealtimeGraph - Refreshes the gridlines for the realtime graph
function GraphFunctions:RefreshRealtimeGraph()
self:HideLines(self)
self:CreateGridlines()
end
--SetFilterRadius - controls the radius of the filter
function GraphFunctions:SetFilterRadius(radius)
self.TimeRadius = radius
end
--SetAutoscaleYAxis - If enabled the maximum y axis is adjusted to be 25% more than the max value
function GraphFunctions:SetAutoscaleYAxis(scale)
self.AutoScale = scale
end
--SetBarColors -
function GraphFunctions:SetBarColors(BotColor, TopColor)
local Temp
if BotColor.r then
Temp = BotColor
BotColor = {Temp.r, Temp.g, Temp.b, Temp.a}
end
if TopColor.r then
Temp = TopColor
TopColor = {Temp.r, Temp.g, Temp.b, Temp.a}
end
for i = 1, self.BarNum do
local t = self.Bars[i]:GetStatusBarTexture()
t:SetGradientAlpha("VERTICAL", BotColor[1], BotColor[2], BotColor[3], BotColor[4], TopColor[1], TopColor[2], TopColor[3], TopColor[4])
end
end
function GraphFunctions:SetMode(mode)
self.Mode = mode
if mode ~= "SLOW" then
self.LastShift = GetTime() + self.XMin
end
end
function GraphFunctions:RealtimeSetColors(BotColor, TopColor)
local Temp
if BotColor.r then
Temp = BotColor
BotColor = {Temp.r, Temp.g, Temp.b, Temp.a}
end
if TopColor.r then
Temp = TopColor
TopColor = {Temp.r, Temp.g, Temp.b, Temp.a}
end
self.BarColorBot = BotColor
self.BarColorTop = TopColor
for _, v in pairs(self.Bars) do
v:GetStatusBarTexture():SetGradientAlpha("VERTICAL", self.BarColorBot[1], self.BarColorBot[2], self.BarColorBot[3], self.BarColorBot[4], self.BarColorTop[1], self.BarColorTop[2], self.BarColorTop[3], self.BarColorTop[4])
end
end
function GraphFunctions:RealtimeSetWidth(Width)
Width = math_floor(Width)
if Width == self.BarNum then
return
end
self.BarNum = Width
for i = 1, Width do
if type(self.Bars[i]) == "nil" then
local bar
bar = CreateFrame("StatusBar", self:GetName().."Bar"..i, self)
bar:SetPoint("BOTTOMLEFT", self, "BOTTOMLEFT", i - 1, 0)
bar:SetHeight(self.Height)
bar:SetWidth(1)
bar:SetOrientation("VERTICAL")
bar:SetMinMaxValues(0, 1)
bar:SetStatusBarTexture("Interface\\Buttons\\WHITE8X8")
--bar:GetStatusBarTexture():SetHorizTile(false)
--bar:GetStatusBarTexture():SetVertTile(false)
local t = bar:GetStatusBarTexture()
t:SetGradientAlpha("VERTICAL", self.BarColorBot[1], self.BarColorBot[2], self.BarColorBot[3], self.BarColorBot[4], self.BarColorTop[1], self.BarColorTop[2], self.BarColorTop[3], self.BarColorTop[4])
tinsert(self.Bars, bar)
else
self.Bars[i]:SetPoint("BOTTOMLEFT", self, "BOTTOMLEFT", i - 1, 0)
end
self.BarHeight[i] = 0
end
local SizeOfBarsUsed = table.maxn(self.BarsUsing)
if Width > SizeOfBarsUsed then
for i = SizeOfBarsUsed + 1, Width do
tinsert(self.BarsUsing, self.Bars[i])
self.Bars[i]:Show()
end
elseif Width < SizeOfBarsUsed then
for i = Width + 1, SizeOfBarsUsed do
tremove(self.BarsUsing, Width + 1)
self.Bars[i]:Hide()
end
end
self.BarWidth = (self.XMax - self.XMin) / self.BarNum
self.Decay = math_pow(self.DecaySet, self.BarWidth)
self.ExpNorm = 1 / (1 - self.Decay) / 0.95 --Actually a finite geometric series
self:OldSetWidth(Width)
self:RefreshGraph()
end
function GraphFunctions:RealtimeSetHeight(Height)
self.Height = Height
for i = 1, self.BarNum do
--self.Bars[i]:Hide()
self.Bars[i]:SetValue(0)
self.Bars[i]:SetHeight(self.Height)
end
self:OldSetHeight(Height)
self:RefreshGraph()
end
function GraphFunctions:GetMaxValue()
--Is there any data that could possibly be not zero?
if self.LastDataTime < (self.LastShift + self.XMin - self.TimeRadius) then
return 0
end
local MaxY = 0
for i = 1, self.BarNum do
MaxY = math_max(MaxY, self.BarHeight[i])
end
return MaxY
end
function GraphFunctions:RealtimeGetValue(Time)
local Bar
if Time < self.XMin or Time > self.XMax then
return 0
end
Bar = math_min(math_max(math_floor(self.BarNum * (Time - self.XMin) / (self.XMax - self.XMin) + 0.5), 1), self.BarNum)
return self.BarHeight[Bar]
end
function GraphFunctions:SetUpdateLimit(Time)
self.LimitUpdates = Time
end
function GraphFunctions:SetDecay(decay)
self.DecaySet = decay
self.Decay = math_pow(self.DecaySet, self.BarWidth)
self.ExpNorm = 1 / (1 - self.Decay) / 0.95 --Actually a finite geometric series (divide 0.96 instead of 1 since seems doesn't quite work right)
end
function GraphFunctions:AddBar(value)
for i = 1, self.BarNum - 1 do
self.BarHeight[i] = self.BarHeight[i + 1]
end
self.BarHeight[self.BarNum] = value
self.AddedBar = true
end
function GraphFunctions:SetBars()
local YHeight = self.YMax - self.YMin
for i, bar in pairs(self.BarsUsing) do
local h
h = (self.BarHeight[i] - self.YMin) / YHeight
bar:SetValue(h)
end
end
-------------------------------------------------------------------------------
--Grid & Axis Drawing Functions
-------------------------------------------------------------------------------
function GraphFunctions:SetAxisDrawing(xaxis, yaxis)
self.XAxisDrawn=xaxis
self.YAxisDrawn=yaxis
self.NeedsUpdate=true
end
function GraphFunctions:SetGridSpacing(xspacing,yspacing)
self.XGridInterval=xspacing
self.YGridInterval=yspacing
self.NeedsUpdate=true
end
function GraphFunctions:SetAxisColor(color)
self.AxisColor=color
self.NeedsUpdate=true
end
function GraphFunctions:SetGridColor(color)
self.GridColor=color
self.NeedsUpdate=true
end
function GraphFunctions:SetYLabels(Left,Right)
self.YLabelsLeft=Left
self.YLabelsRight=Right
end
function GraphFunctions:SetXLabels(bool)
self.XLabels=bool
end
function GraphFunctions:CreateGridlines()
local Width=self:GetWidth()
local Height=self:GetHeight()
self:HideLines(self)
self:HideFontStrings()
if self.YGridInterval then
local LowerYGridLine,UpperYGridLine,TopSpace
LowerYGridLine=self.YMin/self.YGridInterval
LowerYGridLine=math_max(math_floor(LowerYGridLine),math_ceil(LowerYGridLine))
UpperYGridLine=self.YMax/self.YGridInterval
UpperYGridLine=math_min(math_floor(UpperYGridLine),math_ceil(UpperYGridLine))
TopSpace=Height*(1-(UpperYGridLine*self.YGridInterval)/(self.YMax))
local alpha = 0
for i=LowerYGridLine,UpperYGridLine do
if not self.YAxisDrawn or i~=0 then
if alpha>25000 then break end
local YPos,T,F
YPos=Height*(i*self.YGridInterval+self.YBorder)/(self.YMax)
if YPos<(Height-2) and YPos>24 then
if self.GraphType~="REALTIME" then
T=self:DrawLine(self,0,YPos,Width,YPos,24,self.GridColor,"BACKGROUND")
end
if (((i~=UpperYGridLine) or (TopSpace>12))) and alpha==ceil(((UpperYGridLine-LowerYGridLine)/6)) then
if self.GraphType=="REALTIME" then
T=self:DrawLine(self,0,YPos,Width,YPos,24,self.GridColor,"BACKGROUND")
end
if self.YLabelsLeft then
F=self:FindFontString()
F:SetFontObject("GameFontHighlightSmall")
F:SetTextColor(1,1,1)
F:ClearAllPoints()
F:SetPoint("BOTTOMLEFT",T,"LEFT",2,2)
F:SetText(floor(i*self.YGridInterval))
F:Show()
end
if self.YLabelsRight then
F=self:FindFontString()
F:SetFontObject("GameFontHighlightSmall")
F:SetTextColor(1,1,1)
F:ClearAllPoints()
F:SetPoint("BOTTOMRIGHT",T,"RIGHT",-2,2)
F:SetText(i*self.YGridInterval)
F:Show()
end
alpha = 0
end
alpha = alpha+1
end
end
end
end
if self.XGridInterval then
local LowerXGridLine,UpperXGridLine
LowerXGridLine=self.XMin/self.XGridInterval
LowerXGridLine=math_max(math_floor(LowerXGridLine),math_ceil(LowerXGridLine))
UpperXGridLine=self.XMax/self.XGridInterval
UpperXGridLine=math_min(math_floor(UpperXGridLine),math_ceil(UpperXGridLine))
for i=LowerXGridLine,UpperXGridLine do
if i~=0 or not self.XAxisDrawn then
local XPos, T, F
XPos=Width*(i*self.XGridInterval-self.XMin)/(self.XMax-self.XMin)
T=self:DrawLine(self,XPos,0,XPos,Height,24,self.GridColor,"BACKGROUND")
if self.XLabels then
F=self:FindFontString()
F:SetFontObject("GameFontHighlightSmall")
F:SetTextColor(1,1,1)
F:ClearAllPoints()
F:SetPoint("BOTTOM",T,"BOTTOM",0,0)
F:SetText(floor(i*self.XGridInterval))
F:Show()
end
end
end
end
if self.YAxisDrawn and self.YMax>=0 and self.YMin<=0 then
local YPos,T
YPos=Height*(-self.YMin)/(self.YMax-self.YMin)
self.yAxis = self:DrawLine(self,0,YPos,Width,YPos,24,self.AxisColor,"BACKGROUND")
if self.YLabelsLeft then
F=self:FindFontString()
F:SetFontObject("GameFontHighlightSmall")
F:SetTextColor(1,1,1)
F:ClearAllPoints()
F:SetPoint("BOTTOMLEFT",self.yAxis,"LEFT",2,2)
F:SetText(0)
F:Show()
end
if self.YLabelsRight then
F=self:FindFontString()
F:SetFontObject("GameFontHighlightSmall")
F:SetTextColor(1,1,1)
F:ClearAllPoints()
F:SetPoint("BOTTOMRIGHT",self.yAxis,"RIGHT",-2,2)
F:SetText(0)
F:Show()
end
end
if self.XAxisDrawn and self.XMax>=0 and self.XMin<=0 then
local XPos;
XPos=Width*(-self.XMin)/(self.XMax-self.XMin)
self.xAxis = self:DrawLine(self,XPos,0,XPos,Height,24,self.AxisColor,"BACKGROUND")
end
end
--------------------------------------------------------------------------------
--Refresh functions
--------------------------------------------------------------------------------
function GraphFunctions:OnUpdateGraph()
if this.NeedsUpdate and this.RefreshGraph then
this:RefreshGraph()
this.NeedsUpdate=false
end
end
--Performs a convolution in realtime allowing to graph Framerate, DPS, or any other data you want graphed in realtime
function GraphFunctions:OnUpdateGraphRealtime(obj)
local i,j
local CurTime=GetTime()
local MaxBarHeight=obj:GetHeight()
local BarsChanged
if self.NextUpdate > CurTime or (self.Mode == "RAW" and not (self.NeedsUpdate or self.AddedBar)) then
return
end
self.NextUpdate = CurTime + self.LimitUpdates
--Slow Mode performs an entire convolution every frame
if self.Mode=="FAST" then
local ShiftBars = math_floor((CurTime - self.LastShift) / self.BarWidth)
if ShiftBars > 0 and not (self.LastDataTime < (self.LastShift + self.XMin - self.TimeRadius * 2)) then
local RecalcBars = self.BarNum - (ShiftBars + self.FilterOverlap) + 1
for i = 1, self.BarNum do
if i < RecalcBars then
self.BarHeight[i] = self.BarHeight[i + ShiftBars]
else
self.BarHeight[i] = 0
end
end
local BarTimeRadius = (self.XMax - self.XMin) / self.BarNum
local DataValue = 1 / (2 * self.TimeRadius)
local TimeDiff = CurTime-self.LastShift
CurTime = self.LastShift + ShiftBars * self.BarWidth
self.LastShift = CurTime
if self.Filter == "RECT" then
--Take the convolution of the dataset on to the bars wtih a rectangular filter
local DataValue = 1 / (2 * self.TimeRadius)
for k, v in pairs(self.Data) do
if v.Time < (CurTime + self.XMax - self.TimeRadius - TimeDiff) then
tremove(self.Data, k)
else
local DataTime = v.Time - CurTime
local LowestBar = math_max(math_max(math_floor((DataTime - self.XMin - self.TimeRadius) / BarTimeRadius), RecalcBars), 1)
local HighestBar = math_min(math_ceil((DataTime - self.XMin + self.TimeRadius) / BarTimeRadius), self.BarNum)
if LowestBar <= HighestBar then
for i = LowestBar, HighestBar do
self.BarHeight[i] = self.BarHeight[i] + v.Value * DataValue * 2
end
end
end
end
end
BarsChanged = true
else
CurTime = self.LastShift + ShiftBars * self.BarWidth
self.LastShift = CurTime
end
end
if BarsChanged then
if self.AutoScale then
local MaxY = 0
for i = 1, self.BarNum do
MaxY = math_max(MaxY, self.BarHeight[i])
end
MaxY = 1.25 * MaxY
MaxY = math_max(MaxY, self.MinMaxY)
self.XBorder = 10
self.YBorder = 0
if MaxY ~= 0 and math_abs(self.YMax - MaxY) > 0.01 then
self.YMax = MaxY
self.NeedsUpdate = true
end
end
self:SetBars()
end
if self.NeedsUpdate then
self.NeedsUpdate = false
self:RefreshGraph()
end
end
--Line Graph
function GraphFunctions:RefreshLineGraph()
local k1, k2, series
self:HideLines(self)
local Width=self:GetWidth()
local Height=self:GetHeight()
if self.AutoScale and self.Data then -- math_huge not implemented
local MinX, MaxX, MinY, MaxY = 1, -3, 200, -900
for k1, series in pairs(self.Data) do
for k2, point in pairs(series.Points) do
if not MinX or point[1]<MinX then MinX = point[1] end
if not MinY or point[2]<MinY then MinY = point[2] end
if not MaxX or point[1]>MaxX then MaxX = point[1] end
if not MaxY or point[2]>MaxY then MaxY = point[2] end
end
end
local XBorder, YBorder
XBorder=(60/Width)*MaxX
YBorder=(24/Height)*MaxY
self.XBorder=XBorder
self.YBorder = YBorder
self.YGridInterval = (MaxY+200)/7
self.XGridInterval = MaxX/7
if not self.LockOnXMin then
self.XMin=MinX-XBorder
end
if not self.LockOnXMax then
self.XMax=MaxX
end
if not self.LockOnYMin then
self.YMin=MinY-YBorder
end
if not self.LockOnYMax then
self.YMax=MaxY+YBorder
end
end
self:CreateGridlines()
for k1, series in pairs(self.Data) do
local LastPoint
LastPoint=nil
for k2, point in pairs(series.Points) do
if LastPoint then
local TPoint={x=point[1];y=point[2]}
TPoint.x=Width*(TPoint.x-self.XMin)/(self.XMax-self.XMin)
TPoint.y=(Height-24)*(TPoint.y)/(self.YMax-self.YBorder)
if point[3] then
self:DrawLine(self,LastPoint.x,LastPoint.y,TPoint.x,TPoint.y,32,series.Color[2],nil,point, nil, 24)
else
self:DrawLine(self,LastPoint.x,LastPoint.y,TPoint.x,TPoint.y,32,series.Color[1],nil,point, nil, 24)
end
LastPoint=TPoint
else
LastPoint={x=point[1];y=point[2]}
LastPoint.x=Width*(LastPoint.x-self.XMin)/(self.XMax-self.XMin)
LastPoint.y=(Height-24)*(LastPoint.y)/(self.YMax-self.YBorder)
end
end
end
self.ppoints = {}
if self.DataPoints then
for uuu, zzz in pairs(self.DataPoints) do
if zzz[2] then
for k3, p2 in pairs(zzz[2]) do
-- Needs fine tuning
local PPoint = self:CreateTexture()
PPoint:SetTexture(TextureDirectory.."party")
PPoint:SetVertexColor(self.Data[uuu].Color[1][1], self.Data[uuu].Color[1][2], self.Data[uuu].Color[1][3], 1)
local PPLastPointX = Width*(p2[2][1]-self.XMin)/(self.XMax-self.XMin)
local PPLastPointY = (Height-24)*(p2[2][2])/(self.YMax-self.YBorder)
local PPNextPointX = Width*(p2[3][1]-self.XMin)/(self.XMax-self.XMin)
local PPNextPointY = (Height-24)*(p2[3][2])/(self.YMax-self.YBorder)
local pointx = Width*(p2[1]-self.XMin)/(self.XMax-self.XMin)
local pointy = PPLastPointY + (pointx-PPLastPointX)*((PPNextPointY-PPLastPointY)/(PPNextPointX-PPLastPointX))
PPoint:SetPoint("LEFT", self.yAxis, "LEFT", pointx-(12-floor(self:GetWidth()/850)*6.5), pointy-20+24)
PPoint:SetHeight(20)
PPoint:SetWidth(20)
table_insert(self.ppoints, PPoint)
end
end
end
end
--self:ShowFontStrings()
--self:ShowFontStrings()
end
--Scatter Plot Refresh
function GraphFunctions:RefreshScatterPlot()
local k1, k2, series, point
self:HideLines(self)
if self.AutoScale and self.Data then
local MinX, MaxX, MinY, MaxY = math_huge, -math_huge, math_huge, -math_huge
for k1, series in pairs(self.Data) do
for k2, point in pairs(series.Points) do
MinX=math_min(point[1],MinX)
MaxX=math_max(point[1],MaxX)
MinY=math_min(point[2],MinY)
MaxY=math_max(point[2],MaxY)
end
end
local XBorder, YBorder
XBorder=0.1*(MaxX-MinX)
YBorder=0.1*(MaxY-MinY)
if not self.LockOnXMin then
self.XMin=MinX-XBorder
end
if not self.LockOnXMax then
self.XMax=MaxX+XBorder
end
if not self.LockOnYMin then
self.YMin=MinY-YBorder
end
if not self.LockOnYMax then
self.YMax=MaxY+YBorder
end
end
self:CreateGridlines()
local Width=self:GetWidth()
local Height=self:GetHeight()
self:HideTextures()
for k1, series in pairs(self.Data) do
local MinX,MaxX = self.XMax, self.XMin
for k2, point in pairs(series.Points) do
local x,y
MinX=math_min(point[1],MinX)
MaxX=math_max(point[1],MaxX)
x=Width*(point[1]-self.XMin)/(self.XMax-self.XMin)
y=Height*(point[2]-self.YMin)/(self.YMax-self.YMin)
local g=self:FindTexture()
g:SetTexture("Spells\\GENERICGLOW2_64.blp")
g:SetWidth(6)
g:SetHeight(6)
g:ClearAllPoints()
g:SetPoint("CENTER",self,"BOTTOMLEFT",x,y)
g:SetVertexColor(series.Color[1],series.Color[2],series.Color[3],series.Color[4]);
g:Show()
end
if self.LinearFit then
local alpha, beta = self:LinearRegression(series.Points)
local sx,sy,ex,ey
sx=MinX
sy=beta*sx+alpha
ex=MaxX
ey=beta*ex+alpha
sx=Width*(sx-self.XMin)/(self.XMax-self.XMin)
sy=Height*(sy-self.YMin)/(self.YMax-self.YMin)
ex=Width*(ex-self.XMin)/(self.XMax-self.XMin)
ey=Height*(ey-self.YMin)/(self.YMax-self.YMin)
self:DrawLine(self,sx,sy,ex,ey,32,series.Color)
end
end
end
function GraphFunctions:FindNearValue(arr, val)
for cat, var in arr do
if (val+0.5)>=cat and (val-0.5)<=cat then
return cat
end
end
return false
end
-- Stacked Graph
function GraphFunctions:RefreshStackedGraph()
self:HideLines(self)
self:HideBars(self)
-- Format table
for k1, series in pairs(self.Data) do
local p = {}
for c,v in pairs(series.Points) do
for k2, point in pairs(v) do
point[1] = math_floor(point[1])
local near = self:FindNearValue(p, point[1])
if near then
p[near] = p[near] + point[2]
point[2] = p[near]
else
p[point[1]] = point[2]
end
end
end
end
if self.AutoScale and self.Data then -- math_huge not implemented
local MinX, MaxX, MinY, MaxY = 1, -3, 200, -900
for k1, series in pairs(self.Data) do
for c,v in series.Points do
for k2, point in v do
MinX=math_min(point[1],MinX)
MaxX=math_max(point[1],MaxX)
MinY=math_min(point[2],MinY)
MaxY=math_max(point[2],MaxY)
end
end
end
local XBorder, YBorder
XBorder=0.05*(MaxX-MinX)
YBorder=0.1*(MaxY-MinY)
if not self.LockOnXMin then
self.XMin=MinX-XBorder
end
if not self.LockOnXMax then
self.XMax=MaxX
end
if not self.LockOnYMin then
self.YMin=MinY-YBorder
end
if not self.LockOnYMax then
self.YMax=MaxY+YBorder
end
end
self:CreateGridlines()
local Width=self:GetWidth()
local Height=self:GetHeight()
for k1, series in pairs(self.Data) do
for c,v in pairs(series.Points) do
local LastPoint
LastPoint=nil
for k2, point in pairs(v) do
if LastPoint then
local TPoint={x=point[1];y=point[2]}
--DPSMate:SendMessage((TPoint.x or 0).."/"..(TPoint.y or 0))
TPoint.x=Width*(TPoint.x-self.XMin)/(self.XMax-self.XMin)
TPoint.y=Height*(TPoint.y-self.YMin)/(self.YMax-self.YMin)
if not ColorTable[c] then
ColorTable[c] = {0.01*math_random(0,100),0.01*math_random(0,100),0.01*math_random(0,100),1}
end
self:DrawLine(self,LastPoint.x,LastPoint.y,TPoint.x,TPoint.y,32,ColorTable[c],nil,point,series.Label[c])
self:DrawBar(self, LastPoint.x, LastPoint.y, TPoint.x, TPoint.y, ColorTable[c], c, series.Label[c])
LastPoint=TPoint
else
LastPoint={x=point[1];y=point[2]}
LastPoint.x=Width*(LastPoint.x-self.XMin)/(self.XMax-self.XMin)
LastPoint.y=Height*(LastPoint.y-self.YMin)/(self.YMax-self.YMin)
end
end
end
end
end
--Copied from Blizzard's TaxiFrame code and modifed for IMBA then remodified for GraphLib
-- The following function is used with permission from Daniel Stephens <iriel@vigilance-committee.org>
local TAXIROUTE_LINEFACTOR = 128/126; -- Multiplying factor for texture coordinates
local TAXIROUTE_LINEFACTOR_2 = TAXIROUTE_LINEFACTOR / 2; -- Half o that
-- T - Texture
-- C - Canvas Frame (for anchoring)
-- sx,sy - Coordinate of start of line
-- ex,ey - Coordinate of end of line
-- w - Width of line
-- relPoint - Relative point on canvas to interpret coords (Default BOTTOMLEFT)
function lib:DrawLine(C, sx, sy, ex, ey, w, color, layer, point, label, const)
local T, lineNum, relPoint, P;
if (not relPoint) then relPoint = "BOTTOMLEFT"; end
const = const or 0
if not C.GraphLib_Lines then
C.GraphLib_Lines={}
end
T=nil;
for k,v in pairs(C.GraphLib_Lines) do
if not v[1]:IsShown() and not T then
T=v[1];
P=v[2];
lineNum=k;
P:Show();
T:Show();
end
end
if point and T and not T.val then
T.val = ceil(point[2])
end
if label and T and not T.label then
T.label = label
end
if not T then
P = CreateFrame("Frame", C:GetName().."_LineTT"..(getn(C.GraphLib_Lines)+1), C)
P:SetHeight(15)
P:SetWidth(15)
P:EnableMouse(true)
P:SetScript("OnEnter", function()
if T.val then
GameTooltip:SetOwner(P)
GameTooltip:AddLine("Value: "..T.val)
if T.label then
GameTooltip:AddLine("Label: "..T.label)
end
GameTooltip:Show()
end
end)
P:SetScript("OnLeave", function()
if T.val then
GameTooltip:Hide()
end
end)
T=C:CreateTexture(C:GetName().."_Line"..(getn(C.GraphLib_Lines)+1), "ARTWORK");
T:SetTexture(TextureDirectory.."line");
if point then
T.val = ceil(point[2])
end
if label and T then
T.label = label
end
tinsert(C.GraphLib_Lines,{[1]=T,[2]=P});
end
if layer then
T:SetDrawLayer(layer)
end
T:SetVertexColor(color[1],color[2],color[3],color[4]);
-- Determine dimensions and center point of line
local dx,dy = ex - sx, ey - sy;
local cx,cy = (sx + ex) / 2, (sy + ey) / 2;
-- Normalize direction if necessary
if (dx < 0) then
dx,dy = -dx,-dy;
end
-- Calculate actual length of line
local l = sqrt((dx * dx) + (dy * dy));
-- Quick escape if it's zero length
if (l == 0) then
T:Hide()
return;
end
-- Sin and Cosine of rotation, and combination (for later)
local s,c = -dy / l, dx / l;
local sc = s * c;
-- Calculate bounding box size and texture coordinates
local Bwid, Bhgt, BLx, BLy, TLx, TLy, TRx, TRy, BRx, BRy;
if (dy >= 0) then
Bwid = ((l * c) - (w * s)) * TAXIROUTE_LINEFACTOR_2;
Bhgt = ((w * c) - (l * s)) * TAXIROUTE_LINEFACTOR_2;
BLx, BLy, BRy = (w / l) * sc, s * s, (l / w) * sc;
BRx, TLx, TLy, TRx = 1 - BLy, BLy, 1 - BRy, 1 - BLx;
TRy = BRx;
else
Bwid = ((l * c) + (w * s)) * TAXIROUTE_LINEFACTOR_2;
Bhgt = ((w * c) + (l * s)) * TAXIROUTE_LINEFACTOR_2;
BLx, BLy, BRx = s * s, -(l / w) * sc, 1 + (w / l) * sc;
BRy, TLx, TLy, TRy = BLx, 1 - BRx, 1 - BLx, 1 - BLy;
TRx = TLy;
end
-- Set texture coordinates and anchors
T:ClearAllPoints();
T:SetTexCoord(TLx, TLy, BLx, BLy, TRx, TRy, BRx, BRy);
T:SetPoint("BOTTOMLEFT", C, relPoint, cx - Bwid, cy - Bhgt + const);
T:SetPoint("TOPRIGHT", C, relPoint, cx + Bwid, cy + Bhgt + const);
P:ClearAllPoints();
P:SetParent(C);
--P:SetPoint("BOTTOMLEFT", C, relPoint, cx - Bwid, cy - Bhgt);
if (ey-sy)<0 then
P:SetPoint("BOTTOMLEFT", C, relPoint, cx + Bwid -22.5, cy - Bhgt + 11.25 + const);
else
P:SetPoint("BOTTOMLEFT", C, relPoint, cx + Bwid -22.5, cy + Bhgt - 11.25 + const);
end
return T
end
--Thanks to Celandro
function lib:DrawVLine(C, x, sy, ey, w, color, layer)
local relPoint = "BOTTOMLEFT"
if not C.GraphLib_Lines then
C.GraphLib_Lines = {}
C.GraphLib_Lines_Used = {}
end
local T = tremove(C.GraphLib_Lines) or C:CreateTexture(nil, "ARTWORK")
T:SetTexture(TextureDirectory.."sline")
tinsert(C.GraphLib_Lines_Used, T)
T:SetDrawLayer(layer or "ARTWORK")
T:SetVertexColor(color[1], color[2], color[3], color[4])
if sy > ey then
sy, ey = ey, sy
end
-- Set texture coordinates and anchors
T:ClearAllPoints()
T:SetTexCoord(1, 0, 0, 0, 1, 1, 0, 1)
T:SetPoint("BOTTOMLEFT", C, relPoint, x - w / 2, sy)
T:SetPoint("TOPRIGHT", C, relPoint, x + w / 2, ey)
T:Show()
return T
end
function lib:DrawHLine(C, sx, ex, y, w, color, layer)
local relPoint = "BOTTOMLEFT"
if not C.GraphLib_Lines then
C.GraphLib_Lines = {}
C.GraphLib_Lines_Used = {}
end
local T = tremove(C.GraphLib_Lines) or C:CreateTexture(nil, "ARTWORK")
T:SetTexture(TextureDirectory.."sline")
tinsert(C.GraphLib_Lines_Used, T)
T:SetDrawLayer(layer or "ARTWORK")
T:SetVertexColor(color[1], color[2], color[3], color[4])
if sx > ex then
sx, ex = ex, sx
end
-- Set texture coordinates and anchors
T:ClearAllPoints()
T:SetTexCoord(0, 0, 0, 1, 1, 0, 1, 1)
T:SetPoint("BOTTOMLEFT", C, relPoint, sx, y - w / 2)
T:SetPoint("TOPRIGHT", C, relPoint, ex, y + w / 2)
T:Show()
return T
end
function lib:DrawBar(C, sx, sy, ex, ey, color, level, label)
local Bar, Tri, barNum, MinY, MaxY, P
--Want sx <= ex if not then flip them
if sx > ex then
sx, ex = ex, sx
sy, ey = ey, sy
end
if not C.GraphLib_Bars then
C.GraphLib_Bars = {}
C.GraphLib_Tris = {}
C.GraphLib_Bars_Used = {}
C.GraphLib_Tris_Used = {}
C.GraphLib_Frames = {}
end
local bars = getn(C.GraphLib_Bars)
if bars > 0 then
local tris = getn(C.GraphLib_Tris)
Bar = C.GraphLib_Bars[bars][1]
tremove(C.GraphLib_Bars, bars)
Bar:Show()
--P = C.GraphLib_Bars[bars][2]
--P:Show()
Tri = C.GraphLib_Tris[tris]
tremove(C.GraphLib_Tris, tris)
Tri:Show()
end
if not Bar then
--P = CreateFrame("Frame", C:GetName().."_AreaTT"..(getn(C.GraphLib_Bars)+1), C)
--P:SetHeight(10)
--P:SetWidth(10)
--P:EnableMouse(true)
--P:SetScript("OnEnter", function()
--if label then
-- GameTooltip:SetOwner(P)
-- GameTooltip:AddLine("Label: "..label)
-- GameTooltip:Show()
--end
--end)
-- P:SetScript("OnLeave", function()
-- if label then
-- GameTooltip:Hide()
-- end
--end)
Bar = C:CreateTexture(nil, "ARTWORK")
Bar:SetTexture(1, 1, 1, 1)
Tri = C:CreateTexture(nil, "ARTWORK")
Tri:SetTexture(TextureDirectory.."triangle")
end
tinsert(C.GraphLib_Bars_Used, {Bar})
tinsert(C.GraphLib_Tris_Used, Tri)
if level then
if type(C.GraphLib_Frames[level]) == "nil" then
local newLevel = 100 - level*0.1
C.GraphLib_Frames[level] = CreateFrame("Frame", nil, C)
C.GraphLib_Frames[level]:SetFrameLevel(newLevel)
C.GraphLib_Frames[level]:SetAllPoints(C)
if C.TextFrame and C.TextFrame:GetFrameLevel() <= newLevel then
C.TextFrame:SetFrameLevel(newLevel + 1)
self.NeedsUpdate = true
end
end
Bar:SetParent(C.GraphLib_Frames[level])
Tri:SetParent(C.GraphLib_Frames[level])
end
Bar:SetVertexColor(color[1], color[2], color[3], color[4])
Tri:SetVertexColor(color[1], color[2], color[3], color[4])
if sy < ey then
Tri:SetTexCoord(0, 0, 0, 1, 1, 0, 1, 1)
MinY = sy
MaxY = ey
else
Tri:SetTexCoord(1, 0, 1, 1, 0, 0, 0, 1)
MinY = ey
MaxY = sy
end
--Has to be at least 1 wide
if MinY <= 1 then
MinY = 1
end
if self.xAxis then
local aa,bb,cc,dd,ee = self.xAxis:GetPoint()
local xAxisAlpha = dd-self.xAxis:GetWidth()
end
Bar:ClearAllPoints()
Bar:SetPoint("BOTTOMLEFT", C, "BOTTOMLEFT", sx, xAxisAlpha or 24)
local Width = ex - sx
if Width < 1 then
Width = 1
end
Bar:SetWidth(Width)
Bar:SetHeight(MinY-(xAxisAlpha or 24))
if (MaxY-MinY) >= 1 then
Tri:ClearAllPoints()
Tri:SetPoint("BOTTOMLEFT", C, "BOTTOMLEFT", sx, MinY)
Tri:SetWidth(Width)
Tri:SetHeight(MaxY - MinY)
--P:ClearAllPoints()
--P:SetPoint("BOTTOMLEFT", C, "BOTTOMLEFT", sx, MinY)
--P:SetWidth(Width)
--P:SetHeight(MaxY - MinY)
else
Tri:Hide()
--P:Hide()
end
end
function lib:HideBars(C)
if not C.GraphLib_Bars_Used then
return
end
for cat, val in pairs(C.GraphLib_Bars_Used) do
val:Hide()
end
end
function lib:HideLines(C)
if C.GraphLib_Lines then
for k,v in pairs(C.GraphLib_Lines) do
v[1]:Hide()
v[1].val = nil
v[1].label = nil
v[2]:Hide()
end
end
if C.ppoints then
for k,v in pairs(C.ppoints) do
v:Hide()
end
end
end
-- Custom stacked graphs inspired by google graph stacked charts
-- Author: Tom Dymel (Shino/Geigerkind/Albea)
-- Mail: tomdymel@web.de
-- Bitbucket: bitbucket.com/tomdy
-- Credit: Old Stacked graph, whoever created it. I guess the originally author of this library
-- Recycled lots of code from him
function lib:DrawBarNew(C, sx, sy, ex, ey, color, level, label)
local Bar, barNum, MinY, MaxY
--Want sx <= ex if not then flip them
if not C.GraphLib_Bars_Used then
C.GraphLib_Bars_Used = {}
C.GraphLib_Frames = {}
end
for k,v in pairs(C.GraphLib_Bars_Used) do
if not v:IsShown() and not Bar then
Bar=v;
Bar:Show();
end
end
if Bar then
Bar.label = label
end
if not Bar then
-- Create Tooltip
Bar = CreateFrame("Frame", C:GetName().."_BarTT"..(getn(C.GraphLib_Bars_Used)+1), C)
Bar:EnableMouse(true)
Bar.label = label
Bar.Texture = Bar:CreateTexture(nil, "ARTWORK")
Bar.Texture:SetTexture(1,1,1,1)
tinsert(C.GraphLib_Bars_Used, Bar)
end
if level then
if type(C.GraphLib_Frames[level]) == "nil" then
local newLevel = 100-level*0.1
if newLevel<1 then
newLevel = 1
end
C.GraphLib_Frames[level] = CreateFrame("Frame", nil, C)
C.GraphLib_Frames[level]:SetFrameLevel(newLevel)
C.GraphLib_Frames[level]:SetAllPoints(C)
end
Bar:SetParent(C.GraphLib_Frames[level])
end
Bar.Texture:SetVertexColor(color[1], color[2], color[3], color[4])
MinY = ey
--Has to be at least 1 wide
if MinY <= 1 then
MinY = 1
end
if self.xAxis then
local aa,bb,cc,dd,ee = self.xAxis:GetPoint()
local xAxisAlpha = dd-self.xAxis:GetWidth()
end
local Width = ex - sx
local const = 24
if Width < 10 then
Width = 10
end
Bar:SetWidth(Width)
Bar:SetHeight(MinY)
Bar:ClearAllPoints()
Bar:SetPoint("BOTTOMLEFT", C, "BOTTOMLEFT", sx, const)
Bar.Texture:SetWidth(Width)
Bar.Texture:SetHeight(MinY)
Bar.Texture:ClearAllPoints()
Bar.Texture:SetPoint("BOTTOMLEFT", C, "BOTTOMLEFT", sx, const)
Bar:SetScript("OnEnter", function()
if Bar.label then
GameTooltip:SetOwner(Bar, "TOPLEFT")
GameTooltip:AddLine(Bar.label)
GameTooltip:Show()
end
end)
Bar:SetScript("OnLeave", function()
GameTooltip:Hide()
end)
end
function GraphFunctions:RefreshStackedBarGraph()
self:HideLines(self)
self:HideBars(self)
-- Format table
-- Max it to 100 timestamps
-- Issue if less than 100 => Dynamicly increase width
local DataTable = {}
local CAP = 100
local space, mX, mN
-- Step 1: Get Highest Number of Bars
for k1, series in pairs(self.Data) do
for c,v in pairs(series.Points) do
local num = 0
for k2, point in pairs(v) do
num = num + 1
if not mX or point[1]>mX then
mX = point[1]
end
end
if not mN or num>mN then
mN = num
end
end
end
-- Step 2: Compare with CAP and create dummy table
if not mN then
return
end
if mN>CAP then
mN = CAP
end
space = (mX-1)/mN
local taken = {}
for k1, series in pairs(self.Data) do
if not DataTable[k1] then
DataTable[k1] = {}
taken[k1] = {}
end
for c,v in pairs(series.Points) do
if not DataTable[k1][c] then
DataTable[k1][c] = {}
taken[k1][c] = {}
end
for i=1,mN do
DataTable[k1][c][i] = {i*space+1,0}
end
for k2, point in pairs(v) do
for i=1,mN do
if point[1]>=((i-1)*space+1) and point[1]<(i*space+1) and not taken[k1][c][k2] then
DataTable[k1][c][i] = {i*space+1, DataTable[k1][c][i][2] + point[2]}
taken[k1][c][k2] = true
end
end
end
for k2, point in pairs(v) do
if not taken[k1][c][k2] then
DataTable[k1][c][mN] = {mN*space+1, DataTable[k1][c][mN][2] + point[2]}
taken[k1][c][k2] = true
end
end
end
end
taken = nil
local Width=self:GetWidth()
local Height=self:GetHeight()
if self.AutoScale and self.Data then -- math_huge not implemented
local MinX, MaxX, MinY, MaxY
local temp = {}
for k1, series in pairs(DataTable) do
for c,v in pairs(series) do
for k2, point in pairs(v) do
if temp[k2] then
temp[k2] = temp[k2] + point[2]
else
temp[k2] = point[2]
end
if not MinX or point[1]<MinX then MinX = point[1] end
if not MinY or temp[k2]<MinY then MinY = temp[k2] end
if not MaxX or point[1]>MaxX then MaxX = point[1] end
if not MaxY or temp[k2]>MaxY then MaxY = temp[k2] end
end
end
end
local XBorder, YBorder
XBorder=(60/Width)*MaxX
YBorder=(24/Height)*MaxY
self.XBorder=XBorder
self.YBorder = YBorder
self.YGridInterval = MaxY/7
self.XGridInterval = MaxX/7
MinX=0+XBorder
if not self.LockOnXMin then
self.XMin=MinX-XBorder
end
if not self.LockOnXMax then
self.XMax=MaxX
end
if not self.LockOnYMin then
self.YMin=MinY-YBorder
end
if not self.LockOnYMax then
self.YMax=MaxY+YBorder
end
end
self:CreateGridlines()
for k1, series in pairs(DataTable) do
for c,v in pairs(series) do
if v[1] then
local LastPoint = {x=50,y=0}
local num = getn(v)
for i=1,num do
local point = v[i]
local TPoint={x=point[1];y=point[2]}
TPoint.x=Width*(TPoint.x-self.XMin)/(self.XMax-self.XMin)
if point[2]>0 then
local label = 0
for uu=1, (c-1) do
if DataTable[k1][uu][i] then
label = label + DataTable[k1][uu][i][2]
end
end
TPoint.y=(Height-24)*(TPoint.y+label)/(self.YMax-self.YBorder)
local CT
if colorByAbility[self.Data[k1].Label[c]] then
CT = colorByAbility[self.Data[k1].Label[c]]
end
if not CT and ColorTable[c] then
CT = ColorTable[c]
end
if not ColorTable[c] and not CT then
ColorTable[c] = {0.01*math_random(0,100),0.01*math_random(0,100),0.01*math_random(0,100),1}
CT = ColorTable[c]
end
colorByAbility[self.Data[k1].Label[c]] = CT
self:DrawBar(self, LastPoint.x, LastPoint.y, TPoint.x, TPoint.y, CT, c, self.Data[k1].Label[c]..": "..ceil(point[2] or 0))
end
LastPoint = {x=TPoint.x;y=TPoint.y}
end
end
end
end
end
function lib:CreateStackedGraph(name,parent,relative,relativeTo,offsetX,offsetY,Width,Height)
local graph
local i
graph = CreateFrame("Frame",name,parent)
graph:SetPoint(relative,parent,relativeTo,offsetX,offsetY)
graph:SetWidth(Width)
graph:SetHeight(Height)
graph:Show()
--Set the various functions
graph.SetXAxis=GraphFunctions.SetXAxis
graph.SetYAxis=GraphFunctions.SetYAxis
graph.AddDataSeries=GraphFunctions.AddDataSeries
graph.ResetData=GraphFunctions.ResetData
graph.RefreshGraph=GraphFunctions.RefreshStackedBarGraph
graph.CreateGridlines=GraphFunctions.CreateGridlines
graph.SetAxisDrawing=GraphFunctions.SetAxisDrawing
graph.SetGridSpacing=GraphFunctions.SetGridSpacing
graph.SetAxisColor=GraphFunctions.SetAxisColor
graph.SetGridColor=GraphFunctions.SetGridColor
graph.SetAutoScale=GraphFunctions.SetAutoScale
graph.SetYLabels=GraphFunctions.SetYLabels
graph.SetXLabels=GraphFunctions.SetXLabels
graph.OnUpdate=GraphFunctions.OnUpdateGraph
graph.LockXMin=GraphFunctions.LockXMin
graph.LockXMax=GraphFunctions.LockXMax
graph.LockYMin=GraphFunctions.LockYMin
graph.LockYMax=GraphFunctions.LockYMax
graph.FindNearValue=GraphFunctions.FindNearValue
graph.DrawLine=self.DrawLine
graph.DrawBar=self.DrawBarNew
graph.HideLines=self.HideLines
graph.HideBars=self.HideBars
graph.HideFontStrings=GraphFunctions.HideFontStrings
graph.FindFontString=GraphFunctions.FindFontString
graph.ShowFontStrings=GraphFunctions.ShowFontStrings
--Set the update function
graph:SetScript("OnUpdate", graph.OnUpdate)
graph.NeedsUpdate=false
--Initialize Data
graph.GraphType="STACKED_BAR"
graph.YMax=1
graph.YMin=0
graph.XMax=1
graph.XMin=0
graph.AxisColor={1.0,1.0,1.0,1.0}
graph.GridColor={0.5,0.5,0.5,0.5}
graph.XGridInterval=0.25
graph.YGridInterval=0.25
graph.XAxisDrawn=true
graph.YAxisDrawn=true
graph.LockOnXMin=false
graph.LockOnXMax=false
graph.LockOnYMin=false
graph.LockOnYMax=false
graph.Data={}
graph.DataPoints={}
return graph
end
AceLibrary:Register(lib, major, minor)
function TestStackedGraph()
local Graph=AceLibrary("Graph-1.0")
local g=Graph:CreateStackedGraph("TestStackedGraph",UIParent,"CENTER","CENTER",90,90,800,350)
local Data1={{{1,100},{1.2,110},{1.4,120},{1.6,130},{1.8,140},{2,150},{2.2,160},{2.4,170},{2.6,180},{2.8,190},{3,200},{3.2,190},{3.4,180},{3.6,170},{3.8,160},{4,150}},{{1,100},{1.2,110},{1.4,120},{1.6,130},{1.8,140},{2,150},{2.2,160},{2.4,170},{2.6,180},{2.8,190},{3,200},{3.2,190},{3.4,180},{3.6,170},{3.8,160},{4,150}}}
local label = {"a", "b","c", "d","e", "f","g", "h","i", "j","k", "l","m", "n","o", "p","q", "r","s", "t","u", "v","w", "x","y", "z","", "","", "","", "","", "","", "","", "","", "","", "","", "","", "","", "","", "","", "","", "","", "","", "","", ""}
g:SetXAxis(0,4)
g:SetYAxis(0,500)
g:SetGridSpacing(0.5,50)
g:SetGridColor({0.5,0.5,0.5,0.5})
g:SetAxisDrawing(true,true)
g:SetAxisColor({1.0,1.0,1.0,1.0})
g:SetAutoScale(true)
g:SetYLabels(true, false)
g:SetXLabels(true)
g:AddDataSeries(Data1,{1.0,0.0,0.0,0.8}, {}, label)
end
--Test Functions
--To test the library do /script AceLibrary("Graph-1.0");TestGraphLib()
function TestRealtimeGraph()
local Graph=AceLibrary("Graph-1.0")
RealGraph=Graph:CreateGraphRealtime("TestRealtimeGraph",UIParent,"CENTER","CENTER",-90,90,150,150)
local g=RealGraph
g:SetAutoScale(true)
g:SetGridSpacing(1.0,10.0)
g:SetYMax(120)
g:SetXAxis(-11,-1)
g:SetFilterRadius(1)
g:SetBarColors({0.2,0.0,0.0,0.4},{1.0,0.0,0.0,1.0})
local f = CreateFrame("Frame",name,parent)
f:SetScript("OnUpdate",function() g:AddTimeData(DPSMate.DB:GetAlpha()) end)
f:Show()
end
function TestLineGraph()
local Graph=AceLibrary("Graph-1.0")
local g=Graph:CreateGraphLine("TestLineGraph",UIParent,"CENTER","CENTER",90,90,150,150)
g:SetXAxis(-1,1)
g:SetYAxis(-1,1)
g:SetGridSpacing(0.25,0.25)
g:SetGridColor({0.5,0.5,0.5,0.5})
g:SetAxisDrawing(true,true)
g:SetAxisColor({1.0,1.0,1.0,1.0})
g:SetAutoScale(true)
local Data1={{0.05,0.05},{0.2,0.3},{0.4,0.2},{0.9,0.6}}
local Data2={{0.05,0.8},{0.3,0.1},{0.5,0.4},{0.95,0.05}}
g:AddDataSeries(Data1,{1.0,0.0,0.0,0.8})
g:AddDataSeries(Data2,{0.0,1.0,0.0,0.8})
end
function TestScatterPlot()
local Graph=AceLibrary("Graph-1.0")
local g=Graph:CreateGraphScatterPlot("TestScatterPlot",UIParent,"CENTER","CENTER",90,-90,150,150)
g:SetXAxis(-1,1)
g:SetYAxis(-1,1)
g:SetGridSpacing(0.25,0.25)
g:SetGridColor({0.5,0.5,0.5,0.5})
g:SetAxisDrawing(true,true)
g:SetAxisColor({1.0,1.0,1.0,1.0})
g:SetLinearFit(true)
g:SetAutoScale(true)
local Data1={{0.05,0.05},{0.2,0.3},{0.4,0.2},{0.9,0.6}}
local Data2={{0.05,0.8},{0.3,0.1},{0.5,0.4},{0.95,0.05}}
g:AddDataSeries(Data1,{1.0,0.0,0.0,0.8})
g:AddDataSeries(Data2,{0.0,1.0,0.0,0.8})
end
function TestPieChart()
local Graph=AceLibrary("Graph-1.0")
local g=Graph:CreateGraphPieChart("TestPieChart",UIParent,"CENTER","CENTER",-90,-90,150,150)
g:AddPie(35,{1.0,0.0,0.0})
g:AddPie(15,{0.0,1.0,0.0})
g:AddPie(50,{1.0,1.0,1.0})
end
function TestGraphLib()
--TestRealtimeGraph()
TestLineGraph()
--TestScatterPlot()
--TestPieChart()
end | gpl-3.0 |
greasydeal/darkstar | scripts/zones/Southern_San_dOria/npcs/Adaunel.lua | 17 | 1598 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Adaunel
-- General Info NPC
-- @zone 230
-- @pos 80 -7 -22
------------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Southern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if(player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED)then
if(trade:hasItemQty(532,1) and trade:getItemCount() == 1 and player:getVar("tradeAdaunel") == 0)then
player:messageSpecial(8709);
player:setVar("FFR",player:getVar("FFR") - 1);
player:setVar("tradeAdaunel",1);
player:messageSpecial(FLYER_ACCEPTED);
trade:complete();
elseif(player:getVar("tradeAdaunel") ==1)then
player:messageSpecial(8710);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x290);
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 |
gilzoide/hell | src/lua/hell.lua | 1 | 5286 | #!/usr/bin/env lua
--- @file hell.lua
-- The hell script executable
--[[
-- Copyright (C) 2015 Gil Barbosa Reis
-- This file is part of Hell.
--
-- Hell is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- Hell is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with Hell. If not, see <http://www.gnu.org/licenses/>.
--]]
local int = require 'hell.internals'
local util = require 'hell.utils'
-- get OS. As linux/freebsd/solaris are all alike, we gather them as unix.
-- note that MacOSX is called "darwin" here
local OSes = {
windows = {
prefix = os.getenv ("APPDATA"),
obj_ext = 'obj',
shared_ext = 'dll',
exe_ext = 'exe'
},
unix = {
prefix = '/usr',
obj_ext = 'o',
shared_ext = 'so',
exe_ext = ''
},
darwin = {
prefix = '/usr',
obj_ext = 'o',
shared_ext = 'dynlib',
exe_ext = ''
}
}
local os = OSes[int.cpp.getOS ()] or OSes.unix
-- OS name:
-- 'windows'
-- 'darwin'
-- 'unix'
os.name = int.cpp.getOS ()
-- OS processor architecture:
-- 'x86'
-- 'x86_64'
-- 'ia64'
-- 'ppc'
-- 'arm'
-- 'arm64'
-- 'mips'
-- 'unknown'
os.arch = int.cpp.getArch ()
os.dir_sep = package.config:sub (1, 1)
--[[ hell: the table that controls everything that's going on ]]--
hell = {
-- the custom help message. If nil/false, use default help string
help = nil,
-- output directory: used for 'shadow builds'
-- if nil/false, do the builds in the build scripts' own path
-- note that if `outdir = '.'`, hell uses the root script's path
outdir = nil,
-- Builder directory, from where hell loads it's Builders
builder_dir = nil,
-- table with some SO especific stuff
os = os,
-- let users use the utils!
utils = util
}
-- parse our opts, from arg
require 'hell.parseOpts'
-- extract hell opts
local opts = int.opts
-- require builder stuff
local BI = require 'hell.build_install'
require 'hell.Builder'
require 'hell.fireHandler'
--[[ And now, source our first hellbuild script.
It looks respectively into 'opts.file', './hellfire', './hellbuild' ]]--
-- first script to load
local script, err
local build_scripts = { './hellbuild', './hellfire', opts.f }
int.hellMsg ('reading build script(s)')
for i = #build_scripts, 1, -1 do
script, err = int._addHellBuild (build_scripts[i])
if not script then
if not err:match ('open') then
int.quit ("lua: " .. err, true)
end
else
break
end
end
local hellp = require 'hell.hellp'
-- well, let's say the user asked for help, ...
if opts.h then
-- ...but there's no hellbuild to source, no need to let him down, right?
if not script then
hellp ()
-- ...let's not read the entire build script tree
-- for custom help, just search until we find it
else
function hell.__newindex (t, k, v)
if k == 'help' then
hellp (v)
else
rawset (t, k, v)
end
end
setmetatable (hell, hell)
end
end
-- don't let script use require with hell's internals
package.path = oldpath
package.cpath = oldcpath
-- process root build script
int.assert_quit (script, "Can't find any build scripts. Tried \"" .. table.concat (build_scripts, '", "') .. '"')
int.cpp.startTimer ()
script ()
int.cpp.showElapsedTime ('Script reading')
-- remove root hellbuild from path, so commands are rightly executed
table.remove (int.path)
int.cpp.chdir (int.getPath (0))
int.hellMsg ("all set, let's see what we got\n")
-- Called for help, and no custom help appeared? No worries, print the default
if opts.h then
hellp ()
-- Or asked for Builder's hellp, so let's do it!
elseif opts.hb then
hellp (hellp.getBuilderHellp (opts.hb))
end
opts.target = opts.target or ''
local target = int.assert_quit (opts.target == '' or BI.targets[opts.target],
"Can't find target \"" .. opts.target .. '"')
-- maybe get available targets?
if opts.l then
int.hellMsg ("Listing available targets:")
BI.listTargets ()
return
end
-- Command to be executed (build | clean | install | uninstall)
if opts.command == 'build' or opts.command == 'clean' then
if opts.target ~= '' then
BI.builds = BI.getBI (target, 'build')
end
int.assert_quit (#BI.builds ~= 0, "Can't find any builds" .. (opts.target and ' in target "' .. opts.target .. '"' or ''))
-- if `clean`, then let's clean stuff instead of building
if opts.command == 'clean' then
BI.builds = BI.makeClean (BI.builds)
end
-- Process the builds in C++
int.cpp.processBI (BI.builds)
else -- opts.command == 'install' or opts.command == 'uninstall'
if opts.target ~= '' then
BI.installs = BI.getBI (target, 'install')
end
int.assert_quit (#BI.installs ~= 0, "Can't find any installs" .. (opts.target and ' in target "' .. opts.target .. '"' or ''))
-- if `uninstall`, then let's uninstall stuff instead of installing
if opts.command == 'uninstall' then
BI.installs = BI.makeClean (BI.installs)
end
-- Process the installs in C++
int.cpp.processBI (BI.installs)
end
| gpl-3.0 |
ibm2431/darkstar | scripts/zones/Aht_Urhgan_Whitegate/npcs/Waoud.lua | 9 | 7704 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Waoud
-- Standard Info NPC
-- Involved in quests: An Empty Vessel (BLU flag), Beginnings (BLU AF1)
-- !pos 65 -6 -78 50
-----------------------------------
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/missions")
require("scripts/globals/quests")
require("scripts/globals/npc_util")
local ID = require("scripts/zones/Aht_Urhgan_Whitegate/IDs")
-----------------------------------
function onTrade(player,npc,trade)
local anEmptyVessel = player:getQuestStatus(AHT_URHGAN,dsp.quest.id.ahtUrhgan.AN_EMPTY_VESSEL)
local anEmptyVesselProgress = player:getCharVar("AnEmptyVesselProgress")
local StoneID = player:getCharVar("EmptyVesselStone")
-- AN EMPTY VESSEL (dangruf stone, valkurm sunsand, or siren's tear)
if anEmptyVessel == QUEST_ACCEPTED and anEmptyVesselProgress == 3 and trade:hasItemQty(StoneID,1) and trade:getItemCount() == 1 then
player:startEvent(67,StoneID) -- get the stone to Aydeewa
end
end
function onTrigger(player,npc)
local anEmptyVessel = player:getQuestStatus(AHT_URHGAN,dsp.quest.id.ahtUrhgan.AN_EMPTY_VESSEL)
local anEmptyVesselProgress = player:getCharVar("AnEmptyVesselProgress")
local divinationReady = vanaDay() > player:getCharVar("LastDivinationDay")
local beginnings = player:getQuestStatus(AHT_URHGAN,dsp.quest.id.ahtUrhgan.BEGINNINGS)
-- AN EMPTY VESSEL
if ENABLE_TOAU == 1 and anEmptyVessel == QUEST_AVAILABLE and anEmptyVesselProgress <= 1 and player:getMainLvl() >= ADVANCED_JOB_LEVEL then
if divinationReady then
player:setCharVar("SuccessfullyAnswered",0)
player:startEvent(60,player:getGil()) -- you must answer these 10 questions
else
player:startEvent(63) -- you failed, and must wait a gameday to try again
end
elseif anEmptyVesselProgress == 2 then
if divinationReady and not player:needToZone() then
player:startEvent(65) -- gives you a clue about the stone he wants (specific conditions)
else -- Have not zoned, or have not waited, or both.
player:startEvent(64) -- you have succeeded, but you need to wait a gameday and zone
end
elseif anEmptyVesselProgress == 3 then
player:startEvent(66) -- reminds you about the item he wants
elseif anEmptyVesselProgress == 4 then
player:startEvent(68) -- reminds you to bring the item to Aydeewa
elseif anEmptyVessel == QUEST_COMPLETED and beginnings == QUEST_AVAILABLE and player:getCharVar("BluAFBeginnings_Waoud") == 0 then
player:startEvent(69) -- closing cutscene
-- BEGINNINGS
elseif anEmptyVessel == QUEST_COMPLETED and beginnings == QUEST_AVAILABLE and player:getCurrentMission(TOAU) > dsp.mission.id.toau.IMMORTAL_SENTRIES
and player:getMainJob() == dsp.job.BLU and player:getMainLvl() >= ADVANCED_JOB_LEVEL then
if not divinationReady then
player:startEvent(63)
elseif player:needToZone() then
player:startEvent(78,player:getGil()) -- dummy questions, costs you 1000 gil
else
player:startEvent(705,player:getGil()) -- start AF1 quest
end
elseif beginnings == QUEST_ACCEPTED then
local brand1 = player:hasKeyItem(dsp.ki.BRAND_OF_THE_SPRINGSERPENT)
local brand2 = player:hasKeyItem(dsp.ki.BRAND_OF_THE_GALESERPENT)
local brand3 = player:hasKeyItem(dsp.ki.BRAND_OF_THE_FLAMESERPENT)
local brand4 = player:hasKeyItem(dsp.ki.BRAND_OF_THE_SKYSERPENT)
local brand5 = player:hasKeyItem(dsp.ki.BRAND_OF_THE_STONESERPENT)
if brand1 and brand2 and brand3 and brand4 and brand5 then
player:startEvent(707) -- reward immortal's scimitar
else
player:startEvent(706,player:getGil()) -- clue about the five staging points, costs you 1000 gil
end
-- DEFAULT DIALOG
else
player:startEvent(61)
end
end
function onEventUpdate(player,csid,option)
-- AN EMPTY VESSEL
if csid == 60 then
local success = player:getCharVar("SuccessfullyAnswered")
-- record correct answers
if option < 40 then
local correctAnswers = {2,6,9,12,13,18,21,24,26,30}
for k,v in pairs(correctAnswers) do
if (v == option) then
player:setCharVar("SuccessfullyAnswered", success + 1)
break
end
end
-- determine results
elseif option == 40 then
if success < 2 then player:updateEvent(player:getGil(),0,0,0,0,0,0,10) -- Springserpent
elseif success < 4 then player:updateEvent(player:getGil(),0,0,0,0,0,0,20) -- Stoneserpent
elseif success < 6 then player:updateEvent(player:getGil(),0,0,0,0,0,0,30) -- Galeserpent
elseif success < 8 then player:updateEvent(player:getGil(),0,0,0,0,0,0,40) -- Flameserpent
elseif success < 10 then player:updateEvent(player:getGil(),0,0,0,0,0,0,60) -- Skyserpent
else
local rand = math.random(1,3)
switch (rand): caseof {
[1] = function (x) player:setCharVar("EmptyVesselStone",576) end, -- (576) Siren's Tear (576)
[2] = function (x) player:setCharVar("EmptyVesselStone",503) end, -- (502) Valkurm Sunsand (502)
[3] = function (x) player:setCharVar("EmptyVesselStone",553) end -- (553) Dangruf Stone (553)
}
player:setCharVar("SuccessfullyAnswered", 0)
player:updateEvent(player:getGil(),0,0,0,0,0,rand,70) -- all 5 serpents / success!
end
end
elseif csid == 65 and option == 2 then
player:setCharVar("AnEmptyVesselProgress",3)
-- BEGINNINGS
elseif csid == 78 and option == 40 then
local serpent = math.random(1,5) * 10
player:updateEvent(player:getGil(),0,0,0,0,0,0,serpent)
end
end
function onEventFinish(player,csid,option)
-- AN EMPTY VESSEL
if csid == 60 then
if option == 0 then
player:setCharVar("AnEmptyVesselProgress", 1)
elseif option == 50 then
player:needToZone(true)
player:setCharVar("LastDivinationDay",vanaDay())
player:setCharVar("AnEmptyVesselProgress",2)
player:addQuest(AHT_URHGAN,dsp.quest.id.ahtUrhgan.AN_EMPTY_VESSEL)
else
player:setCharVar("LastDivinationDay",vanaDay())
player:setCharVar("AnEmptyVesselProgress",1)
player:delGil(1000)
player:messageSpecial(ID.text.PAY_DIVINATION) -- You pay 1000 gil for the divination.
end
elseif csid == 67 then -- Turn in stone, go to Aydeewa
player:setCharVar("AnEmptyVesselProgress",4)
elseif csid == 69 and option == 1 then
player:needToZone(true)
player:setCharVar("LastDivinationDay",vanaDay())
player:setCharVar("BluAFBeginnings_Waoud",1)
-- BEGINNINGS
elseif csid == 78 and option == 1 then
player:setCharVar("LastDivinationDay",vanaDay())
player:delGil(1000)
player:messageSpecial(ID.text.PAY_DIVINATION) -- You pay 1000 gil for the divination.
elseif csid == 705 and option == 1 then
player:addQuest(AHT_URHGAN,dsp.quest.id.ahtUrhgan.BEGINNINGS)
elseif csid == 706 and option == 1 then
player:delGil(1000)
player:messageSpecial(ID.text.PAY_DIVINATION) -- You pay 1000 gil for the divination.
elseif csid == 707 then
npcUtil.completeQuest(player, AHT_URHGAN, dsp.quest.id.ahtUrhgan.BEGINNINGS, {item=17717})
end
end | gpl-3.0 |
LegionXI/darkstar | scripts/zones/Newton_Movalpolos/Zone.lua | 13 | 1778 | -----------------------------------
--
-- Zone: Newton_Movalpolos (12)
--
-----------------------------------
package.loaded["scripts/zones/Newton_Movalpolos/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Newton_Movalpolos/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
UpdateTreasureSpawnPoint(16826627);
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(451.895,26.214,-19.782,133);
end
return cs;
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
bittorf/luci | applications/luci-app-radvd/luasrc/model/cbi/radvd/prefix.lua | 61 | 3557 | -- Copyright 2010 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
local sid = arg[1]
local utl = require "luci.util"
m = Map("radvd", translatef("Radvd - Prefix"),
translate("Radvd is a router advertisement daemon for IPv6. " ..
"It listens to router solicitations and sends router advertisements " ..
"as described in RFC 4861."))
m.redirect = luci.dispatcher.build_url("admin/network/radvd")
if m.uci:get("radvd", sid) ~= "prefix" then
luci.http.redirect(m.redirect)
return
end
s = m:section(NamedSection, sid, "interface", translate("Prefix Configuration"))
s.addremove = false
s:tab("general", translate("General"))
s:tab("advanced", translate("Advanced"))
--
-- General
--
o = s:taboption("general", Flag, "ignore", translate("Enable"))
o.rmempty = false
function o.cfgvalue(...)
local v = Flag.cfgvalue(...)
return v == "1" and "0" or "1"
end
function o.write(self, section, value)
Flag.write(self, section, value == "1" and "0" or "1")
end
o = s:taboption("general", Value, "interface", translate("Interface"),
translate("Specifies the logical interface name this section belongs to"))
o.template = "cbi/network_netlist"
o.nocreate = true
o.optional = false
function o.formvalue(...)
return Value.formvalue(...) or "-"
end
function o.validate(self, value)
if value == "-" then
return nil, translate("Interface required")
end
return value
end
function o.write(self, section, value)
m.uci:set("radvd", section, "ignore", 0)
m.uci:set("radvd", section, "interface", value)
end
o = s:taboption("general", DynamicList, "prefix", translate("Prefixes"),
translate("Advertised IPv6 prefixes. If empty, the current interface prefix is used"))
o.optional = true
o.datatype = "ip6addr"
o.placeholder = translate("default")
function o.cfgvalue(self, section)
local l = { }
local v = m.uci:get_list("radvd", section, "prefix")
for v in utl.imatch(v) do
l[#l+1] = v
end
return l
end
o = s:taboption("general", Flag, "AdvOnLink", translate("On-link determination"),
translate("Indicates that this prefix can be used for on-link determination (RFC4861)"))
o.rmempty = false
o.default = "1"
o = s:taboption("general", Flag, "AdvAutonomous", translate("Autonomous"),
translate("Indicates that this prefix can be used for autonomous address configuration (RFC4862)"))
o.rmempty = false
o.default = "1"
--
-- Advanced
--
o = s:taboption("advanced", Flag, "AdvRouterAddr", translate("Advertise router address"),
translate("Indicates that the address of interface is sent instead of network prefix, as is required by Mobile IPv6"))
o = s:taboption("advanced", Value, "AdvValidLifetime", translate("Valid lifetime"),
translate("Advertises the length of time in seconds that the prefix is valid for the purpose of on-link determination."))
o.datatype = 'or(uinteger,"infinity")'
o.placeholder = 86400
o = s:taboption("advanced", Value, "AdvPreferredLifetime", translate("Preferred lifetime"),
translate("Advertises the length of time in seconds that addresses generated from the prefix via stateless address autoconfiguration remain preferred."))
o.datatype = 'or(uinteger,"infinity")'
o.placeholder = 14400
o = s:taboption("advanced", Value, "Base6to4Interface", translate("6to4 interface"),
translate("Specifies a logical interface name to derive a 6to4 prefix from. The interfaces public IPv4 address is combined with 2002::/3 and the value of the prefix option"))
o.template = "cbi/network_netlist"
o.nocreate = true
o.unspecified = true
return m
| apache-2.0 |
ibm2431/darkstar | scripts/globals/spells/bluemagic/feather_barrier.lua | 12 | 1203 | -----------------------------------------
-- Spell: Feather Barrier
-- Enhances evasion
-- Spell cost: 29 MP
-- Monster Type: Birds
-- Spell Type: Magical (Wind)
-- Blue Magic Points: 2
-- Stat Bonus: None
-- Level: 56
-- Casting Time: 2 seconds
-- Recast Time: 120 seconds
-- Duration: 30 Seconds
--
-- Combos: Resist Gravity
-----------------------------------------
require("scripts/globals/bluemagic")
require("scripts/globals/status")
require("scripts/globals/magic")
require("scripts/globals/msg")
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0
end
function onSpellCast(caster,target,spell)
local typeEffect = dsp.effect.EVASION_BOOST
local power = 10
local duration = 30
if (caster:hasStatusEffect(dsp.effect.DIFFUSION)) then
local diffMerit = caster:getMerit(dsp.merit.DIFFUSION)
if (diffMerit > 0) then
duration = duration + (duration/100)* diffMerit
end
caster:delStatusEffect(dsp.effect.DIFFUSION)
end
if (target:addStatusEffect(typeEffect,power,0,duration) == false) then
spell:setMsg(dsp.msg.basic.MAGIC_NO_EFFECT)
end
return typeEffect
end
| gpl-3.0 |
ibm2431/darkstar | scripts/zones/Stellar_Fulcrum/mobs/Kamlanaut.lua | 9 | 1220 | -----------------------------------
-- Area: Stellar Fulcrum
-- Mob: Kam'lanaut
-- Zilart Mission 8 BCNM Fight
-----------------------------------
require("scripts/globals/titles");
require("scripts/globals/status");
require("scripts/globals/magic");
local blades = {823, 826, 828, 825, 824, 827};
-----------------------------------
function onMobFight(mob, target)
local changeTime = mob:getLocalVar("changeTime");
local element = mob:getLocalVar("element");
if (changeTime == 0) then
mob:setLocalVar("changeTime",math.random(1,3)*15)
return;
end
if (mob:getBattleTime() >= changeTime) then
local newelement = element;
while (newelement == element) do
newelement = math.random(1,6);
end
if (element ~= 0) then
mob:delMod(dsp.magic.absorbMod[element], 100);
end
mob:useMobAbility(blades[newelement]);
mob:addMod(dsp.magic.absorbMod[newelement], 100);
mob:setLocalVar("changeTime", mob:getBattleTime() + math.random(1,3)*15);
mob:setLocalVar("element", newelement);
end
end;
function onMobDeath(mob, player, isKiller)
player:addTitle(dsp.title.DESTROYER_OF_ANTIQUITY);
end;
| gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.