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 |
|---|---|---|---|---|---|
valhallaGaming/uno | src_trunk/resources/gatekeepers-system/s_hunter.lua | 1 | 16035 | -- ////////////////////////////////////
-- // MYSQL //
-- ////////////////////////////////////
sqlUsername = exports.mysql:getMySQLUsername()
sqlPassword = exports.mysql:getMySQLPassword()
sqlDB = exports.mysql:getMySQLDBName()
sqlHost = exports.mysql:getMySQLHost()
sqlPort = exports.mysql:getMySQLPort()
handler = mysql_connect(sqlHost, sqlUsername, sqlPassword, sqlDB, sqlPort)
function checkMySQL()
if not (mysql_ping(handler)) then
handler = mysql_connect(sqlHost, sqlUsername, sqlPassword, sqlDB, sqlPort)
end
end
setTimer(checkMySQL, 300000, 0)
function closeMySQL()
if (handler~=nil) then
mysql_close(handler)
end
end
addEventHandler("onResourceStop", getResourceRootElement(getThisResource()), closeMySQL)
-- ////////////////////////////////////
-- // MYSQL END //
-- ////////////////////////////////////
local huntersCar = createVehicle ( 506, 618.575193, -74.190429, 997.69464, 0, 0, 110, "D34M0N")
exports.pool:allocateElement(huntersCar)
setVehicleLocked(huntersCar, true)
setVehicleFrozen(huntersCar, true)
setVehicleDamageProof(huntersCar, true)
setElementDimension(huntersCar, 1001)
setElementInterior(huntersCar, 2)
hunter = createPed (250, 616.162109, -75.3720, 997.99)
exports.pool:allocateElement(hunter)
setPedRotation (hunter, 300)
setElementData(hunter, "rotation", getPedRotation(hunter), false)
setPedFrozen(hunter, true)
setElementInterior (hunter, 2)
setElementDimension (hunter, 1001)
setPedAnimation(hunter, "CAR_CHAT", "car_talkm_loop", -1, true, false, true) -- Set the Peds Animation.
setElementData (hunter, "activeConvo", 0) -- Set the convo state to 0 so people can start talking to him.
setElementData(hunter, "name", "Hunter")
setElementData(hunter, "talk", true)
local hunterBlockGarage = createObject ( 8171, 608.9248, -75.0812, 1000.9953, 0, 270 )
exports.pool:allocateElement(hunterBlockGarage)
setElementDimension(hunterBlockGarage, 1001)
setElementInterior(hunterBlockGarage, 2)
function hunterIntro () -- When player enters the colSphere create GUI with intro output to all local players as local chat.
-- Give the player the "Find Hunter" achievement.
if(getElementData(hunter, "activeConvo")==1)then
outputChatBox("Hunter doesn't want to talk to you.", source, 255, 0, 0)
else
local query = mysql_query(handler, "SELECT hunter FROM characters WHERE charactername='" .. mysql_escape_string(handler, getPlayerName(source)) .."'")
local huntersFriend = tonumber(mysql_result(query, 1, 1))
mysql_free_result(query)
if(huntersFriend==1)then -- If they are already a friend.
local pedX, pedY, pedZ = getElementPosition( hunter )
local chatSphere = createColSphere( pedX, pedY, pedZ, 10 )
exports.pool:allocateElement(chatSphere) -- Create the colSphere for chat output to local players
local targetPlayers = getElementsWithinColShape( chatSphere, "player" )
for i, player in ipairs( targetPlayers ) do
outputChatBox("Hunter says: Hey, man. I'll call you when I got some work for you.", player, 255, 255, 255)
end
destroyElement(chatSphere)
else -- If they are not a friend.
triggerClientEvent ( source, "hunterIntroEvent", getRootElement()) -- Trigger Client side function to create GUI.
local pedX, pedY, pedZ = getElementPosition( hunter )
local chatSphere = createColSphere( pedX, pedY, pedZ, 10 )
exports.pool:allocateElement(chatSphere) -- Create the colSphere for chat output to local players
local targetPlayers = getElementsWithinColShape( chatSphere, "player" )
for i, player in ipairs( targetPlayers ) do
outputChatBox("* A muscular man works under the car's hood.", player, 255, 51, 102)
end
destroyElement(chatSphere)
setElementData (hunter, "activeConvo", 1) -- set the NPCs conversation state to active so no one else can begin to talk to him.
talkingToHunter = source
addEventHandler("onPlayerQuit", source, resetHunterConvoStateDelayed)
addEventHandler("onPlayerWasted", source, resetHunterConvoStateDelayed)
end
end
end
addEvent( "startHunterConvo", true )
addEventHandler( "startHunterConvo", getRootElement(), hunterIntro )
-- Statement 2
function statement2_S()
-- Output the text from the last option to all player in radius
local pedX, pedY, pedZ = getElementPosition( source )
local chatSphere = createColSphere( pedX, pedY, pedZ, 10 )
exports.pool:allocateElement(chatSphere) -- Create the colSphere for chat output to local players
local targetPlayers = getElementsWithinColShape( chatSphere, "player" )
local name = string.gsub(getPlayerName(source), "_", " ")
for i, player in ipairs( targetPlayers ) do
outputChatBox(name .. " says: Hey. I'm looking for a mechanic to change a spark plug.", player, 255, 255, 255) -- Players response to last question
outputChatBox("Hunter says: I'm busy. There's a place on ... that can do it.", player, 255, 255, 255) -- Hunter's next question
end
destroyElement (chatSphere)
resetHunterConvoStateDelayed()
end
addEvent( "hunterStatement2ServerEvent", true )
addEventHandler( "hunterStatement2ServerEvent", getRootElement(), statement2_S )
-- Statement 3
function statement3_S()
-- Output the text from the last option to all player in radius
local pedX, pedY, pedZ = getElementPosition( source )
local chatSphere = createColSphere( pedX, pedY, pedZ, 10 )
exports.pool:allocateElement(chatSphere) -- Create the colSphere for chat output to local players
local targetPlayers = getElementsWithinColShape( chatSphere, "player" )
local name = string.gsub(getPlayerName(source), "_", " ")
for i, player in ipairs( targetPlayers ) do
outputChatBox(name .. " says: Nice ride. Is it yours?", player, 255, 255, 255) -- Players response to last question
outputChatBox("Hunter says: It sure is.", player, 255, 255, 255) -- Hunter's next question
end
destroyElement (chatSphere)
end
addEvent( "hunterStatement3ServerEvent", true )
addEventHandler( "hunterStatement3ServerEvent", getRootElement(), statement3_S )
-- Statement 4
function statement4_S()
-- Output the text from the last option to all player in radius
local pedX, pedY, pedZ = getElementPosition( source )
local chatSphere = createColSphere( pedX, pedY, pedZ, 10 )
exports.pool:allocateElement(chatSphere) -- Create the colSphere for chat output to local players
local targetPlayers = getElementsWithinColShape( chatSphere, "player" )
local name = string.gsub(getPlayerName(source), "_", " ")
for i, player in ipairs( targetPlayers ) do
outputChatBox(name .. " says: Whatcha running under there?", player, 255, 255, 255) -- Players response to last question
outputChatBox("Hunter says: Sport air intake, NOS, fogger system and a T4 turbo. But you wouldn't know much about that, would you?", player, 255, 255, 255) -- Hunter's next question
end
destroyElement (chatSphere)
end
addEvent( "hunterStatement4ServerEvent", true )
addEventHandler( "hunterStatement4ServerEvent", getRootElement(), statement4_S )
-- Statement 5
function statement5_S()
-- Output the text from the last option to all player in radius
local pedX, pedY, pedZ = getElementPosition( source )
local chatSphere = createColSphere( pedX, pedY, pedZ, 10 )
exports.pool:allocateElement(chatSphere) -- Create the colSphere for chat output to local players
local targetPlayers = getElementsWithinColShape( chatSphere, "player" )
local name = string.gsub(getPlayerName(source), "_", " ")
for i, player in ipairs( targetPlayers ) do
outputChatBox(name .. " says: I like the paint job.", player, 255, 255, 255) -- Players response to last question
outputChatBox("Hunter says: It's not about how it looks, man. This car will rip your insides out and throw em at you, rookie.", player, 255, 255, 255) -- Hunter's next question
end
destroyElement (chatSphere)
resetHunterConvoStateDelayed()
end
addEvent( "hunterStatement5ServerEvent", true )
addEventHandler( "hunterStatement5ServerEvent", getRootElement(), statement5_S )
-- Statement 6
function statement6_S()
-- Output the text from the last option to all player in radius
local pedX, pedY, pedZ = getElementPosition( source )
local chatSphere = createColSphere( pedX, pedY, pedZ, 10 )
exports.pool:allocateElement(chatSphere) -- Create the colSphere for chat output to local players
local targetPlayers = getElementsWithinColShape( chatSphere, "player" )
local name = string.gsub(getPlayerName(source), "_", " ")
for i, player in ipairs( targetPlayers ) do
outputChatBox(name .. " says: Looks like all show and no go to me.", player, 255, 255, 255) -- Players response to last question
outputChatBox("Hunter says: Just goes to show you aren't a real gear head. Come back when you have a clue.", player, 255, 255, 255) -- Hunter's next question
end
destroyElement (chatSphere)
resetHunterConvoStateDelayed()
end
addEvent( "hunterStatement6ServerEvent", true )
addEventHandler( "hunterStatement6ServerEvent", getRootElement(), statement6_S )
-- Statement 7
function statement7_S()
-- Output the text from the last option to all player in radius
local pedX, pedY, pedZ = getElementPosition( source )
local chatSphere = createColSphere( pedX, pedY, pedZ, 10 )
exports.pool:allocateElement(chatSphere) -- Create the colSphere for chat output to local players
local targetPlayers = getElementsWithinColShape( chatSphere, "player" )
local name = string.gsub(getPlayerName(source), "_", " ")
for i, player in ipairs( targetPlayers ) do
outputChatBox(name .. " says: Is that an AIC controller? ...And direct port nitrous injection?", player, 255, 255, 255) -- Players response to last question
outputChatBox("Hunter says: You almost sound like you know what you're talking about.", player, 255, 255, 255) -- Hunter's next question
end
destroyElement (chatSphere)
end
addEvent( "hunterStatement7ServerEvent", true )
addEventHandler( "hunterStatement7ServerEvent", getRootElement(), statement7_S )
-- Statement 8
function statement8_S()
-- Output the text from the last option to all player in radius
local pedX, pedY, pedZ = getElementPosition( source )
local chatSphere = createColSphere( pedX, pedY, pedZ, 10 )
exports.pool:allocateElement(chatSphere) -- Create the colSphere for chat output to local players
local targetPlayers = getElementsWithinColShape( chatSphere, "player" )
local name = string.gsub(getPlayerName(source), "_", " ")
for i, player in ipairs( targetPlayers ) do
outputChatBox(name .. " says: There's nothing better than living a quarter mile at a time.", player, 255, 255, 255) -- Players response to last question
outputChatBox("Hunter says: Oh, you're a racer? They call me Hunter. I got a real name but unless you're the government you don't need to know it.", player, 255, 255, 255) -- Hunter's next question
end
destroyElement (chatSphere)
end
addEvent( "hunterStatement8ServerEvent", true )
addEventHandler( "hunterStatement8ServerEvent", getRootElement(), statement8_S )
-- Statement 9
function statement9_S()
-- Output the text from the last option to all player in radius
local pedX, pedY, pedZ = getElementPosition( source )
local chatSphere = createColSphere( pedX, pedY, pedZ, 10 )
exports.pool:allocateElement(chatSphere) -- Create the colSphere for chat output to local players
local targetPlayers = getElementsWithinColShape( chatSphere, "player" )
local name = string.gsub(getPlayerName(source), "_", " ")
for i, player in ipairs( targetPlayers ) do
outputChatBox(name .. " says: You work here alone?", player, 255, 255, 255) -- Players response to last question
outputChatBox("Hunter says: Yeah so I got work to do. Nice talkin' to ya.", player, 255, 255, 255) -- Hunter's next question
end
destroyElement (chatSphere)
resetHunterConvoStateDelayed()
end
addEvent( "hunterStatement9ServerEvent", true )
addEventHandler( "hunterStatement9ServerEvent", getRootElement(), statement9_S )
-- Statement 10
function statement10_S()
-- Output the text from the last option to all player in radius
local pedX, pedY, pedZ = getElementPosition( source )
local chatSphere = createColSphere( pedX, pedY, pedZ, 10 )
exports.pool:allocateElement(chatSphere) -- Create the colSphere for chat output to local players
local targetPlayers = getElementsWithinColShape( chatSphere, "player" )
local name = string.gsub(getPlayerName(source), "_", " ")
for i, player in ipairs( targetPlayers ) do
outputChatBox(name .. " says: My mother taught me never to trust a man that won't even tell you his name.", player, 255, 255, 255) -- Players response to last question
outputChatBox("Hunter says: Well here's the thing. One of my usual guys got busted a couple days ago.", player, 255, 255, 255) -- Hunter's next question
outputChatBox("If you're looking to make some money I could use a new go to guy.", player, 255, 255, 255)
outputChatBox("Hunter says: See running a car like this isn't cheap so we ...borrow from other cars if you know what I'm saying.", player, 255, 255, 255) -- Hunter's next question
end
destroyElement (chatSphere)
end
addEvent( "hunterStatement10ServerEvent", true )
addEventHandler( "hunterStatement10ServerEvent", getRootElement(), statement10_S )
-- Statement 11
function statement11_S()
-- Output the text from the last option to all player in radius
local pedX, pedY, pedZ = getElementPosition( source )
local chatSphere = createColSphere( pedX, pedY, pedZ, 10 )
exports.pool:allocateElement(chatSphere) -- Create the colSphere for chat output to local players
local targetPlayers = getElementsWithinColShape( chatSphere, "player" )
local name = string.gsub(getPlayerName(source), "_", " ")
for i, player in ipairs( targetPlayers ) do
outputChatBox(name .. " says: Sounds like easy money. Give me a call.", player, 255, 255, 255) -- Players response to last question
outputChatBox("Hunter says: You can expect my call. I might see you on the circuit some time too.", player, 255, 255, 255) -- Hunter's next question
exports.global:sendLocalMeAction( source,"jots down their number on a scrap of paper and hands it to Hunter.")
end
destroyElement (chatSphere)
resetHunterConvoStateDelayed()
local query = mysql_query(handler, "UPDATE characters SET hunter='1' WHERE charactername='" .. mysql_escape_string(handler, getPlayerName(source)) .. "' LIMIT 1")
mysql_free_result(query)
end
addEvent( "hunterStatement11ServerEvent", true )
addEventHandler( "hunterStatement11ServerEvent", getRootElement(), statement11_S )
-- Statement 12
function statement12_S()
-- Output the text from the last option to all player in radius
local pedX, pedY, pedZ = getElementPosition( source )
local chatSphere = createColSphere( pedX, pedY, pedZ, 10 )
exports.pool:allocateElement(chatSphere) -- Create the colSphere for chat output to local players
local targetPlayers = getElementsWithinColShape( chatSphere, "player" )
local name = string.gsub(getPlayerName(source), "_", " ")
for i, player in ipairs( targetPlayers ) do
outputChatBox(name .. " says: . I'd rather not get involved in all that.", player, 255, 255, 255) -- Players response to last question
outputChatBox("Hunter says: Whatever. I got work to do.", player, 255, 255, 255) -- Hunter's next question
end
destroyElement (chatSphere)
resetHunterConvoStateDelayed()
end
addEvent( "hunterStatement12ServerEvent", true )
addEventHandler( "hunterStatement12ServerEvent", getRootElement(), statement12_S )
function resetHunterConvoState()
setElementData(hunter, "activeConvo", 0)
end
function resetHunterConvoStateDelayed()
if talkingToHunter then
removeEventHandler("onPlayerQuit", talkingToHunter, resetHunterConvoStateDelayed)
removeEventHandler("onPlayerWasted", talkingToHunter, resetHunterConvoStateDelayed)
talkingToHunter = nil
end
setTimer(resetHunterConvoState, 360000, 1)
end
| bsd-3-clause |
mercury233/ygopro-scripts | c88757791.lua | 2 | 2713 | --法眼の魔術師
function c88757791.initial_effect(c)
--pendulum summon
aux.EnablePendulumAttribute(c)
--change scale
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(88757791,0))
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_PZONE)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET)
e2:SetCountLimit(1)
e2:SetTarget(c88757791.sctg)
e2:SetOperation(c88757791.scop)
c:RegisterEffect(e2)
--indes
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS)
e3:SetCode(EVENT_SPSUMMON_SUCCESS)
e3:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e3:SetOperation(c88757791.sumsuc)
c:RegisterEffect(e3)
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_FIELD)
e4:SetCode(EFFECT_INDESTRUCTABLE_EFFECT)
e4:SetRange(LOCATION_MZONE)
e4:SetTargetRange(LOCATION_MZONE,0)
e4:SetCondition(c88757791.indcon)
e4:SetTarget(c88757791.indtg)
e4:SetValue(aux.indoval)
c:RegisterEffect(e4)
end
function c88757791.cfilter(c,tp)
return c:IsType(TYPE_PENDULUM) and not c:IsPublic()
and Duel.IsExistingTarget(c88757791.scfilter,tp,LOCATION_PZONE,0,1,nil,c)
end
function c88757791.scfilter(c,pc)
return c:IsSetCard(0x98) and c:GetLeftScale()~=pc:GetLeftScale()
end
function c88757791.sctg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsControler(tp) and chkc:IsLocation(LOCATION_PZONE) and c88757791.scfilter(chkc,e:GetLabelObject()) end
if chk==0 then return Duel.IsExistingMatchingCard(c88757791.cfilter,tp,LOCATION_HAND,0,1,nil,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_CONFIRM)
local cg=Duel.SelectMatchingCard(tp,c88757791.cfilter,tp,LOCATION_HAND,0,1,1,nil,tp)
Duel.ConfirmCards(1-tp,cg)
Duel.ShuffleHand(tp)
e:SetLabelObject(cg:GetFirst())
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TARGET)
Duel.SelectTarget(tp,c88757791.scfilter,tp,LOCATION_PZONE,0,1,1,nil,cg:GetFirst())
end
function c88757791.scop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
local pc=e:GetLabelObject()
if tc:IsRelateToEffect(e) then
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CHANGE_LSCALE)
e1:SetValue(pc:GetLeftScale())
e1:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END)
tc:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetCode(EFFECT_CHANGE_RSCALE)
e2:SetValue(pc:GetRightScale())
tc:RegisterEffect(e2)
end
end
function c88757791.sumsuc(e,tp,eg,ep,ev,re,r,rp)
e:GetHandler():RegisterFlagEffect(88757791,RESET_EVENT+0x1ec0000+RESET_PHASE+PHASE_END,0,1)
end
function c88757791.indcon(e)
local c=e:GetHandler()
return c:GetFlagEffect(88757791)~=0 and c:IsSummonType(SUMMON_TYPE_PENDULUM)
end
function c88757791.indtg(e,c)
return c:IsSetCard(0x98) and c:IsType(TYPE_PENDULUM)
end
| gpl-2.0 |
mercury233/ygopro-scripts | c9888196.lua | 6 | 4233 | --A・O・J ディサイシブ・アームズ
function c9888196.initial_effect(c)
--synchro summon
aux.AddSynchroProcedure(c,nil,aux.NonTuner(nil),2)
c:EnableReviveLimit()
--destroy1
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(9888196,0))
e1:SetCategory(CATEGORY_DESTROY)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetCountLimit(1,EFFECT_COUNT_CODE_SINGLE)
e1:SetRange(LOCATION_MZONE)
e1:SetCondition(c9888196.con)
e1:SetTarget(c9888196.destg1)
e1:SetOperation(c9888196.desop1)
c:RegisterEffect(e1)
--destroy2
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(9888196,1))
e2:SetCategory(CATEGORY_DESTROY)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetCountLimit(1,EFFECT_COUNT_CODE_SINGLE)
e2:SetRange(LOCATION_MZONE)
e2:SetCondition(c9888196.con)
e2:SetCost(c9888196.descost2)
e2:SetTarget(c9888196.destg2)
e2:SetOperation(c9888196.desop2)
c:RegisterEffect(e2)
--handes
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(9888196,2))
e3:SetCategory(CATEGORY_HANDES+CATEGORY_TOGRAVE+CATEGORY_DAMAGE)
e3:SetType(EFFECT_TYPE_IGNITION)
e3:SetCountLimit(1,EFFECT_COUNT_CODE_SINGLE)
e3:SetRange(LOCATION_MZONE)
e3:SetCondition(c9888196.con)
e3:SetCost(c9888196.hdcost)
e3:SetTarget(c9888196.hdtg)
e3:SetOperation(c9888196.hdop)
c:RegisterEffect(e3)
end
function c9888196.confilter(c)
return c:IsFaceup() and c:IsAttribute(ATTRIBUTE_LIGHT)
end
function c9888196.con(e,tp,eg,ep,ev,re,r,rp)
return Duel.IsExistingMatchingCard(c9888196.confilter,tp,0,LOCATION_MZONE,1,nil)
end
function c9888196.filter1(c)
return c:IsFacedown()
end
function c9888196.destg1(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsControler(1-tp) and chkc:IsOnField() and c9888196.filter1(chkc) end
if chk==0 then return Duel.IsExistingTarget(c9888196.filter1,tp,0,LOCATION_ONFIELD,1,nil) end
Duel.Hint(HINT_OPSELECTED,1-tp,e:GetDescription())
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local g=Duel.SelectTarget(tp,c9888196.filter1,tp,0,LOCATION_ONFIELD,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,g:GetCount(),0,0)
end
function c9888196.desop1(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) and tc:IsFacedown() then
Duel.Destroy(tc,REASON_EFFECT)
end
end
function c9888196.descost2(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(Card.IsAbleToGraveAsCost,tp,LOCATION_HAND,0,1,nil) end
Duel.Hint(HINT_OPSELECTED,1-tp,e:GetDescription())
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE)
local g=Duel.SelectMatchingCard(tp,Card.IsAbleToGraveAsCost,tp,LOCATION_HAND,0,1,1,nil)
Duel.SendtoGrave(g,REASON_COST)
end
function c9888196.filter2(c)
return c:IsType(TYPE_SPELL+TYPE_TRAP)
end
function c9888196.destg2(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c9888196.filter2,tp,0,LOCATION_ONFIELD,1,nil) end
local g=Duel.GetMatchingGroup(c9888196.filter2,tp,0,LOCATION_ONFIELD,nil)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,g:GetCount(),0,0)
end
function c9888196.desop2(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetMatchingGroup(c9888196.filter2,tp,0,LOCATION_ONFIELD,nil)
Duel.Destroy(g,REASON_EFFECT)
end
function c9888196.hdcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(Card.IsAbleToGraveAsCost,tp,LOCATION_HAND,0,1,nil) end
Duel.Hint(HINT_OPSELECTED,1-tp,e:GetDescription())
local g=Duel.GetFieldGroup(tp,LOCATION_HAND,0)
Duel.SendtoGrave(g,REASON_COST)
end
function c9888196.hdtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetFieldGroupCount(tp,0,LOCATION_HAND)>0 end
Duel.SetOperationInfo(0,CATEGORY_HANDES,nil,0,1-tp,0)
Duel.SetOperationInfo(0,CATEGORY_TOGRAVE,nil,0,1-tp,LOCATION_HAND)
end
function c9888196.hdop(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetFieldGroup(tp,0,LOCATION_HAND)
Duel.ConfirmCards(tp,g)
local sg=g:Filter(Card.IsAttribute,nil,ATTRIBUTE_LIGHT)
if sg:GetCount()>0 then
local atk=0
Duel.SendtoGrave(sg,REASON_EFFECT)
local tc=sg:GetFirst()
while tc do
local tatk=tc:GetAttack()
if tatk<0 then tatk=0 end
atk=atk+tatk
tc=sg:GetNext()
end
Duel.BreakEffect()
Duel.Damage(1-tp,atk,REASON_EFFECT)
end
Duel.ShuffleHand(1-tp)
end
| gpl-2.0 |
mercury233/ygopro-scripts | c2047519.lua | 9 | 1435 | --隠れ兵
function c2047519.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_SUMMON_SUCCESS)
e1:SetCondition(c2047519.condition)
e1:SetTarget(c2047519.target)
e1:SetOperation(c2047519.activate)
c:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetType(EFFECT_TYPE_ACTIVATE)
e2:SetCode(EVENT_FLIP_SUMMON_SUCCESS)
e2:SetCondition(c2047519.condition)
e2:SetTarget(c2047519.target)
e2:SetOperation(c2047519.activate)
c:RegisterEffect(e2)
end
function c2047519.condition(e,tp,eg,ep,ev,re,r,rp)
return ep~=tp
end
function c2047519.filter(c,e,tp)
return c:IsLevelBelow(4) and c:IsAttribute(ATTRIBUTE_DARK) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c2047519.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c2047519.filter,tp,LOCATION_HAND,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_HAND)
end
function c2047519.activate(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c2047519.filter,tp,LOCATION_HAND,0,1,1,nil,e,tp)
if g:GetCount()>0 then
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)
end
end
| gpl-2.0 |
ronsavage/MarpaX-Languages-Lua-Parser | lua.sources/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)
| artistic-2.0 |
helgefmi/Unicorn | Unicorn/List.lua | 2 | 8578 | local wm = WINDOW_MANAGER
local TITLE_HEIGHT = 24
local LINES_OFFSET = TITLE_HEIGHT
local SLIDER_WIDTH = 22
-- Utility
local function clamp(val, min_, max_)
val = math.max(val, min_)
return math.min(val, max_)
end
-- Private API
local function _set_line_counts(self)
self.num_visible_lines = math.floor((self.control:GetHeight() - LINES_OFFSET) / self.line_height)
self.num_visible_lines = math.min(self.num_visible_lines, #self.lines)
self.num_hidden_lines = math.max(0, #self.lines - self.num_visible_lines)
if self.num_hidden_lines == 0 then
self.offset = 0
end
end
local function _create_listview_row(self, i)
local control = self.control
local name = control:GetName() .. "_Line" .. i
local line = wm:CreateControl(name, control, CT_CONTROL)
line:SetHeight(self.line_height)
line.text = wm:CreateControl(name .. "_Text", line, CT_LABEL)
line.text:SetFont("ZoFontGame")
line.text:SetColor(255, 255, 255, 1)
line.text:SetText("")
line.text:SetAnchorFill(line)
return line
end
local function _create_listview_lines_if_needed(self)
local control = self.control
-- Makes sure that the main control is filled up with line controls at all times.
for i = 1, self.num_visible_lines do
if control.lines[i] == nil then
local line = _create_listview_row(self, i)
control.lines[i] = line
if i == 1 then
line:SetAnchor(TOPLEFT, control, TOPLEFT, 0, LINES_OFFSET)
else
line:SetAnchor(TOPLEFT, control.lines[i - 1], BOTTOMLEFT, 0, 0)
end
end
end
end
function _on_resize(self)
local control = self.control
-- Need to calculate num_visible_lines etc. for the rest of this function.
_set_line_counts(self)
_create_listview_lines_if_needed(self)
-- Represent how many lines are visible atm.
local viewable_lines_pct = self.num_visible_lines / #self.lines
-- Can we see all the lines?
if viewable_lines_pct >= 1.0 then
control.slider:SetHidden(true)
else
-- If not, make sure the slider is showing.
control.slider:SetHidden(false)
self.control.slider:SetMinMax(0, self.num_hidden_lines)
control.slider:SetHeight(control:GetHeight() - LINES_OFFSET)
-- The more lines we can see, the bigger the slider should be.
local tex = self.slider_texture
-- TODO: I have no idea why I need to do "+ 8" to get it to fit here.. GOD I hate low level UI API's.
control.slider:SetThumbTexture(tex, tex, tex, SLIDER_WIDTH + 8, control.slider:GetHeight() * viewable_lines_pct, 0, 0, 1, 1)
end
-- Update line widths in case we just resized self.control.
local line_width = control:GetWidth()
if not control.slider:IsControlHidden() then
line_width = line_width - control.slider:GetWidth()
end
for _, line in pairs(control.lines) do
line:SetWidth(line_width)
end
end
local function _initialize_listview(self, width, height, left, top)
local control = self.control
local name = control:GetName()
-- control
control:SetDimensions(width, height)
control:SetHidden(false)
control:SetAnchor(TOPLEFT, GuiRoot, TOPLEFT, left, top)
control:SetMovable(true)
control:SetResizeHandleSize(MOUSE_CURSOR_RESIZE_NS)
control:SetMouseEnabled(true)
control:SetClampedToScreen(true)
-- control backdrop
control.bd = wm:CreateControl(name .. "_Backdrop", control, CT_BACKDROP)
control.bd:SetCenterColor(0, 0, 0, 0.6)
control.bd:SetEdgeColor(0, 0, 0, 0)
control.bd:SetAnchorFill(control)
-- title
if self.title then
control.title = wm:CreateControl(name .. "_Title", control, CT_LABEL)
control.title:SetFont("ZoFontGame")
control.title:SetColor(255, 255, 255, 1)
control.title:SetText(" " .. self.title)
control.title:SetHeight(TITLE_HEIGHT)
control.title:SetAnchor(TOPLEFT, control, TOPLEFT, 0, 0)
control.title:SetAnchor(TOPRIGHT, control, TOPRIGHT, 0, 0)
-- title backdrop
control.title.bd = wm:CreateControl(name .. "_Title_Backdrop", control.title, CT_BACKDROP)
control.title.bd:SetCenterColor(0, 0, 0, 0.7)
control.title.bd:SetEdgeColor(0, 0, 0, 0)
control.title.bd:SetAnchorFill(control.title)
end
-- close button
control.close = wm:CreateControl(name .. "_Close", control, CT_BUTTON)
control.close:SetDimensions(20, TITLE_HEIGHT)
control.close:SetAnchor(TOPRIGHT, control, TOPRIGHT, 0, 0)
control.close:SetFont("ZoFontGame")
control.close:SetText("X")
-- close backdrop
control.close.bd = wm:CreateControl(name .. "_Close_Backdrop", control.close, CT_BACKDROP)
control.close.bd:SetCenterColor(0, 0, 0, 1)
control.close.bd:SetEdgeColor(0, 0, 0, 0)
control.close.bd:SetAnchorFill(control.close)
-- slider
local tex = self.slider_texture
control.slider = wm:CreateControl(name .. "_Slider", control, CT_SLIDER)
control.slider:SetWidth(SLIDER_WIDTH)
control.slider:SetMouseEnabled(true)
control.slider:SetValue(0)
control.slider:SetValueStep(1)
control.slider:SetAnchor(TOPRIGHT, control.close, BOTTOMRIGHT, 0, 0)
-- lines
control.lines = {}
_on_resize(self) -- sets important datastructures
_create_listview_lines_if_needed(self)
local me = self
-- event: close button
control.close:SetHandler("OnClicked", function(self, but)
control:SetHidden(true)
end)
-- event: mwheel
control:SetHandler("OnMouseWheel",function(self, delta)
me.offset = clamp(me.offset - delta, 0, me.num_hidden_lines)
control.slider:SetValue(me.offset)
end)
-- event: slider
control.slider:SetHandler("OnValueChanged", function(self, val, eventReason)
me.offset = clamp(val, 0, me.num_hidden_lines)
me:update()
end)
-- event: resize
control:SetHandler("OnResizeStart", function (self)
me.currently_resizing = true
end)
control:SetHandler("OnResizeStop", function (self)
me.currently_resizing = false
_on_resize(me)
end)
-- event: control update
control:SetHandler("OnUpdate", function(self, elapsed)
me:update()
end)
end
-- ListView, public API
local ListView = {}
function ListView.new(control, settings)
settings = settings or {}
-- Not storing these in self; use self.control:GetWidth() and self.control:GetHeight()
local width = settings.width or 400
local height = settings.height or 400
local left = settings.left or 100
local top = settings.top or 100
self = {
line_height = settings.line_height or 20,
slider_texture = settings.slider_texture or "/esoui/art/miscellaneous/scrollbox_elevator.dds",
title = settings.title, -- can be nil
control = control,
name = control:GetName(),
offset = 0,
lines = {},
currently_resizing = false,
}
-- TODO: Translate self:SetHidden() etc. to self.control:SetHidden()
setmetatable(self, {__index = ListView})
_initialize_listview(self, width, height, left, top)
return self
end
function ListView:update()
local throttle_time = self.currently_resizing and 0.02 or 0.1
if Unicorn.throttle(self, 0.05) then
return
end
if self.currently_resizing then
_on_resize(self)
end
-- Goes through each line control and either shows a message or hides it.
for i, line in pairs(self.control.lines) do
local message = self.lines[i + self.offset] -- self.offset = how much we've scrolled down
-- Only show messages that will be displayed within the control.
if message ~= nil and i <= self.num_visible_lines then
line.text:SetText(message)
line:SetHidden(false)
else
line:SetHidden(true)
end
end
end
function ListView:clear()
self.lines = {}
self:update()
end
function ListView:add_message(message)
table.insert(self.lines, " " .. message) -- poor man's padding. for now.
_on_resize(self) -- maybe the function needs a better name :)
end
Unicorn.ListView = ListView
| mit |
mercury233/ygopro-scripts | c21887075.lua | 2 | 2479 | --無尽機関アルギロ・システム
function c21887075.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(21887075,0))
e1:SetCategory(CATEGORY_TOGRAVE)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCountLimit(1,21887075)
e1:SetTarget(c21887075.target)
e1:SetOperation(c21887075.activate)
c:RegisterEffect(e1)
--to hand
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(21887075,1))
e2:SetCategory(CATEGORY_TODECK+CATEGORY_TOHAND)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_GRAVE)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET)
e2:SetCountLimit(1,21887075)
e2:SetTarget(c21887075.tg)
e2:SetOperation(c21887075.op)
c:RegisterEffect(e2)
end
function c21887075.tgfilter(c)
return c:IsSetCard(0x179) and c:IsAbleToGrave()
end
function c21887075.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c21887075.tgfilter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOGRAVE,nil,1,tp,LOCATION_DECK)
end
function c21887075.activate(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE)
local g=Duel.SelectMatchingCard(tp,c21887075.tgfilter,tp,LOCATION_DECK,0,1,1,nil)
if g:GetCount()>0 then
Duel.SendtoGrave(g,REASON_EFFECT)
end
end
function c21887075.filter(c,b1,b2)
return c:IsSetCard(0x179) and ((b1 and c:IsAbleToHand()) or (b2 and c:IsAbleToDeck()))
end
function c21887075.tg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
local c=e:GetHandler()
local b1,b2=c:IsAbleToDeck(),c:IsAbleToHand()
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c21887075.filter(chkc,b1,b2) end
if chk==0 then return Duel.IsExistingTarget(c21887075.filter,tp,LOCATION_GRAVE,0,1,nil,b1,b2) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TARGET)
local g=Duel.SelectTarget(tp,c21887075.filter,tp,LOCATION_GRAVE,0,1,1,nil,b1,b2)
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_GRAVE)
Duel.SetOperationInfo(0,CATEGORY_TODECK,nil,1,tp,LOCATION_GRAVE)
end
function c21887075.op(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
local c=e:GetHandler()
if c:IsRelateToEffect(e) and tc:IsRelateToEffect(e) then
local g=Group.FromCards(tc,c)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local tg=g:FilterSelect(tp,Card.IsAbleToHand,1,1,nil)
g:Sub(tg)
Duel.SendtoHand(tg,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,tg:GetFirst())
Duel.SendtoDeck(g,nil,SEQ_DECKBOTTOM,REASON_EFFECT)
end
end
| gpl-2.0 |
valhallaGaming/uno | src_trunk/resources/lvpd-system/s_policecommands.lua | 1 | 12299 | -- ////////////////////////////////////
-- // MYSQL //
-- ////////////////////////////////////
sqlUsername = exports.mysql:getMySQLUsername()
sqlPassword = exports.mysql:getMySQLPassword()
sqlDB = exports.mysql:getMySQLDBName()
sqlHost = exports.mysql:getMySQLHost()
sqlPort = exports.mysql:getMySQLPort()
handler = mysql_connect(sqlHost, sqlUsername, sqlPassword, sqlDB, sqlPort)
function checkMySQL()
if not (mysql_ping(handler)) then
handler = mysql_connect(sqlHost, sqlUsername, sqlPassword, sqlDB, sqlPort)
end
end
setTimer(checkMySQL, 300000, 0)
function closeMySQL()
if (handler) then
mysql_close(handler)
end
end
addEventHandler("onResourceStop", getResourceRootElement(getThisResource()), closeMySQL)
-- ////////////////////////////////////
-- // MYSQL END //
-- ////////////////////////////////////
local smallRadius = 5 --units
----------------------[CUFF]--------------------
function cuffPlayer(thePlayer, commandName, targetPartialNick)
local username = getPlayerName(thePlayer)
local logged = getElementData(thePlayer, "loggedin")
if (logged==1) then
if not (targetPartialNick) then
outputChatBox("SYNTAX: /" .. commandName .. " [Player Partial Nick]", thePlayer)
else
local faction = getPlayerTeam(thePlayer)
local ftype = getElementData(faction, "type")
if (ftype~=2) then
outputChatBox("You do not have handcuffs.", thePlayer, 255, 0, 0)
else
local targetPlayer = exports.global:findPlayerByPartialNick(targetPartialNick)
if not (targetPlayer) then
outputChatBox("Player not found or multiple were found.", thePlayer, 255, 0, 0)
else
local restrain = getElementData(targetPlayer, "restrain")
if (restrain==1) then
outputChatBox("Player is already restrained.", thePlayer, 255, 0, 0)
else
local targetPlayerName = getPlayerName(targetPlayer)
local x, y, z = getElementPosition(targetPlayer)
local colSphere = createColSphere(x, y, z, smallRadius)
exports.pool:allocateElement(colSphere)
if (isElementWithinColShape(thePlayer, colSphere)) then
outputChatBox("You have been hand cuffed by " .. username .. ".", targetPlayer)
outputChatBox("You are cuffing " .. targetPlayerName .. ".", thePlayer)
toggleControl(targetPlayer, "sprint", false)
toggleControl(targetPlayer, "jump", false)
toggleControl(targetPlayer, "next_weapon", false)
toggleControl(targetPlayer, "previous_weapon", false)
toggleControl(targetPlayer, "accelerate", false)
toggleControl(targetPlayer, "brake_reverse", false)
toggleControl(targetPlayer, "fire", false)
toggleControl(targetPlayer, "aim_weapon", false)
setPedWeaponSlot(targetPlayer, 0)
setElementData(targetPlayer, "restrain", 1)
else
outputChatBox("You are not within range of " .. targetPlayerName .. ".", thePlayer, 255, 0, 0)
end
destroyElement(colSphere)
end
end
end
end
end
end
--addCommandHandler("cuff", cuffPlayer, false, false)
----------------------[UNCUFF]--------------------
function uncuffPlayer(thePlayer, commandName, targetPartialNick)
local username = getPlayerName(thePlayer)
local logged = getElementData(thePlayer, "loggedin")
if (logged==1) then
if not (targetPartialNick) then
outputChatBox("SYNTAX: /" .. commandName .. " [Player Partial Nick]", thePlayer)
else
local faction = getPlayerTeam(thePlayer)
local ftype = getElementData(faction, "type")
if (ftype~=2) then
outputChatBox("You do not have handcuffs.", thePlayer, 255, 0, 0)
else
local targetPlayer = exports.global:findPlayerByPartialNick(targetPartialNick)
if not (targetPlayer) then
outputChatBox("Player not found or multiple were found.", thePlayer, 255, 0, 0)
else
local restrain = getElementData(targetPlayer, "restrain")
if (restrain==0) then
outputChatBox("Player is not restrained.", thePlayer, 255, 0, 0)
else
local targetPlayerName = getPlayerName(targetPlayer)
local x, y, z = getElementPosition(targetPlayer)
local colSphere = createColSphere(x, y, z, smallRadius)
exports.pool:allocateElement(colSphere)
if (isElementWithinColShape(thePlayer, colSphere)) then
outputChatBox("You have been uncuffed by " .. username .. ".", targetPlayer)
outputChatBox("You are uncuffing " .. targetPlayerName .. ".", thePlayer)
toggleControl(targetPlayer, "sprint", true)
toggleControl(targetPlayer, "fire", true)
toggleControl(targetPlayer, "jump", true)
toggleControl(targetPlayer, "next_weapon", true)
toggleControl(targetPlayer, "previous_weapon", true)
toggleControl(targetPlayer, "accelerate", true)
toggleControl(targetPlayer, "brake_reverse", true)
toggleControl(targetPlayer, "aim_weapon", true)
setElementData(targetPlayer, "restrain", 0)
exports.global:removeAnimation(targetPlayer)
else
outputChatBox("You are not within range of " .. targetPlayerName .. ".", thePlayer, 255, 0, 0)
end
destroyElement(colSphere)
end
end
end
end
end
end
--addCommandHandler("uncuff", uncuffPlayer, false, false)
-- /fingerprint
function fingerprintPlayer(thePlayer, commandName, targetPlayerNick)
local logged = getElementData(thePlayer, "loggedin")
if (logged==1) then
local theTeam = getPlayerTeam(thePlayer)
local factionType = getElementData(theTeam, "type")
if (factionType==2) then
if not (targetPlayerNick) then
outputChatBox("SYNTAX: /" .. commandName .. " [Player Partial Nick]", thePlayer, 255, 194, 14)
else
local targetPlayer = exports.global:findPlayerByPartialNick(targetPlayerNick)
if not (targetPlayer) then
outputChatBox("Player is not online.", thePlayer, 255, 0, 0)
else
local x, y, z = getElementPosition(thePlayer)
local tx, ty, tz = getElementPosition(targetPlayer)
local distance = getDistanceBetweenPoints3D(x, y, z, tx, ty, tz)
if (distance<=10) then
local fingerprint = getElementData(targetPlayer, "fingerprint")
outputChatBox(getPlayerName(targetPlayer) .. "'s Fingerprint: " .. tostring(fingerprint) .. ".", thePlayer, 255, 194, 14)
else
outputChatBox("You are too far away from " .. getPlayerName(targetPlayer) .. ".", thePlayer, 255, 0, 0)
end
end
end
end
end
end
addCommandHandler("fingerprint", fingerprintPlayer, false, false)
-- /ticket
function ticketPlayer(thePlayer, commandName, targetPlayerNick, amount, ...)
local logged = getElementData(thePlayer, "loggedin")
if (logged==1) then
local theTeam = getPlayerTeam(thePlayer)
local factionType = getElementData(theTeam, "type")
if (factionType==2) then
if not (targetPlayerNick) or not (amount) or not (...) then
outputChatBox("SYNTAX: /" .. commandName .. " [Player Partial Nick] [Amount] [Reason]", thePlayer, 255, 194, 14)
else
local targetPlayer = exports.global:findPlayerByPartialNick(targetPlayerNick)
if not (targetPlayer) then
outputChatBox("Player is not online.", thePlayer, 255, 0, 0)
else
local x, y, z = getElementPosition(thePlayer)
local tx, ty, tz = getElementPosition(targetPlayer)
local distance = getDistanceBetweenPoints3D(x, y, z, tx, ty, tz)
if (distance<=10) then
amount = tonumber(amount)
local reason = table.concat({...}, " ")
local money = exports.global:getMoney(targetPlayer)
local bankmoney = getElementData(targetPlayer, "bankmoney")
if money + bankmoney < amount then
outputChatBox("This player cannot afford such a ticket.", thePlayer, 255, 0, 0)
else
local takeFromCash = math.min( money, amount )
local takeFromBank = amount - takeFromCash
exports.global:takeMoney(targetPlayer, takeFromCash)
-- Distribute money between the PD and Government
local tax = exports.global:getTaxAmount()
exports.global:giveMoney( getTeamFromName("Los Santos Police Department"), math.ceil((1-tax)*amount) )
exports.global:giveMoney( getTeamFromName("Government of Los Santos"), math.ceil(tax*amount) )
outputChatBox("You ticketed " .. getPlayerName(targetPlayer) .. " for " .. amount .. "$. Reason: " .. reason .. ".", thePlayer)
outputChatBox("You were ticketed for " .. amount .. "$ by " .. getPlayerName(thePlayer) .. ". Reason: " .. reason .. ".", targetPlayer)
if takeFromBank > 0 then
outputChatBox("Since you don't have enough money with you, $" .. takeFromBank .. " have been taken from your bank account.", targetPlayer)
setElementData(targetPlayer, "bankmoney", bankmoney - takeFromBank)
end
end
else
outputChatBox("You are too far away from " .. getPlayerName(targetPlayer) .. ".", thePlayer, 255, 0, 0)
end
end
end
end
end
end
addCommandHandler("ticket", ticketPlayer, false, false)
function takeLicense(thePlayer, commandName, targetPartialNick, licenseType)
local username = getPlayerName(thePlayer)
local logged = getElementData(thePlayer, "loggedin")
if (logged==1) then
local faction = getPlayerTeam(thePlayer)
local ftype = getElementData(faction, "type")
if (ftype==2) then
if not (targetPartialNick) then
outputChatBox("SYNTAX: /" .. commandName .. " [Player Partial Nick][license Type 1:Driving 2:Weapon]", thePlayer)
else
if not (licenseType) then
outputChatBox("SYNTAX: /" .. commandName .. " [Player Partial Nick][license Type 1:Driving 2:Weapon]", thePlayer)
else
local targetPlayer = exports.global:findPlayerByPartialNick(targetPartialNick)
local targetPlayerName = getPlayerName(targetPlayer)
local name = getPlayerName(thePlayer)
if (tonumber(licenseType)==1) then
if(tonumber(getElementData(targetPlayer, "license.car")) == 1) then
local query = mysql_query(handler, "UPDATE characters SET car_license='0' WHERE charactername='" .. mysql_escape_string(handler, getPlayerName(targetPlayer)) .. "' LIMIT 1")
mysql_free_result(query)
outputChatBox(name.." has revoked your driving license.", targetPlayer, 255, 194, 14)
outputChatBox("You have revoked " .. targetPlayerName .. "'s driving license.", thePlayer, 255, 194, 14)
setElementData(targetPlayer, "license.car", 0)
else
outputChatBox(targetPlayerName .. " does not have a driving license.", thePlayer, 255, 0, 0)
end
elseif (tonumber(licenseType)==2) then
if(tonumber(getElementData(targetPlayer, "license.gun")) == 1) then
local query = mysql_query(handler, "UPDATE characters SET gun_license='0' WHERE charactername='" .. mysql_escape_string(handler, getPlayerName(targetPlayer)) .. "' LIMIT 1")
mysql_free_result(query)
outputChatBox(name.." has revoked your weapon license.", targetPlayer, 255, 194, 14)
outputChatBox("You have revoked " .. targetPlayerName .. "'s weapon license.", thePlayer, 255, 194, 14)
setElementData(targetPlayer, "license.gun", 0)
else
outputChatBox(targetPlayerName .. " does not have a weapon license.", thePlayer, 255, 0, 0)
end
else
outputChatBox("License type not recognised.", thePlayer, 255, 194, 14)
end
end
end
end
end
end
addCommandHandler("takelicense", takeLicense, false, false)
function tellNearbyPlayersVehicleStrobesOn()
local x, y, z = getElementType(source)
local checkSphere = createColSphere(x, y, z, 300)
local nearbyPlayers = getElementsWithinColShape(checkSphere, "player")
destroyElement(checkSphere)
for _, nearbyPlayer in ipairs(nearbyPlayers) do
triggerClientEvent(nearbyPlayer, "forceElementStreamIn", source)
end
end
addEvent("forceElementStreamIn", true)
addEventHandler("forceElementStreamIn", getRootElement(), tellNearbyPlayersVehicleStrobesOn) | bsd-3-clause |
Zenny89/darkstar | scripts/zones/Bhaflau_Thickets/TextIDs.lua | 7 | 1158 | -- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 6379; -- You cannot obtain the item <item>. Come back after sorting your inventory.
ITEM_OBTAINED = 6383; -- Obtained: <item>.
GIL_OBTAINED = 6384; -- Obtained <number> gil.
KEYITEM_OBTAINED = 6386; -- Obtained key item: <keyitem>.
FISHING_MESSAGE_OFFSET = 7040; -- You can't fish here.
HOMEPOINT_SET = 7677; -- Home point set!
-- Assault
CANNOT_ENTER = 7570; -- You cannot enter at this time. Please wait a while before trying again.
AREA_FULL = 7571; -- This area is fully occupied. You were unable to enter.
MEMBER_NO_REQS = 7575; -- Not all of your party members meet the requirements for this objective. Unable to enter area.
MEMBER_TOO_FAR = 7579; -- One or more party members are too far away from the entrance. Unable to enter area.
-- Other Texts
NOTHING_HAPPENS = 7556; -- Nothing happens...
RESPONSE = 7315; -- There is no response...
--chocobo digging
DIG_THROW_AWAY = 7053; -- You dig up$, but your inventory is full. You regretfully throw the # away.
FIND_NOTHING = 7055; -- You dig and you dig, but find nothing.
| gpl-3.0 |
mercury233/ygopro-scripts | c48015771.lua | 3 | 2113 | --サモンオーバー
function c48015771.initial_effect(c)
c:EnableCounterPermit(0x4c)
c:SetCounterLimit(0x4c,6)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
c:RegisterEffect(e1)
--counter
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e2:SetCode(EVENT_SPSUMMON_SUCCESS)
e2:SetRange(LOCATION_FZONE)
e2:SetOperation(c48015771.ctop)
c:RegisterEffect(e2)
--indes
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_SINGLE)
e3:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e3:SetCode(EFFECT_INDESTRUCTABLE_EFFECT)
e3:SetRange(LOCATION_FZONE)
e3:SetCondition(c48015771.indcon)
e3:SetValue(1)
c:RegisterEffect(e3)
--tograve
local e4=Effect.CreateEffect(c)
e4:SetDescription(aux.Stringid(48015771,0))
e4:SetCategory(CATEGORY_TOGRAVE)
e4:SetType(EFFECT_TYPE_IGNITION)
e4:SetProperty(EFFECT_FLAG_BOTH_SIDE)
e4:SetRange(LOCATION_FZONE)
e4:SetCondition(c48015771.tgcon)
e4:SetTarget(c48015771.tgtg)
e4:SetOperation(c48015771.tgop)
c:RegisterEffect(e4)
end
function c48015771.ctop(e,tp,eg,ep,ev,re,r,rp)
e:GetHandler():AddCounter(0x4c,1)
end
function c48015771.indcon(e)
return e:GetHandler():GetCounter(0x4c)==6
end
function c48015771.tgcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetCurrentPhase()==PHASE_MAIN1 and not Duel.CheckPhaseActivity() and e:GetHandler():GetCounter(0x4c)==6
end
function c48015771.tgfilter(c)
return c:IsFaceup() and c:IsSummonType(SUMMON_TYPE_SPECIAL) and c:IsAbleToGrave()
end
function c48015771.tgtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c48015771.tgfilter,tp,0,LOCATION_MZONE,1,nil) end
local g=Duel.GetMatchingGroup(c48015771.tgfilter,tp,0,LOCATION_MZONE,nil)
Duel.SetOperationInfo(0,CATEGORY_TOGRAVE,g,g:GetCount(),0,0)
end
function c48015771.tgop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) and Duel.SendtoGrave(c,REASON_EFFECT)~=0 and c:IsLocation(LOCATION_GRAVE) then
local g=Duel.GetMatchingGroup(c48015771.tgfilter,tp,0,LOCATION_MZONE,nil)
Duel.SendtoGrave(g,REASON_EFFECT)
end
end
| gpl-2.0 |
mercury233/ygopro-scripts | c9659580.lua | 2 | 3481 | --方界業
function c9659580.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetTarget(c9659580.target)
c:RegisterEffect(e1)
--lp halve
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(9659580,1))
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F)
e2:SetCode(EVENT_SPSUMMON_SUCCESS)
e2:SetRange(LOCATION_SZONE)
e2:SetCondition(c9659580.lpcon)
e2:SetOperation(c9659580.lpop)
c:RegisterEffect(e2)
--to hand
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(9659580,2))
e3:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH)
e3:SetType(EFFECT_TYPE_IGNITION)
e3:SetRange(LOCATION_GRAVE)
e3:SetCost(aux.bfgcost)
e3:SetTarget(c9659580.thtg)
e3:SetOperation(c9659580.thop)
c:RegisterEffect(e3)
end
function c9659580.tgfilter(c)
return c:IsCode(15610297) and c:IsAbleToGrave()
end
function c9659580.filter(c)
return c:IsFaceup() and c:IsSetCard(0xe3) and not c:IsCode(15610297)
end
function c9659580.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(tp) and c9659580.filter(chkc) end
if chk==0 then return true end
if Duel.IsExistingTarget(c9659580.filter,tp,LOCATION_MZONE,0,1,nil)
and Duel.IsExistingMatchingCard(c9659580.tgfilter,tp,LOCATION_HAND+LOCATION_DECK,0,1,nil)
and Duel.SelectYesNo(tp,aux.Stringid(9659580,0)) then
e:SetCategory(CATEGORY_ATKCHANGE+CATEGORY_TOGRAVE)
e:SetProperty(EFFECT_FLAG_CARD_TARGET)
e:SetOperation(c9659580.activate)
Duel.SelectTarget(tp,c9659580.filter,tp,LOCATION_MZONE,0,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_TOGRAVE,nil,1,tp,LOCATION_DECK)
else
e:SetCategory(0)
e:SetProperty(0)
e:SetOperation(nil)
end
end
function c9659580.activate(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE)
local g=Duel.SelectMatchingCard(tp,c9659580.tgfilter,tp,LOCATION_HAND+LOCATION_DECK,0,1,99,nil)
if Duel.SendtoGrave(g,REASON_EFFECT)~=0 then
local og=Duel.GetOperatedGroup()
local n=og:FilterCount(Card.IsLocation,nil,LOCATION_GRAVE)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) and tc:IsFaceup() and n>0 then
Duel.BreakEffect()
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetValue(n*800)
e1:SetReset(RESET_EVENT+RESETS_STANDARD)
tc:RegisterEffect(e1)
end
end
end
function c9659580.lpcon(e,tp,eg,ep,ev,re,r,rp)
local rc=re:GetHandler()
return Duel.GetTurnPlayer()~=tp and re:IsActiveType(TYPE_MONSTER) and rc and rc:IsSetCard(0xe3)
and eg:IsExists(Card.IsCode,1,nil,15610297)
end
function c9659580.lpop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) and Duel.SendtoGrave(c,REASON_EFFECT)~=0 and c:IsLocation(LOCATION_GRAVE) then
Duel.SetLP(1-tp,math.ceil(Duel.GetLP(1-tp)/2))
end
end
function c9659580.thfilter(c)
return c:IsSetCard(0xe3) and c:IsType(TYPE_MONSTER) and c:IsAbleToHand()
end
function c9659580.thtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c9659580.thfilter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function c9659580.thop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,c9659580.thfilter,tp,LOCATION_DECK,0,1,1,nil)
if g:GetCount()>0 then
Duel.SendtoHand(g,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g)
end
end
| gpl-2.0 |
Zenny89/darkstar | scripts/zones/The_Eldieme_Necropolis/npcs/_5fr.lua | 34 | 2570 | -----------------------------------
-- Area: The Eldieme Necropolis
-- NPC: South Plate
-- @pos 180 -34 -31 195
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local state0 = 8;
local state1 = 9;
local DoorOffset = npc:getID() - 26; -- _5f1
if (npc:getAnimation() == 8) then
state0 = 9;
state1 = 8;
end
-- Gates
-- Shiva's Gate
GetNPCByID(DoorOffset):setAnimation(state0);
GetNPCByID(DoorOffset+1):setAnimation(state0);
GetNPCByID(DoorOffset+2):setAnimation(state0);
GetNPCByID(DoorOffset+3):setAnimation(state0);
GetNPCByID(DoorOffset+4):setAnimation(state0);
-- Odin's Gate
GetNPCByID(DoorOffset+5):setAnimation(state1);
GetNPCByID(DoorOffset+6):setAnimation(state1);
GetNPCByID(DoorOffset+7):setAnimation(state1);
GetNPCByID(DoorOffset+8):setAnimation(state1);
GetNPCByID(DoorOffset+9):setAnimation(state1);
-- Leviathan's Gate
GetNPCByID(DoorOffset+10):setAnimation(state0);
GetNPCByID(DoorOffset+11):setAnimation(state0);
GetNPCByID(DoorOffset+12):setAnimation(state0);
GetNPCByID(DoorOffset+13):setAnimation(state0);
GetNPCByID(DoorOffset+14):setAnimation(state0);
-- Titan's Gate
GetNPCByID(DoorOffset+15):setAnimation(state1);
GetNPCByID(DoorOffset+16):setAnimation(state1);
GetNPCByID(DoorOffset+17):setAnimation(state1);
GetNPCByID(DoorOffset+18):setAnimation(state1);
GetNPCByID(DoorOffset+19):setAnimation(state1);
-- Plates
-- East Plate
GetNPCByID(DoorOffset+20):setAnimation(state0);
GetNPCByID(DoorOffset+21):setAnimation(state0);
-- North Plate
GetNPCByID(DoorOffset+22):setAnimation(state0);
GetNPCByID(DoorOffset+23):setAnimation(state0);
-- West Plate
GetNPCByID(DoorOffset+24):setAnimation(state0);
GetNPCByID(DoorOffset+25):setAnimation(state0);
-- South Plate
GetNPCByID(DoorOffset+26):setAnimation(state0);
GetNPCByID(DoorOffset+27):setAnimation(state0);
return 0;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
wenhuizhang/MoonGen | test/proto/testIPv4.lua | 5 | 2123 | describe("IPv4 class", function()
local ffi = require "ffi"
local pkt = require "packet"
it("should parse", function()
local ip = parseIP4Address("1.2.3.4")
assert.are.same(ip, 0x01020304)
end)
it("should return in correct byteorder", function()
local ipString = "123.56.200.42"
local ip = ffi.new("union ip4_address")
ip:setString(ipString)
assert.are.same(ipString, ip:getString())
end)
it("should support ==", function()
-- in uint32 format
local ip = parseIP4Address("123.56.200.42")
local ip2 = parseIP4Address("123.56.200.42")
local ip3 = parseIP4Address("123.56.200.43")
assert.are.same(ip, ip2)
assert.are.not_same(ip, ip3)
assert.are.not_same(ip, 0)
-- in ipv4_address format
local ipAddress = ffi.new("union ip4_address")
local ipAddress2 = ffi.new("union ip4_address")
local ipAddress3 = ffi.new("union ip4_address")
ipAddress:set(ip)
ipAddress2:set(ip2)
ipAddress3:set(ip3)
assert.are.same(ip, ip2)
assert.are.not_same(ip, ip3)
assert.are.not_same(ip, 0)
end)
it("should do arithmetic", function()
local ip1 = ffi.new("union ip4_address")
local ip2 = ffi.new("union ip4_address")
local ip3 = ffi.new("union ip4_address")
local ip4 = ffi.new("union ip4_address")
local res1 = ffi.new("union ip4_address")
local res2 = ffi.new("union ip4_address")
ip1:set(parseIP4Address("1.2.3.4"))
ip2:set(parseIP4Address("1.2.3.5"))
ip3:set(parseIP4Address("255.255.255.254"))
ip4:set(parseIP4Address("0.0.0.0"))
res1:set(ip1 + 1)
res2:set(ip4 - 2)
assert.are.same(res1:getString(), ip2:getString())
assert.are.same(res2:getString(), ip3:getString())
end)
it("should support in-place arithmetic", function()
local ip1 = ffi.new("union ip4_address")
local ip2 = ffi.new("union ip4_address")
local ip3 = ffi.new("union ip4_address")
local ip4 = ffi.new("union ip4_address")
ip1:set(parseIP4Address("1.2.3.4"))
ip2:set(parseIP4Address("255.255.255.254"))
ip3:set(parseIP4Address("1.2.3.5"))
ip4:set(parseIP4Address("0.0.0.0"))
ip1:add(1)
ip2:add(2)
assert.are.same(ip1, ip3)
assert.are.same(ip2, ip4)
end)
end)
| mit |
mercury233/ygopro-scripts | c770365.lua | 6 | 1674 | --魔導皇聖 トリス
function c770365.initial_effect(c)
--xyz summon
aux.AddXyzProcedure(c,aux.FilterBoolFunction(Card.IsRace,RACE_SPELLCASTER),5,2)
c:EnableReviveLimit()
--atklimit
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetRange(LOCATION_MZONE)
e1:SetValue(c770365.atkval)
c:RegisterEffect(e1)
--confiem
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(770365,0))
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetCountLimit(1)
e2:SetRange(LOCATION_MZONE)
e2:SetCost(c770365.cost)
e2:SetTarget(c770365.target)
e2:SetOperation(c770365.operation)
c:RegisterEffect(e2)
end
function c770365.atkval(e,c)
return Duel.GetOverlayCount(c:GetControler(),1,0)*300
end
function c770365.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():CheckRemoveOverlayCard(tp,1,REASON_COST) end
e:GetHandler():RemoveOverlayCard(tp,1,1,REASON_COST)
end
function c770365.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetFieldGroupCount(tp,LOCATION_DECK,0)>=5 end
end
function c770365.filter(c)
return c:IsSetCard(0x106e)
end
function c770365.operation(e,tp,eg,ep,ev,re,r,rp)
Duel.ShuffleDeck(tp)
Duel.BreakEffect()
Duel.ConfirmDecktop(tp,5)
local g=Duel.GetDecktopGroup(tp,5)
local ct=g:FilterCount(c770365.filter,nil)
local sg=Duel.GetMatchingGroup(aux.TRUE,tp,LOCATION_MZONE,LOCATION_MZONE,nil)
if ct>0 and sg:GetCount()>0 then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local dg=sg:Select(tp,1,ct,nil)
Duel.HintSelection(dg)
Duel.Destroy(dg,REASON_EFFECT)
Duel.BreakEffect()
end
Duel.SortDecktop(tp,tp,5)
end
| gpl-2.0 |
rodamaral/smw-tas | lsnes/scripts/lib/game/misc.lua | 1 | 3661 | local M = {}
local memory, bit = _G.memory, _G.bit
local luap = require('luap')
local config = require('config')
local draw = require('draw')
local state = require('game.state')
local smw = require('game.smw')
local tile = require('game.tile')
local fmt = string.format
local u8 = memory.readbyte
local u16 = memory.readword
local u24 = memory.readhword
local WRAM = smw.WRAM
local SMW = smw.constant
local store = state.store
local OPTIONS = config.OPTIONS
local COLOUR = config.COLOUR
local LSNES_FONT_HEIGHT = config.LSNES_FONT_HEIGHT
function M.global_info()
if not OPTIONS.display_misc_info then return end
-- Font
draw.Font = false
draw.Text_opacity = 1.0
draw.Bg_opacity = 1.0
-- Display
local RNGValue = u16('WRAM', WRAM.RNG)
local main_info = string.format('Frame(%02x, %02x) RNG(%04x) Mode(%02x)', store.Real_frame,
store.Effective_frame, RNGValue, store.Game_mode)
local color = store.Game_mode <= SMW.game_mode_max and COLOUR.text or
SMW.game_modes_level_glitched[store.Game_mode] and COLOUR.warning2 or
COLOUR.warning
draw.text(draw.Buffer_width + draw.Border_right, -draw.Border_top, main_info, color, true, false)
if store.Game_mode == SMW.game_mode_level then
-- Time frame counter of the clock
draw.Font = 'snes9xlua'
local timer_frame_counter = u8('WRAM', WRAM.timer_frame_counter)
draw.text(draw.AR_x * 161, draw.AR_y * 15, fmt('%.2d', timer_frame_counter))
-- Score: sum of digits, useful for avoiding lag
draw.Font = 'Uzebox8x12'
local scoreValue = u24('WRAM', WRAM.mario_score)
draw.text(draw.AR_x * 240, draw.AR_y * 24, fmt('=%d', luap.sum_digits(scoreValue)),
COLOUR.weak)
end
end
function M.level_info()
if not OPTIONS.display_level_info then return end
-- Font
draw.Font = 'Uzebox6x8'
draw.Text_opacity = 1.0
draw.Bg_opacity = 1.0
local y_pos = -draw.Border_top + LSNES_FONT_HEIGHT
local color = COLOUR.text
local pointer = u24('WRAM', WRAM.sprite_data_pointer)
local bank = math.floor(pointer / 0x10000)
local address = pointer % 0x10000
local ROM_pointer = address >= 0x8000 and address <= 0xFFFD
local sprite_buoyancy = bit.lrshift(u8('WRAM', WRAM.sprite_buoyancy), 6)
if sprite_buoyancy == 0 then
sprite_buoyancy = ''
else
sprite_buoyancy = fmt(' %.2x', sprite_buoyancy)
color = COLOUR.warning
end
-- converts the level number to the Lunar Magic number; should not be used outside here
local lm_level_number = store.Level_index
if store.Level_index > 0x24 then lm_level_number = store.Level_index + 0xdc end
-- Number of screens within the level
local level_type, screens_number, hscreen_current, hscreen_number, vscreen_current,
vscreen_number = tile.read_screens()
draw.text(draw.Buffer_width + draw.Border_right, y_pos,
fmt('%.1sLevel(%.2x)%s', level_type, lm_level_number, sprite_buoyancy), color, true,
false)
draw.text(draw.Buffer_width + draw.Border_right, y_pos + draw.font_height(),
fmt('Screens(%d):', screens_number), true)
draw.text(draw.Buffer_width + draw.Border_right, y_pos + 2 * draw.font_height(), fmt(
'(%d/%d, %d/%d)', hscreen_current, hscreen_number, vscreen_current, vscreen_number),
true)
draw.text(draw.Buffer_width + draw.Border_right, y_pos + 3 * draw.font_height(), fmt(
'$CE: %.2x:%.4x', bank, address), ROM_pointer and COLOUR.text or COLOUR.warning, true)
end
return M
| mit |
qq779089973/my_openwrt_mod | 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
| mit |
mercury233/ygopro-scripts | c12015000.lua | 2 | 1846 | --新生代化石竜 スカルガー
function c12015000.initial_effect(c)
aux.AddCodeList(c,59419719)
--fusion summon
c:EnableReviveLimit()
aux.AddFusionProcFun2(c,aux.FilterBoolFunction(Card.IsRace,RACE_ROCK),c12015000.matfilter,true)
--spsummon condition
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e1:SetCode(EFFECT_SPSUMMON_CONDITION)
e1:SetValue(c12015000.splimit)
c:RegisterEffect(e1)
--pierce
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_PIERCE)
c:RegisterEffect(e2)
--search
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(12015000,0))
e3:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH)
e3:SetType(EFFECT_TYPE_IGNITION)
e3:SetRange(LOCATION_GRAVE)
e3:SetCountLimit(1,12015000)
e3:SetCost(aux.bfgcost)
e3:SetTarget(c12015000.thtg)
e3:SetOperation(c12015000.thop)
c:RegisterEffect(e3)
end
function c12015000.matfilter(c,fc)
return c:IsFusionType(TYPE_MONSTER) and c:GetLevel()>0 and c:IsLevelBelow(4) and c:IsLocation(LOCATION_GRAVE) and c:IsControler(1-fc:GetControler())
end
function c12015000.splimit(e,se,sp,st)
return se:GetHandler():IsCode(59419719) or not e:GetHandler():IsLocation(LOCATION_EXTRA)
end
function c12015000.thfilter(c)
return c:IsCode(59419719) and c:IsAbleToHand()
end
function c12015000.thtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c12015000.thfilter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function c12015000.thop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,c12015000.thfilter,tp,LOCATION_DECK,0,1,1,nil)
if #g>0 then
Duel.SendtoHand(g,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g)
end
end
| gpl-2.0 |
LuaDist/loop | lua/loop/collection/UnorderedArray.lua | 12 | 1495 | --------------------------------------------------------------------------------
---------------------- ## ##### ##### ###### -----------------------
---------------------- ## ## ## ## ## ## ## -----------------------
---------------------- ## ## ## ## ## ###### -----------------------
---------------------- ## ## ## ## ## ## -----------------------
---------------------- ###### ##### ##### ## -----------------------
---------------------- -----------------------
----------------------- Lua Object-Oriented Programming ------------------------
--------------------------------------------------------------------------------
-- Project: LOOP Class Library --
-- Release: 2.3 beta --
-- Title : Array Optimized for Insertion/Removal that Doesn't Garantee Order --
-- Author : Renato Maia <maia@inf.puc-rio.br> --
--------------------------------------------------------------------------------
local table = require "table"
local oo = require "loop.base"
module("loop.collection.UnorderedArray", oo.class)
function add(self, value)
self[#self + 1] = value
end
function remove(self, index)
local size = #self
if index == size then
self[size] = nil
elseif (index > 0) and (index < size) then
self[index], self[size] = self[size], nil
end
end | mit |
nikil/entware-packages | net/prosody/files/prosody.cfg.lua | 4 | 7277 | -- Prosody Example Configuration File
--
-- Information on configuring Prosody can be found on our
-- website at http://prosody.im/doc/configure
--
-- Tip: You can check that the syntax of this file is correct
-- when you have finished by running: luac -p prosody.cfg.lua
-- If there are any errors, it will let you know what and where
-- they are, otherwise it will keep quiet.
--
-- The only thing left to do is rename this file to remove the .dist ending, and fill in the
-- blanks. Good luck, and happy Jabbering!
---------- Server-wide settings ----------
-- Settings in this section apply to the whole server and are the default settings
-- for any virtual hosts
-- This is a (by default, empty) list of accounts that are admins
-- for the server. Note that you must create the accounts separately
-- (see http://prosody.im/doc/creating_accounts for info)
-- Example: admins = { "user1@example.com", "user2@example.net" }
admins = { }
-- Enable use of libevent for better performance under high load
-- For more information see: http://prosody.im/doc/libevent
--use_libevent = true;
-- This is the list of modules Prosody will load on startup.
-- It looks for mod_modulename.lua in the plugins folder, so make sure that exists too.
-- Documentation on modules can be found at: http://prosody.im/doc/modules
modules_enabled = {
-- Generally required
"roster"; -- Allow users to have a roster. Recommended ;)
"saslauth"; -- Authentication for clients and servers. Recommended if you want to log in.
"tls"; -- Add support for secure TLS on c2s/s2s connections
"dialback"; -- s2s dialback support
"disco"; -- Service discovery
-- Not essential, but recommended
"private"; -- Private XML storage (for room bookmarks, etc.)
"vcard"; -- Allow users to set vCards
--"privacy"; -- Support privacy lists
--"compression"; -- Stream compression
-- Nice to have
"legacyauth"; -- Legacy authentication. Only used by some old clients and bots.
"version"; -- Replies to server version requests
"uptime"; -- Report how long server has been running
"time"; -- Let others know the time here on this server
"ping"; -- Replies to XMPP pings with pongs
"pep"; -- Enables users to publish their mood, activity, playing music and more
"register"; -- Allow users to register on this server using a client and change passwords
"adhoc"; -- Support for "ad-hoc commands" that can be executed with an XMPP client
-- Admin interfaces
"admin_adhoc"; -- Allows administration via an XMPP client that supports ad-hoc commands
--"admin_telnet"; -- Opens telnet console interface on localhost port 5582
-- Other specific functionality
"posix"; -- POSIX functionality, sends server to background, enables syslog, etc.
--"bosh"; -- Enable BOSH clients, aka "Jabber over HTTP"
--"httpserver"; -- Serve static files from a directory over HTTP
--"groups"; -- Shared roster support
--"announce"; -- Send announcement to all online users
--"welcome"; -- Welcome users who register accounts
--"watchregistrations"; -- Alert admins of registrations
--"motd"; -- Send a message to users when they log in
};
-- These modules are auto-loaded, should you
-- (for some mad reason) want to disable
-- them then uncomment them below
modules_disabled = {
-- "presence"; -- Route user/contact status information
-- "message"; -- Route messages
-- "iq"; -- Route info queries
-- "offline"; -- Store offline messages
};
-- Disable account creation by default, for security
-- For more information see http://prosody.im/doc/creating_accounts
allow_registration = false;
-- Only allow encrypted streams? Encryption is already used when
-- available. These options will cause Prosody to deny connections that
-- are not encrypted. Note that some servers do not support s2s
-- encryption or have it disabled, including gmail.com and Google Apps
-- domains.
--c2s_require_encryption = false
--s2s_require_encryption = false
-- Select the authentication backend to use. The 'internal' providers
-- use Prosody's configured data storage to store the authentication data.
-- To allow Prosody to offer secure authentication mechanisms to clients, the
-- default provider stores passwords in plaintext. If you do not trust your
-- server please see http://prosody.im/doc/modules/mod_auth_internal_hashed
-- for information about using the hashed backend.
-- See http://prosody.im/doc/authentication for other possibilities including
-- Cyrus SASL.
authentication = "internal_plain"
-- Select the storage backend to use. By default Prosody uses flat files
-- in its configured data directory, but it also supports more backends
-- through modules. An "sql" backend is included by default, but requires
-- additional dependencies. See http://prosody.im/doc/storage for more info.
--storage = "sql" -- Default is "internal"
-- For the "sql" backend, you can uncomment *one* of the below to configure:
--sql = { driver = "SQLite3", database = "prosody.sqlite" } -- Default. 'database' is the filename.
--sql = { driver = "MySQL", database = "prosody", username = "prosody", password = "secret", host = "localhost" }
--sql = { driver = "PostgreSQL", database = "prosody", username = "prosody", password = "secret", host = "localhost" }
-- Logging configuration
-- For advanced logging see http://prosody.im/doc/logging
log = {
info = "/opt/var/log/prosody/prosody.log"; -- Change 'info' to 'debug' for verbose logging
error = "/opt/var/log/prosody/prosody.err";
-- "*syslog"; -- Uncomment this for logging to syslog; needs mod_posix
-- "*console"; -- Log to the console, useful for debugging with daemonize=false
}
-- Pidfile, used by prosodyctl and the init.d script
pidfile = "/opt/var/run/prosody/prosody.pid"
-- User and group, used for daemon
prosody_user = "prosody"
prosody_group = "prosody"
----------- Virtual hosts -----------
-- You need to add a VirtualHost entry for each domain you wish Prosody to serve.
-- Settings under each VirtualHost entry apply *only* to that host.
VirtualHost "localhost"
VirtualHost "example.com"
enabled = false -- Remove this line to enable this host
-- Assign this host a certificate for TLS, otherwise it would use the one
-- set in the global section (if any).
-- Note that old-style SSL on port 5223 only supports one certificate, and will always
-- use the global one.
ssl = {
key = "/opt/etc/prosody/certs/example.com.key";
certificate = "/opt/etc/prosody/certs/example.com.crt";
}
------ Components ------
-- You can specify components to add hosts that provide special services,
-- like multi-user conferences, and transports.
-- For more information on components, see http://prosody.im/doc/components
---Set up a MUC (multi-user chat) room server on conference.example.com:
--Component "conference.example.com" "muc"
-- Set up a SOCKS5 bytestream proxy for server-proxied file transfers:
--Component "proxy.example.com" "proxy65"
---Set up an external component (default component port is 5347)
--
-- External components allow adding various services, such as gateways/
-- transports to other networks like ICQ, MSN and Yahoo. For more info
-- see: http://prosody.im/doc/components#adding_an_external_component
--
--Component "gateway.example.com"
-- component_secret = "password"
| gpl-2.0 |
mercury233/ygopro-scripts | c45662855.lua | 9 | 1886 | --ジェムナイト・アイオーラ
function c45662855.initial_effect(c)
aux.EnableDualAttribute(c)
--salvage
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetDescription(aux.Stringid(45662855,0))
e1:SetCategory(CATEGORY_TOHAND)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetRange(LOCATION_MZONE)
e1:SetCountLimit(1)
e1:SetCondition(aux.IsDualState)
e1:SetCost(c45662855.cost)
e1:SetTarget(c45662855.target)
e1:SetOperation(c45662855.operation)
c:RegisterEffect(e1)
end
function c45662855.costfilter(c,tp)
return c:IsSetCard(0x47) and c:IsType(TYPE_MONSTER) and c:IsAbleToRemoveAsCost()
and Duel.IsExistingTarget(c45662855.tgfilter,tp,LOCATION_GRAVE,0,1,c)
end
function c45662855.tgfilter(c)
return c:IsSetCard(0x1047) and c:IsAbleToHand()
end
function c45662855.cost(e,tp,eg,ep,ev,re,r,rp,chk)
e:SetLabel(1)
return true
end
function c45662855.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c45662855.tgfilter(chkc) end
if chk==0 then
if e:GetLabel()==1 then
e:SetLabel(0)
return Duel.IsExistingMatchingCard(c45662855.costfilter,tp,LOCATION_GRAVE,0,1,nil,tp)
else
return Duel.IsExistingTarget(c45662855.tgfilter,tp,LOCATION_GRAVE,0,1,nil)
end
end
if e:GetLabel()==1 then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local cg=Duel.SelectMatchingCard(tp,c45662855.costfilter,tp,LOCATION_GRAVE,0,1,1,nil,tp)
Duel.Remove(cg,POS_FACEUP,REASON_COST)
e:SetLabel(0)
end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectTarget(tp,c45662855.tgfilter,tp,LOCATION_GRAVE,0,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_TOHAND,g,1,0,0)
end
function c45662855.operation(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc and tc:IsRelateToEffect(e) then
Duel.SendtoHand(tc,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,tc)
end
end
| gpl-2.0 |
Zenny89/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 |
Zenny89/darkstar | scripts/zones/Meriphataud_Mountains/npcs/Stone_Monument.lua | 32 | 1308 | -----------------------------------
-- Area: Meriphataud Mountains
-- NPC: Stone Monument
-- Involved in quest "An Explorer's Footsteps"
-- @pos 450.741 2.110 -290.736 119
-----------------------------------
package.loaded["scripts/zones/Meriphataud_Mountains/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Meriphataud_Mountains/TextIDs");
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0384);
end;
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
if (trade:getItemCount() == 1 and trade:hasItemQty(571,1)) then
player:tradeComplete();
player:addItem(570);
player:messageSpecial(ITEM_OBTAINED,570);
player:setVar("anExplorer-CurrentTablet",0x04000);
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 |
mercury233/ygopro-scripts | c81994591.lua | 2 | 1544 | --コアキメイルの金剛核
function c81994591.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(81994591,0))
e1:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetTarget(c81994591.target)
e1:SetOperation(c81994591.activate)
c:RegisterEffect(e1)
--indes
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(81994591,1))
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_GRAVE)
e2:SetCost(aux.bfgcost)
e2:SetOperation(c81994591.indop)
c:RegisterEffect(e2)
end
function c81994591.filter(c)
return c:IsSetCard(0x1d) and not c:IsCode(81994591) and c:IsAbleToHand()
end
function c81994591.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c81994591.filter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function c81994591.activate(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,c81994591.filter,tp,LOCATION_DECK,0,1,1,nil)
if g:GetCount()>0 then
Duel.SendtoHand(g,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g)
end
end
function c81994591.indop(e,tp,eg,ep,ev,re,r,rp)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_INDESTRUCTABLE)
e1:SetTargetRange(LOCATION_MZONE,0)
e1:SetTarget(aux.TargetBoolFunction(Card.IsSetCard,0x1d))
e1:SetReset(RESET_PHASE+PHASE_END)
e1:SetValue(1)
Duel.RegisterEffect(e1,tp)
end
| gpl-2.0 |
Zenny89/darkstar | scripts/globals/mobskills/Psychomancy.lua | 13 | 1127 | ---------------------------------------------------
-- Psychomancy
-- Steals MP from players in range.
-- Type: Magical
-- Utsusemi/Blink absorb: ignore shadow
---------------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------------
function onMobSkillCheck(target,mob,skill)
if (mob:AnimationSub() == 3) then
return 0;
end
return 1;
end;
function onMobWeaponSkill(target, mob, skill)
local dmgmod = 1;
local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*1.6,ELE_DARK,dmgmod,TP_MAB_BONUS,1);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_DARK,MOBPARAM_IGNORE_SHADOWS);
skill:setMsg(MSG_DRAIN_MP);
if (target:isUndead() == false) then
-- can't go over limited mp
if (target:getMP() < dmg) then
dmg = target:getMP();
end
target:delMP(dmg);
mob:addMP(dmg);
else
skill:setMsg(MSG_NO_EFFECT);
end
return dmg;
end;
| gpl-3.0 |
ivansafrin/Polycode | Examples/Lua/Graphics/MaterialsAndLighting/Scripts/AdvancedLighting.lua | 10 | 1668 | Services.ResourceManager:addDirResource("Resources", false)
scene = Scene(Scene.SCENE_3D)
ground = ScenePrimitive(ScenePrimitive.TYPE_PLANE, 5,5)
ground:setMaterialByName("GroundMaterial", Services.ResourceManager:getGlobalPool())
scene:addEntity(ground)
box = ScenePrimitive(ScenePrimitive.TYPE_TORUS, 0.8,0.3,30,20)
box:setMaterialByName("CubeMaterial", Services.ResourceManager:getGlobalPool())
box:setPosition(0.0, 0.5, 0.0)
scene:addEntity(box)
lightBase = Entity()
scene:addChild(lightBase)
light = SceneLight(SceneLight.POINT_LIGHT, scene, 20)
light:setPosition(3,2,7)
light:setLightColor(1,0,0)
scene:addLight(light)
light = SceneLight(SceneLight.POINT_LIGHT, scene, 20)
light:setPosition(-3,2,7)
light:setLightColor(0,1,0)
scene:addLight(light)
light = SceneLight(SceneLight.POINT_LIGHT, scene, 20)
light:setPosition(-3,2,-7)
light:setLightColor(0,0,1)
scene:addLight(light)
light = SceneLight(SceneLight.POINT_LIGHT, scene, 20)
light:setPosition(3,2,-7)
light:setLightColor(1,0,1)
scene:addLight(light)
light = SceneLight(SceneLight.SPOT_LIGHT, scene, 10)
light:setPosition(0,3,1)
light:setLightColor(1,1,0)
scene:addLight(light)
lightBase:addChild(light)
light:lookAt(Vector3(0,0,0), Vector3(0,1,0))
light:enableShadows(true)
light = SceneLight(SceneLight.SPOT_LIGHT, scene, 10)
light:setPosition(0,3,-1)
light:setLightColor(0,1,1)
scene:addLight(light)
lightBase:addChild(light)
light:lookAt(Vector3(0,0,0), Vector3(0,1,0))
light:enableShadows(true)
scene:getDefaultCamera():setPosition(5,5,5)
scene:getDefaultCamera():lookAt(Vector3(0,0,0), Vector3(0,1,0))
function Update(elapsed)
lightBase:setYaw(lightBase:getYaw()+ (elapsed * 10.0))
end
| mit |
mercury233/ygopro-scripts | c30430448.lua | 2 | 3574 | --凍てつく呪いの神碑
local s,id,o=GetID()
function s.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(id,0))
e1:SetCategory(CATEGORY_DISABLE+CATEGORY_REMOVE)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCountLimit(1,id+EFFECT_COUNT_CODE_OATH)
e1:SetTarget(s.target)
e1:SetOperation(s.activate)
c:RegisterEffect(e1)
--spsummon
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(id,1))
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetType(EFFECT_TYPE_ACTIVATE)
e2:SetCode(EVENT_FREE_CHAIN)
e2:SetCountLimit(1,id+EFFECT_COUNT_CODE_OATH)
e2:SetTarget(s.sptg)
e2:SetOperation(s.spop)
c:RegisterEffect(e2)
end
function s.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(1-tp) and aux.NegateEffectMonsterFilter(chkc) end
if chk==0 then return Duel.IsExistingTarget(aux.NegateEffectMonsterFilter,tp,0,LOCATION_MZONE,1,nil)
and Duel.GetDecktopGroup(1-tp,3):FilterCount(Card.IsAbleToRemove,nil)==3 end
Duel.Hint(HINT_OPSELECTED,1-tp,e:GetDescription())
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DISABLE)
Duel.SelectTarget(tp,aux.NegateEffectMonsterFilter,tp,0,LOCATION_MZONE,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_REMOVE,nil,3,1-tp,LOCATION_DECK)
end
function s.activate(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=Duel.GetFirstTarget()
if tc:IsFaceup() and tc:IsRelateToEffect(e) and tc:IsCanBeDisabledByEffect(e) then
Duel.NegateRelatedChain(tc,RESET_TURN_SET)
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_DISABLE)
e1:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END)
tc:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_DISABLE_EFFECT)
e2:SetValue(RESET_TURN_SET)
e2:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END)
tc:RegisterEffect(e2)
local g=Duel.GetDecktopGroup(1-tp,3)
if #g>0 then
Duel.BreakEffect()
Duel.DisableShuffleCheck()
Duel.Remove(g,POS_FACEUP,REASON_EFFECT)
end
end
s.skipop(e,tp)
end
function s.spfilter(c,e,tp)
return c:IsSetCard(0x17f) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
and Duel.GetLocationCountFromEx(tp,tp,nil,c,0x60)>0
end
function s.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(s.spfilter,tp,LOCATION_EXTRA,0,1,nil,e,tp) end
Duel.Hint(HINT_OPSELECTED,1-tp,e:GetDescription())
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_EXTRA)
end
function s.spop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,s.spfilter,tp,LOCATION_EXTRA,0,1,1,nil,e,tp)
if g:GetCount()>0 then
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP,0x60)
end
s.skipop(e,tp)
end
function s.skipop(e,tp)
if e:IsHasType(EFFECT_TYPE_ACTIVATE) then
local ph=Duel.GetCurrentPhase()
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_SKIP_BP)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_OATH)
e1:SetTargetRange(1,0)
if Duel.GetTurnPlayer()==tp and ph>PHASE_MAIN1 and ph<PHASE_MAIN2 then
e1:SetLabel(Duel.GetTurnCount())
e1:SetCondition(s.skipcon)
e1:SetReset(RESET_PHASE+PHASE_BATTLE+RESET_SELF_TURN,2)
else
e1:SetReset(RESET_PHASE+PHASE_BATTLE+RESET_SELF_TURN,1)
end
Duel.RegisterEffect(e1,tp)
end
end
function s.skipcon(e)
return Duel.GetTurnCount()~=e:GetLabel()
end
| gpl-2.0 |
mercury233/ygopro-scripts | c32663969.lua | 2 | 1739 | --ドミノ
function c32663969.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
c:RegisterEffect(e1)
--destroy
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(32663969,0))
e2:SetCategory(CATEGORY_DESTROY)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e2:SetRange(LOCATION_SZONE)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET)
e2:SetCode(EVENT_BATTLE_DESTROYED)
e2:SetCondition(c32663969.descon)
e2:SetCost(c32663969.descost)
e2:SetTarget(c32663969.destg)
e2:SetOperation(c32663969.desop)
c:RegisterEffect(e2)
end
function c32663969.cfilter(c,tp)
return c:IsLocation(LOCATION_GRAVE) and c:IsReason(REASON_BATTLE) and c:IsPreviousControler(tp)
end
function c32663969.descon(e,tp,eg,ep,ev,re,r,rp)
return eg:IsExists(c32663969.cfilter,1,nil,1-tp)
end
function c32663969.descost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(Card.IsAbleToGraveAsCost,tp,LOCATION_MZONE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE)
local g=Duel.SelectMatchingCard(tp,Card.IsAbleToGraveAsCost,tp,LOCATION_MZONE,0,1,1,nil)
Duel.SendtoGrave(g,REASON_COST)
end
function c32663969.destg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(1-tp) end
if chk==0 then return Duel.IsExistingTarget(aux.TRUE,tp,0,LOCATION_MZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local g=Duel.SelectTarget(tp,aux.TRUE,tp,0,LOCATION_MZONE,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,1,0,0)
end
function c32663969.desop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.Destroy(tc,REASON_EFFECT)
end
end
| gpl-2.0 |
Cavitt/vanilla-ot | data/npc/lib/npcsystem/modules.lua | 1 | 48869 | -- Advanced NPC System (Created by Jiddo),
-- Modified by TheForgottenServer Team.
if(Modules == nil) then
-- Constants used to separate buying from selling.
SHOPMODULE_SELL_ITEM = 1
SHOPMODULE_BUY_ITEM = 2
SHOPMODULE_BUY_ITEM_CONTAINER = 3
-- Constants used for shop mode. Notice: addBuyableItemContainer is working on all modes
SHOPMODULE_MODE_TALK = 1 -- Old system used before Tibia 8.2: sell/buy item name
SHOPMODULE_MODE_TRADE = 2 -- Trade window system introduced in Tibia 8.2
SHOPMODULE_MODE_BOTH = 3 -- Both working at one time
-- Used in shop mode
SHOPMODULE_MODE = SHOPMODULE_MODE_BOTH
-- Constants used for outfit giving mode
OUTFITMODULE_FUNCTION_OLD = { doPlayerAddOutfit, canPlayerWearOutfit } -- lookType usage
OUTFITMODULE_FUNCTION_NEW = { doPlayerAddOutfitId, canPlayerWearOutfitId } -- OutfitId usage
-- Used in outfit module
OUTFITMODULE_FUNCTION = OUTFITMODULE_FUNCTION_NEW
if(OUTFITMODULE_FUNCTION[1] == nil or OUTFITMODULE_FUNCTION[2] == nil) then
OUTFITMODULE_FUNCTION = OUTFITMODULE_FUNCTION_OLD
end
Modules = {
parseableModules = {}
}
StdModule = {}
-- These callback function must be called with parameters.npcHandler = npcHandler in the parameters table or they will not work correctly.
-- Notice: The members of StdModule have not yet been tested. If you find any bugs, please report them to me.
-- Usage:
-- keywordHandler:addKeyword({'offer'}, StdModule.say, {npcHandler = npcHandler, text = 'I sell many powerful melee weapons.'})
function StdModule.say(cid, message, keywords, parameters, node)
local npcHandler = parameters.npcHandler
if(npcHandler == nil) then
print('[Warning - ' .. getCreatureName(getNpcId()) .. '] NpcSystem:', 'StdModule.say - Call without any npcHandler instance.')
return false
end
local onlyFocus = (parameters.onlyFocus == nil or parameters.onlyFocus == true)
if(not npcHandler:isFocused(cid) and onlyFocus) then
return false
end
local parseInfo = {[TAG_PLAYERNAME] = getCreatureName(cid)}
npcHandler:say(npcHandler:parseMessage(parameters.text or parameters.message, parseInfo), cid, parameters.publicize and true)
if(parameters.reset) then
npcHandler:resetNpc(cid)
elseif(parameters.moveup and type(parameters.moveup) == 'number') then
npcHandler.keywordHandler:moveUp(parameters.moveup)
end
return true
end
--Usage:
-- local node1 = keywordHandler:addKeyword({'promot'}, StdModule.say, {npcHandler = npcHandler, text = 'I can promote you for 20000 brozne coins. Do you want me to promote you?'})
-- node1:addChildKeyword({'yes'}, StdModule.promotePlayer, {npcHandler = npcHandler, cost = 20000, promotion = 1, level = 20}, text = 'Congratulations! You are now promoted.')
-- node1:addChildKeyword({'no'}, StdModule.say, {npcHandler = npcHandler, text = 'Alright then, come back when you are ready.'}, reset = true)
function StdModule.promotePlayer(cid, message, keywords, parameters, node)
local npcHandler = parameters.npcHandler
if(npcHandler == nil) then
print('[Warning - ' .. getCreatureName(getNpcId()) .. '] NpcSystem:', 'StdModule.promotePlayer - Call without any npcHandler instance.')
return false
end
if(not npcHandler:isFocused(cid)) then
return false
end
if(isPremium(cid) or not getBooleanFromString(getConfigValue('premiumForPromotion'))) then
if(getPlayerPromotionLevel(cid) >= parameters.promotion) then
npcHandler:say('You are already promoted!', cid)
elseif(getPlayerLevel(cid) < parameters.level) then
npcHandler:say('I am sorry, but I can only promote you once you have reached level ' .. parameters.level .. '.', cid)
elseif(not doPlayerRemoveMoney(cid, parameters.cost)) then
npcHandler:say('You do not have enough money!', cid)
else
doPlayerSetPromotionLevel(cid, parameters.promotion)
npcHandler:say(parameters.text, cid)
end
else
npcHandler:say("You need a premium account in order to get promoted.", cid)
end
npcHandler:resetNpc(cid)
return true
end
function StdModule.learnSpell(cid, message, keywords, parameters, node)
local npcHandler = parameters.npcHandler
if(npcHandler == nil) then
print('[Warning - ' .. getCreatureName(getNpcId()) .. '] NpcSystem:', 'StdModule.learnSpell - Call without any npcHandler instance.')
return false
end
if(not npcHandler:isFocused(cid)) then
return false
end
if(isPremium(cid) or not(parameters.premium)) then
if(getPlayerLearnedInstantSpell(cid, parameters.spellName)) then
npcHandler:say('You already know this spell.', cid)
elseif(getPlayerLevel(cid) < parameters.level) then
npcHandler:say('You need to obtain a level of ' .. parameters.level .. ' or higher to be able to learn ' .. parameters.spellName .. '.', cid)
elseif(not parameters.vocation(cid)) then
npcHandler:say('This spell is not for your vocation', cid)
elseif(not doPlayerRemoveMoney(cid, parameters.price)) then
npcHandler:say('You do not have enough money, this spell costs ' .. parameters.price .. ' gold coins.', cid)
else
npcHandler:say('You have learned ' .. parameters.spellName .. '.', cid)
playerLearnInstantSpell(cid, parameters.spellName)
end
else
npcHandler:say('You need a premium account in order to buy ' .. parameters.spellName .. '.', cid)
end
npcHandler:resetNpc(cid)
return true
end
function StdModule.bless(cid, message, keywords, parameters, node)
local npcHandler = parameters.npcHandler
if(npcHandler == nil) then
print('[Warning - ' .. getCreatureName(getNpcId()) .. '] NpcSystem:', 'StdModule.bless - Call without any npcHandler instance.')
return false
end
if(not getBooleanFromString(getConfigValue('blessings'))) then
npcHandler:say("Sorry, but Gods moved back my permission to bless anyone.", cid)
return false
end
if(not npcHandler:isFocused(cid)) then
return false
end
if(isPremium(cid) or not getBooleanFromString(getConfigValue('blessingsOnlyPremium')) or not parameters.premium) then
local price = parameters.baseCost
if(getPlayerLevel(cid) > parameters.startLevel) then
price = (price + ((math.min(parameters.endLevel, getPlayerLevel(cid)) - parameters.startLevel) * parameters.levelCost))
end
if(parameters.number > 0) then
if(getPlayerBlessing(cid, parameters.number)) then
npcHandler:say("Gods have already blessed you with this blessing!", cid)
elseif(not doPlayerRemoveMoney(cid, price)) then
npcHandler:say("You don't have enough money for blessing.", cid)
else
npcHandler:say("You have been blessed by one of the five gods!", cid)
doPlayerAddBlessing(cid, parameters.number)
end
else
if(getPlayerPVPBlessing(cid)) then
npcHandler:say("Gods have already blessed you with this blessing!", cid)
elseif(not doPlayerRemoveMoney(cid, price)) then
npcHandler:say("You don't have enough money for blessing.", cid)
else
local any = false
for i = 1, 5 do
if(getPlayerBlessing(cid, i)) then
any = true
break
end
end
if(any) then
npcHandler:say("You have been blessed by the god of war!", cid)
doPlayerSetPVPBlessing(cid)
else
npcHandler:say("You need to be blessed by at least one god to get this blessing.", cid)
end
end
end
else
npcHandler:say('You need a premium account in order to be blessed.', cid)
end
npcHandler:resetNpc(cid)
return true
end
function StdModule.travel(cid, message, keywords, parameters, node)
local npcHandler = parameters.npcHandler
if(npcHandler == nil) then
print('[Warning - ' .. getCreatureName(getNpcId()) .. '] NpcSystem:', 'StdModule.travel - Call without any npcHandler instance.')
return false
end
if(not npcHandler:isFocused(cid)) then
return false
end
local storage, pzLocked = parameters.storageValue or (EMPTY_STORAGE + 1), parameters.allowLocked or false
if(parameters.premium and not isPremium(cid)) then
npcHandler:say('I\'m sorry, but you need a premium account to go there.', cid)
elseif(parameters.level ~= nil and getPlayerLevel(cid) < parameters.level) then
npcHandler:say('You must reach level ' .. parameters.level .. ' before I can let you go there.', cid)
elseif(parameters.storageId ~= nil and getPlayerStorageValue(cid, parameters.storageId) < storage) then
npcHandler:say(parameters.storageInfo or 'You may not travel there yet!', cid)
elseif(not pzLocked and isPlayerPzLocked(cid)) then
npcHandler:say('First get rid of those blood stains!', cid)
elseif(not doPlayerRemoveMoney(cid, parameters.cost)) then
npcHandler:say('You don\'t have enough money.', cid)
else
npcHandler:say('Happy hunting.', cid)
npcHandler:releaseFocus(cid)
doTeleportThing(cid, parameters.destination, false)
doSendMagicEffect(parameters.destination, CONST_ME_TELEPORT)
end
npcHandler:resetNpc(cid)
return true
end
FocusModule = {
npcHandler = nil
}
-- Creates a new instance of FocusModule without an associated NpcHandler.
function FocusModule:new()
local obj = {}
setmetatable(obj, self)
self.__index = self
return obj
end
-- Inits the module and associates handler to it.
function FocusModule:init(handler)
self.npcHandler = handler
for i, word in pairs(FOCUS_GREETWORDS) do
local obj = {}
table.insert(obj, word)
obj.callback = FOCUS_GREETWORDS.callback or FocusModule.messageMatcher
handler.keywordHandler:addKeyword(obj, FocusModule.onGreet, {module = self})
end
for i, word in pairs(FOCUS_FAREWELLWORDS) do
local obj = {}
table.insert(obj, word)
obj.callback = FOCUS_FAREWELLWORDS.callback or FocusModule.messageMatcher
handler.keywordHandler:addKeyword(obj, FocusModule.onFarewell, {module = self})
end
end
-- Greeting callback function.
function FocusModule.onGreet(cid, message, keywords, parameters)
parameters.module.npcHandler:onGreet(cid)
return true
end
-- UnGreeting callback function.
function FocusModule.onFarewell(cid, message, keywords, parameters)
if(not parameters.module.npcHandler:isFocused(cid)) then
return false
end
parameters.module.npcHandler:onFarewell(cid)
parameters.module.npcHandler:resetNpc(cid)
return true
end
-- Custom message matching callback function for greeting messages.
function FocusModule.messageMatcher(keywords, message)
local spectators = getSpectators(getCreaturePosition(getNpcId()), 7, 7)
for i, word in pairs(keywords) do
if(type(word) == 'string') then
if(string.find(message, word) and not string.find(message, '[%w+]' .. word) and not string.find(message, word .. '[%w+]')) then
if(string.find(message, getCreatureName(getNpcId()))) then
return true
end
for i, uid in ipairs(spectators) do
if(string.find(message, getCreatureName(uid))) then
return false
end
end
return true
end
end
end
return false
end
KeywordModule = {
npcHandler = nil
}
-- Add it to the parseable module list.
Modules.parseableModules['module_keywords'] = KeywordModule
function KeywordModule:new()
local obj = {}
setmetatable(obj, self)
self.__index = self
return obj
end
function KeywordModule:init(handler)
self.npcHandler = handler
end
-- Parses all known parameters.
function KeywordModule:parseParameters()
local ret = NpcSystem.getParameter('keywords')
if(ret ~= nil) then
self:parseKeywords(ret)
end
end
function KeywordModule:parseKeywords(data)
local n = 1
for keys in string.gmatch(data, '[^;]+') do
local i = 1
local keywords = {}
for temp in string.gmatch(keys, '[^,]+') do
table.insert(keywords, temp)
i = i + 1
end
if(i ~= 1) then
local reply = NpcSystem.getParameter('keyword_reply' .. n)
if(reply ~= nil) then
self:addKeyword(keywords, reply)
else
print('[Warning - ' .. getCreatureName(getNpcId()) .. '] NpcSystem:', 'Parameter \'' .. 'keyword_reply' .. n .. '\' missing. Skipping...')
end
else
print('[Warning - ' .. getCreatureName(getNpcId()) .. '] NpcSystem:', 'No keywords found for keyword set #' .. n .. '. Skipping...')
end
n = n + 1
end
end
function KeywordModule:addKeyword(keywords, reply)
self.npcHandler.keywordHandler:addKeyword(keywords, StdModule.say, {npcHandler = self.npcHandler, onlyFocus = true, text = reply, reset = true})
end
TravelModule = {
npcHandler = nil,
destinations = nil,
yesNode = nil,
noNode = nil,
}
-- Add it to the parseable module list.
Modules.parseableModules['module_travel'] = TravelModule
function TravelModule:new()
local obj = {}
setmetatable(obj, self)
self.__index = self
return obj
end
function TravelModule:init(handler)
self.npcHandler = handler
self.yesNode = KeywordNode:new(SHOP_YESWORD, TravelModule.onConfirm, {module = self})
self.noNode = KeywordNode:new(SHOP_NOWORD, TravelModule.onDecline, {module = self})
self.destinations = {}
end
-- Parses all known parameters.
function TravelModule:parseParameters()
local ret = NpcSystem.getParameter('travel_destinations')
if(ret ~= nil) then
self:parseDestinations(ret)
for _, word in ipairs({'destination', 'list', 'where', 'travel'}) do
self.npcHandler.keywordHandler:addKeyword({word}, TravelModule.listDestinations, {module = self})
end
end
end
function TravelModule:parseDestinations(data)
for destination in string.gmatch(data, '[^;]+') do
local i, name, pos, cost, premium, level, storage = 1, nil, {x = nil, y = nil, z = nil}, nil, false
for tmp in string.gmatch(destination, '[^,]+') do
if(i == 1) then
name = tmp
elseif(i == 2) then
pos.x = tonumber(tmp)
elseif(i == 3) then
pos.y = tonumber(tmp)
elseif(i == 4) then
pos.z = tonumber(tmp)
elseif(i == 5) then
cost = tonumber(tmp)
elseif(i == 6) then
premium = getBooleanFromString(tmp)
else
print('[Warning - ' .. getCreatureName(getNpcId()) .. '] NpcSystem:', 'Unknown parameter found in travel destination parameter.', tmp, destination)
end
i = i + 1
end
if(name ~= nil and pos.x ~= nil and pos.y ~= nil and pos.z ~= nil and cost ~= nil) then
self:addDestination(name, pos, cost, premium)
else
print('[Warning - ' .. getCreatureName(getNpcId()) .. '] NpcSystem:', 'Parameter(s) missing for travel destination:', name, pos, cost, premium)
end
end
end
function TravelModule:addDestination(name, position, price, premium)
table.insert(self.destinations, name)
local parameters = {
cost = price,
destination = position,
premium = premium,
module = self
}
local keywords, bringWords = {}, {}
table.insert(keywords, name)
table.insert(bringWords, 'bring me to ' .. name)
self.npcHandler.keywordHandler:addKeyword(bringWords, TravelModule.bring, parameters)
local node = self.npcHandler.keywordHandler:addKeyword(keywords, TravelModule.travel, parameters)
node:addChildKeywordNode(self.yesNode)
node:addChildKeywordNode(self.noNode)
end
function TravelModule.travel(cid, message, keywords, parameters, node)
local module = parameters.module
if(not module.npcHandler:isFocused(cid)) then
return false
end
local _priceMsg = (parameters.cost > 0) and ' for ' .. parameters.cost .. ' gold coins' or ''
module.npcHandler:say('Do you want to travel to ' .. keywords[1] .. _priceMsg .. '?', cid)
return true
end
function TravelModule.onConfirm(cid, message, keywords, parameters, node)
local module = parameters.module
if(not module.npcHandler:isFocused(cid)) then
return false
end
local parent = node:getParent():getParameters()
if(isPremium(cid) or not parent.premium) then
if(not isPlayerPzLocked(cid)) then
if(doPlayerRemoveMoney(cid, parent.cost)) then
module.npcHandler:say('Very well.', cid)
module.npcHandler:releaseFocus(cid)
-- START CUSTOM: Mercenary
local function spawnMerc(master, name, destination)
if(getCreatureSummons(master)[1] == nil)then
local spawnedMerc = doCreateMonster(name, destination, true, true)
doConvinceCreature(master, spawnedMerc)
end
end
local merc = getCreatureSummons(cid)[1]
if(merc)then
local vocID = getCreatureStorage(merc, "vocation")
if(getCreatureMaxMana(merc) > 0) then
local vocations = {"Sorcerer", "Druid", "Paladin", "Knight"}
local name = vocations[vocID]
if(name)then
addEvent(spawnMerc, 500, cid, name, parent.destination)
end
end
end
-- END CUSTOM: Mercenary
doTeleportThing(cid, parent.destination, true)
doSendMagicEffect(parent.destination, CONST_ME_TELEPORT)
else
module.npcHandler:say('You don\'t have enough money.', cid)
end
else
module.npcHandler:say('First get rid of those blood stains!', cid)
end
else
module.npcHandler:say('I\'m sorry, but you need a premium account to go there.', cid)
end
module.npcHandler:resetNpc(cid)
return true
end
-- onDecline keyword callback function. Generally called when the player sais 'no' after wanting to buy an item.
function TravelModule.onDecline(cid, message, keywords, parameters, node)
local module = parameters.module
if(not module.npcHandler:isFocused(cid)) then
return false
end
module.npcHandler:say(module.npcHandler:parseMessage(module.npcHandler:getMessage(MESSAGE_DECLINE), {[TAG_PLAYERNAME] = getCreatureName(cid)}), cid)
module.npcHandler:resetNpc(cid)
return true
end
function TravelModule.bring(cid, message, keywords, parameters, node)
local module = parameters.module
if(not module.npcHandler:isFocused(cid)) then
return false
end
if((isPremium(cid) or not parameters.premium) and not isPlayerPzLocked(cid) and doPlayerRemoveMoney(cid, parameters.cost)) then
module.npcHandler:say('Set the sails!', cid)
module.npcHandler:releaseFocus(cid)
doTeleportThing(cid, parameters.destination, false)
doSendMagicEffect(parameters.destination, CONST_ME_TELEPORT)
end
module.npcHandler:releaseFocus(cid)
return true
end
function TravelModule.listDestinations(cid, message, keywords, parameters, node)
local module = parameters.module
if(not module.npcHandler:isFocused(cid)) then
return false
end
local msg = nil
for _, destination in ipairs(module.destinations) do
if(msg ~= nil) then
msg = msg .. ", "
else
msg = ""
end
msg = msg .. "{" .. destination .. "}"
end
module.npcHandler:say(msg .. ".", cid)
module.npcHandler:resetNpc(cid)
return true
end
OutfitModule = {
npcHandler = nil,
outfits = nil,
yesNode = nil,
noNode = nil,
}
-- Add it to the parseable module list.
Modules.parseableModules['module_outfit'] = OutfitModule
function OutfitModule:new()
if(OUTFITMODULE_FUNCTION[1] == nil or OUTFITMODULE_FUNCTION[2] == nil) then
return nil
end
local obj = {}
setmetatable(obj, self)
self.__index = self
return obj
end
function OutfitModule:init(handler)
self.npcHandler = handler
self.yesNode = KeywordNode:new(SHOP_YESWORD, OutfitModule.onConfirm, {module = self})
self.noNode = KeywordNode:new(SHOP_NOWORD, OutfitModule.onDecline, {module = self})
self.outfits = {}
end
-- Parses all known parameters.
function OutfitModule:parseParameters()
local ret = NpcSystem.getParameter('outfits')
if(ret ~= nil) then
self:parseKeywords(ret)
for _, word in ipairs({'outfits', 'addons'}) do
self.npcHandler.keywordHandler:addKeyword({word}, OutfitModule.listOutfits, {module = self})
end
end
end
function OutfitModule:parseKeywords(data)
local n = 1
for outfit in string.gmatch(data, '[^;]+') do
local i, keywords = 1, {}
for tmp in string.gmatch(outfit, '[^,]+') do
table.insert(keywords, tmp)
i = i + 1
end
if(i > 0) then
local ret = NpcSystem.getParameter('outfit' .. n)
if(ret ~= nil) then
self:parseList(keywords, ret)
else
print('[Warning - ' .. getCreatureName(getNpcId()) .. '] NpcSystem:', 'Missing \'outfit' .. n .. '\' parameter, skipping...')
end
else
print('[Warning - ' .. getCreatureName(getNpcId()) .. '] NpcSystem:', 'No keywords found for outfit set #' .. n .. ', skipping...')
end
n = n + 1
end
end
function OutfitModule:parseList(keywords, data)
local outfit, items = nil, {}
for list in string.gmatch(data, '[^;]+') do
local a, b, c, d, e = nil, nil, nil, nil, 1
for tmp in string.gmatch(list, '[^,]+') do
if(e == 1) then
a = tmp
elseif(e == 2) then
b = tmp
elseif(e == 3) then
c = tmp
elseif(e == 4) then
d = tmp
else
print('[Warning - ' .. getCreatureName(getNpcId()) .. '] NpcSystem:', 'Unknown parameter found in outfit list while parsing ' .. (outfit == nil and 'outfit' or 'item') .. '.', tmp, list)
end
e = e + 1
end
if(outfit == nil) then
outfit = {tonumber(a), tonumber(b), getBooleanFromString(c), d}
elseif(a ~= nil) then
local tmp = tonumber(a)
if((tmp ~= nil or tostring(a) == "money") and b ~= nil and c ~= nil) then
a = tmp or 20000
tmp = tonumber(d)
if(tmp == nil) then
tmp = -1
end
items[a] = {b, tmp, c}
else
print('[Warning - ' .. getCreatureName(getNpcId()) .. '] NpcSystem:', 'Missing parameter(s) for outfit items.', b, c, d)
end
else
print('[Warning - ' .. getCreatureName(getNpcId()) .. '] NpcSystem:', 'Missing base parameter for outfit items.', a)
end
end
if(type(outfit) == 'table') then
local tmp = true
for i = 1, 2 do
if(outfit[i] == nil) then
tmp = false
break
end
end
if(tmp and table.maxn(items) > 0) then
self:addOutfit(keywords, outfit, items)
else
print('[Warning - ' .. getCreatureName(getNpcId()) .. '] NpcSystem:', 'Invalid outfit, addon or empty items pool.', data)
end
end
end
function OutfitModule:addOutfit(keywords, outfit, items)
table.insert(self.outfits, keywords[1])
local parameters = {
outfit = outfit[1],
addon = outfit[2],
premium = outfit[3],
gender = nil,
items = items,
module = self
}
if(outfit[4] ~= nil) then
local tmp = string.lower(tostring(outfit[5]))
if(tmp == 'male' or tmp == '1') then
parameters.gender = 1
elseif(tmp == 'female' or tmp == '0') then
parameters.gender = 0
end
end
for i, name in pairs(keywords) do
local words = {}
table.insert(words, name)
local node = self.npcHandler.keywordHandler:addKeyword(words, OutfitModule.obtain, parameters)
node:addChildKeywordNode(self.yesNode)
node:addChildKeywordNode(self.noNode)
end
end
function OutfitModule.obtain(cid, message, keywords, parameters, node)
local module = parameters.module
if(not module.npcHandler:isFocused(cid)) then
return false
end
local i, items, size = 0, nil, table.maxn(parameters.items)
for k, v in pairs(parameters.items) do
if(v[1] ~= "storageset") then
i = i + 1
if(items ~= nil) then
if(i == size) then
items = items .. " and "
else
items = items .. ", "
end
else
items = ""
end
if(tonumber(v[1]) ~= nil and tonumber(v[1]) > 1) then
items = items .. v[1] .. " "
end
items = items .. v[3]
end
end
module.npcHandler:say('Do you want ' .. keywords[1] .. ' ' .. (addon == 0 and "outfit" or "addon") .. ' for ' .. items .. '?', cid)
return true
end
function OutfitModule.onConfirm(cid, message, keywords, parameters, node)
local module = parameters.module
if(not module.npcHandler:isFocused(cid)) then
return false
end
local parent = node:getParent():getParameters()
if(isPremium(cid) or not parent.premium) then
if(not OUTFITMODULE_FUNCTION[2](cid, parent.outfit, parent.addon)) then
if(parent.addon == 0 or OUTFITMODULE_FUNCTION[2](cid, parent.outfit)) then
if(parent.gender == nil or parent.gender == getPlayerSex(cid)) then
local found = true
for k, v in pairs(parent.items) do
local tmp = tonumber(v[1])
if(tmp == nil) then
if(v[1] == "storagecheck") then
if(getCreatureStorage(cid, k) < v[2]) then
found = false
end
elseif(v[1] == "outfitid") then
if(not canPlayerWearOutfitId(cid, k, v[2])) then
found = false
end
elseif(v[1] == "outfit") then
if(not canPlayerWearOutfit(cid, k, v[2])) then
found = false
end
else
found = false
end
elseif(k == 20000) then
if(getPlayerMoney(cid) < tmp) then
found = false
end
elseif(getPlayerItemCount(cid, k, v[2]) < tmp) then
found = false
end
if(not found) then
break
end
end
if(found) then
for k, v in pairs(parent.items) do
if(tonumber(v[1]) ~= nil) then
if(k == 20000) then
doPlayerRemoveMoney(cid, v[1])
else
doPlayerRemoveItem(cid, k, v[1], v[2])
end
elseif(v[1] == "storageset") then
doCreatureSetStorage(cid, k, v[2])
end
end
module.npcHandler:say('It was a pleasure to dress you.', cid)
OUTFITMODULE_FUNCTION[1](cid, parent.outfit, parent.addon)
doPlayerSetStorageValue(cid, parent.storageId, storage)
else
module.npcHandler:say('You don\'t have these items!', cid)
end
else
module.npcHandler:say('Sorry, this ' .. (parent.addon == 0 and 'outfit' or 'addon') .. ' is not for your gender.', cid)
end
else
module.npcHandler:say('I will not dress you with addon of outfit you cannot wear!', cid)
end
else
module.npcHandler:say('You already have this ' .. (parent.addon == 0 and 'outfit' or 'addon') .. '!', cid)
end
else
module.npcHandler:say('Sorry, I dress only premium players.', cid)
end
module.npcHandler:resetNpc(cid)
return true
end
-- onDecline keyword callback function. Generally called when the player sais 'no' after wanting to buy an item.
function OutfitModule.onDecline(cid, message, keywords, parameters, node)
local module = parameters.module
if(not module.npcHandler:isFocused(cid)) then
return false
end
module.npcHandler:say(module.npcHandler:parseMessage(module.npcHandler:getMessage(MESSAGE_DECLINE), {[TAG_PLAYERNAME] = getCreatureName(cid)}), cid)
module.npcHandler:resetNpc(cid)
return true
end
function OutfitModule.listOutfits(cid, message, keywords, parameters, node)
local module = parameters.module
if(not module.npcHandler:isFocused(cid)) then
return false
end
local msg, size = nil, table.maxn(module.outfits)
if(size > 0) then
for i, outfit in ipairs(module.outfits) do
if(msg ~= nil) then
if(i == size) then
msg = msg .. " and "
else
msg = msg .. ", "
end
else
msg = "I can dress you into "
end
msg = msg .. "{" .. outfit .. "}"
end
else
msg = "Sorry, I have nothing to offer right now."
end
module.npcHandler:say(msg .. ".", cid)
module.npcHandler:resetNpc(cid)
return true
end
ShopModule = {
npcHandler = nil,
yesNode = nil,
noNode = nil,
noText = '',
maxCount = 100,
amount = 0
}
-- Add it to the parseable module list.
Modules.parseableModules['module_shop'] = ShopModule
-- Creates a new instance of ShopModule
function ShopModule:new()
local obj = {}
setmetatable(obj, self)
self.__index = self
return obj
end
-- Parses all known parameters.
function ShopModule:parseParameters()
local ret = NpcSystem.getParameter('shop_buyable')
if(ret ~= nil) then
self:parseBuyable(ret)
end
local ret = NpcSystem.getParameter('shop_sellable')
if(ret ~= nil) then
self:parseSellable(ret)
end
local ret = NpcSystem.getParameter('shop_buyable_containers')
if(ret ~= nil) then
self:parseBuyableContainers(ret)
end
end
-- Parse a string contaning a set of buyable items.
function ShopModule:parseBuyable(data)
for item in string.gmatch(data, '[^;]+') do
local i, name, itemid, cost, subType, realName = 1, nil, nil, nil, nil, nil
for tmp in string.gmatch(item, '[^,]+') do
if(i == 1) then
name = tmp
elseif(i == 2) then
itemid = tonumber(tmp)
elseif(i == 3) then
cost = tonumber(tmp)
elseif(i == 4) then
subType = tonumber(tmp)
elseif(i == 5) then
realName = tmp
else
print('[Warning - ' .. getCreatureName(getNpcId()) .. '] NpcSystem:', 'Unknown parameter found in buyable items parameter.', tmp, item)
end
i = i + 1
end
if(SHOPMODULE_MODE == SHOPMODULE_MODE_TRADE) then
if(itemid ~= nil and cost ~= nil) then
if(isItemFluidContainer(itemid) and subType == nil) then
print('[Warning - ' .. getCreatureName(getNpcId()) .. '] NpcSystem:', 'SubType missing for parameter item:', item)
else
self:addBuyableItem(nil, itemid, cost, subType, realName)
end
else
print('[Warning - ' .. getCreatureName(getNpcId()) .. '] NpcSystem:', 'Parameter(s) missing for item:', itemid, cost)
end
elseif(name ~= nil and itemid ~= nil and cost ~= nil) then
if(isItemFluidContainer(itemid) and subType == nil) then
print('[Warning - ' .. getCreatureName(getNpcId()) .. '] NpcSystem:', 'SubType missing for parameter item:', item)
else
local names = {}
table.insert(names, name)
self:addBuyableItem(names, itemid, cost, subType, realName)
end
else
print('[Warning - ' .. getCreatureName(getNpcId()) .. '] NpcSystem:', 'Parameter(s) missing for item:', name, itemid, cost)
end
end
end
-- Parse a string contaning a set of sellable items.
function ShopModule:parseSellable(data)
for item in string.gmatch(data, '[^;]+') do
local i, name, itemid, cost, realName = 1, nil, nil, nil, nil
for temp in string.gmatch(item, '[^,]+') do
if(i == 1) then
name = temp
elseif(i == 2) then
itemid = tonumber(temp)
elseif(i == 3) then
cost = tonumber(temp)
elseif(i == 4) then
realName = temp
else
print('[Warning - ' .. getCreatureName(getNpcId()) .. '] NpcSystem:', 'Unknown parameter found in sellable items parameter.', temp, item)
end
i = i + 1
end
if(SHOPMODULE_MODE == SHOPMODULE_MODE_TRADE) then
if(itemid ~= nil and cost ~= nil) then
self:addSellableItem(nil, itemid, cost, realName)
else
print('[Warning - ' .. getCreatureName(getNpcId()) .. '] NpcSystem:', 'Parameter(s) missing for item:', itemid, cost)
end
elseif(name ~= nil and itemid ~= nil and cost ~= nil) then
local names = {}
table.insert(names, name)
self:addSellableItem(names, itemid, cost, realName)
else
print('[Warning - ' .. getCreatureName(getNpcId()) .. '] NpcSystem:', 'Parameter(s) missing for item:', name, itemid, cost)
end
end
end
-- Parse a string contaning a set of buyable items.
function ShopModule:parseBuyableContainers(data)
for item in string.gmatch(data, '[^;]+') do
local i, name, container, itemid, cost, subType, realName = 1, nil, nil, nil, nil, nil, nil
for temp in string.gmatch(item, '[^,]+') do
if(i == 1) then
name = temp
elseif(i == 2) then
itemid = tonumber(temp)
elseif(i == 3) then
itemid = tonumber(temp)
elseif(i == 4) then
cost = tonumber(temp)
elseif(i == 5) then
subType = tonumber(temp)
elseif(i == 6) then
realName = temp
else
print('[Warning - ' .. getCreatureName(getNpcId()) .. '] NpcSystem:', 'Unknown parameter found in buyable items parameter.', temp, item)
end
i = i + 1
end
if(name ~= nil and container ~= nil and itemid ~= nil and cost ~= nil) then
if(isItemFluidContainer(itemid) and subType == nil) then
print('[Warning - ' .. getCreatureName(getNpcId()) .. '] NpcSystem:', 'SubType missing for parameter item:', item)
else
local names = {}
table.insert(names, name)
self:addBuyableItemContainer(names, container, itemid, cost, subType, realName)
end
else
print('[Warning - ' .. getCreatureName(getNpcId()) .. '] NpcSystem:', 'Parameter(s) missing for item:', name, container, itemid, cost)
end
end
end
-- Initializes the module and associates handler to it.
function ShopModule:init(handler)
self.npcHandler = handler
self.yesNode = KeywordNode:new(SHOP_YESWORD, ShopModule.onConfirm, {module = self})
self.noNode = KeywordNode:new(SHOP_NOWORD, ShopModule.onDecline, {module = self})
self.noText = handler:getMessage(MESSAGE_DECLINE)
if(SHOPMODULE_MODE ~= SHOPMODULE_MODE_TALK) then
for i, word in pairs(SHOP_TRADEREQUEST) do
local obj = {}
table.insert(obj, word)
obj.callback = SHOP_TRADEREQUEST.callback or ShopModule.messageMatcher
handler.keywordHandler:addKeyword(obj, ShopModule.requestTrade, {module = self})
end
end
end
-- Custom message matching callback function for requesting trade messages.
function ShopModule.messageMatcher(keywords, message)
for i, word in pairs(keywords) do
if(type(word) == 'string' and string.find(message, word) and not string.find(message, '[%w+]' .. word) and not string.find(message, word .. '[%w+]')) then
return true
end
end
return false
end
-- Resets the module-specific variables.
function ShopModule:reset()
self.amount = 0
end
-- Function used to match a number value from a string.
function ShopModule:getCount(message)
local ret, b, e = 1, string.find(message, PATTERN_COUNT)
if(b ~= nil and e ~= nil) then
ret = tonumber(string.sub(message, b, e))
end
return math.max(1, math.min(self.maxCount, ret))
end
-- Adds a new buyable item.
-- names = A table containing one or more strings of alternative names to this item. Used only for old buy/sell system.
-- itemid = The itemid of the buyable item
-- cost = The price of one single item
-- subType - The subType of each rune or fluidcontainer item. Can be left out if it is not a rune/fluidcontainer. Default value is 0 and 1 (depending on shop mode)
-- realName - The real, full name for the item. Will be used as ITEMNAME in MESSAGE_ONBUY and MESSAGE_ONSELL if defined. Default value is nil (getItemNameById will be used)
function ShopModule:addBuyableItem(names, itemid, cost, subType, realName)
if(type(subType) == 'string' and realName == nil) then
realName = subType
subType = nil
end
local v = getItemInfo(itemid)
if(SHOPMODULE_MODE ~= SHOPMODULE_MODE_TALK) then
local item = {
id = itemid,
buy = cost,
sell = -1,
subType = tonumber(subType) or (v.charges > 0 and v.charges or 0),
name = realName or v.name
}
for i, shopItem in ipairs(self.npcHandler.shopItems) do
if(shopItem.id == item.id and (shopItem.subType == item.subType or shopItem.subType == 0)) then
if(item.sell ~= shopItem.sell) then
item.sell = shopItem.sell
end
self.npcHandler.shopItems[i] = item
item = nil
break
end
end
if(item ~= nil) then
table.insert(self.npcHandler.shopItems, item)
end
end
if(names ~= nil and SHOPMODULE_MODE ~= SHOPMODULE_MODE_TRADE) then
local parameters = {
itemid = itemid,
cost = cost,
eventType = SHOPMODULE_BUY_ITEM,
module = self,
realName = realName or v.name,
subType = tonumber(subType) or (v.charges > 0 and v.charges or 1)
}
for i, name in pairs(names) do
local keywords = {}
table.insert(keywords, 'buy')
table.insert(keywords, name)
local node = self.npcHandler.keywordHandler:addKeyword(keywords, ShopModule.tradeItem, parameters)
node:addChildKeywordNode(self.yesNode)
node:addChildKeywordNode(self.noNode)
end
end
end
-- Adds a new buyable container of items.
-- names = A table containing one or more strings of alternative names to this item.
-- container = Backpack, bag or any other itemid of container where bought items will be stored
-- itemid = The itemid of the buyable item
-- cost = The price of one single item
-- subType - The subType of each rune or fluidcontainer item. Can be left out if it is not a rune/fluidcontainer. Default value is 1.
-- realName - The real, full name for the item. Will be used as ITEMNAME in MESSAGE_ONBUY and MESSAGE_ONSELL if defined. Default value is nil (getItemNameById will be used)
function ShopModule:addBuyableItemContainer(names, container, itemid, cost, subType, realName)
if(names ~= nil) then
local v = getItemInfo(itemid)
local parameters = {
container = container,
itemid = itemid,
cost = cost,
eventType = SHOPMODULE_BUY_ITEM_CONTAINER,
module = self,
realName = realName or v.name,
subType = tonumber(subType) or (v.charges > 0 and v.charges or 1)
}
for i, name in pairs(names) do
local keywords = {}
table.insert(keywords, 'buy')
table.insert(keywords, name)
local node = self.npcHandler.keywordHandler:addKeyword(keywords, ShopModule.tradeItem, parameters)
node:addChildKeywordNode(self.yesNode)
node:addChildKeywordNode(self.noNode)
end
end
end
-- Adds a new sellable item.
-- names = A table containing one or more strings of alternative names to this item. Used only by old buy/sell system.
-- itemid = The itemid of the sellable item
-- cost = The price of one single item
-- realName - The real, full name for the item. Will be used as ITEMNAME in MESSAGE_ONBUY and MESSAGE_ONSELL if defined. Default value is nil (getItemNameById will be used)
function ShopModule:addSellableItem(names, itemid, cost, realName)
local v = getItemInfo(itemid)
if(SHOPMODULE_MODE ~= SHOPMODULE_MODE_TALK) then
local item = {
id = itemid,
buy = -1,
sell = cost,
subType = ((v.charges > 0 and v.stackable) and v.charges or 0),
name = realName or v.name
}
for i, shopItem in ipairs(self.npcHandler.shopItems) do
if(shopItem.id == item.id and shopItem.subType == item.subType) then
if(item.buy ~= shopItem.buy) then
item.buy = shopItem.buy
end
self.npcHandler.shopItems[i] = item
item = nil
break
end
end
if(item ~= nil) then
table.insert(self.npcHandler.shopItems, item)
end
end
if(names ~= nil and SHOPMODULE_MODE ~= SHOPMODULE_MODE_TRADE) then
local parameters = {
itemid = itemid,
cost = cost,
eventType = SHOPMODULE_SELL_ITEM,
module = self,
realName = realName or v.name
}
for i, name in pairs(names) do
local keywords = {}
table.insert(keywords, 'sell')
table.insert(keywords, name)
local node = self.npcHandler.keywordHandler:addKeyword(keywords, ShopModule.tradeItem, parameters)
node:addChildKeywordNode(self.yesNode)
node:addChildKeywordNode(self.noNode)
end
end
end
-- onModuleReset callback function. Calls ShopModule:reset()
function ShopModule:callbackOnModuleReset()
self:reset()
return true
end
-- Callback onBuy() function. If you wish, you can change certain Npc to use your onBuy().
function ShopModule:callbackOnBuy(cid, itemid, subType, amount, ignoreCap, inBackpacks)
local shopItem = nil
for _, item in ipairs(self.npcHandler.shopItems) do
if(item.id == itemid and item.subType == subType) then
shopItem = item
break
end
end
if(shopItem == nil) then
print('[Warning - ' .. getCreatureName(getNpcId()) .. '] NpcSystem:', 'ShopModule.onBuy - Item not found on shopItems list')
return false
end
if(shopItem.buy == -1) then
print('[Warning - ' .. getCreatureName(getNpcId()) .. '] NpcSystem:', 'ShopModule.onBuy - Attempt to purchase an item which only sellable')
return false
end
if(amount <= 0) then
print('[Warning - ' .. getCreatureName(getNpcId()) .. '] NpcSystem:', 'ShopModule.onBuy - Attempt to purchase ' .. amount .. ' items')
return false
end
local subType, count = shopItem.subType or 0, amount
if(inBackpacks and isItemStackable(itemid)) then
amount = amount * 100 / math.max(1, subType)
end
local backpack, backpackPrice, totalCost = 1988, 20, amount * shopItem.buy
if(inBackpacks) then
totalCost = totalCost + (math.max(1, math.floor(count / getContainerCapById(backpack))) * backpackPrice)
end
local parseInfo = {
[TAG_PLAYERNAME] = getPlayerName(cid),
[TAG_ITEMCOUNT] = amount,
[TAG_TOTALCOST] = totalCost,
[TAG_ITEMNAME] = shopItem.name
}
if(getPlayerMoney(cid) < totalCost) then
local msg = self.npcHandler:getMessage(MESSAGE_NEEDMONEY)
doPlayerSendCancel(cid, self.npcHandler:parseMessage(msg, parseInfo))
return false
end
local a, b = doNpcSellItem(cid, itemid, count, subType, ignoreCap, inBackpacks, backpack)
if(a < amount) then
local msgId = MESSAGE_NEEDMORESPACE
if(a == 0) then
msgId = MESSAGE_NEEDSPACE
end
local msg = self.npcHandler:getMessage(msgId)
parseInfo[TAG_ITEMCOUNT] = a
doPlayerSendCancel(cid, self.npcHandler:parseMessage(msg, parseInfo))
if(NPCHANDLER_CONVBEHAVIOR ~= CONVERSATION_DEFAULT) then
self.npcHandler.talkStart[cid] = os.time()
else
self.npcHandler.talkStart = os.time()
end
if(a > 0) then
doPlayerRemoveMoney(cid, ((a * shopItem.buy) + (b * backpackPrice)))
return true
end
return false
end
local msg = self.npcHandler:getMessage(MESSAGE_BOUGHT)
doPlayerSendTextMessage(cid, MESSAGE_INFO_DESCR, self.npcHandler:parseMessage(msg, parseInfo))
doPlayerRemoveMoney(cid, totalCost)
if(NPCHANDLER_CONVBEHAVIOR ~= CONVERSATION_DEFAULT) then
self.npcHandler.talkStart[cid] = os.time()
else
self.npcHandler.talkStart = os.time()
end
return true
end
-- Callback onSell() function. If you wish, you can change certain Npc to use your onSell().
function ShopModule:callbackOnSell(cid, itemid, subType, amount, ignoreEquipped, dummy)
local shopItem = nil
for _, item in ipairs(self.npcHandler.shopItems) do
if(item.id == itemid and item.subType == subType) then
shopItem = item
break
end
end
if(shopItem == nil) then
print('[Warning - ' .. getCreatureName(getNpcId()) .. '] NpcSystem:', 'ShopModule.onSell - Item not found on shopItems list')
return false
end
if(shopItem.sell == -1) then
print('[Warning - ' .. getCreatureName(getNpcId()) .. '] NpcSystem:', 'ShopModule.onSell - Attempt to sell an item which is only buyable')
return false
end
local parseInfo = {
[TAG_PLAYERNAME] = getPlayerName(cid),
[TAG_ITEMCOUNT] = amount,
[TAG_TOTALCOST] = amount * shopItem.sell,
[TAG_ITEMNAME] = shopItem.name
}
if(subType < 1 or getItemInfo(itemid).stackable) then
subType = -1
end
if(doPlayerRemoveItem(cid, itemid, amount, subType, ignoreEquipped)) then
local msg = self.npcHandler:getMessage(MESSAGE_SOLD)
doPlayerSendTextMessage(cid, MESSAGE_INFO_DESCR, self.npcHandler:parseMessage(msg, parseInfo))
doPlayerAddMoney(cid, amount * shopItem.sell)
if(NPCHANDLER_CONVBEHAVIOR ~= CONVERSATION_DEFAULT) then
self.npcHandler.talkStart[cid] = os.time()
else
self.npcHandler.talkStart = os.time()
end
return true
end
local msg = self.npcHandler:getMessage(MESSAGE_NEEDITEM)
doPlayerSendCancel(cid, self.npcHandler:parseMessage(msg, parseInfo))
if(NPCHANDLER_CONVBEHAVIOR ~= CONVERSATION_DEFAULT) then
self.npcHandler.talkStart[cid] = os.time()
else
self.npcHandler.talkStart = os.time()
end
return false
end
-- Callback for requesting a trade window with the NPC.
function ShopModule.requestTrade(cid, message, keywords, parameters, node)
local module = parameters.module
if(not module.npcHandler:isFocused(cid)) then
return false
end
local shop = getShopOwner(cid)
if(shop and shop == getNpcId()) then
return true
end
if(table.maxn(module.npcHandler.shopItems) == 0) then
local parseInfo = { [TAG_PLAYERNAME] = getPlayerName(cid) }
local msg = module.npcHandler:parseMessage(module.npcHandler:getMessage(MESSAGE_NOSHOP), parseInfo)
module.npcHandler:say(msg, cid)
return true
end
local parseInfo = { [TAG_PLAYERNAME] = getPlayerName(cid) }
local msg = module.npcHandler:parseMessage(module.npcHandler:getMessage(MESSAGE_SENDTRADE), parseInfo)
addEvent(openShopWindow, 500, cid, module.npcHandler.shopItems,
function(cid, itemid, subType, amount, ignoreCap, inBackpacks)
module.npcHandler:onBuy(cid, itemid, subType, amount, ignoreCap, inBackpacks)
end,
function(cid, itemid, subType, amount, ignoreCap, inBackpacks)
module.npcHandler:onSell(cid, itemid, subType, amount, ignoreCap, inBackpacks)
end
)
module.npcHandler:say(msg, cid)
return true
end
-- onConfirm keyword callback function. Sells/buys the actual item.
function ShopModule.onConfirm(cid, message, keywords, parameters, node)
local module = parameters.module
if(not module.npcHandler:isFocused(cid)) then
return false
end
local parentParameters = node:getParent():getParameters()
local parseInfo = {
[TAG_PLAYERNAME] = getPlayerName(cid),
[TAG_ITEMCOUNT] = module.amount,
[TAG_TOTALCOST] = parentParameters.cost * module.amount,
[TAG_ITEMNAME] = parentParameters.realName
}
if(parentParameters.eventType == SHOPMODULE_SELL_ITEM) then
local ret = doPlayerSellItem(cid, parentParameters.itemid, module.amount, parentParameters.cost * module.amount)
if(ret) then
local msg = module.npcHandler:getMessage(MESSAGE_ONSELL)
msg = module.npcHandler:parseMessage(msg, parseInfo)
module.npcHandler:say(msg, cid)
else
local msg = module.npcHandler:getMessage(MESSAGE_MISSINGITEM)
msg = module.npcHandler:parseMessage(msg, parseInfo)
module.npcHandler:say(msg, cid)
end
elseif(parentParameters.eventType == SHOPMODULE_BUY_ITEM) then
local ret = doPlayerBuyItem(cid, parentParameters.itemid, module.amount, parentParameters.cost * module.amount, parentParameters.subType)
if(ret) then
if parentParameters.itemid == ITEM_PARCEL then
doPlayerBuyItem(cid, ITEM_LABEL, module.amount, 0, parentParameters.subType)
end
local msg = module.npcHandler:getMessage(MESSAGE_ONBUY)
msg = module.npcHandler:parseMessage(msg, parseInfo)
module.npcHandler:say(msg, cid)
else
local msg = module.npcHandler:getMessage(MESSAGE_MISSINGMONEY)
msg = module.npcHandler:parseMessage(msg, parseInfo)
module.npcHandler:say(msg, cid)
end
elseif(parentParameters.eventType == SHOPMODULE_BUY_ITEM_CONTAINER) then
local ret = doPlayerBuyItemContainer(cid, parentParameters.container, parentParameters.itemid, module.amount, parentParameters.cost * module.amount, parentParameters.subType)
if(ret) then
local msg = module.npcHandler:getMessage(MESSAGE_ONBUY)
msg = module.npcHandler:parseMessage(msg, parseInfo)
module.npcHandler:say(msg, cid)
else
local msg = module.npcHandler:getMessage(MESSAGE_MISSINGMONEY)
msg = module.npcHandler:parseMessage(msg, parseInfo)
module.npcHandler:say(msg, cid)
end
end
module.npcHandler:resetNpc(cid)
return true
end
-- onDecliune keyword callback function. Generally called when the player sais 'no' after wanting to buy an item.
function ShopModule.onDecline(cid, message, keywords, parameters, node)
local module = parameters.module
if(not module.npcHandler:isFocused(cid)) then
return false
end
local parentParameters = node:getParent():getParameters()
local parseInfo = {
[TAG_PLAYERNAME] = getPlayerName(cid),
[TAG_ITEMCOUNT] = module.amount,
[TAG_TOTALCOST] = parentParameters.cost * module.amount,
[TAG_ITEMNAME] = parentParameters.realName
}
local msg = module.npcHandler:parseMessage(module.noText, parseInfo)
module.npcHandler:say(msg, cid)
module.npcHandler:resetNpc(cid)
return true
end
-- tradeItem callback function. Makes the npc say the message defined by MESSAGE_BUY or MESSAGE_SELL
function ShopModule.tradeItem(cid, message, keywords, parameters, node)
local module = parameters.module
if(not module.npcHandler:isFocused(cid)) then
return false
end
local count = module:getCount(message)
module.amount = count
local parseInfo = {
[TAG_PLAYERNAME] = getPlayerName(cid),
[TAG_ITEMCOUNT] = module.amount,
[TAG_TOTALCOST] = parameters.cost * module.amount,
[TAG_ITEMNAME] = parameters.realName
}
if(parameters.eventType == SHOPMODULE_SELL_ITEM) then
local msg = module.npcHandler:getMessage(MESSAGE_SELL)
msg = module.npcHandler:parseMessage(msg, parseInfo)
module.npcHandler:say(msg, cid)
elseif(parameters.eventType == SHOPMODULE_BUY_ITEM) then
local msg = module.npcHandler:getMessage(MESSAGE_BUY)
msg = module.npcHandler:parseMessage(msg, parseInfo)
module.npcHandler:say(msg, cid)
elseif(parameters.eventType == SHOPMODULE_BUY_ITEM_CONTAINER) then
local msg = module.npcHandler:getMessage(MESSAGE_BUY)
msg = module.npcHandler:parseMessage(msg, parseInfo)
module.npcHandler:say(msg, cid)
end
return true
end
end
| agpl-3.0 |
Zenny89/darkstar | scripts/zones/Lower_Jeuno/npcs/Chetak.lua | 37 | 1430 | -----------------------------------
-- Area: Lower Jeuno
-- NPC: Chetak
-- Standard Merchant NPC
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil;
require("scripts/zones/Lower_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,CHETAK_SHOP_DIALOG);
stock = {0x30B2,20000, -- Red Cap
0x30B3,45760, -- Wool Cap
0x30BA,11166, -- Wool Hat
0x3132,32500, -- Gambison
0x3142,33212, -- Cloak
0x3133,68640, -- Wool Gambison
0x313A,18088, -- Wool Robe
0x3141,9527, -- Black Tunic
0x31B2,16900, -- Bracers
0x31C2,15732, -- Linen Mitts
0x31BA,10234, -- Wool Cuffs
0x31C1,4443} -- White Mitts
showShop(player, STATIC, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
3245as/a123w | plugins/banhammer.lua | 7 | 36665 | local function pre_process(msg)
chat = msg.chat_id_
user = msg.sender_user_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_.." ]* _از گروه محروم است_", 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(user, chat) then
del_msg(msg.chat_id_, msg.id_)
end
if is_banned(user, chat) then
del_msg(msg.chat_id_, tonumber(msg.id_))
kick_user(user, chat)
end
if is_gbanned(user) then
del_msg(msg.chat_id_, tonumber(msg.id_))
kick_user(user, chat)
end
end
local function action_by_reply(arg, data)
local hash = "gp_lang:"..data.chat_id_
local lang = redis:get(hash)
local cmd = arg.cmd
if not tonumber(data.sender_user_id_) then return false end
if data.sender_user_id_ then
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
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 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
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 run(msg, matches)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
local data = load_data(_config.moderation.data)
chat = msg.chat_id_
user = msg.sender_user_id_
if matches[1] == "kick" and is_mod(msg) then
if not matches[2] and tonumber(msg.reply_to_message_id_) ~= 0 then
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.chat_id_,
message_id_ = msg.reply_to_message_id_
}, action_by_reply, {chat_id=msg.chat_id_,cmd="kick"})
end
if matches[2] and string.match(matches[2], '^%d+$') then
if is_mod1(msg.chat_id_, matches[2]) then
if not lang then
tdcli.sendMessage(msg.chat_id_, "", 0, "_You can't kick mods,owners or bot admins_", 0, "md")
elseif lang then
tdcli.sendMessage(msg.chat_id_, "", 0, "*شما نمیتوانید مدیران،صاحبان گروه و ادمین های ربات رو اخراج کنید*", 0, "md")
end
else
kick_user(matches[2], msg.chat_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.chat_id_,username=matches[2],cmd="kick"})
end
end
if matches[1] == "delall" and is_mod(msg) then
if not matches[2] and tonumber(msg.reply_to_message_id_) ~= 0 then
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.chat_id_,
message_id_ = msg.reply_to_message_id_
}, action_by_reply, {chat_id=msg.chat_id_,cmd="delall"})
end
if matches[2] and string.match(matches[2], '^%d+$') then
if is_mod1(msg.chat_id_, matches[2]) then
if not lang then
return tdcli.sendMessage(msg.chat_id_, "", 0, "_You can't delete messages mods,owners or bot admins_", 0, "md")
elseif lang then
return tdcli.sendMessage(msg.chat_id_, "", 0, "*شما نمیتوانید پیام های مدیران،صاحبان گروه و ادمین های ربات رو پاک کنید*", 0, "md")
end
else
tdcli.deleteMessagesFromUser(msg.chat_id_, matches[2], dl_cb, nil)
if not lang then
return tdcli.sendMessage(msg.chat_id_, "", 0, "_All_ *messages* _of_ *[ "..matches[2].." ]* _has been_ *deleted*", 0, "md")
elseif lang then
return tdcli.sendMessage(msg.chat_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.chat_id_,username=matches[2],cmd="delall"})
end
end
if matches[1] == "banall" and is_admin(msg) then
if not matches[2] and tonumber(msg.reply_to_message_id_) ~= 0 then
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.chat_id_,
message_id_ = msg.reply_to_message_id_
}, action_by_reply, {chat_id=msg.chat_id_,cmd="banall"})
end
if matches[2] and string.match(matches[2], '^%d+$') then
if is_admin1(matches[2]) then
if not lang then
return tdcli.sendMessage(msg.chat_id_, "", 0, "_You can't globally ban other admins_", 0, "md")
else
return tdcli.sendMessage(msg.chat_id_, "", 0, "*شما نمیتوانید ادمین های ربات رو از گروه های ربات محروم کنید*", 0, "md")
end
end
if is_gbanned(matches[2]) then
if not lang then
return tdcli.sendMessage(msg.chat_id_, "", 0, "*User "..matches[2].." is already globally banned*", 0, "md")
else
return tdcli.sendMessage(msg.chat_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.chat_id_)
if not lang then
return tdcli.sendMessage(msg.chat_id_, msg.id_, 0, "*User "..matches[2].." has been globally banned*", 0, "md")
else
return tdcli.sendMessage(msg.chat_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.chat_id_,username=matches[2],cmd="banall"})
end
end
if matches[1] == "unbanall" and is_admin(msg) then
if not matches[2] and tonumber(msg.reply_to_message_id_) ~= 0 then
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.chat_id_,
message_id_ = msg.reply_to_message_id_
}, action_by_reply, {chat_id=msg.chat_id_,cmd="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.chat_id_, "", 0, "*User "..matches[2].." is not globally banned*", 0, "md")
else
return tdcli.sendMessage(msg.chat_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.chat_id_, msg.id_, 0, "*User "..matches[2].." has been globally unbanned*", 0, "md")
else
return tdcli.sendMessage(msg.chat_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.chat_id_,username=matches[2],cmd="unbanall"})
end
end
if matches[1] == "ban" and is_mod(msg) then
if not matches[2] and tonumber(msg.reply_to_message_id_) ~= 0 then
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.chat_id_,
message_id_ = msg.reply_to_message_id_
}, action_by_reply, {chat_id=msg.chat_id_,cmd="ban"})
end
if matches[2] and string.match(matches[2], '^%d+$') then
if is_mod1(msg.chat_id_, matches[2]) then
if not lang then
return tdcli.sendMessage(msg.chat_id_, "", 0, "_You can't ban mods,owners or bot admins_", 0, "md")
else
return tdcli.sendMessage(msg.chat_id_, "", 0, "*شما نمیتوانید مدیران،صاحبان گروه و ادمین های ربات رو از گروه محروم کنید*", 0, "md")
end
end
if is_banned(matches[2], msg.chat_id_) then
if not lang then
return tdcli.sendMessage(msg.chat_id_, "", 0, "_User "..matches[2].." is already banned_", 0, "md")
else
return tdcli.sendMessage(msg.chat_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.chat_id_)
if not lang then
return tdcli.sendMessage(msg.chat_id_, msg.id_, 0, "_User "..matches[2].." has been banned_", 0, "md")
else
return tdcli.sendMessage(msg.chat_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.chat_id_,username=matches[2],cmd="ban"})
end
end
if matches[1] == "unban" and is_mod(msg) then
if not matches[2] and tonumber(msg.reply_to_message_id_) ~= 0 then
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.chat_id_,
message_id_ = msg.reply_to_message_id_
}, action_by_reply, {chat_id=msg.chat_id_,cmd="unban"})
end
if matches[2] and string.match(matches[2], '^%d+$') then
if not is_banned(matches[2], msg.chat_id_) then
if not lang then
return tdcli.sendMessage(msg.chat_id_, "", 0, "_User "..matches[2].." is not banned_", 0, "md")
else
return tdcli.sendMessage(msg.chat_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.chat_id_, msg.id_, 0, "_User "..matches[2].." has been unbanned_", 0, "md")
else
return tdcli.sendMessage(msg.chat_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.chat_id_,username=matches[2],cmd="unban"})
end
end
if matches[1] == "silent" and is_mod(msg) then
if not matches[2] and tonumber(msg.reply_to_message_id_) ~= 0 then
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.chat_id_,
message_id_ = msg.reply_to_message_id_
}, action_by_reply, {chat_id=msg.chat_id_,cmd="silent"})
end
if matches[2] and string.match(matches[2], '^%d+$') then
if is_mod1(msg.chat_id_, matches[2]) then
if not lang then
return tdcli.sendMessage(msg.chat_id_, "", 0, "_You can't silent mods,leaders or bot admins_", 0, "md")
else
return tdcli.sendMessage(msg.chat_id_, "", 0, "*شما نمیتوانید توانایی چت کردن رو از مدیران،صاحبان گروه و ادمین های ربات بگیرید*", 0, "md")
end
end
if is_silent_user(matches[2], chat) then
if not lang then
return tdcli.sendMessage(msg.chat_id_, "", 0, "_User "..matches[2].." is already silent_", 0, "md")
else
return tdcli.sendMessage(msg.chat_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.chat_id_, msg.id_, 0, "_User "..matches[2].." added to silent users list_", 0, "md")
else
return tdcli.sendMessage(msg.chat_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.chat_id_,username=matches[2],cmd="silent"})
end
end
if matches[1] == "unsilent" and is_mod(msg) then
if not matches[2] and tonumber(msg.reply_to_message_id_) ~= 0 then
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.chat_id_,
message_id_ = msg.reply_to_message_id_
}, action_by_reply, {chat_id=msg.chat_id_,cmd="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.chat_id_, "", 0, "_User "..matches[2].." is not silent_", 0, "md")
else
return tdcli.sendMessage(msg.chat_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.chat_id_, msg.id_, 0, "_User "..matches[2].." removed from silent users list_", 0, "md")
else
return tdcli.sendMessage(msg.chat_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.chat_id_,username=matches[2],cmd="unsilent"})
end
end
if matches[1]:lower() == 'clean' and is_owner(msg) then
if matches[2] == 'bans' then
if next(data[tostring(chat)]['banned']) == nil then
if not lang then
return "_No_ *banned* _users in this group_"
else
return "*هیچ کاربری از این گروه محروم نشده*"
end
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
if not lang then
return "_All_ *banned* _users has been unbanned_"
else
return "*تمام کاربران محروم شده از گروه از محرومیت خارج شدند*"
end
end
if matches[2] == 'silentlist' then
if next(data[tostring(chat)]['is_silent_users']) == nil then
if not lang then
return "_No_ *silent* _users in this group_"
else
return "*لیست کاربران سایلنت شده خالی است*"
end
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
if not lang then
return "*Silent list* _has been cleaned_"
else
return "*لیست کاربران سایلنت شده پاک شد*"
end
end
end
if matches[1]:lower() == 'clean' and is_sudo(msg) then
if matches[2] == 'gbans' then
if next(data['gban_users']) == nil then
if not lang then
return "_No_ *globally banned* _users available_"
else
return "*هیچ کاربری از گروه های ربات محروم نشده*"
end
end
for k,v in pairs(data['gban_users']) do
data['gban_users'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
if not lang then
return "_All_ *globally banned* _users has been unbanned_"
else
return "*تمام کاربرانی که از گروه های ربات محروم بودند از محرومیت خارج شدند*"
end
end
end
if matches[1] == "gbanlist" and is_admin(msg) then
return gbanned_list(msg)
end
if matches[1] == "silentlist" and is_mod(msg) then
return silent_users_list(chat)
end
if matches[1] == "banlist" and is_mod(msg) then
return banned_list(chat)
end
end
return {
patterns = {
"^[!/#](banall)$",
"^[!/#](banall) (.*)$",
"^[!/#](unbanall)$",
"^[!/#](unbanall) (.*)$",
"^[!/#](gbanlist)$",
"^[!/#](ban)$",
"^[!/#](ban) (.*)$",
"^[!/#](unban)$",
"^[!/#](unban) (.*)$",
"^[!/#](banlist)$",
"^[!/#](silent)$",
"^[!/#](silent) (.*)$",
"^[!/#](unsilent)$",
"^[!/#](unsilent) (.*)$",
"^[!/#](silentlist)$",
"^[!/#](kick)$",
"^[!/#](kick) (.*)$",
"^[!/#](delall)$",
"^[!/#](delall) (.*)$",
"^[!/#](clean) (.*)$",
},
run = run,
pre_process = pre_process
}
| gpl-3.0 |
Zenny89/darkstar | scripts/zones/Pashhow_Marshlands_[S]/Zone.lua | 28 | 1346 | -----------------------------------
--
-- Zone: Pashhow_Marshlands_[S] (90)
--
-----------------------------------
package.loaded["scripts/zones/Pashhow_Marshlands_[S]/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Pashhow_Marshlands_[S]/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
player:setPos(547.841,23.192,696.323,134);
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
Zenny89/darkstar | scripts/zones/Tavnazian_Safehold/npcs/Caiphimonride.lua | 37 | 1316 | -----------------------------------
-- Area: Tavnazian Safehold
-- NPC: Caiphimonride
-- Standard Merchant NPC
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil;
require("scripts/zones/Tavnazian_Safehold/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,CAIPHIMONRIDE_SHOP_DIALOG);
stock = {0x4042,1867, --Dagger
0x40b6,8478, --Longsword
0x43B7,8, --Rusty Bolt
0x47C7,93240, --Falx (COP Chapter 4 Needed; not implemented yet)
0x4726,51905} --Voulge (COP Chapter 4 Needed; not implemented yet)
showShop(player, STATIC, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
ZeroK-RTS/SpringRTS-Tools | aoplate baker/platetank.lua | 1 | 3493 | return { platetank = {
unitname = [[platetank]],
name = [[Tank Plate]],
description = [[Augments Production]],
acceleration = 0,
brakeRate = 0,
buildCostMetal = Shared.FACTORY_PLATE_COST,
builder = true,
buildingGroundDecalDecaySpeed = 30,
buildingGroundDecalSizeX = 11,
buildingGroundDecalSizeY = 11,
buildingGroundDecalType = [[pad_decal.dds]],
buildoptions = {
[[tankcon]],
[[tankraid]],
[[tankheavyraid]],
[[tankriot]],
[[tankassault]],
[[tankheavyassault]],
[[tankarty]],
[[tankheavyarty]],
[[tankaa]],
},
buildPic = [[platetank.png]],
canMove = true,
canPatrol = true,
category = [[SINK UNARMED]],
corpse = [[DEAD]],
collisionVolumeOffsets = [[0 0 -25]],
collisionVolumeScales = [[110 28 44]],
collisionVolumeType = [[box]],
selectionVolumeOffsets = [[0 0 10]],
selectionVolumeScales = [[120 28 120]],
selectionVolumeType = [[box]],
customParams = {
sortName = [[6]],
solid_factory = [[4]],
default_spacing = 4,
aimposoffset = [[0 15 -35]],
midposoffset = [[0 15 -10]],
modelradius = [[100]],
unstick_help = 1,
selectionscalemult = 1,
child_of_factory = [[factorytank]],
},
energyUse = 0,
explodeAs = [[FAC_PLATEEX]],
footprintX = 6,
footprintZ = 8,
iconType = [[padtank]],
idleAutoHeal = 5,
idleTime = 1800,
levelGround = false,
maxDamage = Shared.FACTORY_PLATE_HEALTH,
maxSlope = 15,
maxVelocity = 0,
maxWaterDepth = 0,
minCloakDistance = 150,
moveState = 1,
noAutoFire = false,
objectName = [[plate_tank.s3o]],
script = [[platetank.lua]],
selfDestructAs = [[FAC_PLATEEX]],
showNanoSpray = false,
sightDistance = 273,
turnRate = 0,
useBuildingGroundDecal = true,
workerTime = Shared.FACTORY_BUILDPOWER,
yardMap = "oooooo oooooo oooooo oooooo yyyyyy yyyyyy yyyyyy yyyyyy",
featureDefs = {
DEAD = {
blocking = true,
featureDead = [[HEAP]],
footprintX = 6,
footprintZ = 8,
object = [[plate_tank_dead.s3o]],
collisionVolumeOffsets = [[0 14 -34]],
collisionVolumeScales = [[110 28 44]],
collisionVolumeType = [[box]],
},
HEAP = {
blocking = false,
footprintX = 6,
footprintZ = 8,
object = [[debris4x4a.s3o]],
},
},
buildingGroundDecalDecaySpeed=30,
buildingGroundDecalSizeX=11,
buildingGroundDecalSizeY=11,
useBuildingGroundDecal = true,
buildingGroundDecalType=[[platetank_aoplane.dds]],
}
| gpl-2.0 |
rouing/FHLG-BW | entities/entities/ent_mad_arrow/init.lua | 1 | 3449 | // I took a look on Kogitsune's wiretrap code
// I took the .phy of the crossbow_bolt made by Silver Spirit
AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")
include('shared.lua')
/*---------------------------------------------------------
Name: ENT:Initialize()
---------------------------------------------------------*/
function ENT:Initialize()
self.Owner = self.Entity:GetOwner()
if !IsValid(self.Owner) then
self:Remove()
return
end
self.Entity:SetModel("models/crossbow_bolt.mdl")
self.Entity:PhysicsInit(SOLID_VPHYSICS)
self.Entity:SetMoveType(MOVETYPE_VPHYSICS)
self.Entity:SetSolid(SOLID_VPHYSICS)
self.Entity:DrawShadow(false)
// self.Entity:SetCollisionGroup(COLLISION_GROUP_WEAPON)
local phys = self.Entity:GetPhysicsObject()
if (phys:IsValid()) then
phys:EnableGravity(false)
phys:EnableDrag(false)
phys:SetMass(2)
phys:Wake()
phys:AddGameFlag(FVPHYSICS_NO_IMPACT_DMG)
phys:AddGameFlag(FVPHYSICS_NO_NPC_IMPACT_DMG)
phys:AddGameFlag(FVPHYSICS_PENETRATING)
end
self.Moving = true
end
/*---------------------------------------------------------
Name: ENT:Think()
---------------------------------------------------------*/
function ENT:Think()
local phys = self.Entity:GetPhysicsObject()
local ang = self.Entity:GetForward() * 100000
local up = self.Entity:GetUp() * -800
local force = ang + up
phys:ApplyForceCenter(force)
if (self.Entity.HitWeld) then
self.HitWeld = false
constraint.Weld(self.Entity.HitEnt, self.Entity, 0, 0, 0, true)
end
end
/*---------------------------------------------------------
Name: ENT:Impact()
---------------------------------------------------------*/
function ENT:Impact(sent, normal, pos)
if not IsValid(self) then
return
end
local tr, info
tr = {}
tr.start = self:GetPos()
tr.filter = {self, self.Owner}
tr.endpos = pos
tr = util.TraceLine(tr)
if tr.HitSky then self:Remove() return end
bullet = {}
bullet.Num = 1
bullet.Src = pos
bullet.Dir = normal
bullet.Spread = Vector(0, 0, 0)
bullet.Tracer = 0
bullet.Force = 0
bullet.Damage = 0
self.Entity:FireBullets(bullet)
if not sent:IsPlayer() and not sent:IsNPC() then
local effectdata = EffectData()
effectdata:SetOrigin(pos - normal * 10)
effectdata:SetEntity(self.Entity)
effectdata:SetStart(pos)
effectdata:SetNormal(normal)
util.Effect("effect_mad_shotgunsmoke", effectdata)
end
if IsValid(sent) then
info = DamageInfo()
info:SetAttacker(self.Owner)
info:SetInflictor(self)
info:SetDamageType(DMG_GENERIC or DMG_SHOCK)
info:SetDamage(100)
info:SetMaxDamage(100)
info:SetDamageForce(tr.HitNormal * 10)
self.Entity:EmitSound("Weapon_Crossbow.BoltHitBody")
sent:TakeDamageInfo(info)
self.Entity:Remove()
return
end
self.Entity:EmitSound("Weapon_Crossbow.BoltHitWorld")
// We've hit a prop, so let's weld to it
// Also embed this in the object for looks
self:SetPos(pos - normal * 10)
self:SetAngles(normal:Angle())
if not IsValid(sent) then
self:GetPhysicsObject():EnableMotion(false)
end
self.Entity:Fire("kill", "", 10)
end
/*---------------------------------------------------------
Name: ENT:PhysicsCollide()
---------------------------------------------------------*/
function ENT:PhysicsCollide(data, phys)
if self.Moving then
self.Moving = false
phys:Sleep()
self.Entity:Impact(data.HitEntity, data.HitNormal, data.HitPos)
end
end | unlicense |
adminmagma/test2 | plugins/Member_Manager.lua | 24 | 11556 | local function pre_process(msg)
-- SERVICE MESSAGE
if msg.action and msg.action.type then
local action = msg.action.type
-- Check if banned user joins chat by link
if action == 'chat_add_user_link' then
local user_id = msg.from.id
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('User is banned!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs
kick_user(user_id, msg.to.id)
end
end
-- Check if banned user joins chat
if action == 'chat_add_user' then
local user_id = msg.action.user.id
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('User is banned!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs
kick_user(user_id, msg.to.id)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:incr(banhash)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
local banaddredis = redis:get(banhash)
if banaddredis then
if tonumber(banaddredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times
end
if tonumber(banaddredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:set(banhash, 0)-- Reset the Counter
end
end
end
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings'] then
if data[tostring(msg.to.id)]['settings']['lock_bots'] then
bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots']
end
end
end
if msg.action.user.username ~= nil then
if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs
kick_user(msg.action.user.id, msg.to.id)
end
end
end
-- No further checks
return msg
end
-- banned user is talking !
if msg.to.type == 'chat' then
local data = load_data(_config.moderation.data)
local group = msg.to.id
local texttext = 'groups'
--if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not
--chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false)
--return
--end
local user_id = msg.from.id
local chat_id = msg.to.id
local banned = is_banned(user_id, chat_id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('Banned user talking!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs
kick_user(user_id, chat_id)
msg.text = ''
end
end
return msg
end
local function kick_ban_res(extra, success, result)
--vardump(result)
--vardump(extra)
local member_id = result.id
local user_id = member_id
local member = result.username
local chat_id = extra.chat_id
local from_id = extra.from_id
local get_cmd = extra.get_cmd
local receiver = "chat#id"..chat_id
if get_cmd == "kick" then
if member_id == from_id then
return send_large_msg(receiver, "You can't kick yourself")
end
if is_momod2(member_id, chat_id) and not is_admin2(sender) then
return send_large_msg(receiver, "You can't kick mods/owner/admins")
end
return kick_user(member_id, chat_id)
elseif get_cmd == 'ban' then
if is_momod2(member_id, chat_id) and not is_admin2(sender) then
return send_large_msg(receiver, "You can't ban mods/owner/admins")
end
send_large_msg(receiver, 'User @'..member..' '..member_id..' banned!')
return ban_user(member_id, chat_id)
elseif get_cmd == 'unban' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned')
local hash = 'banned:'..chat_id
redis:srem(hash, member_id)
return 'User '..user_id..' unbanned'
elseif get_cmd == 'globalban' then
send_large_msg(receiver, 'User @'..member..' '..member_id..'globally banned!')
return banall_user(member_id, chat_id)
elseif get_cmd == 'globalunban' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] un-globally banned')
return unbanall_user(member_id, chat_id)
end
end
local function run(msg, matches)
if matches[1]:lower() == 'id' then
if msg.to.type == "user" then
return "Bot ID: "..msg.to.id.. "\n\nYour ID: "..msg.from.id
end
if type(msg.reply_id) ~= "nil" then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
id = get_message(msg.reply_id,get_message_callback_id, false)
elseif matches[1]:lower() == 'id' then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
return "Group " ..string.gsub(msg.to.print_name, "_", " ").. " ID:"..msg.to.id
end
end
if matches[1]:lower() == 'kickme' then-- /kickme
local receiver = get_receiver(msg)
if msg.to.type == 'chat' then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs
chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false)
end
end
if not is_momod(msg) then -- Ignore normal users
return
end
if matches[1]:lower() == "banlist" then -- Ban list !
local chat_id = msg.to.id
if matches[2] and is_admin(msg) then
chat_id = matches[2]
end
return ban_list(chat_id)
end
if matches[1]:lower() == 'ban' then-- /ban
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin(msg) then
local msgr = get_message(msg.reply_id,ban_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,ban_by_reply, false)
end
end
local user_id = matches[2]
local chat_id = msg.to.id
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then
return "you can't ban mods/owner/admins"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "You can't ban your self !"
end
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2])
ban_user(user_id, chat_id)
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'ban',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'unban' then -- /unban
if type(msg.reply_id)~="nil" and is_momod(msg) then
local msgr = get_message(msg.reply_id,unban_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
local targetuser = matches[2]
if string.match(targetuser, '^%d+$') then
local user_id = targetuser
local hash = 'banned:'..chat_id
redis:srem(hash, user_id)
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2])
return 'User '..user_id..' unbanned'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'unban',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'kick' then
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin(msg) then
local msgr = get_message(msg.reply_id,Kick_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,Kick_by_reply, false)
end
end
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then
return "you can't kick mods/owner/admins"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "You can't kick your self !"
end
local user_id = matches[2]
local chat_id = msg.to.id
name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2])
kick_user(user_id, chat_id)
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'kick',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if not is_admin(msg) then
return
end
if matches[1]:lower() == 'globalban' then -- Global ban
if type(msg.reply_id) ~="nil" and is_admin(msg) then
return get_message(msg.reply_id,banall_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
local targetuser = matches[2]
if string.match(targetuser, '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return false
end
banall_user(targetuser)
return 'User '..user_id..' globally banned!'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'banall',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'globalunban' then -- Global unban
local user_id = matches[2]
local chat_id = msg.to.id
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return false
end
unbanall_user(user_id)
return 'User '..user_id..' globally unbanned!'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'unbanall',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == "glbanlist" then -- Global ban list
return banall_list()
end
end
return {
patterns = {
"^[!/]([Gg]lobalban) (.*)$",
"^[!/]([Gg]lobalban)$",
"^[!/]([Bb]anlist) (.*)$",
"^[!/]([Bb]anlist)$",
"^[!/]([Gg]lbanlist)$",
"^[!/]([Bb]an) (.*)$",
"^[!/]([Kk]ick)$",
"^[!/]([Uu]nban) (.*)$",
"^[!/]([Gg]lobalunban) (.*)$",
"^[!/]([Gg]lobalunban)$",
"^[!/]([Kk]ick) (.*)$",
"^[!/]([Kk]ickme)$",
"^[!/]([Bb]an)$",
"^[!/]([Uu]nban)$",
"^[!/]([Ii]d)$",
"^!!tgservice (.+)$"
},
run = run,
pre_process = pre_process
}
| gpl-2.0 |
ajayk/kong | kong/plugins/response-ratelimiting/handler.lua | 2 | 1095 | -- Copyright (C) Mashape, Inc.
local BasePlugin = require "kong.plugins.base_plugin"
local access = require "kong.plugins.response-ratelimiting.access"
local log = require "kong.plugins.response-ratelimiting.log"
local header_filter = require "kong.plugins.response-ratelimiting.header_filter"
local ResponseRateLimitingHandler = BasePlugin:extend()
function ResponseRateLimitingHandler:new()
ResponseRateLimitingHandler.super.new(self, "response-ratelimiting")
end
function ResponseRateLimitingHandler:access(conf)
ResponseRateLimitingHandler.super.access(self)
access.execute(conf)
end
function ResponseRateLimitingHandler:header_filter(conf)
ResponseRateLimitingHandler.super.header_filter(self)
header_filter.execute(conf)
end
function ResponseRateLimitingHandler:log(conf)
if not ngx.ctx.stop_log and ngx.ctx.usage then
ResponseRateLimitingHandler.super.log(self)
log.execute(ngx.ctx.api.id, ngx.ctx.identifier, ngx.ctx.current_timestamp, ngx.ctx.increments, ngx.ctx.usage)
end
end
ResponseRateLimitingHandler.PRIORITY = 900
return ResponseRateLimitingHandler
| apache-2.0 |
mercury233/ygopro-scripts | c91907707.lua | 2 | 4213 | --クリフォート・アーカイブ
function c91907707.initial_effect(c)
--pendulum summon
aux.EnablePendulumAttribute(c)
--splimit
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON)
e2:SetProperty(EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_CANNOT_NEGATE)
e2:SetRange(LOCATION_PZONE)
e2:SetTargetRange(1,0)
e2:SetTarget(c91907707.splimit)
c:RegisterEffect(e2)
--atk up
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_FIELD)
e3:SetRange(LOCATION_PZONE)
e3:SetCode(EFFECT_UPDATE_ATTACK)
e3:SetTargetRange(LOCATION_MZONE,0)
e3:SetTarget(aux.TargetBoolFunction(Card.IsSetCard,0xaa))
e3:SetValue(300)
c:RegisterEffect(e3)
--summon with no tribute
local e4=Effect.CreateEffect(c)
e4:SetDescription(aux.Stringid(91907707,0))
e4:SetType(EFFECT_TYPE_SINGLE)
e4:SetCode(EFFECT_SUMMON_PROC)
e4:SetCondition(c91907707.ntcon)
c:RegisterEffect(e4)
--change level
local e5=Effect.CreateEffect(c)
e5:SetType(EFFECT_TYPE_SINGLE)
e5:SetCode(EFFECT_SUMMON_COST)
e5:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e5:SetOperation(c91907707.lvop)
c:RegisterEffect(e5)
local e6=Effect.CreateEffect(c)
e6:SetType(EFFECT_TYPE_SINGLE)
e6:SetCode(EFFECT_SPSUMMON_COST)
e6:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e6:SetOperation(c91907707.lvop2)
c:RegisterEffect(e6)
--immune
local e7=Effect.CreateEffect(c)
e7:SetType(EFFECT_TYPE_SINGLE)
e7:SetCode(EFFECT_IMMUNE_EFFECT)
e7:SetProperty(EFFECT_FLAG_SINGLE_RANGE+EFFECT_FLAG_UNCOPYABLE)
e7:SetRange(LOCATION_MZONE)
e7:SetCondition(c91907707.immcon)
e7:SetValue(aux.qlifilter)
c:RegisterEffect(e7)
--tohand
local e8=Effect.CreateEffect(c)
e8:SetDescription(aux.Stringid(91907707,1))
e8:SetCategory(CATEGORY_TOHAND)
e8:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e8:SetCode(EVENT_RELEASE)
e8:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY)
e8:SetTarget(c91907707.thtg)
e8:SetOperation(c91907707.thop)
c:RegisterEffect(e8)
end
function c91907707.splimit(e,c)
return not c:IsSetCard(0xaa)
end
function c91907707.ntcon(e,c,minc)
if c==nil then return true end
return minc==0 and c:IsLevelAbove(5) and Duel.GetLocationCount(c:GetControler(),LOCATION_MZONE)>0
end
function c91907707.lvcon(e)
return e:GetHandler():GetMaterialCount()==0
end
function c91907707.lvop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CHANGE_LEVEL)
e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e1:SetRange(LOCATION_MZONE)
e1:SetCondition(c91907707.lvcon)
e1:SetValue(4)
e1:SetReset(RESET_EVENT+0xff0000)
c:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_SET_BASE_ATTACK)
e2:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e2:SetRange(LOCATION_MZONE)
e2:SetCondition(c91907707.lvcon)
e2:SetValue(1800)
e2:SetReset(RESET_EVENT+0xff0000)
c:RegisterEffect(e2)
end
function c91907707.lvop2(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CHANGE_LEVEL)
e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e1:SetRange(LOCATION_MZONE)
e1:SetValue(4)
e1:SetReset(RESET_EVENT+0x7f0000)
c:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_SET_BASE_ATTACK)
e2:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e2:SetRange(LOCATION_MZONE)
e2:SetValue(1800)
e2:SetReset(RESET_EVENT+0x7f0000)
c:RegisterEffect(e2)
end
function c91907707.immcon(e)
return e:GetHandler():IsSummonType(SUMMON_TYPE_NORMAL)
end
function c91907707.thtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsAbleToHand() end
if chk==0 then return Duel.IsExistingTarget(Card.IsAbleToHand,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_RTOHAND)
local g=Duel.SelectTarget(tp,Card.IsAbleToHand,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_TOHAND,g,1,0,0)
end
function c91907707.thop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.SendtoHand(tc,nil,REASON_EFFECT)
end
end
| gpl-2.0 |
mercury233/ygopro-scripts | c71734607.lua | 2 | 2895 | --六花のひとひら
function c71734607.initial_effect(c)
--to hand or grave
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(71734607,0))
e1:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH+CATEGORY_TOGRAVE)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_MZONE)
e1:SetCountLimit(1,71734607)
e1:SetTarget(c71734607.target)
e1:SetOperation(c71734607.operation)
c:RegisterEffect(e1)
--spsummon
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(71734607,1))
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e2:SetCode(EVENT_PHASE+PHASE_END)
e2:SetRange(LOCATION_GRAVE)
e2:SetCountLimit(1,71734608)
e2:SetCondition(c71734607.spcon)
e2:SetTarget(c71734607.sptg)
e2:SetOperation(c71734607.spop)
c:RegisterEffect(e2)
end
function c71734607.cfilter(c)
return c:IsType(TYPE_MONSTER) and c:IsSetCard(0x141) and not c:IsCode(71734607) and (c:IsAbleToHand() or c:IsAbleToGrave())
end
function c71734607.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c71734607.cfilter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
Duel.SetOperationInfo(0,CATEGORY_TOGRAVE,nil,1,tp,LOCATION_DECK)
end
function c71734607.operation(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_OPERATECARD)
local g=Duel.SelectMatchingCard(tp,c71734607.cfilter,tp,LOCATION_DECK,0,1,1,nil)
if g:GetCount()>0 then
local tc=g:GetFirst()
if tc and tc:IsAbleToHand() and (not tc:IsAbleToGrave() or Duel.SelectOption(tp,1190,1191)==0) then
Duel.SendtoHand(tc,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,tc)
else
Duel.SendtoGrave(tc,REASON_EFFECT)
end
end
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON)
e1:SetTargetRange(1,0)
e1:SetTarget(c71734607.splimit)
e1:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e1,tp)
end
function c71734607.splimit(e,c)
return not c:IsRace(RACE_PLANT)
end
function c71734607.spfilter(c)
return c:IsFaceup() and c:IsRace(RACE_PLANT)
end
function c71734607.spcon(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetTurnPlayer()~=1-tp then return false end
local ct1=Duel.GetFieldGroupCount(tp,LOCATION_MZONE,0)
local ct2=Duel.GetMatchingGroupCount(c71734607.spfilter,tp,LOCATION_MZONE,0,nil)
local chk1=ct1==0
local chk2=ct2>0 and ct1-ct2==0
return chk1 or chk2
end
function c71734607.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0)
end
function c71734607.spop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) then
Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP)
end
end
| gpl-2.0 |
mercury233/ygopro-scripts | c63806265.lua | 2 | 1474 | --虹の引力
function c63806265.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetHintTiming(0,TIMING_END_PHASE)
e1:SetCondition(c63806265.condition)
e1:SetTarget(c63806265.target)
e1:SetOperation(c63806265.activate)
c:RegisterEffect(e1)
end
function c63806265.cfilter(c)
return c:IsSetCard(0x1034) and (not c:IsOnField() or c:IsFaceup())
end
function c63806265.condition(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetMatchingGroup(c63806265.cfilter,tp,LOCATION_ONFIELD+LOCATION_GRAVE,0,nil)
local ct=g:GetClassCount(Card.GetCode)
return ct>6
end
function c63806265.filter(c,e,tp)
return c:IsSetCard(0x2034) and c:IsCanBeSpecialSummoned(e,0,tp,true,false)
end
function c63806265.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c63806265.filter,tp,LOCATION_DECK+LOCATION_GRAVE,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK+LOCATION_GRAVE)
end
function c63806265.activate(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,aux.NecroValleyFilter(c63806265.filter),tp,LOCATION_DECK+LOCATION_GRAVE,0,1,1,nil,e,tp)
if g:GetCount()>0 then
Duel.SpecialSummon(g,0,tp,tp,true,false,POS_FACEUP)
end
end
| gpl-2.0 |
Zenny89/darkstar | scripts/zones/Northern_San_dOria/npcs/Justi.lua | 36 | 1852 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Justi
-- Conquest depending furniture seller
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/globals/quests");
require("scripts/zones/Northern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
count = trade:getItemCount();
MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,JUSTI_SHOP_DIALOG);
stock = {0x0037,69888,1, --Cabinet
0x003b,57333,1, --Chiffonier
0x0020,170726,1, --Dresser
0x0031,35272,2, --Coffer
0x002e,8376,3, --Armor Box
0x0679,92,3, --Bundling Twine
0x0039,15881,3, --Cupboard
0x0018,129168,3, --Oak Table
0x005d,518,3} --Water Cask
showNationShop(player, SANDORIA, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
mercury233/ygopro-scripts | c81128478.lua | 4 | 1385 | --ライヤー・ワイヤー
function c81128478.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_DESTROY)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetHintTiming(0,TIMINGS_CHECK_MONSTER)
e1:SetCost(c81128478.cost)
e1:SetTarget(c81128478.target)
e1:SetOperation(c81128478.activate)
c:RegisterEffect(e1)
end
function c81128478.cfilter(c)
return c:IsRace(RACE_INSECT) and c:IsAbleToRemoveAsCost()
end
function c81128478.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c81128478.cfilter,tp,LOCATION_GRAVE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=Duel.SelectMatchingCard(tp,c81128478.cfilter,tp,LOCATION_GRAVE,0,1,1,nil)
Duel.Remove(g,POS_FACEUP,REASON_COST)
end
function c81128478.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(1-tp) end
if chk==0 then return Duel.IsExistingTarget(aux.TRUE,tp,0,LOCATION_MZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local g=Duel.SelectTarget(tp,aux.TRUE,tp,0,LOCATION_MZONE,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,1,0,0)
end
function c81128478.activate(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.Destroy(tc,REASON_EFFECT)
end
end
| gpl-2.0 |
mercury233/ygopro-scripts | c54423935.lua | 4 | 2337 | --R・R・R
function c54423935.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetTarget(c54423935.target)
e1:SetOperation(c54423935.activate)
c:RegisterEffect(e1)
end
function c54423935.filter(c,e,tp)
return c:IsFaceup() and c:IsSetCard(0xba)
and Duel.IsExistingMatchingCard(c54423935.spfilter,tp,LOCATION_DECK,0,1,nil,e,tp,c:GetCode())
end
function c54423935.spfilter(c,e,tp,cd)
return c:IsCode(cd) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c54423935.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(tp) and chkc:IsCode(e:GetLabel()) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingTarget(c54423935.filter,tp,LOCATION_MZONE,0,1,nil,e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP)
local g=Duel.SelectTarget(tp,c54423935.filter,tp,LOCATION_MZONE,0,1,1,nil,e,tp)
e:SetLabel(g:GetFirst():GetCode())
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK)
end
function c54423935.activate(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
local tc=Duel.GetFirstTarget()
if tc:IsFaceup() and tc:IsRelateToEffect(e) then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c54423935.spfilter,tp,LOCATION_DECK,0,1,1,nil,e,tp,tc:GetCode())
local sc=g:GetFirst()
if sc and Duel.SpecialSummon(sc,0,tp,tp,false,false,POS_FACEUP)>0 then
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CANNOT_BE_BATTLE_TARGET)
e1:SetLabelObject(sc)
e1:SetLabel(sc:GetFieldID())
e1:SetCondition(c54423935.imcon)
e1:SetValue(aux.imval1)
e1:SetReset(RESET_EVENT+RESETS_STANDARD)
tc:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetProperty(EFFECT_FLAG_IGNORE_IMMUNE)
e2:SetCode(EFFECT_CANNOT_BE_EFFECT_TARGET)
e2:SetValue(aux.tgoval)
tc:RegisterEffect(e2)
end
end
end
function c54423935.imcon(e)
local tp=e:GetHandlerPlayer()
local sc=e:GetLabelObject()
return sc and sc:GetFieldID()==e:GetLabel() and sc:IsFaceup() and sc:IsLocation(LOCATION_MZONE)
and sc:IsControler(tp)
end
| gpl-2.0 |
PasdarTeam/BulletProofCli | libs/serpent.lua | 656 | 7877 | local n, v = "serpent", 0.28 -- (C) 2012-15 Paul Kulchenko; MIT License
local c, d = "Paul Kulchenko", "Lua serializer and pretty printer"
local snum = {[tostring(1/0)]='1/0 --[[math.huge]]',[tostring(-1/0)]='-1/0 --[[-math.huge]]',[tostring(0/0)]='0/0'}
local badtype = {thread = true, userdata = true, cdata = true}
local keyword, globals, G = {}, {}, (_G or _ENV)
for _,k in ipairs({'and', 'break', 'do', 'else', 'elseif', 'end', 'false',
'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat',
'return', 'then', 'true', 'until', 'while'}) do keyword[k] = true end
for k,v in pairs(G) do globals[v] = k end -- build func to name mapping
for _,g in ipairs({'coroutine', 'debug', 'io', 'math', 'string', 'table', 'os'}) do
for k,v in pairs(G[g] or {}) do globals[v] = g..'.'..k end end
local function s(t, opts)
local name, indent, fatal, maxnum = opts.name, opts.indent, opts.fatal, opts.maxnum
local sparse, custom, huge = opts.sparse, opts.custom, not opts.nohuge
local space, maxl = (opts.compact and '' or ' '), (opts.maxlevel or math.huge)
local iname, comm = '_'..(name or ''), opts.comment and (tonumber(opts.comment) or math.huge)
local seen, sref, syms, symn = {}, {'local '..iname..'={}'}, {}, 0
local function gensym(val) return '_'..(tostring(tostring(val)):gsub("[^%w]",""):gsub("(%d%w+)",
-- tostring(val) is needed because __tostring may return a non-string value
function(s) if not syms[s] then symn = symn+1; syms[s] = symn end return tostring(syms[s]) end)) end
local function safestr(s) return type(s) == "number" and tostring(huge and snum[tostring(s)] or s)
or type(s) ~= "string" and tostring(s) -- escape NEWLINE/010 and EOF/026
or ("%q"):format(s):gsub("\010","n"):gsub("\026","\\026") end
local function comment(s,l) return comm and (l or 0) < comm and ' --[['..tostring(s)..']]' or '' end
local function globerr(s,l) return globals[s] and globals[s]..comment(s,l) or not fatal
and safestr(select(2, pcall(tostring, s))) or error("Can't serialize "..tostring(s)) end
local function safename(path, name) -- generates foo.bar, foo[3], or foo['b a r']
local n = name == nil and '' or name
local plain = type(n) == "string" and n:match("^[%l%u_][%w_]*$") and not keyword[n]
local safe = plain and n or '['..safestr(n)..']'
return (path or '')..(plain and path and '.' or '')..safe, safe end
local alphanumsort = type(opts.sortkeys) == 'function' and opts.sortkeys or function(k, o, n) -- k=keys, o=originaltable, n=padding
local maxn, to = tonumber(n) or 12, {number = 'a', string = 'b'}
local function padnum(d) return ("%0"..tostring(maxn).."d"):format(tonumber(d)) end
table.sort(k, function(a,b)
-- sort numeric keys first: k[key] is not nil for numerical keys
return (k[a] ~= nil and 0 or to[type(a)] or 'z')..(tostring(a):gsub("%d+",padnum))
< (k[b] ~= nil and 0 or to[type(b)] or 'z')..(tostring(b):gsub("%d+",padnum)) end) end
local function val2str(t, name, indent, insref, path, plainindex, level)
local ttype, level, mt = type(t), (level or 0), getmetatable(t)
local spath, sname = safename(path, name)
local tag = plainindex and
((type(name) == "number") and '' or name..space..'='..space) or
(name ~= nil and sname..space..'='..space or '')
if seen[t] then -- already seen this element
sref[#sref+1] = spath..space..'='..space..seen[t]
return tag..'nil'..comment('ref', level) end
if type(mt) == 'table' and (mt.__serialize or mt.__tostring) then -- knows how to serialize itself
seen[t] = insref or spath
if mt.__serialize then t = mt.__serialize(t) else t = tostring(t) end
ttype = type(t) end -- new value falls through to be serialized
if ttype == "table" then
if level >= maxl then return tag..'{}'..comment('max', level) end
seen[t] = insref or spath
if next(t) == nil then return tag..'{}'..comment(t, level) end -- table empty
local maxn, o, out = math.min(#t, maxnum or #t), {}, {}
for key = 1, maxn do o[key] = key end
if not maxnum or #o < maxnum then
local n = #o -- n = n + 1; o[n] is much faster than o[#o+1] on large tables
for key in pairs(t) do if o[key] ~= key then n = n + 1; o[n] = key end end end
if maxnum and #o > maxnum then o[maxnum+1] = nil end
if opts.sortkeys and #o > maxn then alphanumsort(o, t, opts.sortkeys) end
local sparse = sparse and #o > maxn -- disable sparsness if only numeric keys (shorter output)
for n, key in ipairs(o) do
local value, ktype, plainindex = t[key], type(key), n <= maxn and not sparse
if opts.valignore and opts.valignore[value] -- skip ignored values; do nothing
or opts.keyallow and not opts.keyallow[key]
or opts.valtypeignore and opts.valtypeignore[type(value)] -- skipping ignored value types
or sparse and value == nil then -- skipping nils; do nothing
elseif ktype == 'table' or ktype == 'function' or badtype[ktype] then
if not seen[key] and not globals[key] then
sref[#sref+1] = 'placeholder'
local sname = safename(iname, gensym(key)) -- iname is table for local variables
sref[#sref] = val2str(key,sname,indent,sname,iname,true) end
sref[#sref+1] = 'placeholder'
local path = seen[t]..'['..tostring(seen[key] or globals[key] or gensym(key))..']'
sref[#sref] = path..space..'='..space..tostring(seen[value] or val2str(value,nil,indent,path))
else
out[#out+1] = val2str(value,key,indent,insref,seen[t],plainindex,level+1)
end
end
local prefix = string.rep(indent or '', level)
local head = indent and '{\n'..prefix..indent or '{'
local body = table.concat(out, ','..(indent and '\n'..prefix..indent or space))
local tail = indent and "\n"..prefix..'}' or '}'
return (custom and custom(tag,head,body,tail) or tag..head..body..tail)..comment(t, level)
elseif badtype[ttype] then
seen[t] = insref or spath
return tag..globerr(t, level)
elseif ttype == 'function' then
seen[t] = insref or spath
local ok, res = pcall(string.dump, t)
local func = ok and ((opts.nocode and "function() --[[..skipped..]] end" or
"((loadstring or load)("..safestr(res)..",'@serialized'))")..comment(t, level))
return tag..(func or globerr(t, level))
else return tag..safestr(t) end -- handle all other types
end
local sepr = indent and "\n" or ";"..space
local body = val2str(t, name, indent) -- this call also populates sref
local tail = #sref>1 and table.concat(sref, sepr)..sepr or ''
local warn = opts.comment and #sref>1 and space.."--[[incomplete output with shared/self-references skipped]]" or ''
return not name and body..warn or "do local "..body..sepr..tail.."return "..name..sepr.."end"
end
local function deserialize(data, opts)
local env = (opts and opts.safe == false) and G
or setmetatable({}, {
__index = function(t,k) return t end,
__call = function(t,...) error("cannot call functions") end
})
local f, res = (loadstring or load)('return '..data, nil, nil, env)
if not f then f, res = (loadstring or load)(data, nil, nil, env) end
if not f then return f, res end
if setfenv then setfenv(f, env) end
return pcall(f)
end
local function merge(a, b) if b then for k,v in pairs(b) do a[k] = v end end; return a; end
return { _NAME = n, _COPYRIGHT = c, _DESCRIPTION = d, _VERSION = v, serialize = s,
load = deserialize,
dump = function(a, opts) return s(a, merge({name = '_', compact = true, sparse = true}, opts)) end,
line = function(a, opts) return s(a, merge({sortkeys = true, comment = true}, opts)) end,
block = function(a, opts) return s(a, merge({indent = ' ', sortkeys = true, comment = true}, opts)) end }
| gpl-2.0 |
mercury233/ygopro-scripts | c45877457.lua | 2 | 3900 | --魔鍵砲-ガレスヴェート
function c45877457.initial_effect(c)
c:EnableReviveLimit()
--different attr check
local e0=Effect.CreateEffect(c)
e0:SetType(EFFECT_TYPE_SINGLE)
e0:SetCode(EFFECT_MATERIAL_CHECK)
e0:SetValue(c45877457.valcheck)
c:RegisterEffect(e0)
--atkup
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e1:SetRange(LOCATION_MZONE)
e1:SetValue(c45877457.atkval)
c:RegisterEffect(e1)
--negate
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(45877457,0))
e2:SetCategory(CATEGORY_NEGATE+CATEGORY_DESTROY)
e2:SetType(EFFECT_TYPE_QUICK_O)
e2:SetCode(EVENT_CHAINING)
e2:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DAMAGE_CAL)
e2:SetRange(LOCATION_MZONE)
e2:SetCountLimit(1,45877457)
e2:SetCondition(c45877457.condition)
e2:SetTarget(c45877457.target)
e2:SetOperation(c45877457.activate)
c:RegisterEffect(e2)
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS)
e3:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e3:SetCode(EVENT_SPSUMMON_SUCCESS)
e3:SetCondition(c45877457.matcon)
e3:SetOperation(c45877457.matop)
c:RegisterEffect(e3)
e0:SetLabelObject(e3)
--search
local e4=Effect.CreateEffect(c)
e4:SetDescription(aux.Stringid(45877457,1))
e4:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH)
e4:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e4:SetCode(EVENT_TO_GRAVE)
e4:SetProperty(EFFECT_FLAG_DELAY)
e4:SetCountLimit(1,45877458)
e4:SetCondition(c45877457.thcon)
e4:SetTarget(c45877457.thtg)
e4:SetOperation(c45877457.thop)
c:RegisterEffect(e4)
end
function c45877457.atkval(e,c)
local g=Duel.GetMatchingGroup(Card.IsType,c:GetControler(),LOCATION_GRAVE,0,nil,TYPE_MONSTER)
return g:GetClassCount(Card.GetAttribute)*300
end
function c45877457.matcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsSummonType(SUMMON_TYPE_RITUAL) and e:GetLabel()==1
end
function c45877457.matop(e,tp,eg,ep,ev,re,r,rp)
e:GetHandler():RegisterFlagEffect(45877457,RESET_EVENT+RESETS_STANDARD,EFFECT_FLAG_CLIENT_HINT,1,0,aux.Stringid(45877457,2))
end
function c45877457.attfilter(c)
return c:GetAttribute()>0
end
function c45877457.valcheck(e,c)
local mg=c:GetMaterial()
local fg=mg:Filter(c45877457.attfilter,nil)
if fg:GetClassCount(Card.GetAttribute)>1 then
e:GetLabelObject():SetLabel(1)
else
e:GetLabelObject():SetLabel(0)
end
end
function c45877457.condition(e,tp,eg,ep,ev,re,r,rp)
return rp==1-tp and re:IsActiveType(TYPE_MONSTER) and Duel.IsChainNegatable(ev) and e:GetHandler():GetFlagEffect(45877457)>0
and Duel.IsExistingMatchingCard(Card.IsAttribute,tp,LOCATION_GRAVE,0,1,nil,re:GetHandler():GetAttribute())
end
function c45877457.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_NEGATE,eg,1,0,0)
if re:GetHandler():IsRelateToEffect(re) then
Duel.SetOperationInfo(0,CATEGORY_DESTROY,eg,1,0,0)
end
end
function c45877457.activate(e,tp,eg,ep,ev,re,r,rp)
if Duel.NegateActivation(ev) and re:GetHandler():IsRelateToEffect(re) then
Duel.Destroy(eg,REASON_EFFECT)
end
end
function c45877457.thcon(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
return c:IsPreviousLocation(LOCATION_MZONE) and c:IsSummonType(SUMMON_TYPE_RITUAL)
end
function c45877457.thfilter(c)
return c:IsSetCard(0x165) and c:IsType(TYPE_MONSTER) and c:IsAbleToHand()
end
function c45877457.thtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c45877457.thfilter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function c45877457.thop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local hg=Duel.SelectMatchingCard(tp,c45877457.thfilter,tp,LOCATION_DECK,0,1,1,nil)
if hg:GetCount()>0 then
Duel.SendtoHand(hg,tp,REASON_EFFECT)
Duel.ConfirmCards(1-tp,hg)
end
end
| gpl-2.0 |
Anti-Plus/Anti-Plus | libs/serpent.lua | 656 | 7877 | local n, v = "serpent", 0.28 -- (C) 2012-15 Paul Kulchenko; MIT License
local c, d = "Paul Kulchenko", "Lua serializer and pretty printer"
local snum = {[tostring(1/0)]='1/0 --[[math.huge]]',[tostring(-1/0)]='-1/0 --[[-math.huge]]',[tostring(0/0)]='0/0'}
local badtype = {thread = true, userdata = true, cdata = true}
local keyword, globals, G = {}, {}, (_G or _ENV)
for _,k in ipairs({'and', 'break', 'do', 'else', 'elseif', 'end', 'false',
'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat',
'return', 'then', 'true', 'until', 'while'}) do keyword[k] = true end
for k,v in pairs(G) do globals[v] = k end -- build func to name mapping
for _,g in ipairs({'coroutine', 'debug', 'io', 'math', 'string', 'table', 'os'}) do
for k,v in pairs(G[g] or {}) do globals[v] = g..'.'..k end end
local function s(t, opts)
local name, indent, fatal, maxnum = opts.name, opts.indent, opts.fatal, opts.maxnum
local sparse, custom, huge = opts.sparse, opts.custom, not opts.nohuge
local space, maxl = (opts.compact and '' or ' '), (opts.maxlevel or math.huge)
local iname, comm = '_'..(name or ''), opts.comment and (tonumber(opts.comment) or math.huge)
local seen, sref, syms, symn = {}, {'local '..iname..'={}'}, {}, 0
local function gensym(val) return '_'..(tostring(tostring(val)):gsub("[^%w]",""):gsub("(%d%w+)",
-- tostring(val) is needed because __tostring may return a non-string value
function(s) if not syms[s] then symn = symn+1; syms[s] = symn end return tostring(syms[s]) end)) end
local function safestr(s) return type(s) == "number" and tostring(huge and snum[tostring(s)] or s)
or type(s) ~= "string" and tostring(s) -- escape NEWLINE/010 and EOF/026
or ("%q"):format(s):gsub("\010","n"):gsub("\026","\\026") end
local function comment(s,l) return comm and (l or 0) < comm and ' --[['..tostring(s)..']]' or '' end
local function globerr(s,l) return globals[s] and globals[s]..comment(s,l) or not fatal
and safestr(select(2, pcall(tostring, s))) or error("Can't serialize "..tostring(s)) end
local function safename(path, name) -- generates foo.bar, foo[3], or foo['b a r']
local n = name == nil and '' or name
local plain = type(n) == "string" and n:match("^[%l%u_][%w_]*$") and not keyword[n]
local safe = plain and n or '['..safestr(n)..']'
return (path or '')..(plain and path and '.' or '')..safe, safe end
local alphanumsort = type(opts.sortkeys) == 'function' and opts.sortkeys or function(k, o, n) -- k=keys, o=originaltable, n=padding
local maxn, to = tonumber(n) or 12, {number = 'a', string = 'b'}
local function padnum(d) return ("%0"..tostring(maxn).."d"):format(tonumber(d)) end
table.sort(k, function(a,b)
-- sort numeric keys first: k[key] is not nil for numerical keys
return (k[a] ~= nil and 0 or to[type(a)] or 'z')..(tostring(a):gsub("%d+",padnum))
< (k[b] ~= nil and 0 or to[type(b)] or 'z')..(tostring(b):gsub("%d+",padnum)) end) end
local function val2str(t, name, indent, insref, path, plainindex, level)
local ttype, level, mt = type(t), (level or 0), getmetatable(t)
local spath, sname = safename(path, name)
local tag = plainindex and
((type(name) == "number") and '' or name..space..'='..space) or
(name ~= nil and sname..space..'='..space or '')
if seen[t] then -- already seen this element
sref[#sref+1] = spath..space..'='..space..seen[t]
return tag..'nil'..comment('ref', level) end
if type(mt) == 'table' and (mt.__serialize or mt.__tostring) then -- knows how to serialize itself
seen[t] = insref or spath
if mt.__serialize then t = mt.__serialize(t) else t = tostring(t) end
ttype = type(t) end -- new value falls through to be serialized
if ttype == "table" then
if level >= maxl then return tag..'{}'..comment('max', level) end
seen[t] = insref or spath
if next(t) == nil then return tag..'{}'..comment(t, level) end -- table empty
local maxn, o, out = math.min(#t, maxnum or #t), {}, {}
for key = 1, maxn do o[key] = key end
if not maxnum or #o < maxnum then
local n = #o -- n = n + 1; o[n] is much faster than o[#o+1] on large tables
for key in pairs(t) do if o[key] ~= key then n = n + 1; o[n] = key end end end
if maxnum and #o > maxnum then o[maxnum+1] = nil end
if opts.sortkeys and #o > maxn then alphanumsort(o, t, opts.sortkeys) end
local sparse = sparse and #o > maxn -- disable sparsness if only numeric keys (shorter output)
for n, key in ipairs(o) do
local value, ktype, plainindex = t[key], type(key), n <= maxn and not sparse
if opts.valignore and opts.valignore[value] -- skip ignored values; do nothing
or opts.keyallow and not opts.keyallow[key]
or opts.valtypeignore and opts.valtypeignore[type(value)] -- skipping ignored value types
or sparse and value == nil then -- skipping nils; do nothing
elseif ktype == 'table' or ktype == 'function' or badtype[ktype] then
if not seen[key] and not globals[key] then
sref[#sref+1] = 'placeholder'
local sname = safename(iname, gensym(key)) -- iname is table for local variables
sref[#sref] = val2str(key,sname,indent,sname,iname,true) end
sref[#sref+1] = 'placeholder'
local path = seen[t]..'['..tostring(seen[key] or globals[key] or gensym(key))..']'
sref[#sref] = path..space..'='..space..tostring(seen[value] or val2str(value,nil,indent,path))
else
out[#out+1] = val2str(value,key,indent,insref,seen[t],plainindex,level+1)
end
end
local prefix = string.rep(indent or '', level)
local head = indent and '{\n'..prefix..indent or '{'
local body = table.concat(out, ','..(indent and '\n'..prefix..indent or space))
local tail = indent and "\n"..prefix..'}' or '}'
return (custom and custom(tag,head,body,tail) or tag..head..body..tail)..comment(t, level)
elseif badtype[ttype] then
seen[t] = insref or spath
return tag..globerr(t, level)
elseif ttype == 'function' then
seen[t] = insref or spath
local ok, res = pcall(string.dump, t)
local func = ok and ((opts.nocode and "function() --[[..skipped..]] end" or
"((loadstring or load)("..safestr(res)..",'@serialized'))")..comment(t, level))
return tag..(func or globerr(t, level))
else return tag..safestr(t) end -- handle all other types
end
local sepr = indent and "\n" or ";"..space
local body = val2str(t, name, indent) -- this call also populates sref
local tail = #sref>1 and table.concat(sref, sepr)..sepr or ''
local warn = opts.comment and #sref>1 and space.."--[[incomplete output with shared/self-references skipped]]" or ''
return not name and body..warn or "do local "..body..sepr..tail.."return "..name..sepr.."end"
end
local function deserialize(data, opts)
local env = (opts and opts.safe == false) and G
or setmetatable({}, {
__index = function(t,k) return t end,
__call = function(t,...) error("cannot call functions") end
})
local f, res = (loadstring or load)('return '..data, nil, nil, env)
if not f then f, res = (loadstring or load)(data, nil, nil, env) end
if not f then return f, res end
if setfenv then setfenv(f, env) end
return pcall(f)
end
local function merge(a, b) if b then for k,v in pairs(b) do a[k] = v end end; return a; end
return { _NAME = n, _COPYRIGHT = c, _DESCRIPTION = d, _VERSION = v, serialize = s,
load = deserialize,
dump = function(a, opts) return s(a, merge({name = '_', compact = true, sparse = true}, opts)) end,
line = function(a, opts) return s(a, merge({sortkeys = true, comment = true}, opts)) end,
block = function(a, opts) return s(a, merge({indent = ' ', sortkeys = true, comment = true}, opts)) end }
| lgpl-2.1 |
goblinor/BomBus | plugins/filter.lua | 2 | 2816 | local function addword(msg, name)
local hash = 'chat:'..msg.chat_id_..':badword'
redis:hset(hash, name, 'newword')
return "کلمه جدید به فیلتر کلمات اضافه شد\n🔹➕ "..name
end
local function get_badword_hash(msg)
return 'chat:'..msg.chat_id_..':badword'
end
local function list_badwords(msg)
local hash = get_badword_hash(msg)
local result=''
if hash then
local names = redis:hkeys(hash)
local text = '📋لیست کلمات غیرمجاز :\n\n'
for i=1, #names do
result = result..'🔹 '..names[i]..'\n'
end
if #result>0 then
return text..result
else
return'⭕️لیست کلمات غیرمجاز خالی میباشد.⭕️'
end
end
end
local function clear_badwords(msg, var_name)
local hash = get_badword_hash(msg)
redis:del(hash, var_name)
return '❌لیست کلمات غیرمجاز حذف شد❌'
end
local function list_badword2(msg, arg)
local hash = get_badword_hash(msg)
if hash then
local names = redis:hkeys(hash)
local text = ''
for i=1, #names do
if string.match(arg, names[i]) and not is_mod(msg) then
if gp_type(chat) == "channel" then
tdcli.deleteMessages(msg.chat_id_, {[0] = msg.id_}, dl_cb, nil)
elseif gp_type(chat) == "chat" then
kick_user(msg.sende_user_id_, msg.chat_id_)
end
return
end
end
end
end
local function clear_badword(msg, cmd_name)
local hash = get_badword_hash(msg)
redis:hdel(hash, cmd_name)
return '❌کلمه غیرمجاز '..cmd_name..' حذف شد.'
end
local function pre_process(msg)
msg.text = msg.content_.text_
local hash = get_badword_hash(msg)
if hash then
local names = redis:hkeys(hash)
local text = ''
for i=1, #names do
if string.match(msg.text, names[i]) and not is_mod(msg) then
if gp_type(chat) == "channel" then
tdcli.deleteMessages(msg.chat_id_, {[0] = msg.id_}, dl_cb, nil)
elseif gp_type(chat) == "chat" then
kick_user(msg.sende_user_id_, msg.chat_id_)
end
return
end
end
end
end
local function run(msg, matches)
if is_mod(msg) then
if matches[2]:lower() == 'filter' then
local name = string.sub(matches[3], 1, 50)
local text = addword(msg, name)
return text
end
if matches[2]:lower() == 'filterlist' then
return list_badwords(msg)
elseif matches[2]:lower() == 'clean' then
local number = '1'
return clear_badwords(msg, number)
elseif matches[2]:lower() == 'unfilter' then
return clear_badword(msg, matches[3])
end
end
end
return {
patterns = {
"^([!/#])([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][Ll][Ee][Aa][Nn]) ([Ff][Ii][Ll][Tt][Ee][Rr][Ll][Ii][Ss][Tt])$",
},
run = run,
pre_process = pre_process
}
| gpl-2.0 |
mercury233/ygopro-scripts | c32986898.lua | 2 | 2858 | --粛星の鋼機
function c32986898.initial_effect(c)
--link summon
aux.AddLinkProcedure(c,aux.NOT(aux.FilterBoolFunction(Card.IsLinkType,TYPE_LINK)),3,3)
c:EnableReviveLimit()
--atkup
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetCode(EVENT_SPSUMMON_SUCCESS)
e1:SetCondition(c32986898.atkcon)
e1:SetOperation(c32986898.atkop)
c:RegisterEffect(e1)
--Destroy
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(32986898,0))
e2:SetCategory(CATEGORY_DESTROY+CATEGORY_DAMAGE)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET)
e2:SetCountLimit(1,32986898)
e2:SetRange(LOCATION_MZONE)
e2:SetTarget(c32986898.destg)
e2:SetOperation(c32986898.desop)
c:RegisterEffect(e2)
--
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_SINGLE)
e4:SetCode(EFFECT_MATERIAL_CHECK)
e4:SetValue(c32986898.valcheck)
c:RegisterEffect(e4)
e4:SetLabelObject(e1)
end
function c32986898.atkcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsSummonType(SUMMON_TYPE_LINK)
end
function c32986898.atkop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local g=c:GetMaterial()
local atk=0
local tc=g:GetFirst()
while tc do
local lk
if tc:IsType(TYPE_XYZ) then
lk=tc:GetOriginalRank()
else
lk=tc:GetOriginalLevel()
end
atk=atk+lk
tc=g:GetNext()
end
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetValue(atk*100)
e1:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_DISABLE)
c:RegisterEffect(e1)
if e:GetLabel()==1 then
c:RegisterFlagEffect(32986898,RESET_EVENT+RESETS_STANDARD,0,1)
end
end
function c32986898.desfilter(c,atk)
return c:IsFaceup() and c:IsAttackBelow(atk) and not c:IsType(TYPE_LINK)
end
function c32986898.destg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
local c=e:GetHandler()
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(1-tp) and c32986898.desfilter(chkc,c:GetAttack()) end
if chk==0 then return Duel.IsExistingTarget(c32986898.desfilter,tp,0,LOCATION_MZONE,1,nil,c:GetAttack()) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local g=Duel.SelectTarget(tp,c32986898.desfilter,tp,0,LOCATION_MZONE,1,1,nil,c:GetAttack())
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,1,0,0)
end
function c32986898.desop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
if Duel.Destroy(tc,REASON_EFFECT)~=0 and e:GetHandler():GetFlagEffect(32986898)~=0 then
Duel.BreakEffect()
local atk=tc:GetBaseAttack()
if atk<0 then atk=0 end
Duel.Damage(1-tp,math.ceil(atk/2),REASON_EFFECT)
end
end
end
function c32986898.valcheck(e,c)
local g=c:GetMaterial()
if g:IsExists(Card.IsLinkType,1,nil,TYPE_XYZ) then
e:GetLabelObject():SetLabel(1)
else
e:GetLabelObject():SetLabel(0)
end
end
| gpl-2.0 |
mercury233/ygopro-scripts | c66765023.lua | 2 | 1900 | --飛行エレファント
function c66765023.initial_effect(c)
--indes
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e1:SetRange(LOCATION_MZONE)
e1:SetCode(EFFECT_INDESTRUCTABLE_COUNT)
e1:SetCountLimit(1)
e1:SetCondition(c66765023.indcon)
e1:SetValue(c66765023.valcon)
c:RegisterEffect(e1)
--add win effect
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F)
e2:SetCode(EVENT_PHASE+PHASE_END)
e2:SetRange(LOCATION_MZONE)
e2:SetCountLimit(1)
e2:SetCondition(c66765023.effcon)
e2:SetOperation(c66765023.effop)
c:RegisterEffect(e2)
end
function c66765023.indcon(e)
return Duel.GetTurnPlayer()~=e:GetHandlerPlayer()
end
function c66765023.valcon(e,re,r,rp)
local res=false
if bit.band(r,REASON_EFFECT)~=0 and rp==1-e:GetHandlerPlayer() then
res=true
e:GetHandler():RegisterFlagEffect(66765023,RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END,0,1)
end
return res
end
function c66765023.effcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetFlagEffect(66765023)~=0 and Duel.GetTurnPlayer()~=e:GetHandlerPlayer()
end
function c66765023.effop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if not c:IsRelateToEffect(e) then return end
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(66765023,0))
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS)
e1:SetProperty(EFFECT_FLAG_CLIENT_HINT+EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e1:SetCode(EVENT_BATTLE_DAMAGE)
e1:SetCondition(c66765023.wincon)
e1:SetOperation(c66765023.winop)
e1:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END,2)
c:RegisterEffect(e1)
end
function c66765023.wincon(e,tp,eg,ep,ev,re,r,rp)
return ep~=tp and Duel.GetAttackTarget()==nil
end
function c66765023.winop(e,tp,eg,ep,ev,re,r,rp)
local WIN_REASON_FLYING_ELEPHANT=0x1e
Duel.Win(tp,WIN_REASON_FLYING_ELEPHANT)
end
| gpl-2.0 |
mercury233/ygopro-scripts | c29085954.lua | 2 | 3008 | --No.78 ナンバーズ・アーカイブ
function c29085954.initial_effect(c)
--xyz summon
aux.AddXyzProcedure(c,nil,1,2)
c:EnableReviveLimit()
--spsummon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(29085954,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_QUICK_O)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetRange(LOCATION_MZONE)
e1:SetCountLimit(1)
e1:SetCost(c29085954.cost)
e1:SetTarget(c29085954.sptg)
e1:SetOperation(c29085954.spop)
c:RegisterEffect(e1)
end
aux.xyz_number[29085954]=78
function c29085954.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():CheckRemoveOverlayCard(tp,1,REASON_COST) end
e:GetHandler():RemoveOverlayCard(tp,1,1,REASON_COST)
end
function c29085954.filter(c,e,tp,mc)
local no=aux.GetXyzNumber(c)
return no and no>=1 and no<=99 and c:IsSetCard(0x48)
and mc:IsCanBeXyzMaterial(c)
and c:IsCanBeSpecialSummoned(e,SUMMON_TYPE_XYZ,tp,false,false) and Duel.GetLocationCountFromEx(tp,tp,mc,c)>0
end
function c29085954.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return aux.MustMaterialCheck(e:GetHandler(),tp,EFFECT_MUST_BE_XMATERIAL)
and Duel.IsExistingMatchingCard(c29085954.filter,tp,LOCATION_EXTRA,0,1,nil,e,tp,e:GetHandler()) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_EXTRA)
end
function c29085954.spop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local g=Duel.GetFieldGroup(tp,LOCATION_EXTRA,0)
if g:GetCount()>0 and aux.MustMaterialCheck(c,tp,EFFECT_MUST_BE_XMATERIAL)
and c:IsFaceup() and c:IsRelateToEffect(e) and c:IsControler(tp) and not c:IsImmuneToEffect(e) then
local tg=g:RandomSelect(1-tp,1)
Duel.ConfirmCards(1-tp,tg)
if tg:IsExists(c29085954.filter,1,nil,e,tp,c) then
local tc=tg:GetFirst()
local mg=c:GetOverlayGroup()
if mg:GetCount()~=0 then
Duel.Overlay(tc,mg)
end
tc:SetMaterial(Group.FromCards(c))
Duel.Overlay(tc,Group.FromCards(c))
Duel.SpecialSummon(tc,SUMMON_TYPE_XYZ,tp,tp,false,false,POS_FACEUP)
local fid=c:GetFieldID()
tc:RegisterFlagEffect(29085954,RESET_EVENT+RESETS_STANDARD,0,1,fid)
tc:CompleteProcedure()
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e1:SetProperty(EFFECT_FLAG_IGNORE_IMMUNE)
e1:SetCode(EVENT_PHASE+PHASE_END)
e1:SetCountLimit(1)
e1:SetLabel(fid)
e1:SetLabelObject(tc)
e1:SetCondition(c29085954.rmcon)
e1:SetOperation(c29085954.rmop)
Duel.RegisterEffect(e1,tp)
end
end
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e2:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON)
e2:SetReset(RESET_PHASE+PHASE_END)
e2:SetTargetRange(1,0)
Duel.RegisterEffect(e2,tp)
end
function c29085954.rmcon(e,tp,eg,ep,ev,re,r,rp)
if e:GetLabelObject():GetFlagEffectLabel(29085954)~=e:GetLabel() then
e:Reset()
return false
else return true end
end
function c29085954.rmop(e,tp,eg,ep,ev,re,r,rp)
local tc=e:GetLabelObject()
Duel.Remove(tc,POS_FACEUP,REASON_EFFECT)
end
| gpl-2.0 |
Zenny89/darkstar | scripts/commands/reloadglobal.lua | 26 | 1230 | ---------------------------------------------------------------------------------------------------
-- func: @reloadglobal
-- desc: Attempt to reload specified global lua without a restart.
--
-- Use with caution, some files ( like player.lua )
-- can cause you problems if you reload them using this.
-- This command expects the user to know wtf they are doing,
-- but has a default permission lv of 4 so that helpers or
-- less experienced GMs do not mistakenly misuse it.
---------------------------------------------------------------------------------------------------
cmdprops =
{
permission = 4,
parameters = "s"
};
function onTrigger(player,globalLua)
if (globalLua == "player" or globalLua == "server" ) then
player:PrintToPlayer( "Some file should not be live reloaded. This is one of them." );
return
end
if (globalLua ~= nil) then
local String = table.concat({"scripts/globals/",globalLua});
package.loaded[String] = nil;
require(String);
player:PrintToPlayer( string.format( "Lua file '%s' has been reloaded.", String ) );
else
player:PrintToPlayer( "Must Specify a global lua file.");
end
end; | gpl-3.0 |
ZeroK-RTS/SpringRTS-Tools | SpringModEdit/ParamDefs/fd.params.lua | 2 | 1761 | -- $Id: fd.params.lua 3171 2008-11-06 09:06:29Z det $
local intMap = {
footprintX = true, -- fdTable -- footprintX --
footprintZ = true, -- fdTable -- footprintZ --
}
local boolMap = {
blocking = true, -- fdTable -- blocking --
flammable = true, -- fdTable -- flammable --
indestructible = true, -- fdTable -- indestructible --
nodrawundergray = true, -- fdTable -- nodrawundergray --
noselect = true, -- fdTable -- noselect --
reclaimable = true, -- fdTable -- reclaimable --
upright = true, -- fdTable -- upright --
}
local floatMap = {
collisionSphereScale = true, -- fdTable -- collisionSphereScale --
damage = true, -- fdTable -- damage --
energy = true, -- fdTable -- energy --
mass = true, -- fdTable -- mass --
metal = true, -- fdTable -- metal --
reclaimTime = true, -- fdTable -- reclaimTime --
}
local float3Map = {
collisionSphereOffset = true, -- fdTable -- collisionSphereOffset --
}
local stringMap = {
description = true, -- fdTable -- description --
featureDead = true, -- fdTable -- featureDead --
filename = true, -- fdTable -- filename --
object = true, -- fdTable -- object --
}
return {
intMap = intMap,
boolMap = boolMap,
floatMap = floatMap,
float3Map = float3Map,
stringMap = stringMap,
}
-- SubTable: const LuaTable rootTable = game->defsParser->GetRoot().SubTable("FeatureDefs");
-- SubTable: const LuaTable fdTable = rootTable.SubTable(name);
| gpl-2.0 |
mercury233/ygopro-scripts | c23440062.lua | 2 | 2770 | --ウィキッド・リボーン
function c23440062.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetHintTiming(0,TIMING_END_PHASE)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCost(c23440062.cost)
e1:SetTarget(c23440062.target)
e1:SetOperation(c23440062.operation)
c:RegisterEffect(e1)
--Destroy
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_CONTINUOUS+EFFECT_TYPE_SINGLE)
e2:SetCode(EVENT_LEAVE_FIELD)
e2:SetOperation(c23440062.desop)
c:RegisterEffect(e2)
--Destroy2
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_CONTINUOUS+EFFECT_TYPE_FIELD)
e3:SetRange(LOCATION_SZONE)
e3:SetCode(EVENT_LEAVE_FIELD)
e3:SetCondition(c23440062.descon2)
e3:SetOperation(c23440062.desop2)
c:RegisterEffect(e3)
--disable
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_TARGET)
e4:SetCode(EFFECT_DISABLE)
e4:SetRange(LOCATION_SZONE)
c:RegisterEffect(e4)
end
function c23440062.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.CheckLPCost(tp,800) end
Duel.PayLPCost(tp,800)
end
function c23440062.filter(c,e,tp)
return c:IsType(TYPE_SYNCHRO) and c:IsCanBeSpecialSummoned(e,0,tp,false,false,POS_FACEUP_ATTACK)
end
function c23440062.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c23440062.filter(chkc,e,tp) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingTarget(c23440062.filter,tp,LOCATION_GRAVE,0,1,nil,e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectTarget(tp,c23440062.filter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0)
end
function c23440062.operation(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=Duel.GetFirstTarget()
if c:IsRelateToEffect(e) and tc:IsRelateToEffect(e) and Duel.SpecialSummonStep(tc,0,tp,tp,false,false,POS_FACEUP_ATTACK) then
c:SetCardTarget(tc)
--cannot attack
local e5=Effect.CreateEffect(c)
e5:SetType(EFFECT_TYPE_TARGET)
e5:SetCode(EFFECT_CANNOT_ATTACK)
e5:SetRange(LOCATION_SZONE)
e5:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END)
c:RegisterEffect(e5)
end
Duel.SpecialSummonComplete()
end
function c23440062.desop(e,tp,eg,ep,ev,re,r,rp)
local tc=e:GetHandler():GetFirstCardTarget()
if tc and tc:IsLocation(LOCATION_MZONE) then
Duel.Destroy(tc,REASON_EFFECT)
end
end
function c23440062.descon2(e,tp,eg,ep,ev,re,r,rp)
local tc=e:GetHandler():GetFirstCardTarget()
return tc and eg:IsContains(tc) and tc:IsReason(REASON_DESTROY)
end
function c23440062.desop2(e,tp,eg,ep,ev,re,r,rp)
Duel.Destroy(e:GetHandler(),REASON_EFFECT)
end
| gpl-2.0 |
mercury233/ygopro-scripts | c68392533.lua | 2 | 2879 | --念動増幅装置
function c68392533.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_EQUIP)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_CONTINUOUS_TARGET)
e1:SetTarget(c68392533.target)
e1:SetOperation(c68392533.operation)
c:RegisterEffect(e1)
--Cost Change
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetCode(EFFECT_LPCOST_CHANGE)
e2:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e2:SetRange(LOCATION_SZONE)
e2:SetTargetRange(1,1)
e2:SetValue(c68392533.costchange)
c:RegisterEffect(e2)
--Equip limit
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_SINGLE)
e3:SetCode(EFFECT_EQUIP_LIMIT)
e3:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e3:SetValue(c68392533.eqlimit)
c:RegisterEffect(e3)
--tohand
local e4=Effect.CreateEffect(c)
e4:SetDescription(aux.Stringid(68392533,0))
e4:SetCategory(CATEGORY_TOHAND)
e4:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e4:SetProperty(EFFECT_FLAG_DAMAGE_STEP)
e4:SetCode(EVENT_TO_GRAVE)
e4:SetCondition(c68392533.thcon)
e4:SetCost(c68392533.thcost)
e4:SetTarget(c68392533.thtg)
e4:SetOperation(c68392533.thop)
c:RegisterEffect(e4)
end
function c68392533.eqlimit(e,c)
return c:IsRace(RACE_PSYCHO)
end
function c68392533.filter(c)
return c:IsFaceup() and c:IsRace(RACE_PSYCHO)
end
function c68392533.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and c68392533.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c68392533.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_EQUIP)
Duel.SelectTarget(tp,c68392533.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_EQUIP,e:GetHandler(),1,0,0)
end
function c68392533.operation(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=Duel.GetFirstTarget()
if c:IsRelateToEffect(e) and tc:IsRelateToEffect(e) and tc:IsFaceup() then
Duel.Equip(tp,c,tc)
end
end
function c68392533.costchange(e,re,rp,val)
if re and re:IsActivated() and re:GetHandler()==e:GetHandler():GetEquipTarget() then
return 0
else return val end
end
function c68392533.thcon(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local ec=c:GetPreviousEquipTarget()
return c:IsReason(REASON_LOST_TARGET) and ec and ec:IsReason(REASON_DESTROY)
end
function c68392533.thcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.CheckLPCost(tp,1000) end
Duel.PayLPCost(tp,1000)
end
function c68392533.thtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsAbleToHand() end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,e:GetHandler(),1,0,0)
end
function c68392533.thop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) then
Duel.SendtoHand(c,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,c)
end
end
| gpl-2.0 |
mercury233/ygopro-scripts | c65187687.lua | 2 | 3210 | --巨骸竜フェルグラント
local s,id,o=GetID()
function c65187687.initial_effect(c)
--synchro summon
aux.AddSynchroProcedure(c,c65187687.synfilter,aux.NonTuner(nil),1)
c:EnableReviveLimit()
--remove
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(id,0))
e1:SetCategory(CATEGORY_REMOVE)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetCode(EVENT_SPSUMMON_SUCCESS)
e1:SetProperty(EFFECT_FLAG_DELAY+EFFECT_FLAG_CARD_TARGET)
e1:SetCountLimit(1,65187687)
e1:SetTarget(c65187687.rmtg)
e1:SetOperation(c65187687.rmop)
c:RegisterEffect(e1)
--disable
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(id,1))
e2:SetCategory(CATEGORY_DISABLE)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e2:SetCode(EVENT_SPSUMMON_SUCCESS)
e2:SetRange(LOCATION_MZONE)
e2:SetProperty(EFFECT_FLAG_DELAY+EFFECT_FLAG_CARD_TARGET)
e2:SetCountLimit(1,65187687+o)
e2:SetCondition(c65187687.discon)
e2:SetTarget(c65187687.distg)
e2:SetOperation(c65187687.disop)
c:RegisterEffect(e2)
end
function c65187687.synfilter(c)
return c:IsRace(RACE_ZOMBIE)
end
function c65187687.rmfilter(c)
return c:IsType(TYPE_MONSTER) and c:IsAbleToRemove()
end
function c65187687.rmtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE+LOCATION_GRAVE) and chkc:IsControler(1-tp) and c65187687.rmfilter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c65187687.rmfilter,tp,0,LOCATION_MZONE+LOCATION_GRAVE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=Duel.SelectTarget(tp,c65187687.rmfilter,tp,0,LOCATION_GRAVE+LOCATION_MZONE,1,1,nil)
if g:GetFirst():IsLocation(LOCATION_GRAVE) then
Duel.SetOperationInfo(0,CATEGORY_REMOVE,g,1,1-tp,LOCATION_GRAVE)
else
Duel.SetOperationInfo(0,CATEGORY_REMOVE,g,1,0,0)
end
end
function c65187687.rmop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.Remove(tc,POS_FACEUP,REASON_EFFECT)
end
end
function c65187687.spfilter(c)
return c:IsSummonLocation(LOCATION_GRAVE)
end
function c65187687.discon(e,tp,eg,ep,ev,re,r,rp)
return eg:IsExists(c65187687.spfilter,1,nil) and not eg:IsContains(e:GetHandler())
end
function c65187687.distg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and aux.NegateEffectMonsterFilter(chkc) end
if chk==0 then return Duel.IsExistingTarget(aux.NegateEffectMonsterFilter,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DISABLE)
Duel.SelectTarget(tp,aux.NegateEffectMonsterFilter,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil)
end
function c65187687.disop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=Duel.GetFirstTarget()
if tc:IsFaceup() and tc:IsRelateToEffect(e) then
Duel.NegateRelatedChain(tc,RESET_TURN_SET)
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_DISABLE)
e1:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END)
tc:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_DISABLE_EFFECT)
e2:SetValue(RESET_TURN_SET)
e2:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END)
tc:RegisterEffect(e2)
end
end
| gpl-2.0 |
mercury233/ygopro-scripts | c58607704.lua | 2 | 1479 | --悪魔の手鏡
function c58607704.initial_effect(c)
--activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCode(EVENT_CHAINING)
e1:SetCondition(c58607704.tgcon)
e1:SetTarget(c58607704.tgtg)
e1:SetOperation(c58607704.tgop)
c:RegisterEffect(e1)
end
function c58607704.tgcon(e,tp,eg,ep,ev,re,r,rp)
if rp==tp or not re:IsHasType(EFFECT_TYPE_ACTIVATE) or not re:IsActiveType(TYPE_SPELL)
or not re:IsHasProperty(EFFECT_FLAG_CARD_TARGET) then return false end
local g=Duel.GetChainInfo(ev,CHAININFO_TARGET_CARDS)
if not g or g:GetCount()~=1 then return false end
local tc=g:GetFirst()
e:SetLabelObject(tc)
return tc:IsOnField() and tc:IsType(TYPE_SPELL+TYPE_TRAP)
end
function c58607704.filter(c,ct)
return c:IsType(TYPE_SPELL+TYPE_TRAP) and Duel.CheckChainTarget(ct,c)
end
function c58607704.tgtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc~=e:GetLabelObject() and chkc:IsOnField() and c58607704.filter(chkc,ev) end
if chk==0 then return Duel.IsExistingTarget(c58607704.filter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,e:GetLabelObject(),ev) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TARGET)
Duel.SelectTarget(tp,c58607704.filter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,1,e:GetLabelObject(),ev)
end
function c58607704.tgop(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS)
if g and g:GetFirst():IsRelateToEffect(e) then
Duel.ChangeTargetCard(ev,g)
end
end
| gpl-2.0 |
mercury233/ygopro-scripts | c22171591.lua | 9 | 1315 | --カバリスト
function c22171591.initial_effect(c)
--special summon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(22171591,0))
e1:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetCode(EVENT_BATTLE_DESTROYED)
e1:SetCondition(c22171591.condition)
e1:SetCost(c22171591.cost)
e1:SetTarget(c22171591.target)
e1:SetOperation(c22171591.operation)
c:RegisterEffect(e1)
end
function c22171591.condition(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsLocation(LOCATION_GRAVE) and e:GetHandler():IsReason(REASON_BATTLE)
end
function c22171591.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.CheckLPCost(tp,800) end
Duel.PayLPCost(tp,800)
end
function c22171591.filter(c)
return c:IsRace(RACE_PSYCHO) and c:IsAbleToHand()
end
function c22171591.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c22171591.filter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function c22171591.operation(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,c22171591.filter,tp,LOCATION_DECK,0,1,1,nil)
if g:GetCount()>0 then
Duel.SendtoHand(g,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g)
end
end
| gpl-2.0 |
Zenny89/darkstar | scripts/zones/Ship_bound_for_Mhaura/npcs/Chhaya.lua | 34 | 1338 | -----------------------------------
-- Area: Ship Bound for Mhaura
-- NPC: Chhaya
-- Standard Merchant NPC
-- @pos -1.139 -2.101 -9.000 221
-----------------------------------
package.loaded["scripts/zones/Ship_bound_for_Mhaura/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/zones/Ship_bound_for_Mhaura/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,CHHAYA_SHOP_DIALOG);
stock = {0x1010,910, --Potion
0x1020,4832, --Ether
0x1034,316, --Antidote
0x1036,2595, --Eye Drops
0x1037,800} --Echo Drops
showShop(player, STATIC, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
linushsao/marsu_game-linus-v0.2 | mods/mars_pack/mars_mobs_redo/mobs_animal/warthog.lua | 1 | 1910 |
local S = mobs.intllib
-- Warthog by KrupnoPavel
mobs:register_mob("mobs_animal:pumba", {
type = "animal",
passive = false,
attack_type = "dogfight",
group_attack = true,
owner_loyal = true,
reach = 2,
damage = 2,
hp_min = 5,
hp_max = 15,
armor = 200,
collisionbox = {-0.4, -0.01, -0.4, 0.4, 1, 0.4},
visual = "mesh",
mesh = "mobs_pumba.x",
textures = {
{"mobs_pumba.png"},
},
makes_footstep_sound = true,
sounds = {
random = "mobs_pig",
attack = "mobs_pig_angry",
},
walk_velocity = 2,
run_velocity = 3,
jump = true,
follow = {"default:apple", "farming:potato"},
view_range = 10,
drops = {
{name = "mobs:pork_raw", chance = 1, min = 1, max = 3},
},
water_damage = 1,
lava_damage = 5,
light_damage = 0,
fear_height = 2,
animation = {
speed_normal = 15,
stand_start = 25,
stand_end = 55,
walk_start = 70,
walk_end = 100,
punch_start = 70,
punch_end = 100,
},
on_rightclick = function(self, clicker)
if mobs:feed_tame(self, clicker, 8, true, true) then return end
if mobs:protect(self, clicker) then return end
if mobs:capture_mob(self, clicker, 0, 5, 50, false, nil) then return end
end,
})
local spawn_on = "default:dirt_with_grass"
if minetest.get_modpath("ethereal") then
spawn_on = "ethereal:mushroom_dirt"
end
mobs:register_egg("mobs_animal:pumba", S("Warthog"), "wool_pink.png", 1)
mobs:alias_mob("mobs:pumba", "mobs_animal:pumba") -- compatibility
-- raw porkchop
minetest.register_craftitem(":mobs:pork_raw", {
description = S("Raw Porkchop"),
inventory_image = "mobs_pork_raw.png",
on_use = minetest.item_eat(4),
})
-- cooked porkchop
minetest.register_craftitem(":mobs:pork_cooked", {
description = S("Cooked Porkchop"),
inventory_image = "mobs_pork_cooked.png",
on_use = minetest.item_eat(8),
})
minetest.register_craft({
type = "cooking",
output = "mobs:pork_cooked",
recipe = "mobs:pork_raw",
cooktime = 5,
})
| gpl-3.0 |
mercury233/ygopro-scripts | c62107612.lua | 6 | 1180 | --ディメンション・ワンダラー
function c62107612.initial_effect(c)
--damage
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(62107612,0))
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetCode(EVENT_REMOVE)
e1:SetRange(LOCATION_HAND)
e1:SetCountLimit(1,62107612)
e1:SetCondition(c62107612.condition)
e1:SetCost(c62107612.cost)
e1:SetTarget(c62107612.target)
e1:SetOperation(c62107612.operation)
c:RegisterEffect(e1)
end
function c62107612.condition(e,tp,eg,ep,ev,re,r,rp)
return bit.band(r,REASON_EFFECT)~=0 and re and re:GetHandler():IsCode(93717133)
end
function c62107612.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsAbleToGraveAsCost() end
Duel.SendtoGrave(e:GetHandler(),REASON_COST)
end
function c62107612.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetTargetPlayer(1-tp)
Duel.SetTargetParam(3000)
Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,1-tp,3000)
end
function c62107612.operation(e,tp,eg,ep,ev,re,r,rp)
local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM)
Duel.Damage(p,d,REASON_EFFECT)
end
| gpl-2.0 |
siilaas/silas-super-bot | bot/seedbot.lua | 22 | 14096 | package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua'
..';.luarocks/share/lua/5.2/?/init.lua'
package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so'
require("./bot/utils")
local f = assert(io.popen('/usr/bin/git describe --tags', 'r'))
VERSION = assert(f:read('*a'))
f:close()
-- This function is called when tg receive a msg
function on_msg_receive (msg)
if not started then
return
end
msg = backward_msg_format(msg)
local receiver = get_receiver(msg)
print(receiver)
--vardump(msg)
--vardump(msg)
msg = pre_process_service_msg(msg)
if msg_valid(msg) then
msg = pre_process_msg(msg)
if msg then
match_plugins(msg)
if redis:get("bot:markread") then
if redis:get("bot:markread") == "on" then
mark_read(receiver, ok_cb, false)
end
end
end
end
end
function ok_cb(extra, success, result)
end
function on_binlog_replay_end()
started = true
postpone (cron_plugins, false, 60*5.0)
-- See plugins/isup.lua as an example for cron
_config = load_config()
-- load plugins
plugins = {}
load_plugins()
end
function msg_valid(msg)
-- Don't process outgoing messages
if msg.out then
print('\27[36mNot valid: msg from us\27[39m')
return false
end
-- Before bot was started
if msg.date < os.time() - 5 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
--send_large_msg(*group id*, msg.text) *login code will be sent to GroupID*
return false
end
return true
end
--
function pre_process_service_msg(msg)
if msg.service then
local action = msg.action or {type=""}
-- Double ! to discriminate of normal actions
msg.text = "!!tgservice " .. action.type
-- wipe the data to allow the bot to read service messages
if msg.out then
msg.out = false
end
if msg.from.id == our_id then
msg.from.id = 0
end
end
return msg
end
-- Apply plugin.pre_process function
function pre_process_msg(msg)
for name,plugin in pairs(plugins) do
if plugin.pre_process and msg then
print('Preprocess', name)
msg = plugin.pre_process(msg)
end
end
return msg
end
-- Go over enabled plugins patterns.
function match_plugins(msg)
for name, plugin in pairs(plugins) do
match_plugin(plugin, name, msg)
end
end
-- Check if plugin is on _config.disabled_plugin_on_chat table
local function is_plugin_disabled_on_chat(plugin_name, receiver)
local disabled_chats = _config.disabled_plugin_on_chat
-- Table exists and chat has disabled plugins
if disabled_chats and disabled_chats[receiver] then
-- Checks if plugin is disabled on this chat
for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do
if disabled_plugin == plugin_name and disabled then
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("Sudo 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 = {
"admin",
"onservice",
"inrealm",
"ingroup",
"inpm",
"banhammer",
"stats",
"anti_spam",
"owners",
"arabic_lock",
"set",
"get",
"broadcast",
"invite",
"all",
"leave_ban",
"supergroup",
"whitelist",
"msg_checks"
},
sudo_users = {110626080,103649648,111020322,0,tonumber(our_id)},--Sudo users
moderation = {data = 'data/moderation.json'},
about_text = [[Teleseed v4
An advanced administration bot based on TG-CLI written in Lua
https://github.com/SEEDTEAM/TeleSeed
Admins
@iwals [Founder]
@imandaneshi [Developer]
@POTUS [Developer]
@seyedan25 [Manager]
@aRandomStranger [Admin]
Special thanks to
awkward_potato
Siyanew
topkecleon
Vamptacus
Our channels
@teleseedch [English]
@iranseed [persian]
Our website
http://teleseed.seedteam.org/
]],
help_text_realm = [[
Realm Commands:
!creategroup [Name]
Create a group
!createrealm [Name]
Create a realm
!setname [Name]
Set realm name
!setabout [group|sgroup] [GroupID] [Text]
Set a group's about text
!setrules [GroupID] [Text]
Set a group's rules
!lock [GroupID] [setting]
Lock a group's setting
!unlock [GroupID] [setting]
Unock a group's setting
!settings [group|sgroup] [GroupID]
Set settings for GroupID
!wholist
Get a list of members in group/realm
!who
Get a file of members in group/realm
!type
Get group type
!kill chat [GroupID]
Kick all memebers and delete group
!kill realm [RealmID]
Kick all members and delete realm
!addadmin [id|username]
Promote an admin by id OR username *Sudo only
!removeadmin [id|username]
Demote an admin by id OR username *Sudo only
!list groups
Get a list of all groups
!list realms
Get a list of all realms
!support
Promote user to support
!-support
Demote user from support
!log
Get a logfile of current group or realm
!broadcast [text]
!broadcast Hello !
Send text to all groups
Only sudo users can run this command
!bc [group_id] [text]
!bc 123456789 Hello !
This command will send text to [group_id]
**You can use "#", "!", or "/" to begin all commands
*Only admins and sudo can add bots in group
*Only admins and sudo can use kick,ban,unban,newlink,setphoto,setname,lock,unlock,set rules,set about and settings commands
*Only admins and sudo can use res, setowner, commands
]],
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
Returns help text
!lock [links|flood|spam|Arabic|member|rtl|sticker|contacts|strict]
Lock group settings
*rtl: Kick user if Right To Left Char. is in name*
!unlock [links|flood|spam|Arabic|member|rtl|sticker|contacts|strict]
Unlock group settings
*rtl: Kick user if Right To Left Char. is in name*
!mute [all|audio|gifs|photo|video]
mute group message types
*If "muted" message type: user is kicked if message type is posted
!unmute [all|audio|gifs|photo|video]
Unmute group message types
*If "unmuted" message type: user is not kicked if message type is posted
!set rules <text>
Set <text> as rules
!set about <text>
Set <text> as about
!settings
Returns group settings
!muteslist
Returns mutes for chat
!muteuser [username]
Mute a user in chat
*user is kicked if they talk
*only owners can mute | mods and owners can unmute
!mutelist
Returns list of muted users in chat
!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
Returns group logs
!banlist
will return group ban list
**You can use "#", "!", or "/" to begin all commands
*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
]],
help_text_super =[[
SuperGroup Commands:
!info
Displays general info about the SuperGroup
!admins
Returns SuperGroup admins list
!owner
Returns group owner
!modlist
Returns Moderators list
!bots
Lists bots in SuperGroup
!who
Lists all users in SuperGroup
!block
Kicks a user from SuperGroup
*Adds user to blocked list*
!ban
Bans user from the SuperGroup
!unban
Unbans user from the SuperGroup
!id
Return SuperGroup ID or user id
*For userID's: !id @username or reply !id*
!id from
Get ID of user message is forwarded from
!kickme
Kicks user from SuperGroup
*Must be unblocked by owner or use join by pm to return*
!setowner
Sets the SuperGroup owner
!promote [username|id]
Promote a SuperGroup moderator
!demote [username|id]
Demote a SuperGroup moderator
!setname
Sets the chat name
!setphoto
Sets the chat photo
!setrules
Sets the chat rules
!setabout
Sets the about section in chat info(members list)
!save [value] <text>
Sets extra info for chat
!get [value]
Retrieves extra info for chat by value
!newlink
Generates a new group link
!link
Retireives the group link
!rules
Retrieves the chat rules
!lock [links|flood|spam|Arabic|member|rtl|sticker|contacts|strict]
Lock group settings
*rtl: Delete msg if Right To Left Char. is in name*
*strict: enable strict settings enforcement (violating user will be kicked)*
!unlock [links|flood|spam|Arabic|member|rtl|sticker|contacts|strict]
Unlock group settings
*rtl: Delete msg if Right To Left Char. is in name*
*strict: disable strict settings enforcement (violating user will not be kicked)*
!mute [all|audio|gifs|photo|video|service]
mute group message types
*A "muted" message type is auto-deleted if posted
!unmute [all|audio|gifs|photo|video|service]
Unmute group message types
*A "unmuted" message type is not auto-deleted if posted
!setflood [value]
Set [value] as flood sensitivity
!settings
Returns chat settings
!muteslist
Returns mutes for chat
!muteuser [username]
Mute a user in chat
*If a muted user posts a message, the message is deleted automaically
*only owners can mute | mods and owners can unmute
!mutelist
Returns list of muted users in chat
!banlist
Returns SuperGroup ban list
!clean [rules|about|modlist|mutelist]
!del
Deletes a message by reply
!public [yes|no]
Set chat visibility in pm !chats or !chatlist commands
!res [username]
Returns users name and id by username
!log
Returns group logs
*Search for kick reasons using [#RTL|#spam|#lockmember]
**You can use "#", "!", or "/" to begin all commands
*Only owner can add members to SuperGroup
(use invite link to invite)
*Only moderators and owner can use block, ban, unban, newlink, link, setphoto, setname, lock, unlock, setrules, setabout 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)
--vardump (chat)
end
function on_secret_chat_update (schat, what)
--vardump (schat)
end
function on_get_difference_end ()
end
-- Enable plugins in config.json
function load_plugins()
for k, v in pairs(_config.enabled_plugins) do
print("Loading plugin", v)
local ok, err = pcall(function()
local t = loadfile("plugins/"..v..'.lua')()
plugins[v] = t
end)
if not ok then
print('\27[31mError loading plugin '..v..'\27[39m')
print(tostring(io.popen("lua plugins/"..v..".lua"):read('*all')))
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 |
icgood/Restic.spoon | commands/backup.lua | 1 | 1927 |
local obj = { name = "backup" }
obj.__index = obj
local PROGRESS_PATTERN = [[%[([%d%:]+)%]%s+([%d%.]+)%%%s+]]
function obj.new(spoon)
local self = { spoon = spoon, log = spoon.log, exec = spoon.exec }
setmetatable(self, obj)
return self
end
function obj:start()
if self:active() then
self.spoon:warn("Backup is already running")
return
end
if self.logFile then
os.remove(self.logFile)
end
local args = self:buildArgs()
local onComplete = function (...) return self:onTaskComplete(...) end
local onOutput = function (...) return self:onTaskOutput(...) end
self.task, self.terminate, self.logFile = self.exec:newResticTask(
args, onComplete, onOutput, true)
self.task:start()
self.log.df("restic %s started", obj.name)
end
function obj:active()
return self.task ~= nil
end
function obj:stop()
if self:active() then
local terminate = self.terminate
self.terminate = nil
terminate()
end
end
function obj:buildArgs()
local args = { obj.name, "-x" }
for i, pattern in ipairs(self.spoon:getExclusionPatterns()) do
table.insert(args, "-e")
table.insert(args, pattern)
end
for i, path in ipairs(self.spoon:getBackupDirs()) do
table.insert(args, path)
end
return args
end
function obj:onTaskComplete(exitCode, stdOut, stdErr)
self.task = nil
self.terminate = nil
self.log.df("restic %s exited with code %s", obj.name, exitCode)
if exitCode ~= 0 and self.terminate ~= nil then
self.spoon:warn(stdOut .. stdErr)
end
self.spoon:updateProgress()
self.spoon:refreshLatestBackup()
end
function obj:onTaskOutput(task, stdOut)
local elapsed, percent = stdOut:match(PROGRESS_PATTERN)
self.spoon:updateProgress(elapsed, tonumber(percent))
return true
end
function obj:getLogFile()
return self.logFile
end
return obj
| mit |
Zenny89/darkstar | scripts/globals/items/bunny_ball.lua | 35 | 1739 | -----------------------------------------
-- ID: 4349
-- Item: Bunny Ball
-- Food Effect: 240Min, All Races
-----------------------------------------
-- Health 10
-- Strength 2
-- Vitality 2
-- Intelligence -1
-- Attack % 30
-- Attack Cap 25
-- Ranged ATT % 30
-- Ranged ATT Cap 25
-----------------------------------------
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,4349);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 10);
target:addMod(MOD_STR, 2);
target:addMod(MOD_VIT, 2);
target:addMod(MOD_INT, -1);
target:addMod(MOD_FOOD_ATTP, 30);
target:addMod(MOD_FOOD_ATT_CAP, 25);
target:addMod(MOD_FOOD_RATTP, 30);
target:addMod(MOD_FOOD_RATT_CAP, 25);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 10);
target:delMod(MOD_STR, 2);
target:delMod(MOD_VIT, 2);
target:delMod(MOD_INT, -1);
target:delMod(MOD_FOOD_ATTP, 30);
target:delMod(MOD_FOOD_ATT_CAP, 25);
target:delMod(MOD_FOOD_RATTP, 30);
target:delMod(MOD_FOOD_RATT_CAP, 25);
end;
| gpl-3.0 |
mercury233/ygopro-scripts | c9464441.lua | 2 | 2606 | --魔救の奇跡-ドラガイト
function c9464441.initial_effect(c)
--synchro summon
aux.AddSynchroProcedure(c,nil,aux.NonTuner(nil),1)
c:EnableReviveLimit()
--to hand
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(9464441,0))
e1:SetCategory(CATEGORY_TOHAND)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_MZONE)
e1:SetCountLimit(1,9464441)
e1:SetTarget(c9464441.thtg)
e1:SetOperation(c9464441.thop)
c:RegisterEffect(e1)
--negate
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(9464441,1))
e2:SetCategory(CATEGORY_NEGATE+CATEGORY_DESTROY)
e2:SetType(EFFECT_TYPE_QUICK_O)
e2:SetCode(EVENT_CHAINING)
e2:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DAMAGE_CAL)
e2:SetRange(LOCATION_MZONE)
e2:SetCountLimit(1,9464442)
e2:SetCondition(c9464441.discon)
e2:SetTarget(c9464441.distg)
e2:SetOperation(c9464441.disop)
c:RegisterEffect(e2)
end
function c9464441.thtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetFieldGroupCount(tp,LOCATION_DECK,0)>4 end
end
function c9464441.thop(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetFieldGroupCount(tp,LOCATION_DECK,0)<=4 then return end
Duel.ConfirmDecktop(tp,5)
local g=Duel.GetDecktopGroup(tp,5)
if g:GetCount()>0 and g:FilterCount(Card.IsRace,nil,RACE_ROCK)>0 and Duel.IsExistingMatchingCard(Card.IsAbleToHand,tp,0,LOCATION_ONFIELD,1,nil) and Duel.SelectYesNo(tp,aux.Stringid(9464441,2)) then
local ct=g:FilterCount(Card.IsRace,nil,RACE_ROCK)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_RTOHAND)
local sg=Duel.SelectMatchingCard(tp,Card.IsAbleToHand,tp,0,LOCATION_ONFIELD,1,ct,nil)
Duel.HintSelection(sg)
Duel.SendtoHand(sg,nil,REASON_EFFECT)
end
if g:GetCount()>0 then
Duel.SortDecktop(tp,tp,g:GetCount())
for i=1,g:GetCount() do
local mg=Duel.GetDecktopGroup(tp,1)
Duel.MoveSequence(mg:GetFirst(),SEQ_DECKBOTTOM)
end
end
end
function c9464441.discon(e,tp,eg,ep,ev,re,r,rp)
if ep==tp or e:GetHandler():IsStatus(STATUS_BATTLE_DESTROYED) then return false end
return re:IsActiveType(TYPE_SPELL+TYPE_TRAP) and Duel.IsChainNegatable(ev) and Duel.IsExistingMatchingCard(Card.IsAttribute,tp,LOCATION_GRAVE,0,1,nil,ATTRIBUTE_WATER)
end
function c9464441.distg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_NEGATE,eg,1,0,0)
if re:GetHandler():IsDestructable() and re:GetHandler():IsRelateToEffect(re) then
Duel.SetOperationInfo(0,CATEGORY_DESTROY,eg,1,0,0)
end
end
function c9464441.disop(e,tp,eg,ep,ev,re,r,rp)
if Duel.NegateActivation(ev) and re:GetHandler():IsRelateToEffect(re) then
Duel.Destroy(eg,REASON_EFFECT)
end
end
| gpl-2.0 |
rouing/FHLG-BW | entities/entities/base_gmodentity/shared.lua | 3 | 1054 |
ENT.Type = "anim"
ENT.Base = "base_anim"
ENT.PrintName = ""
ENT.Author = ""
ENT.Contact = ""
ENT.Purpose = ""
ENT.Instructions = ""
ENT.Spawnable = false
ENT.AdminSpawnable = false
function ENT:SetOverlayText( text )
self:SetNetworkedString( "GModOverlayText", text )
end
function ENT:GetOverlayText()
local txt = self:GetNetworkedString( "GModOverlayText" )
if ( txt == "" ) then
return ""
end
if ( SinglePlayer() ) then
return txt
end
local PlayerName = self:GetPlayerName()
return txt .. "\n(" .. PlayerName .. ")"
end
function ENT:SetPlayer( ply )
self:SetVar( "Founder", ply )
self:SetVar( "FounderIndex", ply:UniqueID() )
self:SetNetworkedString( "FounderName", ply:Nick() )
end
function ENT:GetPlayer()
return self:GetVar( "Founder", NULL )
end
function ENT:GetPlayerIndex()
return self:GetVar( "FounderIndex", 0 )
end
function ENT:GetPlayerName()
local ply = self:GetPlayer()
if ( ply != NULL ) then
return ply:Nick()
end
return self:GetNetworkedString( "FounderName" )
end
| unlicense |
mercury233/ygopro-scripts | c85551711.lua | 2 | 3472 | --虚空の黒魔導師
function c85551711.initial_effect(c)
--xyz summon
aux.AddXyzProcedure(c,aux.FilterBoolFunction(Card.IsRace,RACE_SPELLCASTER),7,2)
c:EnableReviveLimit()
--act qp/trap in hand
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_QP_ACT_IN_NTPHAND)
e1:SetRange(LOCATION_MZONE)
e1:SetTargetRange(LOCATION_HAND,0)
e1:SetCondition(c85551711.handcon)
c:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetCode(EFFECT_TRAP_ACT_IN_HAND)
c:RegisterEffect(e2)
local e3=e1:Clone()
e3:SetCode(85551711)
c:RegisterEffect(e3)
--activate cost
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_FIELD)
e4:SetCode(EFFECT_ACTIVATE_COST)
e4:SetRange(LOCATION_MZONE)
e4:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e4:SetTargetRange(1,0)
e4:SetCost(c85551711.costchk)
e4:SetTarget(c85551711.costtg)
e4:SetOperation(c85551711.costop)
c:RegisterEffect(e4)
--spsummon
local e5=Effect.CreateEffect(c)
e5:SetDescription(aux.Stringid(85551711,1))
e5:SetCategory(CATEGORY_SPECIAL_SUMMON+CATEGORY_DESTROY)
e5:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e5:SetProperty(EFFECT_FLAG_DELAY)
e5:SetCode(EVENT_TO_GRAVE)
e5:SetCondition(c85551711.spcon)
e5:SetTarget(c85551711.sptg)
e5:SetOperation(c85551711.spop)
c:RegisterEffect(e5)
end
function c85551711.handcon(e)
return Duel.GetTurnPlayer()~=e:GetHandlerPlayer() and e:GetHandler():GetOverlayCount()~=0
end
function c85551711.costtg(e,te,tp)
local tc=te:GetHandler()
return Duel.GetTurnPlayer()~=e:GetHandlerPlayer()
and tc:IsLocation(LOCATION_HAND) and tc:GetEffectCount(85551711)>0
and ((tc:GetEffectCount(EFFECT_QP_ACT_IN_NTPHAND)<=tc:GetEffectCount(85551711) and tc:IsType(TYPE_QUICKPLAY))
or (tc:GetEffectCount(EFFECT_TRAP_ACT_IN_HAND)<=tc:GetEffectCount(85551711) and tc:IsType(TYPE_TRAP)))
end
function c85551711.costchk(e,te_or_c,tp)
return e:GetHandler():CheckRemoveOverlayCard(tp,1,REASON_EFFECT)
end
function c85551711.costop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_CARD,0,85551711)
e:GetHandler():RemoveOverlayCard(tp,1,1,REASON_EFFECT)
end
function c85551711.spcon(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
return ((rp==1-tp and c:IsReason(REASON_EFFECT) and c:IsPreviousControler(tp) and c:IsPreviousLocation(LOCATION_MZONE))
or c:IsReason(REASON_BATTLE)) and c:IsSummonType(SUMMON_TYPE_XYZ)
end
function c85551711.spfilter(c,e,tp)
return c:IsRace(RACE_SPELLCASTER) and c:IsAttribute(ATTRIBUTE_DARK) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c85551711.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c85551711.spfilter,tp,LOCATION_HAND+LOCATION_DECK,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_HAND+LOCATION_DECK)
end
function c85551711.spop(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c85551711.spfilter,tp,LOCATION_HAND+LOCATION_DECK,0,1,1,nil,e,tp)
local dg=Duel.GetMatchingGroup(aux.TRUE,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,nil)
if g:GetCount()>0 and Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)~=0
and dg:GetCount()>0 and Duel.SelectYesNo(tp,aux.Stringid(85551711,0)) then
Duel.BreakEffect()
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local sg=dg:Select(tp,1,1,nil)
Duel.HintSelection(sg)
Duel.Destroy(sg,REASON_EFFECT)
end
end
| gpl-2.0 |
equinox0815/packages | utils/prometheus-node-exporter-lua/files/usr/lib/lua/prometheus-collectors/nat_traffic.lua | 79 | 1251 | local function scrape()
-- documetation about nf_conntrack:
-- https://www.frozentux.net/iptables-tutorial/chunkyhtml/x1309.html
nat_metric = metric("node_nat_traffic", "gauge" )
for e in io.lines("/proc/net/nf_conntrack") do
-- output(string.format("%s\n",e ))
local fields = space_split(e)
local src, dest, bytes;
bytes = 0;
for _, field in ipairs(fields) do
if src == nil and string.match(field, '^src') then
src = string.match(field,"src=([^ ]+)");
elseif dest == nil and string.match(field, '^dst') then
dest = string.match(field,"dst=([^ ]+)");
elseif string.match(field, '^bytes') then
local b = string.match(field, "bytes=([^ ]+)");
bytes = bytes + b;
-- output(string.format("\t%d %s",ii,field ));
end
end
-- local src, dest, bytes = string.match(natstat[i], "src=([^ ]+) dst=([^ ]+) .- bytes=([^ ]+)");
-- local src, dest, bytes = string.match(natstat[i], "src=([^ ]+) dst=([^ ]+) sport=[^ ]+ dport=[^ ]+ packets=[^ ]+ bytes=([^ ]+)")
local labels = { src = src, dest = dest }
-- output(string.format("src=|%s| dest=|%s| bytes=|%s|", src, dest, bytes ))
nat_metric(labels, bytes )
end
end
return { scrape = scrape }
| gpl-2.0 |
wrxck/telegram-bot-lua | src/core.lua | 1 | 70228 | --[[
_ _ _ _ _
| | | | | | | | | |
| |_ ___| | ___ __ _ _ __ __ _ _ __ ___ ______| |__ ___ | |_ ______| |_ _ __ _
| __/ _ \ |/ _ \/ _` | '__/ _` | '_ ` _ \______| '_ \ / _ \| __|______| | | | |/ _` |
| || __/ | __/ (_| | | | (_| | | | | | | | |_) | (_) | |_ | | |_| | (_| |
\__\___|_|\___|\__, |_| \__,_|_| |_| |_| |_.__/ \___/ \__| |_|\__,_|\__,_|
__/ |
|___/
Version 1.10-0
Copyright (c) 2020 Matthew Hesketh
See LICENSE for details
]]
local api = {}
local https = require('ssl.https')
local multipart = require('multipart-post')
local ltn12 = require('ltn12')
local json = require('dkjson')
local html = require('htmlEntities')
local config = require('telegram-bot-lua.config')
function api.configure(token, debug)
if not token or type(token) ~= 'string' then
token = nil
end
api.debug = debug and true or false
api.token = assert(token, 'Please specify your bot API token you received from @BotFather!')
repeat
api.info = api.get_me()
until api.info.result
api.info = api.info.result
api.info.name = api.info.first_name
return api
end
function api.request(endpoint, parameters, file)
assert(endpoint, 'You must specify an endpoint to make this request to!')
parameters = parameters or {}
for k, v in pairs(parameters) do
parameters[k] = tostring(v)
end
if api.debug then
local output = json.encode(parameters, { ['indent'] = true })
print(output)
end
if file and next(file) ~= nil then
local file_type, file_name = next(file)
local file_res = io.open(file_name, 'r')
if file_res then
parameters[file_type] = {
filename = file_name,
data = file_res:read('*a')
}
file_res:close()
else
parameters[file_type] = file_name
end
end
parameters = next(parameters) == nil and { '' } or parameters
local response = {}
local body, boundary = multipart.encode(parameters)
local success, res = https.request(
{
['url'] = endpoint,
['method'] = 'POST',
['headers'] = {
['Content-Type'] = 'multipart/form-data; boundary=' .. boundary,
['Content-Length'] = #body
},
['source'] = ltn12.source.string(body),
['sink'] = ltn12.sink.table(response)
}
)
if not success then
print('Connection error [' .. res .. ']')
return false, res
end
local jstr = table.concat(response)
local jdat = json.decode(jstr)
if not jdat then
return false, res
elseif not jdat.ok then
local output = '\n' .. jdat.description .. ' [' .. jdat.error_code .. ']\n\nPayload: '
output = output .. json.encode(parameters, { ['indent'] = true }) .. '\n'
print(output)
return false, jdat
end
return jdat, res
end
function api.get_me()
local success, res = api.request(config.endpoint .. api.token .. '/getMe')
return success, res
end
-------------
-- UPDATES --
-------------
function api.get_updates(timeout, offset, limit, allowed_updates, use_beta_endpoint) -- https://core.telegram.org/bots/api#getupdates
allowed_updates = type(allowed_updates) == 'table' and json.encode(allowed_updates) or allowed_updates
local success, res = api.request(
string.format(
'https://api.telegram.org/%sbot%s/getUpdates',
use_beta_endpoint and 'beta/' or '',
api.token
),
{
['timeout'] = timeout,
['offset'] = offset,
['limit'] = limit,
['allowed_updates'] = allowed_updates
}
)
return success, res
end
function api.set_webhook(url, certificate, max_connections, allowed_updates) -- https://core.telegram.org/bots/api#setwebhook
allowed_updates = type(allowed_updates) == 'table' and json.encode(allowed_updates) or allowed_updates
local success, res = api.request(config.endpoint .. api.token .. '/setWebhook',
{
['url'] = url,
['max_connections'] = max_connections,
['allowed_updates'] = allowed_updates
},
{ ['certificate'] = certificate }
)
return success, res
end
function api.delete_webhook() -- https://core.telegram.org/bots/api#deletewebhook
local success, res = api.request(config.endpoint .. api.token .. '/deleteWebhook')
return success, res
end
function api.get_webhook_info() -- https://core.telegram.org/bots/api#get_webhook_info
local success, res = api.request(config.endpoint .. api.token .. '/getWebhookInfo')
return success, res
end
-------------
-- METHODS --
-------------
function api.send_message(message, text, parse_mode, disable_web_page_preview, disable_notification, reply_to_message_id, reply_markup) -- https://core.telegram.org/bots/api#sendmessage
reply_markup = type(reply_markup) == 'table' and json.encode(reply_markup) or reply_markup
message = (type(message) == 'table' and message.chat and message.chat.id) and message.chat.id or message
parse_mode = (type(parse_mode) == 'boolean' and parse_mode == true) and 'markdown' or parse_mode
if disable_web_page_preview == nil then
disable_web_page_preview = true
end
local success, res = api.request(
config.endpoint .. api.token .. '/sendMessage',
{
['chat_id'] = message,
['text'] = text,
['parse_mode'] = parse_mode,
['disable_web_page_preview'] = disable_web_page_preview,
['disable_notification'] = disable_notification,
['reply_to_message_id'] = reply_to_message_id,
['reply_markup'] = reply_markup
}
)
return success, res
end
function api.send_reply(message, text, parse_mode, disable_web_page_preview, reply_markup, disable_notification) -- A variant of api.send_message(), optimised for sending a message as a reply.
if type(message) ~= 'table' or not message.chat or not message.chat.id or not message.message_id then
return false
end
reply_markup = type(reply_markup) == 'table' and json.encode(reply_markup) or reply_markup
parse_mode = (type(parse_mode) == 'boolean' and parse_mode == true) and 'markdown' or parse_mode
local success, res = api.request(
config.endpoint .. api.token .. '/sendMessage',
{
['chat_id'] = message.chat.id,
['text'] = text,
['parse_mode'] = parse_mode,
['disable_web_page_preview'] = disable_web_page_preview,
['disable_notification'] = disable_notification,
['reply_to_message_id'] = message.message_id,
['reply_markup'] = reply_markup
}
)
return success, res
end
function api.forward_message(chat_id, from_chat_id, disable_notification, message_id) -- https://core.telegram.org/bots/api#forwardmessage
local success, res = api.request(
config.endpoint .. api.token .. '/forwardMessage',
{
['chat_id'] = chat_id,
['from_chat_id'] = from_chat_id,
['disable_notification'] = disable_notification,
['message_id'] = message_id
}
)
return success, res
end
function api.send_photo(chat_id, photo, caption, parse_mode, disable_notification, reply_to_message_id, reply_markup) -- https://core.telegram.org/bots/api#sendphoto
reply_markup = type(reply_markup) == 'table' and json.encode(reply_markup) or reply_markup
local success, res = api.request(
config.endpoint .. api.token .. '/sendPhoto',
{
['chat_id'] = chat_id,
['caption'] = caption,
['parse_mode'] = parse_mode,
['disable_notification'] = disable_notification,
['reply_to_message_id'] = reply_to_message_id,
['reply_markup'] = reply_markup
},
{
['photo'] = photo
}
)
return success, res
end
function api.send_audio(chat_id, audio, caption, parse_mode, duration, performer, title, disable_notification, reply_to_message_id, reply_markup) -- https://core.telegram.org/bots/api#sendaudio
reply_markup = type(reply_markup) == 'table' and json.encode(reply_markup) or reply_markup
local success, res = api.request(
config.endpoint .. api.token .. '/sendAudio',
{
['chat_id'] = chat_id,
['caption'] = caption,
['parse_mode'] = parse_mode,
['duration'] = duration,
['performer'] = performer,
['title'] = title,
['disable_notification'] = disable_notification,
['reply_to_message_id'] = reply_to_message_id,
['reply_markup'] = reply_markup
},
{ ['audio'] = audio }
)
return success, res
end
function api.send_document(chat_id, document, caption, parse_mode, disable_notification, reply_to_message_id, reply_markup) -- https://core.telegram.org/bots/api#senddocument
reply_markup = type(reply_markup) == 'table' and json.encode(reply_markup) or reply_markup
local success, res = api.request(
config.endpoint .. api.token .. '/sendDocument',
{
['chat_id'] = chat_id,
['caption'] = caption,
['parse_mode'] = parse_mode,
['disable_notification'] = disable_notification,
['reply_to_message_id'] = reply_to_message_id,
['reply_markup'] = reply_markup
},
{ ['document'] = document }
)
return success, res
end
function api.send_video(chat_id, video, duration, width, height, caption, parse_mode, supports_streaming, disable_notification, reply_to_message_id, reply_markup) -- https://core.telegram.org/bots/api#sendvideo
reply_markup = type(reply_markup) == 'table' and json.encode(reply_markup) or reply_markup
local success, res = api.request(
config.endpoint .. api.token .. '/sendVideo',
{
['chat_id'] = chat_id,
['duration'] = duration,
['width'] = width,
['height'] = height,
['caption'] = caption,
['parse_mode'] = parse_mode,
['supports_streaming'] = supports_streaming,
['disable_notification'] = disable_notification,
['reply_to_message_id'] = reply_to_message_id,
['reply_markup'] = reply_markup
},
{ ['video'] = video }
)
return success, res
end
function api.send_animation(chat_id, animation, duration, width, height, thumb, caption, parse_mode, disable_notification, reply_to_message_id, reply_markup) -- https://core.telegram.org/bots/api#sendanimation
reply_markup = type(reply_markup) == 'table' and json.encode(reply_markup) or reply_markup
local success, res = api.request(
config.endpoint .. api.token .. '/sendAnimation',
{
['chat_id'] = chat_id,
['duration'] = duration,
['width'] = width,
['height'] = height,
['caption'] = caption,
['parse_mode'] = parse_mode,
['disable_notification'] = disable_notification,
['reply_to_message_id'] = reply_to_message_id,
['reply_markup'] = reply_markup
}, {
['animation'] = animation,
['thumb'] = thumb
}
)
return success, res
end
function api.send_voice(chat_id, voice, caption, parse_mode, duration, disable_notification, reply_to_message_id, reply_markup) -- https://core.telegram.org/bots/api#sendvoice
reply_markup = type(reply_markup) == 'table' and json.encode(reply_markup) or reply_markup
local success, res = api.request(
config.endpoint .. api.token .. '/sendVoice',
{
['chat_id'] = chat_id,
['caption'] = caption,
['parse_mode'] = parse_mode,
['duration'] = duration,
['disable_notification'] = disable_notification,
['reply_to_message_id'] = reply_to_message_id,
['reply_markup'] = reply_markup
},
{ ['voice'] = voice }
)
return success, res
end
function api.send_video_note(chat_id, video_note, duration, length, disable_notification, reply_to_message_id, reply_markup) -- https://core.telegram.org/bots/api#sendvideonote
reply_markup = type(reply_markup) == 'table' and json.encode(reply_markup) or reply_markup
local success, res = api.request(
config.endpoint .. api.token .. '/sendVideoNote',
{
['chat_id'] = chat_id,
['duration'] = duration,
['length'] = length,
['disable_notification'] = disable_notification,
['reply_to_message_id'] = reply_to_message_id,
['reply_markup'] = reply_markup
},
{ ['video_note'] = video_note }
)
return success, res
end
function api.send_media_group(chat_id, media, disable_notification, reply_to_message_id) -- https://core.telegram.org/bots/api#sendmediagroup
local success, res = api.request(
config.endpoint .. api.token .. '/sendMediaGroup',
{
['chat_id'] = chat_id,
['media'] = media,
['disable_notification'] = disable_notification,
['reply_to_message_id'] = reply_to_message_id
}
)
return success, res
end
function api.send_location(chat_id, latitude, longitude, live_period, disable_notification, reply_to_message_id, reply_markup) -- https://core.telegram.org/bots/api#sendlocation
reply_markup = type(reply_markup) == 'table' and json.encode(reply_markup) or reply_markup
local success, res = api.request(
config.endpoint .. api.token .. '/sendLocation',
{
['chat_id'] = chat_id,
['latitude'] = latitude,
['longitude'] = longitude,
['live_period'] = live_period,
['disable_notification'] = disable_notification,
['reply_to_message_id'] = reply_to_message_id,
['reply_markup'] = reply_markup
}
)
return success, res
end
function api.edit_message_live_location(chat_id, message_id, inline_message_id, latitude, longitude, reply_markup) -- https://core.telegram.org/bots/api#editmessagelivelocation
reply_markup = type(reply_markup) == 'table' and json.encode(reply_markup) or reply_markup
local success, res = api.request(
config.endpoint .. api.token .. '/editMessageLiveLocation',
{
['chat_id'] = chat_id,
['message_id'] = message_id,
['inline_message_id'] = inline_message_id,
['latitude'] = latitude,
['longitude'] = longitude,
['reply_markup'] = reply_markup
}
)
return success, res
end
function api.stop_message_live_location(chat_id, message_id, inline_message_id, reply_markup) -- https://core.telegram.org/bots/api#stopmessagelivelocation
reply_markup = type(reply_markup) == 'table' and json.encode(reply_markup) or reply_markup
local success, res = api.request(
config.endpoint .. api.token .. '/stopMessageLiveLocation',
{
['chat_id'] = chat_id,
['message_id'] = message_id,
['inline_message_id'] = inline_message_id,
['reply_markup'] = reply_markup
}
)
return success, res
end
function api.send_venue(chat_id, latitude, longitude, title, address, foursquare_id, foursquare_type, disable_notification, reply_to_message_id, reply_markup) -- https://core.telegram.org/bots/api#sendvenue
reply_markup = type(reply_markup) == 'table' and json.encode(reply_markup) or reply_markup
local success, res = api.request(
config.endpoint .. api.token .. '/sendVenue',
{
['chat_id'] = chat_id,
['latitude'] = latitude,
['longitude'] = longitude,
['title'] = title,
['address'] = address,
['foursquare_id'] = foursquare_id,
['foursquare_type'] = foursquare_type,
['disable_notification'] = disable_notification,
['reply_to_message_id'] = reply_to_message_id,
['reply_markup'] = reply_markup
}
)
return success, res
end
function api.send_contact(chat_id, phone_number, first_name, last_name, vcard, disable_notification, reply_to_message_id, reply_markup) -- https://core.telegram.org/bots/api#sendcontact
reply_markup = type(reply_markup) == 'table' and json.encode(reply_markup) or reply_markup
local success, res = api.request(
config.endpoint .. api.token .. '/sendContact',
{
['chat_id'] = chat_id,
['phone_number'] = phone_number,
['first_name'] = first_name,
['last_name'] = last_name,
['vcard'] = vcard,
['disable_notification'] = disable_notification,
['reply_to_message_id'] = reply_to_message_id,
['reply_markup'] = reply_markup
}
)
return success, res
end
function api.send_poll(chat_id, question, options, is_anonymous, poll_type, allows_multiple_answers, correct_option_id, explanation, explanation_parse_mode, open_period, close_date, is_closed, disable_notification, reply_to_message_id, reply_markup) -- https://core.telegram.org/bots/api#sendpoll
reply_markup = type(reply_markup) == 'table' and json.encode(reply_markup) or reply_markup
is_anonymous = type(is_anonymous) == 'boolean' and is_anonymous or false
allows_multiple_answers = type(allows_multiple_answers) == 'boolean' and allows_multiple_answers or false
local success, res = api.request(
config.endpoint .. api.token .. '/sendPoll',
{
['chat_id'] = chat_id,
['question'] = question,
['options'] = options,
['is_anonymous'] = is_anonymous,
['type'] = poll_type,
['allows_multiple_answers'] = allows_multiple_answers,
['correct_option_id'] = correct_option_id,
['explanation'] = explanation,
['explanation_parse_mode'] = explanation_parse_mode,
['open_period'] = open_period,
['close_date'] = close_date,
['is_closed'] = is_closed,
['disable_notification'] = disable_notification,
['reply_to_message_id'] = reply_to_message_id,
['reply_markup'] = reply_markup
}
)
return success, res
end
function api.send_dice(chat_id, emoji, disable_notification, reply_to_message_id, reply_markup) -- https://core.telegram.org/bots/api#senddice
local success, res = api.request(
config.endpoint .. api.token .. '/sendDice',
{
['chat_id'] = chat_id,
['emoji'] = emoji,
['disable_notification'] = disable_notification,
['reply_to_message_id'] = reply_to_message_id,
['reply_markup'] = reply_markup
}
)
return success, res
end
function api.send_chat_action(chat_id, action) -- https://core.telegram.org/bots/api#sendchataction
local success, res = api.request(
config.endpoint .. api.token .. '/sendChatAction',
{
['chat_id'] = chat_id,
['action'] = action or 'typing' -- Fallback to `typing` as the default action.
}
)
return success, res
end
function api.get_user_profile_photos(user_id, offset, limit) -- https://core.telegram.org/bots/api#getuserprofilephotos
local success, res = api.request(
config.endpoint .. api.token .. '/getUserProfilePhotos',
{
['user_id'] = user_id,
['offset'] = offset,
['limit'] = limit
}
)
return success, res
end
function api.get_file(file_id) -- https://core.telegram.org/bots/api#getfile
local success, res = api.request(
config.endpoint .. api.token .. '/getFile',
{ ['file_id'] = file_id }
)
return success, res
end
function api.ban_chat_member(chat_id, user_id, until_date) -- https://core.telegram.org/bots/api#kickchatmember
local success, res = api.request(
config.endpoint .. api.token .. '/kickChatMember',
{
['chat_id'] = chat_id,
['user_id'] = user_id,
['until_date'] = until_date
}
)
return success, res
end
function api.kick_chat_member(chat_id, user_id)
local success, res = api.request(
config.endpoint .. api.token .. '/unbanChatMember',
{
['chat_id'] = chat_id,
['user_id'] = user_id
}
)
return success, res
end
function api.unban_chat_member(chat_id, user_id) -- https://core.telegram.org/bots/api#unbanchatmember
local success, res
for _ = 1, 3 do -- Repeat 3 times to ensure the user was unbanned (I've encountered issues before so
-- this is for precautionary measures.)
success, res = api.request(
config.endpoint .. api.token .. '/unbanChatMember',
{
['chat_id'] = chat_id,
['user_id'] = user_id
}
)
if success then -- If one of the first 3 attempts is a success (which it typically will be), we can just stop the loop
return success, res
end
end
return success, res
end
function api.restrict_chat_member(chat_id, user_id, until_date, can_send_messages, can_send_media_messages, can_send_polls, can_send_other_messages, can_add_web_page_previews, can_change_info, can_invite_users, can_pin_messages) -- https://core.telegram.org/bots/api#restrictchatmember
if until_date == ('forever' or 'permanently') then
until_date = os.time() - 1000 -- indefinite restriction
end
local permissions = type(can_send_messages) == 'table' and can_send_messages or { -- allows the user to pass the permissions as a table should they want to do so
['can_send_messages'] = can_send_messages,
['can_send_media_messages'] = can_send_media_messages,
['can_send_polls'] = can_send_polls,
['can_send_other_messages'] = can_send_other_messages,
['can_add_web_page_previews'] = can_add_web_page_previews,
['can_change_info'] = can_change_info,
['can_invite_users'] = can_invite_users,
['can_pin_messages'] = can_pin_messages
}
local success, res = api.request(
config.endpoint .. api.token .. '/restrictChatMember',
{
['chat_id'] = chat_id,
['user_id'] = user_id,
['permissions'] = json.encode(permissions),
['until_date'] = until_date
}
)
return success, res
end
function api.promote_chat_member(chat_id, user_id, can_change_info, can_post_messages, can_edit_messages, can_delete_messages, can_invite_users, can_restrict_members, can_pin_messages, can_promote_members) -- https://core.telegram.org/bots/api#promotechatmember
local success, res = api.request(
config.endpoint .. api.token .. '/promoteChatMember',
{
['chat_id'] = chat_id,
['user_id'] = user_id,
['can_change_info'] = can_change_info,
['can_post_messages'] = can_post_messages,
['can_edit_messages'] = can_edit_messages,
['can_delete_messages'] = can_delete_messages,
['can_invite_users'] = can_invite_users,
['can_restrict_members'] = can_restrict_members,
['can_pin_messages'] = can_pin_messages,
['can_promote_members'] = can_promote_members
}
)
return success, res
end
function api.set_chat_administrator_custom_title(chat_id, user_id, custom_title) -- https://core.telegram.org/bots/api#setchatadministratorcustomtitle
if custom_title:len() > 16 then -- telegram doesn't allow custom titles longer than 16 chars
custom_title = custom_title:sub(1, 16)
end
local success, res = api.request(
config.endpoint .. api.token .. '/setChatAdministratorCustomTitle',
{
['chat_id'] = chat_id,
['user_id'] = user_id,
['custom_title'] = custom_title
}
)
return success, res
end
function api.set_chat_permissions(chat_id, can_send_messages, can_send_media_messages, can_send_polls, can_send_other_messages, can_add_web_page_previews, can_change_info, can_invite_users, can_pin_messages) -- https://core.telegram.org/bots/api#setchatpermissions
local permissions = type(can_send_messages) == 'table' and can_send_messages or { -- allows the user to pass the permissions as a table should they want to do so
['can_send_messages'] = can_send_messages,
['can_send_media_messages'] = can_send_media_messages,
['can_send_polls'] = can_send_polls,
['can_send_other_messages'] = can_send_other_messages,
['can_add_web_page_previews'] = can_add_web_page_previews,
['can_change_info'] = can_change_info,
['can_invite_users'] = can_invite_users,
['can_pin_messages'] = can_pin_messages
}
local success, res = api.request(
config.endpoint .. api.token .. '/setChatPermissions',
{
['chat_id'] = chat_id,
['permissions'] = json.encode(permissions)
}
)
return success, res
end
function api.export_chat_invite_link(chat_id) -- https://core.telegram.org/bots/api#exportchatinvitelink
local success, res = api.request(
config.endpoint .. api.token .. '/exportChatInviteLink',
{ ['chat_id'] = chat_id }
)
return success, res
end
function api.set_chat_photo(chat_id, photo) -- https://core.telegram.org/bots/api#setchatphoto
local success, res = api.request(
config.endpoint .. api.token .. '/setChatPhoto',
{ ['chat_id'] = chat_id },
{ ['photo'] = photo }
)
return success, res
end
function api.delete_chat_photo(chat_id) -- https://core.telegram.org/bots/api#deletechatphoto
local success, res = api.request(
config.endpoint .. api.token .. '/deleteChatPhoto',
{ ['chat_id'] = chat_id }
)
return success, res
end
function api.set_chat_title(chat_id, title) -- https://core.telegram.org/bots/api#setchattitle
if title:len() > 255 then -- telegram won't allow chat titles greater than 255 chars
title = title:sub(1, 255)
end
local success, res = api.request(
config.endpoint .. api.token .. '/setChatTitle',
{
['chat_id'] = chat_id,
['title'] = title
}
)
return success, res
end
function api.set_chat_description(chat_id, description) -- https://core.telegram.org/bots/api#setchatdescription
if description:len() > 255 then -- telegram won't allow chat descriptions greater than 255 chars
description = description:sub(1, 255)
end
local success, res = api.request(
config.endpoint .. api.token .. '/setChatDescription',
{
['chat_id'] = chat_id,
['description'] = description
}
)
return success, res
end
function api.pin_chat_message(chat_id, message_id, disable_notification) -- https://core.telegram.org/bots/api#pinchatmessage
local success, res = api.request(
config.endpoint .. api.token .. '/pinChatMessage',
{
['chat_id'] = chat_id,
['message_id'] = message_id,
['disable_notification'] = disable_notification
}
)
return success, res
end
function api.unpin_chat_message(chat_id) -- https://core.telegram.org/bots/api#unpinchatmessage
local success, res = api.request(
config.endpoint .. api.token .. '/unpinChatMessage',
{ ['chat_id'] = chat_id }
)
return success, res
end
function api.leave_chat(chat_id) -- https://core.telegram.org/bots/api#leavechat
local success, res = api.request(
config.endpoint .. api.token .. '/leaveChat',
{ ['chat_id'] = chat_id }
)
return success, res
end
function api.get_chat(chat_id) -- https://core.telegram.org/bots/api#getchat
local success, result = api.request(
config.endpoint .. api.token .. '/getChat',
{ ['chat_id'] = chat_id }
)
if not success or not success.result then
return success, result
end
if success.result.username and success.result.type == 'private' then
local old_timeout = https.TIMEOUT
https.TIMEOUT = 1
local scrape, scrape_res = https.request('https://t.me/' .. success.result.username)
https.TIMEOUT = old_timeout
if scrape_res ~= 200 then
return success, result
end
local bio = scrape:match('%<div class="tgme_page_description "%>(.-)%</div%>')
if not bio then
return success
end
bio = bio:gsub('%b<>', '')
bio = html.decode(bio)
success.result.bio = bio
end
return success, result
end
function api.get_chat_administrators(chat_id) -- https://core.telegram.org/bots/api#getchatadministrators
local success, res = api.request(
config.endpoint .. api.token .. '/getChatAdministrators',
{ ['chat_id'] = chat_id }
)
return success, res
end
function api.get_chat_members_count(chat_id) -- https://core.telegram.org/bots/api#getchatmemberscount
local success, res = api.request(
config.endpoint .. api.token .. '/getChatMembersCount',
{ ['chat_id'] = chat_id }
)
return success, res
end
function api.get_chat_member(chat_id, user_id) -- https://core.telegram.org/bots/api#getchatmember
local success, res = api.request(
config.endpoint .. api.token .. '/getChatMember',
{
['chat_id'] = chat_id,
['user_id'] = user_id
}
)
return success, res
end
function api.set_chat_sticker_set(chat_id, sticker_set_name) -- https://core.telegram.org/bots/api#setchatstickerset
local success, res = api.request(
config.endpoint .. api.token .. '/setChatStickerSet',
{
['chat_id'] = chat_id,
['sticker_set_name'] = sticker_set_name
}
)
return success, res
end
function api.delete_chat_sticker_set(chat_id) -- https://core.telegram.org/bots/api#deletechatstickerset
local success, res = api.request(
config.endpoint .. api.token .. '/deleteChatStickerSet',
{ ['chat_id'] = chat_id }
)
return success, res
end
function api.answer_callback_query(callback_query_id, text, show_alert, url, cache_time) -- https://core.telegram.org/bots/api#answercallbackquery
local success, res = api.request(
config.endpoint .. api.token .. '/answerCallbackQuery',
{
['callback_query_id'] = callback_query_id,
['text'] = text,
['show_alert'] = show_alert,
['url'] = url,
['cache_time'] = cache_time
}
)
return success, res
end
function api.set_my_commands(commands) -- https://core.telegram.org/bots/api#setmycommands
local success, res = api.request(
config.endpoint .. api.token .. '/setMyCommands',
{ ['commands'] = commands }
)
return success, res
end
function api.get_my_commands() -- https://core.telegram.org/bots/api#getmycommands
local success, res = api.request(config.endpoint .. api.token .. '/getMyCommands')
return success, res
end
function api.edit_message_text(chat_id, message_id, text, parse_mode, disable_web_page_preview, reply_markup, inline_message_id) -- https://core.telegram.org/bots/api#editmessagetext
reply_markup = type(reply_markup) == 'table' and json.encode(reply_markup) or reply_markup
parse_mode = (type(parse_mode) == 'boolean' and parse_mode == true) and 'markdown' or parse_mode
local success, res = api.request(
config.endpoint .. api.token .. '/editMessageText',
{
['chat_id'] = chat_id,
['message_id'] = message_id,
['inline_message_id'] = inline_message_id,
['text'] = text,
['parse_mode'] = parse_mode,
['disable_web_page_preview'] = disable_web_page_preview,
['reply_markup'] = reply_markup
}
)
if not success then
success, res = api.request(
config.endpoint .. api.token .. '/editMessageText',
{
['chat_id'] = chat_id,
['message_id'] = inline_message_id,
['inline_message_id'] = message_id,
['text'] = text,
['parse_mode'] = parse_mode,
['disable_web_page_preview'] = disable_web_page_preview,
['reply_markup'] = reply_markup
}
)
end
return success, res
end
function api.edit_message_caption(chat_id, message_id, caption, reply_markup, inline_message_id) -- https://core.telegram.org/bots/api#editmessagecaption
reply_markup = type(reply_markup) == 'table' and json.encode(reply_markup) or reply_markup
local success, res = api.request(
config.endpoint .. api.token .. '/editMessageCaption',
{
['chat_id'] = chat_id,
['message_id'] = message_id,
['inline_message_id'] = inline_message_id,
['caption'] = caption,
['reply_markup'] = reply_markup
}
)
if not success then
success, res = api.request(
config.endpoint .. api.token .. '/editMessageCaption',
{
['chat_id'] = chat_id,
['message_id'] = inline_message_id,
['inline_message_id'] = message_id,
['caption'] = caption,
['reply_markup'] = reply_markup
}
)
end
return success, res
end
function api.edit_message_media(chat_id, message_id, media, reply_markup, inline_message_id) -- https://core.telegram.org/bots/api#editmessagemedia
reply_markup = type(reply_markup) == 'table' and json.encode(reply_markup) or reply_markup
media = type(media) == 'table' and json.encode(media) or media
local success, res = api.request(
config.endpoint .. api.token .. '/editMessageMedia',
{
['chat_id'] = chat_id,
['message_id'] = message_id,
['inline_message_id'] = inline_message_id,
['media'] = media,
['reply_markup'] = reply_markup
}
)
if not success then
success, res = api.request(
config.endpoint .. api.token .. '/editMessageMedia',
{
['chat_id'] = chat_id,
['message_id'] = inline_message_id,
['inline_message_id'] = message_id,
['media'] = media,
['reply_markup'] = reply_markup
}
)
end
return success, res
end
function api.edit_message_reply_markup(chat_id, message_id, inline_message_id, reply_markup) -- https://core.telegram.org/bots/api#editmessagereplymarkup
reply_markup = type(reply_markup) == 'table' and json.encode(reply_markup) or reply_markup
local success, res = api.request(
config.endpoint .. api.token .. '/editMessageReplyMarkup',
{
['chat_id'] = chat_id,
['message_id'] = message_id,
['inline_message_id'] = inline_message_id,
['reply_markup'] = reply_markup
}
)
if not success then
success, res = api.request(
config.endpoint .. api.token .. '/editMessageReplyMarkup',
{
['chat_id'] = chat_id,
['message_id'] = inline_message_id,
['inline_message_id'] = message_id,
['reply_markup'] = reply_markup
}
)
end
return success, res
end
function api.stop_poll(chat_id, message_id, reply_markup) -- https://core.telegram.org/bots/api#stoppoll
local success, res = api.request(
config.endpoint .. api.token .. '/stopPoll',
{
['chat_id'] = chat_id,
['message_id'] = message_id,
['reply_markup'] = reply_markup
}
)
return success, res
end
function api.delete_message(chat_id, message_id) -- https://core.telegram.org/bots/api#deletemessage
local success, res = api.request(
config.endpoint .. api.token .. '/deleteMessage',
{
['chat_id'] = chat_id,
['message_id'] = message_id
}
)
return success, res
end
--------------
-- STICKERS --
--------------
function api.send_sticker(chat_id, sticker, disable_notification, reply_to_message_id, reply_markup) -- https://core.telegram.org/bots/api#sendsticker
reply_markup = type(reply_markup) == 'table' and json.encode(reply_markup) or reply_markup
local success, res = api.request(
config.endpoint .. api.token .. '/sendSticker',
{
['chat_id'] = chat_id,
['disable_notification'] = disable_notification,
['reply_to_message_id'] = reply_to_message_id,
['reply_markup'] = reply_markup
},
{ ['sticker'] = sticker }
)
return success, res
end
function api.get_sticker_set(name) -- https://core.telegram.org/bots/api#getstickerset
local success, res = api.request(
config.endpoint .. api.token .. '/getStickerSet',
{ ['name'] = name }
)
return success, res
end
function api.upload_sticker_file(user_id, png_sticker) -- https://core.telegram.org/bots/api#uploadstickerfile
local success, res = api.request(
config.endpoint .. api.token .. '/uploadStickerFile',
{ ['user_id'] = user_id },
{ ['png_sticker'] = png_sticker }
)
return success, res
end
function api.create_new_sticker_set(user_id, name, title, png_sticker, emojis, contains_masks, mask_position) -- https://core.telegram.org/bots/api#createnewstickerset
mask_position = type(mask_position) == 'table' and json.encode(mask_position) or mask_position
local success, res = api.request(
config.endpoint .. api.token .. '/createNewStickerSet',
{
['user_id'] = user_id,
['name'] = name,
['title'] = title,
['emojis'] = emojis,
['contains_masks'] = contains_masks,
['mask_position'] = mask_position
},
{ ['png_sticker'] = png_sticker }
)
return success, res
end
function api.add_sticker_to_set(user_id, name, png_sticker, emojis, mask_position) -- https://core.telegram.org/bots/api#addstickertoset
mask_position = type(mask_position) == 'table' and json.encode(mask_position) or mask_position
local success, res = api.request(
config.endpoint .. api.token .. '/addStickerToSet',
{
['user_id'] = user_id,
['name'] = name,
['emojis'] = emojis,
['mask_position'] = mask_position
},
{ ['png_sticker'] = png_sticker }
)
return success, res
end
function api.set_sticker_position_in_set(sticker, position) -- https://core.telegram.org/bots/api#setstickerpositioninset
local success, res = api.request(
config.endpoint .. api.token .. '/setStickerPositionInSet',
{
['sticker'] = sticker,
['position'] = position
}
)
return success, res
end
function api.delete_sticker_from_set(sticker) -- https://core.telegram.org/bots/api#deletestickerfromset
local success, res = api.request(
config.endpoint .. api.token .. '/deleteStickerFromSet',
{ ['sticker'] = sticker }
)
return success, res
end
function api.set_sticker_set_thumb(name, user_id, thumb) -- https://core.telegram.org/bots/api#setstickersetthumb
local success, res = api.request(
config.endpoint .. api.token .. '/setStickerSetThumb',
{
['name'] = name,
['user_id'] = user_id
},
{ ['thumb'] = thumb }
)
return success, res
end
function api.answer_inline_query(inline_query_id, results, cache_time, is_personal, next_offset, switch_pm_text, switch_pm_parameter) -- https://core.telegram.org/bots/api#answerinlinequery
if results and type(results) == 'table' then
if results.id then
results = { results }
end
results = json.encode(results)
end
local success, res = api.request(
config.endpoint .. api.token .. '/answerInlineQuery',
{
['inline_query_id'] = inline_query_id,
['results'] = results,
['switch_pm_text'] = switch_pm_text,
['switch_pm_parameter'] = switch_pm_parameter,
['cache_time'] = cache_time,
['is_personal'] = is_personal,
['next_offset'] = next_offset
}
)
return success, res
end
--------------
-- PAYMENTS --
--------------
function api.send_invoice(chat_id, title, description, payload, provider_token, start_parameter, currency, prices, provider_data, photo_url, photo_size, photo_width, photo_height, need_name, need_phone_number, need_email, need_shipping_address, is_flexible, disable_notification, reply_to_message_id, reply_markup)
local success, res = api.request(
config.endpoint .. api.token .. '/sendInvoice',
{
['chat_id'] = chat_id,
['title'] = title,
['description'] = description,
['payload'] = payload,
['provider_token'] = provider_token,
['start_parameter'] = start_parameter,
['currency'] = currency,
['prices'] = prices,
['provider_data'] = provider_data,
['photo_url'] = photo_url,
['photo_size'] = photo_size,
['photo_width'] = photo_width,
['photo_height'] = photo_height,
['need_name'] = need_name,
['need_phone_number'] = need_phone_number,
['need_email'] = need_email,
['need_shipping_address'] = need_shipping_address,
['is_flexible'] = is_flexible,
['disable_notification'] = disable_notification,
['reply_to_message_id'] = reply_to_message_id,
['reply_markup'] = reply_markup
}
)
return success, res
end
function api.answer_shipping_query(shipping_query_id, ok, shipping_options, error_message)
local success, res = api.request(
config.endpoint .. api.token .. '/answerShippingQuery',
{
['shipping_query_id'] = shipping_query_id,
['ok'] = ok,
['shipping_options'] = shipping_options,
['error_message'] = error_message
}
)
return success, res
end
function api.answer_pre_checkout_query(pre_checkout_query_id, ok, error_message)
local success, res = api.request(
config.endpoint .. api.token .. '/answerPreCheckoutQuery',
{
['pre_checkout_query_id'] = pre_checkout_query_id,
['ok'] = ok,
['error_message'] = error_message
}
)
return success, res
end
-----------
-- GAMES --
-----------
function api.send_game(chat_id, game_short_name, disable_notification, reply_to_message_id, reply_markup) -- https://core.telegram.org/bots/api#sendgame
reply_markup = type(reply_markup) == 'table' and json.encode(reply_markup) or reply_markup
local success, res = api.request(
config.endpoint .. api.token .. '/sendGame',
{
['chat_id'] = chat_id,
['game_short_name'] = game_short_name,
['disable_notification'] = disable_notification,
['reply_to_message_id'] = reply_to_message_id,
['reply_markup'] = reply_markup
}
)
return success, res
end
function api.set_game_score(chat_id, user_id, message_id, score, force, disable_edit_message, inline_message_id) -- https://core.telegram.org/bots/api#setgamescore
local success, res = api.request(
config.endpoint .. api.token .. '/setGameScore',
{
['user_id'] = user_id,
['score'] = score,
['force'] = force,
['disable_edit_message'] = disable_edit_message,
['chat_id'] = chat_id,
['message_id'] = message_id,
['inline_message_id'] = inline_message_id
}
)
return success, res
end
function api.get_game_high_scores(chat_id, user_id, message_id, inline_message_id) -- https://core.telegram.org/bots/api#getgamehighscores
local success, res = api.request(
config.endpoint .. api.token .. '/getGameHighScores',
{
['user_id'] = user_id,
['chat_id'] = chat_id,
['message_id'] = message_id,
['inline_message_id'] = inline_message_id
}
)
return success, res
end
function api.on_update(_) end
function api.on_message(_) end
function api.on_private_message(_) end
function api.on_group_message(_) end
function api.on_supergroup_message(_) end
function api.on_callback_query(_) end
function api.on_inline_query(_) end
function api.on_channel_post(_) end
function api.on_edited_message(_) end
function api.on_edited_private_message(_) end
function api.on_edited_group_message(_) end
function api.on_edited_supergroup_message(_) end
function api.on_edited_channel_post(_) end
function api.on_chosen_inline_result(_) end
function api.on_shipping_query(_) end
function api.on_pre_checkout_query(_) end
function api.on_poll(_) end
function api.on_poll_answer(_) end
function api.process_update(update)
if update then
api.on_update(update)
end
if update.message then
if update.message.chat.type == 'private' then
api.on_private_message(update.message)
elseif update.message.chat.type == 'group' then
api.on_group_message(update.message)
elseif update.message.chat.type == 'supergroup' then
api.on_supergroup_message(update.message)
end
return api.on_message(update.message)
elseif update.edited_message then
if update.edited_message.chat.type == 'private' then
api.on_edited_private_message(update.edited_message)
elseif update.edited_message.chat.type == 'group' then
api.on_edited_group_message(update.edited_message)
elseif update.edited_message.chat.type == 'supergroup' then
api.on_edited_supergroup_message(update.edited_message)
end
return api.on_edited_message(update.edited_message)
elseif update.callback_query then
return api.on_callback_query(update.callback_query)
elseif update.inline_query then
return api.on_inline_query(update.inline_query)
elseif update.channel_post then
return api.on_channel_post(update.channel_post)
elseif update.edited_channel_post then
return api.on_edited_channel_post(update.edited_channel_post)
elseif update.chosen_inline_result then
return api.on_chosen_inline_result(update.chosen_inline_result)
elseif update.shipping_query then
return api.on_shipping_query(update.shipping_query)
elseif update.pre_checkout_query then
return api.on_pre_checkout_query(update.pre_checkout_query)
elseif update.poll then
return api.on_poll(update.poll)
elseif update.poll_answer then
return api.on_poll_answer
end
return false
end
function api.run(limit, timeout, offset, allowed_updates, use_beta_endpoint)
limit = tonumber(limit) ~= nil and limit or 1
timeout = tonumber(timeout) ~= nil and timeout or 0
offset = tonumber(offset) ~= nil and offset or 0
while true do
local updates = api.get_updates(timeout, offset, limit, allowed_updates, use_beta_endpoint)
if updates and type(updates) == 'table' and updates.result then
for _, v in pairs(updates.result) do
api.process_update(v)
offset = v.update_id + 1
end
end
end
end
function api.input_text_message_content(message_text, parse_mode, disable_web_page_preview, encoded)
parse_mode = (type(parse_mode) == 'boolean' and parse_mode == true) and 'markdown' or parse_mode
local input_message_content = {
['message_text'] = tostring(message_text),
['parse_mode'] = parse_mode,
['disable_web_page_preview'] = disable_web_page_preview
}
input_message_content = encoded and json.encode(input_message_content) or input_message_content
return input_message_content
end
function api.input_location_message_content(latitude, longitude, encoded)
local input_message_content = {
['latitude'] = tonumber(latitude),
['longitude'] = tonumber(longitude)
}
input_message_content = encoded and json.encode(input_message_content) or input_message_content
return input_message_content
end
function api.input_venue_message_content(latitude, longitude, title, address, foursquare_id, encoded)
local input_message_content = {
['latitude'] = tonumber(latitude),
['longitude'] = tonumber(longitude),
['title'] = tostring(title),
['address'] = tostring(address),
['foursquare_id'] = foursquare_id
}
input_message_content = encoded and json.encode(input_message_content) or input_message_content
return input_message_content
end
function api.input_contact_message_content(phone_number, first_name, last_name, encoded)
local input_message_content = {
['phone_number'] = tostring(phone_number),
['first_name'] = tonumber(first_name),
['last_name'] = last_name
}
input_message_content = encoded and json.encode(input_message_content) or input_message_content
return input_message_content
end
function api.input_media_photo(media, caption, parse_mode)
return {
['type'] = 'photo',
['caption'] = caption,
['parse_mode'] = parse_mode
}, { ['media'] = media }
end
function api.input_media_video(media, thumb, caption, parse_mode, width, height, duration, supports_streaming)
return {
['type'] = 'video',
['caption'] = caption,
['parse_mode'] = parse_mode,
['width'] = tonumber(width),
['height'] = tonumber(height),
['duration'] = tonumber(duration),
['supports_streaming'] = supports_streaming
}, {
['media'] = media,
['thumb'] = thumb
}
end
function api.input_media_animation(media, thumb, caption, parse_mode, width, height, duration)
return {
['type'] = 'animation',
['caption'] = caption,
['parse_mode'] = parse_mode,
['width'] = tonumber(width),
['height'] = tonumber(height),
['duration'] = tonumber(duration)
}, {
['media'] = media,
['thumb'] = thumb
}
end
function api.input_media_audio(media, thumb, caption, parse_mode, duration, performer, title)
return {
['type'] = 'audio',
['caption'] = caption,
['parse_mode'] = parse_mode,
['duration'] = tonumber(duration),
['performer'] = performer,
['title'] = title
}, {
['media'] = media,
['thumb'] = thumb
}
end
function api.input_media_document(media, thumb, caption, parse_mode)
return {
['type'] = 'document',
['caption'] = caption,
['parse_mode'] = parse_mode
}, {
['media'] = media,
['thumb'] = thumb
}
end
-- Functions to handle ChatPermissions
function api.chat_permissions(can_send_messages, can_send_media_messages, can_send_polls, can_send_other_messages, can_add_web_page_previews, can_change_info, can_invite_users, can_pin_messages)
return {
['can_send_messages'] = can_send_messages,
['can_send_media_messages'] = can_send_media_messages,
['can_send_polls'] = can_send_polls,
['can_send_other_messages'] = can_send_other_messages,
['can_add_web_page_previews'] = can_add_web_page_previews,
['can_change_info'] = can_change_info,
['can_invite_users'] = can_invite_users,
['can_pin_messages'] = can_pin_messages
}
end
-- Functions and meta-methods for handling mask positioning arrays to use with various
-- sticker-related functions.
api.mask_position_meta = {}
api.mask_position_meta.__index = api.mask_position_meta
function api.mask_position_meta:position(point, x_shift, y_shift, scale)
table.insert(
self,
{
['point'] = tostring(point), -- Available points include "forehead", "eyes", "mouth" or "chin".
['x_shift'] = tonumber(x_shift),
['y_shift'] = tonumber(y_shift),
['scale'] = tonumber(scale)
}
)
return self
end
function api.mask_position()
local output = setmetatable({}, api.mask_position_meta)
return output
end
-- Functions for handling inline objects to use with api.answer_inline_query().
function api.send_inline_article(inline_query_id, title, description, message_text, parse_mode, reply_markup)
description = description or title
message_text = message_text or description
parse_mode = (type(parse_mode) == 'boolean' and parse_mode == true) and 'markdown' or parse_mode
return api.answer_inline_query(
inline_query_id,
json.encode(
{
{
['type'] = 'article',
['id'] = '1',
['title'] = title,
['description'] = description,
['input_message_content'] = {
['message_text'] = message_text,
['parse_mode'] = parse_mode
},
['reply_markup'] = reply_markup
}
}
)
)
end
function api.send_inline_article_url(inline_query_id, title, url, hide_url, input_message_content, reply_markup, id)
return api.answer_inline_query(
inline_query_id,
json.encode(
{
{
['type'] = 'article',
['id'] = tonumber(id) ~= nil and tostring(id) or '1',
['title'] = tostring(title),
['url'] = tostring(url),
['hide_url'] = hide_url or false,
['input_message_content'] = input_message_content,
['reply_markup'] = reply_markup
}
}
)
)
end
api.inline_result_meta = {}
api.inline_result_meta.__index = api.inline_result_meta
function api.inline_result_meta:type(type)
self['type'] = tostring(type)
return self
end
function api.inline_result_meta:id(id)
self['id'] = id and tostring(id) or '1'
return self
end
function api.inline_result_meta:title(title)
self['title'] = tostring(title)
return self
end
function api.inline_result_meta:input_message_content(input_message_content)
self['input_message_content'] = input_message_content
return self
end
function api.inline_result_meta:reply_markup(reply_markup)
self['reply_markup'] = reply_markup
return self
end
function api.inline_result_meta:url(url)
self['url'] = tostring(url)
return self
end
function api.inline_result_meta:hide_url(hide_url)
self['hide_url'] = hide_url or false
return self
end
function api.inline_result_meta:description(description)
self['description'] = tostring(description)
return self
end
function api.inline_result_meta:thumb_url(thumb_url)
self['thumb_url'] = tostring(thumb_url)
return self
end
function api.inline_result_meta:thumb_width(thumb_width)
self['thumb_width'] = tonumber(thumb_width)
return self
end
function api.inline_result_meta:thumb_height(thumb_height)
self['thumb_height'] = tonumber(thumb_height)
return self
end
function api.inline_result_meta:photo_url(photo_url)
self['photo_url'] = tostring(photo_url)
return self
end
function api.inline_result_meta:photo_width(photo_width)
self['photo_width'] = tonumber(photo_width)
return self
end
function api.inline_result_meta:photo_height(photo_height)
self['photo_height'] = tonumber(photo_height)
return self
end
function api.inline_result_meta:caption(caption)
self['caption'] = tostring(caption)
return self
end
function api.inline_result_meta:gif_url(gif_url)
self['gif_url'] = tostring(gif_url)
return self
end
function api.inline_result_meta:gif_width(gif_width)
self['gif_width'] = tonumber(gif_width)
return self
end
function api.inline_result_meta:gif_height(gif_height)
self['gif_height'] = tonumber(gif_height)
return self
end
function api.inline_result_meta:mpeg4_url(mpeg4_url)
self['mpeg4_url'] = tostring(mpeg4_url)
return self
end
function api.inline_result_meta:mpeg4_width(mpeg4_width)
self['mpeg4_width'] = tonumber(mpeg4_width)
return self
end
function api.inline_result_meta:mpeg4_height(mpeg4_height)
self['mpeg4_height'] = tonumber(mpeg4_height)
return self
end
function api.inline_result_meta:video_url(video_url)
self['video_url'] = tostring(video_url)
return self
end
function api.inline_result_meta:mime_type(mime_type)
self['mime_type'] = tostring(mime_type)
return self
end
function api.inline_result_meta:video_width(video_width)
self['video_width'] = tonumber(video_width)
return self
end
function api.inline_result_meta:video_height(video_height)
self['video_height'] = tonumber(video_height)
return self
end
function api.inline_result_meta:video_duration(video_duration)
self['video_duration'] = tonumber(video_duration)
return self
end
function api.inline_result_meta:audio_url(audio_url)
self['audio_url'] = tostring(audio_url)
return self
end
function api.inline_result_meta:performer(performer)
self['performer'] = tostring(performer)
return self
end
function api.inline_result_meta:audio_duration(audio_duration)
self['audio_duration'] = tonumber(audio_duration)
return self
end
function api.inline_result_meta:voice_url(voice_url)
self['voice_url'] = tostring(voice_url)
return self
end
function api.inline_result_meta:voice_duration(voice_duration)
self['voice_duration'] = tonumber(voice_duration)
return self
end
function api.inline_result_meta:document_url(document_url)
self['document_url'] = tostring(document_url)
return self
end
function api.inline_result_meta:latitude(latitude)
self['latitude'] = tonumber(latitude)
return self
end
function api.inline_result_meta:longitude(longitude)
self['longitude'] = tonumber(longitude)
return self
end
function api.inline_result_meta:live_period(live_period)
self['live_period'] = tonumber(live_period)
return self
end
function api.inline_result_meta:address(address)
self['address'] = tostring(address)
return self
end
function api.inline_result_meta:foursquare_id(foursquare_id)
self['foursquare_id'] = tostring(foursquare_id)
return self
end
function api.inline_result_meta:phone_number(phone_number)
self['phone_number'] = tostring(phone_number)
return self
end
function api.inline_result_meta:first_name(first_name)
self['first_name'] = tostring(first_name)
return self
end
function api.inline_result_meta:last_name(last_name)
self['last_name'] = tostring(last_name)
return self
end
function api.inline_result_meta:game_short_name(game_short_name)
self['game_short_name'] = tostring(game_short_name)
return self
end
function api.inline_result()
local output = setmetatable({}, api.inline_result_meta)
return output
end
function api.send_inline_photo(inline_query_id, photo_url, caption, reply_markup)
return api.answer_inline_query(
inline_query_id,
json.encode(
{
{
['type'] = 'photo',
['id'] = '1',
['photo_url'] = photo_url,
['thumb_url'] = photo_url,
['caption'] = caption,
['reply_markup'] = reply_markup
}
}
)
)
end
function api.send_inline_cached_photo(inline_query_id, photo_file_id, caption, reply_markup)
return api.answer_inline_query(
inline_query_id,
json.encode(
{
{
['type'] = 'photo',
['id'] = '1',
['photo_file_id'] = photo_file_id,
['caption'] = caption,
['reply_markup'] = reply_markup
}
}
)
)
end
function api.url_button(text, url, encoded)
if not text or not url then
return false
end
local button = {
['text'] = tostring(text),
['url'] = tostring(url)
}
if encoded then
button = json.encode(button)
end
return button
end
function api.callback_data_button(text, callback_data, encoded)
if not text or not callback_data then
return false
end
local button = {
['text'] = tostring(text),
['callback_data'] = tostring(callback_data)
}
if encoded then
button = json.encode(button)
end
return button
end
function api.switch_inline_query_button(text, switch_inline_query, encoded)
if not text or not switch_inline_query then
return false
end
local button = {
['text'] = tostring(text),
['switch_inline_query'] = tostring(switch_inline_query)
}
if encoded then
button = json.encode(button)
end
return button
end
function api.switch_inline_query_current_chat_button(text, switch_inline_query_current_chat, encoded)
if not text or not switch_inline_query_current_chat then
return false
end
local button = {
['text'] = tostring(text),
['switch_inline_query_current_chat'] = tostring(switch_inline_query_current_chat)
}
if encoded then
button = json.encode(button)
end
return button
end
function api.callback_game_button(text, callback_game, encoded)
if not text or not callback_game then
return false
end
local button = {
['text'] = tostring(text),
['callback_game'] = tostring(callback_game)
}
if encoded then
button = json.encode(button)
end
return button
end
function api.pay_button(text, pay, encoded)
if not text or pay == nil then
return false
end
local button = {
['text'] = tostring(text),
['pay'] = pay
}
if encoded then
button = json.encode(button)
end
return button
end
function api.remove_keyboard(selective)
return {
['remove_keyboard'] = true,
['selective'] = selective or false
}
end
api.keyboard_meta = {}
api.keyboard_meta.__index = api.keyboard_meta
function api.keyboard_meta:row(row)
table.insert(self.keyboard, row)
return self
end
function api.keyboard(resize_keyboard, one_time_keyboard, selective)
return setmetatable(
{
['keyboard'] = {},
['resize_keyboard'] = resize_keyboard or false,
['one_time_keyboard'] = one_time_keyboard or false,
['selective'] = selective or false
},
api.keyboard_meta
)
end
api.inline_keyboard_meta = {}
api.inline_keyboard_meta.__index = api.inline_keyboard_meta
function api.inline_keyboard_meta:row(row)
table.insert(self.inline_keyboard, row)
return self
end
function api.inline_keyboard()
return setmetatable({ ['inline_keyboard'] = {} }, api.inline_keyboard_meta)
end
api.prices_meta = {}
api.prices_meta.__index = api.prices_meta
function api.prices_meta:labeled_price(label, amount)
table.insert(
self,
{
['label'] = tostring(label),
['amount'] = tonumber(amount)
}
)
return self
end
function api.prices()
return setmetatable({}, api.prices_meta)
end
api.shipping_options_meta = {}
api.shipping_options_meta.__index = api.shipping_options_meta
function api.shipping_options_meta:shipping_option(id, title, prices)
table.insert(
self,
{
['id'] = tostring(id),
['title'] = tostring(title),
['prices'] = prices
}
)
return self
end
function api.shipping_options()
return setmetatable({}, api.shipping_options_meta)
end
api.row_meta = {}
api.row_meta.__index = api.row_meta
function api.row_meta:url_button(text, url)
table.insert(
self,
{
['text'] = tostring(text),
['url'] = tostring(url)
}
)
return self
end
function api.row_meta:callback_data_button(text, callback_data)
table.insert(
self,
{
['text'] = tostring(text),
['callback_data'] = tostring(callback_data)
}
)
return self
end
function api.row_meta:switch_inline_query_button(text, switch_inline_query)
table.insert(
self,
{
['text'] = tostring(text),
['switch_inline_query'] = tostring(switch_inline_query)
}
)
return self
end
function api.row_meta:switch_inline_query_current_chat_button(text, switch_inline_query_current_chat)
table.insert(
self,
{
['text'] = tostring(text),
['switch_inline_query_current_chat'] = tostring(switch_inline_query_current_chat)
}
)
return self
end
function api.row_meta:pay_button(text, pay)
table.insert(
self,
{
['text'] = tostring(text),
['pay'] = pay
}
)
return self
end
function api.row(_)
return setmetatable({}, api.row_meta)
end
api.input_media_meta = {}
api.input_media_meta.__index = api.input_media_meta
function api.input_media_meta:photo(media, caption)
table.insert(
self,
{
['type'] = 'photo',
['media'] = tostring(media),
['caption'] = caption
}
)
return self
end
function api.input_media_meta:video(media, caption, width, height, duration)
table.insert(
self,
{
['type'] = 'video',
['media'] = tostring(media),
['caption'] = caption,
['width'] = width,
['height'] = height,
['duration'] = duration
}
)
return self
end
function api.input_media(_)
return setmetatable({}, api.input_media_meta)
end
function api.labeled_price(label, amount, encoded)
if not label or not amount or tonumber(amount) == nil then
return false
end
local button = {
['label'] = tostring(label),
['amount'] = tonumber(amount)
}
if encoded then
button = json.encode(button)
end
return button
end
function api.get_chat_member_permissions(chat_id, user_id)
if not chat_id or not user_id then
return false
end
local success = api.get_chat_member(chat_id, user_id)
if not success then
return success
end
local p = success.result
return {
['can_be_edited'] = p.can_be_edited or false,
['can_post_messages'] = p.can_post_messages or false,
['can_edit_messages'] = p.can_edit_messages or false,
['can_delete_messages'] = p.can_delete_messages or false,
['can_restrict_members'] = p.can_restrict_members or false,
['can_promote_members'] = p.can_promote_members or false,
['can_change_info'] = p.can_change_info or false,
['can_invite_users'] = p.can_invite_users or false,
['can_pin_messages'] = p.can_pin_messages or false,
['can_send_messages'] = p.can_send_messages or false,
['can_send_media_messages'] = p.can_send_media_messages or false,
['can_send_polls'] = p.can_send_polls or false,
['can_send_other_messages'] = p.can_send_other_messages or false,
['can_add_web_page_previews'] = p.can_add_web_page_previews or false
}
end
function api.is_user_kicked(chat_id, user_id)
if not chat_id or not user_id then
return false
end
local user, res = api.get_chat_member(chat_id, user_id)
if not user or not user.result then
return false, res
elseif user.result.status == 'kicked' then
return true, res
end
return false, user.result.status
end
function api.is_user_group_admin(chat_id, user_id)
if not chat_id or not user_id then
return false
end
local user, res = api.get_chat_member(chat_id, user_id)
if not user or not user.result then
return false, res
elseif user.result.status == ('administrator' or 'creator') then
return true, res
end
return false, user.result.status
end
function api.is_user_group_creator(chat_id, user_id)
if not chat_id or not user_id then
return false
end
local user, res = api.get_chat_member(chat_id, user_id)
if not user or not user.result then
return false, res
elseif user.result.status == 'creator' then
return true, res
end
return false, user.result.status
end
function api.is_user_restricted(chat_id, user_id)
if not chat_id or not user_id then
return false
end
local user, res = api.get_chat_member(chat_id, user_id)
if not user or not user.result then
return false, res
elseif user.result.status == 'kicked' then
return true, res
end
return false, user.result.status
end
function api.has_user_left(chat_id, user_id)
if not chat_id or not user_id then
return false
end
local user, res = api.get_chat_member(chat_id, user_id)
if not user or not user.result then
return false, res
elseif user.result.status == 'left' then
return true, res
end
return false, user.result.status
end
return api
| gpl-3.0 |
Zenny89/darkstar | scripts/zones/PsoXja/npcs/_091.lua | 17 | 1614 | -----------------------------------
-- Area: Pso'Xja
-- NPC: _091 (Stone Gate)
-- Notes: Spawns Gargoyle when triggered
-- @pos -330.000 14.074 -261.600 9
-----------------------------------
package.loaded["scripts/zones/PsoXja/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/PsoXja/TextIDs");
require("scripts/globals/keyitems");
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
local Z=player:getZPos();
if (npc:getAnimation() == 9) then
if (Z >= -61) then
if (GetMobAction(16814082) == 0) then
local Rand = math.random(1,10);
if (Rand <=9) then -- Spawn Gargoyle
player:messageSpecial(TRAP_ACTIVATED);
SpawnMob(16814082,120):updateClaim(player); -- Gargoyle
else
player:messageSpecial(TRAP_FAILS);
npc:openDoor(30);
end
else
player:messageSpecial(DOOR_LOCKED);
end
elseif (Z <= -62) then
player:startEvent(0x001A);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
if (csid == 0x001A and option == 1) then
player:setPos(260,-0.25,-20,254,111);
end
end; | gpl-3.0 |
mercury233/ygopro-scripts | c88617904.lua | 2 | 2506 | --プロモーション
function c88617904.initial_effect(c)
--activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_TOGRAVE+CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCountLimit(1,88617904+EFFECT_COUNT_CODE_OATH)
e1:SetTarget(c88617904.target)
e1:SetOperation(c88617904.operation)
c:RegisterEffect(e1)
end
function c88617904.tgfilter(c,tp)
return c:IsFaceup() and c:IsRace(RACE_WARRIOR) and c:IsAttribute(ATTRIBUTE_EARTH) and c:IsLevelBelow(3)
and c:IsAbleToGrave() and Duel.GetMZoneCount(tp,c)>0
end
function c88617904.spfilter(c,e,tp)
return c:IsRace(RACE_WARRIOR) and c:IsAttribute(ATTRIBUTE_EARTH) and c:IsLevelAbove(4)
and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c88617904.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(tp) and c88617904.tgfilter(chkc,tp) end
if chk==0 then return Duel.IsExistingTarget(c88617904.tgfilter,tp,LOCATION_MZONE,0,1,nil,tp)
and Duel.IsExistingMatchingCard(c88617904.spfilter,tp,LOCATION_DECK,0,1,nil,e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE)
local g=Duel.SelectTarget(tp,c88617904.tgfilter,tp,LOCATION_MZONE,0,1,1,nil,tp)
Duel.SetOperationInfo(0,CATEGORY_TOGRAVE,g,1,0,0)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK)
end
function c88617904.operation(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) and Duel.SendtoGrave(tc,REASON_EFFECT)>0 and tc:IsLocation(LOCATION_GRAVE) then
local g=Duel.GetMatchingGroup(c88617904.spfilter,tp,LOCATION_DECK,0,nil,e,tp)
if g:GetCount()>0 then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local sc=g:Select(tp,1,1,nil):GetFirst()
Duel.SpecialSummon(sc,0,tp,tp,false,false,POS_FACEUP)
if Duel.IsExistingMatchingCard(c88617904.atkfilter,tp,LOCATION_MZONE,0,1,nil) then
Duel.BreakEffect()
local ct=Duel.GetFieldGroupCount(tp,0,LOCATION_GRAVE)*100
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetReset(RESET_EVENT+RESETS_STANDARD)
e1:SetValue(ct)
sc:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetCode(EFFECT_UPDATE_DEFENSE)
sc:RegisterEffect(e2)
end
end
end
end
function c88617904.atkfilter(c)
return c:GetOriginalRace()==RACE_WARRIOR and c:GetOriginalAttribute()==ATTRIBUTE_EARTH and c:IsSetCard(0x83) and c:IsFaceup()
end
| gpl-2.0 |
lingkeyang/slua | build/luajit-2.1.0/src/jit/dis_ppc.lua | 78 | 20318 | ----------------------------------------------------------------------------
-- LuaJIT PPC disassembler module.
--
-- Copyright (C) 2005-2015 Mike Pall. All rights reserved.
-- Released under the MIT/X license. See Copyright Notice in luajit.h
----------------------------------------------------------------------------
-- This is a helper module used by the LuaJIT machine code dumper module.
--
-- It disassembles all common, non-privileged 32/64 bit PowerPC instructions
-- plus the e500 SPE instructions and some Cell/Xenon extensions.
--
-- NYI: VMX, VMX128
------------------------------------------------------------------------------
local type = type
local sub, byte, format = string.sub, string.byte, string.format
local match, gmatch, gsub = string.match, string.gmatch, string.gsub
local concat = table.concat
local bit = require("bit")
local band, bor, tohex = bit.band, bit.bor, bit.tohex
local lshift, rshift, arshift = bit.lshift, bit.rshift, bit.arshift
------------------------------------------------------------------------------
-- Primary and extended opcode maps
------------------------------------------------------------------------------
local map_crops = {
shift = 1, mask = 1023,
[0] = "mcrfXX",
[33] = "crnor|crnotCCC=", [129] = "crandcCCC",
[193] = "crxor|crclrCCC%", [225] = "crnandCCC",
[257] = "crandCCC", [289] = "creqv|crsetCCC%",
[417] = "crorcCCC", [449] = "cror|crmoveCCC=",
[16] = "b_lrKB", [528] = "b_ctrKB",
[150] = "isync",
}
local map_rlwinm = setmetatable({
shift = 0, mask = -1,
},
{ __index = function(t, x)
local rot = band(rshift(x, 11), 31)
local mb = band(rshift(x, 6), 31)
local me = band(rshift(x, 1), 31)
if mb == 0 and me == 31-rot then
return "slwiRR~A."
elseif me == 31 and mb == 32-rot then
return "srwiRR~-A."
else
return "rlwinmRR~AAA."
end
end
})
local map_rld = {
shift = 2, mask = 7,
[0] = "rldiclRR~HM.", "rldicrRR~HM.", "rldicRR~HM.", "rldimiRR~HM.",
{
shift = 1, mask = 1,
[0] = "rldclRR~RM.", "rldcrRR~RM.",
},
}
local map_ext = setmetatable({
shift = 1, mask = 1023,
[0] = "cmp_YLRR", [32] = "cmpl_YLRR",
[4] = "twARR", [68] = "tdARR",
[8] = "subfcRRR.", [40] = "subfRRR.",
[104] = "negRR.", [136] = "subfeRRR.",
[200] = "subfzeRR.", [232] = "subfmeRR.",
[520] = "subfcoRRR.", [552] = "subfoRRR.",
[616] = "negoRR.", [648] = "subfeoRRR.",
[712] = "subfzeoRR.", [744] = "subfmeoRR.",
[9] = "mulhduRRR.", [73] = "mulhdRRR.", [233] = "mulldRRR.",
[457] = "divduRRR.", [489] = "divdRRR.",
[745] = "mulldoRRR.",
[969] = "divduoRRR.", [1001] = "divdoRRR.",
[10] = "addcRRR.", [138] = "addeRRR.",
[202] = "addzeRR.", [234] = "addmeRR.", [266] = "addRRR.",
[522] = "addcoRRR.", [650] = "addeoRRR.",
[714] = "addzeoRR.", [746] = "addmeoRR.", [778] = "addoRRR.",
[11] = "mulhwuRRR.", [75] = "mulhwRRR.", [235] = "mullwRRR.",
[459] = "divwuRRR.", [491] = "divwRRR.",
[747] = "mullwoRRR.",
[971] = "divwouRRR.", [1003] = "divwoRRR.",
[15] = "iselltRRR", [47] = "iselgtRRR", [79] = "iseleqRRR",
[144] = { shift = 20, mask = 1, [0] = "mtcrfRZ~", "mtocrfRZ~", },
[19] = { shift = 20, mask = 1, [0] = "mfcrR", "mfocrfRZ", },
[371] = { shift = 11, mask = 1023, [392] = "mftbR", [424] = "mftbuR", },
[339] = {
shift = 11, mask = 1023,
[32] = "mferR", [256] = "mflrR", [288] = "mfctrR", [16] = "mfspefscrR",
},
[467] = {
shift = 11, mask = 1023,
[32] = "mtxerR", [256] = "mtlrR", [288] = "mtctrR", [16] = "mtspefscrR",
},
[20] = "lwarxRR0R", [84] = "ldarxRR0R",
[21] = "ldxRR0R", [53] = "lduxRRR",
[149] = "stdxRR0R", [181] = "stduxRRR",
[341] = "lwaxRR0R", [373] = "lwauxRRR",
[23] = "lwzxRR0R", [55] = "lwzuxRRR",
[87] = "lbzxRR0R", [119] = "lbzuxRRR",
[151] = "stwxRR0R", [183] = "stwuxRRR",
[215] = "stbxRR0R", [247] = "stbuxRRR",
[279] = "lhzxRR0R", [311] = "lhzuxRRR",
[343] = "lhaxRR0R", [375] = "lhauxRRR",
[407] = "sthxRR0R", [439] = "sthuxRRR",
[54] = "dcbst-R0R", [86] = "dcbf-R0R",
[150] = "stwcxRR0R.", [214] = "stdcxRR0R.",
[246] = "dcbtst-R0R", [278] = "dcbt-R0R",
[310] = "eciwxRR0R", [438] = "ecowxRR0R",
[470] = "dcbi-RR",
[598] = {
shift = 21, mask = 3,
[0] = "sync", "lwsync", "ptesync",
},
[758] = "dcba-RR",
[854] = "eieio", [982] = "icbi-R0R", [1014] = "dcbz-R0R",
[26] = "cntlzwRR~", [58] = "cntlzdRR~",
[122] = "popcntbRR~",
[154] = "prtywRR~", [186] = "prtydRR~",
[28] = "andRR~R.", [60] = "andcRR~R.", [124] = "nor|notRR~R=.",
[284] = "eqvRR~R.", [316] = "xorRR~R.",
[412] = "orcRR~R.", [444] = "or|mrRR~R=.", [476] = "nandRR~R.",
[508] = "cmpbRR~R",
[512] = "mcrxrX",
[532] = "ldbrxRR0R", [660] = "stdbrxRR0R",
[533] = "lswxRR0R", [597] = "lswiRR0A",
[661] = "stswxRR0R", [725] = "stswiRR0A",
[534] = "lwbrxRR0R", [662] = "stwbrxRR0R",
[790] = "lhbrxRR0R", [918] = "sthbrxRR0R",
[535] = "lfsxFR0R", [567] = "lfsuxFRR",
[599] = "lfdxFR0R", [631] = "lfduxFRR",
[663] = "stfsxFR0R", [695] = "stfsuxFRR",
[727] = "stfdxFR0R", [759] = "stfduxFR0R",
[855] = "lfiwaxFR0R",
[983] = "stfiwxFR0R",
[24] = "slwRR~R.",
[27] = "sldRR~R.", [536] = "srwRR~R.",
[792] = "srawRR~R.", [824] = "srawiRR~A.",
[794] = "sradRR~R.", [826] = "sradiRR~H.", [827] = "sradiRR~H.",
[922] = "extshRR~.", [954] = "extsbRR~.", [986] = "extswRR~.",
[539] = "srdRR~R.",
},
{ __index = function(t, x)
if band(x, 31) == 15 then return "iselRRRC" end
end
})
local map_ld = {
shift = 0, mask = 3,
[0] = "ldRRE", "lduRRE", "lwaRRE",
}
local map_std = {
shift = 0, mask = 3,
[0] = "stdRRE", "stduRRE",
}
local map_fps = {
shift = 5, mask = 1,
{
shift = 1, mask = 15,
[0] = false, false, "fdivsFFF.", false,
"fsubsFFF.", "faddsFFF.", "fsqrtsF-F.", false,
"fresF-F.", "fmulsFF-F.", "frsqrtesF-F.", false,
"fmsubsFFFF~.", "fmaddsFFFF~.", "fnmsubsFFFF~.", "fnmaddsFFFF~.",
}
}
local map_fpd = {
shift = 5, mask = 1,
[0] = {
shift = 1, mask = 1023,
[0] = "fcmpuXFF", [32] = "fcmpoXFF", [64] = "mcrfsXX",
[38] = "mtfsb1A.", [70] = "mtfsb0A.", [134] = "mtfsfiA>>-A>",
[8] = "fcpsgnFFF.", [40] = "fnegF-F.", [72] = "fmrF-F.",
[136] = "fnabsF-F.", [264] = "fabsF-F.",
[12] = "frspF-F.",
[14] = "fctiwF-F.", [15] = "fctiwzF-F.",
[583] = "mffsF.", [711] = "mtfsfZF.",
[392] = "frinF-F.", [424] = "frizF-F.",
[456] = "fripF-F.", [488] = "frimF-F.",
[814] = "fctidF-F.", [815] = "fctidzF-F.", [846] = "fcfidF-F.",
},
{
shift = 1, mask = 15,
[0] = false, false, "fdivFFF.", false,
"fsubFFF.", "faddFFF.", "fsqrtF-F.", "fselFFFF~.",
"freF-F.", "fmulFF-F.", "frsqrteF-F.", false,
"fmsubFFFF~.", "fmaddFFFF~.", "fnmsubFFFF~.", "fnmaddFFFF~.",
}
}
local map_spe = {
shift = 0, mask = 2047,
[512] = "evaddwRRR", [514] = "evaddiwRAR~",
[516] = "evsubwRRR~", [518] = "evsubiwRAR~",
[520] = "evabsRR", [521] = "evnegRR",
[522] = "evextsbRR", [523] = "evextshRR", [524] = "evrndwRR",
[525] = "evcntlzwRR", [526] = "evcntlswRR",
[527] = "brincRRR",
[529] = "evandRRR", [530] = "evandcRRR", [534] = "evxorRRR",
[535] = "evor|evmrRRR=", [536] = "evnor|evnotRRR=",
[537] = "eveqvRRR", [539] = "evorcRRR", [542] = "evnandRRR",
[544] = "evsrwuRRR", [545] = "evsrwsRRR",
[546] = "evsrwiuRRA", [547] = "evsrwisRRA",
[548] = "evslwRRR", [550] = "evslwiRRA",
[552] = "evrlwRRR", [553] = "evsplatiRS",
[554] = "evrlwiRRA", [555] = "evsplatfiRS",
[556] = "evmergehiRRR", [557] = "evmergeloRRR",
[558] = "evmergehiloRRR", [559] = "evmergelohiRRR",
[560] = "evcmpgtuYRR", [561] = "evcmpgtsYRR",
[562] = "evcmpltuYRR", [563] = "evcmpltsYRR",
[564] = "evcmpeqYRR",
[632] = "evselRRR", [633] = "evselRRRW",
[634] = "evselRRRW", [635] = "evselRRRW",
[636] = "evselRRRW", [637] = "evselRRRW",
[638] = "evselRRRW", [639] = "evselRRRW",
[640] = "evfsaddRRR", [641] = "evfssubRRR",
[644] = "evfsabsRR", [645] = "evfsnabsRR", [646] = "evfsnegRR",
[648] = "evfsmulRRR", [649] = "evfsdivRRR",
[652] = "evfscmpgtYRR", [653] = "evfscmpltYRR", [654] = "evfscmpeqYRR",
[656] = "evfscfuiR-R", [657] = "evfscfsiR-R",
[658] = "evfscfufR-R", [659] = "evfscfsfR-R",
[660] = "evfsctuiR-R", [661] = "evfsctsiR-R",
[662] = "evfsctufR-R", [663] = "evfsctsfR-R",
[664] = "evfsctuizR-R", [666] = "evfsctsizR-R",
[668] = "evfststgtYRR", [669] = "evfststltYRR", [670] = "evfststeqYRR",
[704] = "efsaddRRR", [705] = "efssubRRR",
[708] = "efsabsRR", [709] = "efsnabsRR", [710] = "efsnegRR",
[712] = "efsmulRRR", [713] = "efsdivRRR",
[716] = "efscmpgtYRR", [717] = "efscmpltYRR", [718] = "efscmpeqYRR",
[719] = "efscfdR-R",
[720] = "efscfuiR-R", [721] = "efscfsiR-R",
[722] = "efscfufR-R", [723] = "efscfsfR-R",
[724] = "efsctuiR-R", [725] = "efsctsiR-R",
[726] = "efsctufR-R", [727] = "efsctsfR-R",
[728] = "efsctuizR-R", [730] = "efsctsizR-R",
[732] = "efststgtYRR", [733] = "efststltYRR", [734] = "efststeqYRR",
[736] = "efdaddRRR", [737] = "efdsubRRR",
[738] = "efdcfuidR-R", [739] = "efdcfsidR-R",
[740] = "efdabsRR", [741] = "efdnabsRR", [742] = "efdnegRR",
[744] = "efdmulRRR", [745] = "efddivRRR",
[746] = "efdctuidzR-R", [747] = "efdctsidzR-R",
[748] = "efdcmpgtYRR", [749] = "efdcmpltYRR", [750] = "efdcmpeqYRR",
[751] = "efdcfsR-R",
[752] = "efdcfuiR-R", [753] = "efdcfsiR-R",
[754] = "efdcfufR-R", [755] = "efdcfsfR-R",
[756] = "efdctuiR-R", [757] = "efdctsiR-R",
[758] = "efdctufR-R", [759] = "efdctsfR-R",
[760] = "efdctuizR-R", [762] = "efdctsizR-R",
[764] = "efdtstgtYRR", [765] = "efdtstltYRR", [766] = "efdtsteqYRR",
[768] = "evlddxRR0R", [769] = "evlddRR8",
[770] = "evldwxRR0R", [771] = "evldwRR8",
[772] = "evldhxRR0R", [773] = "evldhRR8",
[776] = "evlhhesplatxRR0R", [777] = "evlhhesplatRR2",
[780] = "evlhhousplatxRR0R", [781] = "evlhhousplatRR2",
[782] = "evlhhossplatxRR0R", [783] = "evlhhossplatRR2",
[784] = "evlwhexRR0R", [785] = "evlwheRR4",
[788] = "evlwhouxRR0R", [789] = "evlwhouRR4",
[790] = "evlwhosxRR0R", [791] = "evlwhosRR4",
[792] = "evlwwsplatxRR0R", [793] = "evlwwsplatRR4",
[796] = "evlwhsplatxRR0R", [797] = "evlwhsplatRR4",
[800] = "evstddxRR0R", [801] = "evstddRR8",
[802] = "evstdwxRR0R", [803] = "evstdwRR8",
[804] = "evstdhxRR0R", [805] = "evstdhRR8",
[816] = "evstwhexRR0R", [817] = "evstwheRR4",
[820] = "evstwhoxRR0R", [821] = "evstwhoRR4",
[824] = "evstwwexRR0R", [825] = "evstwweRR4",
[828] = "evstwwoxRR0R", [829] = "evstwwoRR4",
[1027] = "evmhessfRRR", [1031] = "evmhossfRRR", [1032] = "evmheumiRRR",
[1033] = "evmhesmiRRR", [1035] = "evmhesmfRRR", [1036] = "evmhoumiRRR",
[1037] = "evmhosmiRRR", [1039] = "evmhosmfRRR", [1059] = "evmhessfaRRR",
[1063] = "evmhossfaRRR", [1064] = "evmheumiaRRR", [1065] = "evmhesmiaRRR",
[1067] = "evmhesmfaRRR", [1068] = "evmhoumiaRRR", [1069] = "evmhosmiaRRR",
[1071] = "evmhosmfaRRR", [1095] = "evmwhssfRRR", [1096] = "evmwlumiRRR",
[1100] = "evmwhumiRRR", [1101] = "evmwhsmiRRR", [1103] = "evmwhsmfRRR",
[1107] = "evmwssfRRR", [1112] = "evmwumiRRR", [1113] = "evmwsmiRRR",
[1115] = "evmwsmfRRR", [1127] = "evmwhssfaRRR", [1128] = "evmwlumiaRRR",
[1132] = "evmwhumiaRRR", [1133] = "evmwhsmiaRRR", [1135] = "evmwhsmfaRRR",
[1139] = "evmwssfaRRR", [1144] = "evmwumiaRRR", [1145] = "evmwsmiaRRR",
[1147] = "evmwsmfaRRR",
[1216] = "evaddusiaawRR", [1217] = "evaddssiaawRR",
[1218] = "evsubfusiaawRR", [1219] = "evsubfssiaawRR",
[1220] = "evmraRR",
[1222] = "evdivwsRRR", [1223] = "evdivwuRRR",
[1224] = "evaddumiaawRR", [1225] = "evaddsmiaawRR",
[1226] = "evsubfumiaawRR", [1227] = "evsubfsmiaawRR",
[1280] = "evmheusiaawRRR", [1281] = "evmhessiaawRRR",
[1283] = "evmhessfaawRRR", [1284] = "evmhousiaawRRR",
[1285] = "evmhossiaawRRR", [1287] = "evmhossfaawRRR",
[1288] = "evmheumiaawRRR", [1289] = "evmhesmiaawRRR",
[1291] = "evmhesmfaawRRR", [1292] = "evmhoumiaawRRR",
[1293] = "evmhosmiaawRRR", [1295] = "evmhosmfaawRRR",
[1320] = "evmhegumiaaRRR", [1321] = "evmhegsmiaaRRR",
[1323] = "evmhegsmfaaRRR", [1324] = "evmhogumiaaRRR",
[1325] = "evmhogsmiaaRRR", [1327] = "evmhogsmfaaRRR",
[1344] = "evmwlusiaawRRR", [1345] = "evmwlssiaawRRR",
[1352] = "evmwlumiaawRRR", [1353] = "evmwlsmiaawRRR",
[1363] = "evmwssfaaRRR", [1368] = "evmwumiaaRRR",
[1369] = "evmwsmiaaRRR", [1371] = "evmwsmfaaRRR",
[1408] = "evmheusianwRRR", [1409] = "evmhessianwRRR",
[1411] = "evmhessfanwRRR", [1412] = "evmhousianwRRR",
[1413] = "evmhossianwRRR", [1415] = "evmhossfanwRRR",
[1416] = "evmheumianwRRR", [1417] = "evmhesmianwRRR",
[1419] = "evmhesmfanwRRR", [1420] = "evmhoumianwRRR",
[1421] = "evmhosmianwRRR", [1423] = "evmhosmfanwRRR",
[1448] = "evmhegumianRRR", [1449] = "evmhegsmianRRR",
[1451] = "evmhegsmfanRRR", [1452] = "evmhogumianRRR",
[1453] = "evmhogsmianRRR", [1455] = "evmhogsmfanRRR",
[1472] = "evmwlusianwRRR", [1473] = "evmwlssianwRRR",
[1480] = "evmwlumianwRRR", [1481] = "evmwlsmianwRRR",
[1491] = "evmwssfanRRR", [1496] = "evmwumianRRR",
[1497] = "evmwsmianRRR", [1499] = "evmwsmfanRRR",
}
local map_pri = {
[0] = false, false, "tdiARI", "twiARI",
map_spe, false, false, "mulliRRI",
"subficRRI", false, "cmpl_iYLRU", "cmp_iYLRI",
"addicRRI", "addic.RRI", "addi|liRR0I", "addis|lisRR0I",
"b_KBJ", "sc", "bKJ", map_crops,
"rlwimiRR~AAA.", map_rlwinm, false, "rlwnmRR~RAA.",
"oriNRR~U", "orisRR~U", "xoriRR~U", "xorisRR~U",
"andi.RR~U", "andis.RR~U", map_rld, map_ext,
"lwzRRD", "lwzuRRD", "lbzRRD", "lbzuRRD",
"stwRRD", "stwuRRD", "stbRRD", "stbuRRD",
"lhzRRD", "lhzuRRD", "lhaRRD", "lhauRRD",
"sthRRD", "sthuRRD", "lmwRRD", "stmwRRD",
"lfsFRD", "lfsuFRD", "lfdFRD", "lfduFRD",
"stfsFRD", "stfsuFRD", "stfdFRD", "stfduFRD",
false, false, map_ld, map_fps,
false, false, map_std, map_fpd,
}
------------------------------------------------------------------------------
local map_gpr = {
[0] = "r0", "sp", "r2", "r3", "r4", "r5", "r6", "r7",
"r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15",
"r16", "r17", "r18", "r19", "r20", "r21", "r22", "r23",
"r24", "r25", "r26", "r27", "r28", "r29", "r30", "r31",
}
local map_cond = { [0] = "lt", "gt", "eq", "so", "ge", "le", "ne", "ns", }
-- Format a condition bit.
local function condfmt(cond)
if cond <= 3 then
return map_cond[band(cond, 3)]
else
return format("4*cr%d+%s", rshift(cond, 2), map_cond[band(cond, 3)])
end
end
------------------------------------------------------------------------------
-- Output a nicely formatted line with an opcode and operands.
local function putop(ctx, text, operands)
local pos = ctx.pos
local extra = ""
if ctx.rel then
local sym = ctx.symtab[ctx.rel]
if sym then extra = "\t->"..sym end
end
if ctx.hexdump > 0 then
ctx.out(format("%08x %s %-7s %s%s\n",
ctx.addr+pos, tohex(ctx.op), text, concat(operands, ", "), extra))
else
ctx.out(format("%08x %-7s %s%s\n",
ctx.addr+pos, text, concat(operands, ", "), extra))
end
ctx.pos = pos + 4
end
-- Fallback for unknown opcodes.
local function unknown(ctx)
return putop(ctx, ".long", { "0x"..tohex(ctx.op) })
end
-- Disassemble a single instruction.
local function disass_ins(ctx)
local pos = ctx.pos
local b0, b1, b2, b3 = byte(ctx.code, pos+1, pos+4)
local op = bor(lshift(b0, 24), lshift(b1, 16), lshift(b2, 8), b3)
local operands = {}
local last = nil
local rs = 21
ctx.op = op
ctx.rel = nil
local opat = map_pri[rshift(b0, 2)]
while type(opat) ~= "string" do
if not opat then return unknown(ctx) end
opat = opat[band(rshift(op, opat.shift), opat.mask)]
end
local name, pat = match(opat, "^([a-z0-9_.]*)(.*)")
local altname, pat2 = match(pat, "|([a-z0-9_.]*)(.*)")
if altname then pat = pat2 end
for p in gmatch(pat, ".") do
local x = nil
if p == "R" then
x = map_gpr[band(rshift(op, rs), 31)]
rs = rs - 5
elseif p == "F" then
x = "f"..band(rshift(op, rs), 31)
rs = rs - 5
elseif p == "A" then
x = band(rshift(op, rs), 31)
rs = rs - 5
elseif p == "S" then
x = arshift(lshift(op, 27-rs), 27)
rs = rs - 5
elseif p == "I" then
x = arshift(lshift(op, 16), 16)
elseif p == "U" then
x = band(op, 0xffff)
elseif p == "D" or p == "E" then
local disp = arshift(lshift(op, 16), 16)
if p == "E" then disp = band(disp, -4) end
if last == "r0" then last = "0" end
operands[#operands] = format("%d(%s)", disp, last)
elseif p >= "2" and p <= "8" then
local disp = band(rshift(op, rs), 31) * p
if last == "r0" then last = "0" end
operands[#operands] = format("%d(%s)", disp, last)
elseif p == "H" then
x = band(rshift(op, rs), 31) + lshift(band(op, 2), 4)
rs = rs - 5
elseif p == "M" then
x = band(rshift(op, rs), 31) + band(op, 0x20)
elseif p == "C" then
x = condfmt(band(rshift(op, rs), 31))
rs = rs - 5
elseif p == "B" then
local bo = rshift(op, 21)
local cond = band(rshift(op, 16), 31)
local cn = ""
rs = rs - 10
if band(bo, 4) == 0 then
cn = band(bo, 2) == 0 and "dnz" or "dz"
if band(bo, 0x10) == 0 then
cn = cn..(band(bo, 8) == 0 and "f" or "t")
end
if band(bo, 0x10) == 0 then x = condfmt(cond) end
name = name..(band(bo, 1) == band(rshift(op, 15), 1) and "-" or "+")
elseif band(bo, 0x10) == 0 then
cn = map_cond[band(cond, 3) + (band(bo, 8) == 0 and 4 or 0)]
if cond > 3 then x = "cr"..rshift(cond, 2) end
name = name..(band(bo, 1) == band(rshift(op, 15), 1) and "-" or "+")
end
name = gsub(name, "_", cn)
elseif p == "J" then
x = arshift(lshift(op, 27-rs), 29-rs)*4
if band(op, 2) == 0 then x = ctx.addr + pos + x end
ctx.rel = x
x = "0x"..tohex(x)
elseif p == "K" then
if band(op, 1) ~= 0 then name = name.."l" end
if band(op, 2) ~= 0 then name = name.."a" end
elseif p == "X" or p == "Y" then
x = band(rshift(op, rs+2), 7)
if x == 0 and p == "Y" then x = nil else x = "cr"..x end
rs = rs - 5
elseif p == "W" then
x = "cr"..band(op, 7)
elseif p == "Z" then
x = band(rshift(op, rs-4), 255)
rs = rs - 10
elseif p == ">" then
operands[#operands] = rshift(operands[#operands], 1)
elseif p == "0" then
if last == "r0" then
operands[#operands] = nil
if altname then name = altname end
end
elseif p == "L" then
name = gsub(name, "_", band(op, 0x00200000) ~= 0 and "d" or "w")
elseif p == "." then
if band(op, 1) == 1 then name = name.."." end
elseif p == "N" then
if op == 0x60000000 then name = "nop"; break end
elseif p == "~" then
local n = #operands
operands[n-1], operands[n] = operands[n], operands[n-1]
elseif p == "=" then
local n = #operands
if last == operands[n-1] then
operands[n] = nil
name = altname
end
elseif p == "%" then
local n = #operands
if last == operands[n-1] and last == operands[n-2] then
operands[n] = nil
operands[n-1] = nil
name = altname
end
elseif p == "-" then
rs = rs - 5
else
assert(false)
end
if x then operands[#operands+1] = x; last = x end
end
return putop(ctx, name, operands)
end
------------------------------------------------------------------------------
-- Disassemble a block of code.
local function disass_block(ctx, ofs, len)
if not ofs then ofs = 0 end
local stop = len and ofs+len or #ctx.code
stop = stop - stop % 4
ctx.pos = ofs - ofs % 4
ctx.rel = nil
while ctx.pos < stop do disass_ins(ctx) end
end
-- Extended API: create a disassembler context. Then call ctx:disass(ofs, len).
local function create(code, addr, out)
local ctx = {}
ctx.code = code
ctx.addr = addr or 0
ctx.out = out or io.write
ctx.symtab = {}
ctx.disass = disass_block
ctx.hexdump = 8
return ctx
end
-- Simple API: disassemble code (a string) at address and output via out.
local function disass(code, addr, out)
create(code, addr, out):disass()
end
-- Return register name for RID.
local function regname(r)
if r < 32 then return map_gpr[r] end
return "f"..(r-32)
end
-- Public module functions.
return {
create = create,
disass = disass,
regname = regname
}
| mit |
tjormola/tj-awesome-themes | Radiance-Flat-Green/theme.lua | 1 | 15929 | -- Radiance-Flat-Green theme for Awesome 3.5
-- Copyright (C) 2016 Tuomas Jormola <tj@solitudo.net>
--
-- Licensed under the terms of GNU General Public License Version 2.0.
--
-- Designed to be used with Radiance-Flat-Green GTK+ theme available at
-- http://www.ravefinity.com/p/our-themes-work.html.
-- freedesktop.org module for Awesome is required for the icon support.
--
-- Theme also uses Inconsolata font. On Ubuntu system this font
-- is available in the package fonts-inconsolata.
local awful = require('awful')
local freedesktop = { utils = require('freedesktop.utils') }
local theme = {}
-- Icon theme and font
freedesktop.utils.icon_theme = 'Adwaita'
theme.icon_theme = freedesktop.utils.icon_theme
theme.font = 'Inconsolata Medium 12'
theme.monospace_font = theme.font
-- Colors
theme.bg_focus = '#6aa022'
theme.bg_normal = '#e8e8e8'
theme.bg_urgent = '#4e9a06'
theme.bg_minimize = '#4c4c4c'
theme.bg_systray = theme.bg_normal
theme.fg_normal = '#4c4c4c'
theme.fg_focus = '#ffffff'
theme.fg_urgent = theme.fg_focus
theme.fg_minimize = '#dfdfdf'
theme.border_normal = '#000000'
theme.border_focus = theme.bg_focus
theme.border_marked = theme.bg_urgent
theme.bg_widget = theme.bg_normal
theme.fg_widget = '#4c4c4c'
theme.fg_center_widget = '#3c3c3c'
theme.fg_end_widget = '#000000'
theme.tooltip_bg_color = '#000000'
theme.tooltip_fg_color = '#ffffff'
-- Misc. settings
theme.wallpaper_cmd = { 'xsetroot -solid \\#40659f' }
theme.taglist_squares = 'true'
theme.titlebar_close_button = 'true'
theme.border_width = '1'
theme.menu_height = '16'
theme.menu_width = '250'
-- Use default images for layout, tasklist, taglist and menu submenus
theme.layout_fairh = '/usr/share/awesome/themes/default/layouts/fairh.png'
theme.layout_fairv = '/usr/share/awesome/themes/default/layouts/fairv.png'
theme.layout_floating = '/usr/share/awesome/themes/default/layouts/floating.png'
theme.layout_magnifier = '/usr/share/awesome/themes/default/layouts/magnifier.png'
theme.layout_max = '/usr/share/awesome/themes/default/layouts/max.png'
theme.layout_fullscreen = '/usr/share/awesome/themes/default/layouts/fullscreen.png'
theme.layout_tilebottom = '/usr/share/awesome/themes/default/layouts/tilebottom.png'
theme.layout_tileleft = '/usr/share/awesome/themes/default/layouts/tileleft.png'
theme.layout_tile = '/usr/share/awesome/themes/default/layouts/tile.png'
theme.layout_tiletop = '/usr/share/awesome/themes/default/layouts/tiletop.png'
theme.layout_spiral = '/usr/share/awesome/themes/default/layouts/spiral.png'
theme.layout_dwindle = '/usr/share/awesome/themes/default/layouts/dwindle.png'
theme.taglist_squares_sel = '/usr/share/awesome/themes/default/taglist/squarefw.png'
theme.taglist_squares_unsel = '/usr/share/awesome/themes/default/taglist/squarew.png'
theme.tasklist_floating_icon = '/usr/share/awesome/themes/default/layouts/floating.png'
theme.menu_submenu_icon = '/usr/share/awesome/themes/default/submenu.png'
-- Awesome icon
theme.awesome_icon = '/usr/share/awesome/icons/awesome16.png'
-- Titlebar images
theme.titlebar_close_button_normal = '/usr/share/awesome/themes/default/titlebar/close_normal.png'
theme.titlebar_close_button_focus = '/usr/share/awesome/themes/default/titlebar/close_focus.png'
theme.titlebar_ontop_button_normal_inactive = '/usr/share/awesome/themes/default/titlebar/ontop_normal_inactive.png'
theme.titlebar_ontop_button_focus_inactive = '/usr/share/awesome/themes/default/titlebar/ontop_focus_inactive.png'
theme.titlebar_ontop_button_normal_active = '/usr/share/awesome/themes/default/titlebar/ontop_normal_active.png'
theme.titlebar_ontop_button_focus_active = '/usr/share/awesome/themes/default/titlebar/ontop_focus_active.png'
theme.titlebar_sticky_button_normal_inactive = '/usr/share/awesome/themes/default/titlebar/sticky_normal_inactive.png'
theme.titlebar_sticky_button_focus_inactive = '/usr/share/awesome/themes/default/titlebar/sticky_focus_inactive.png'
theme.titlebar_sticky_button_normal_active = '/usr/share/awesome/themes/default/titlebar/sticky_normal_active.png'
theme.titlebar_sticky_button_focus_active = '/usr/share/awesome/themes/default/titlebar/sticky_focus_active.png'
theme.titlebar_floating_button_normal_inactive = '/usr/share/awesome/themes/default/titlebar/floating_normal_inactive.png'
theme.titlebar_floating_button_focus_inactive = '/usr/share/awesome/themes/default/titlebar/floating_focus_inactive.png'
theme.titlebar_floating_button_normal_active = '/usr/share/awesome/themes/default/titlebar/floating_normal_active.png'
theme.titlebar_floating_button_focus_active = '/usr/share/awesome/themes/default/titlebar/floating_focus_active.png'
theme.titlebar_maximized_button_normal_inactive = '/usr/share/awesome/themes/default/titlebar/maximized_normal_inactive.png'
theme.titlebar_maximized_button_focus_inactive = '/usr/share/awesome/themes/default/titlebar/maximized_focus_inactive.png'
theme.titlebar_maximized_button_normal_active = '/usr/share/awesome/themes/default/titlebar/maximized_normal_active.png'
theme.titlebar_maximized_button_focus_active = '/usr/share/awesome/themes/default/titlebar/maximized_focus_active.png'
-- Delightful Widget icons
theme.delightful_weather_clear = '/usr/share/icons/mate/16x16/status/weather-clear.png'
theme.delightful_weather_clear_night = '/usr/share/icons/mate/16x16/status/weather-clear-night.png'
theme.delightful_weather_clear_night_000 = '/usr/share/icons/mate/16x16/status/weather-clear-night-000.png'
theme.delightful_weather_clear_night_010 = '/usr/share/icons/mate/16x16/status/weather-clear-night-010.png'
theme.delightful_weather_clear_night_020 = '/usr/share/icons/mate/16x16/status/weather-clear-night-020.png'
theme.delightful_weather_clear_night_030 = '/usr/share/icons/mate/16x16/status/weather-clear-night-030.png'
theme.delightful_weather_clear_night_040 = '/usr/share/icons/mate/16x16/status/weather-clear-night-040.png'
theme.delightful_weather_clear_night_050 = '/usr/share/icons/mate/16x16/status/weather-clear-night-050.png'
theme.delightful_weather_clear_night_060 = '/usr/share/icons/mate/16x16/status/weather-clear-night-060.png'
theme.delightful_weather_clear_night_070 = '/usr/share/icons/mate/16x16/status/weather-clear-night-070.png'
theme.delightful_weather_clear_night_080 = '/usr/share/icons/mate/16x16/status/weather-clear-night-080.png'
theme.delightful_weather_clear_night_090 = '/usr/share/icons/mate/16x16/status/weather-clear-night-090.png'
theme.delightful_weather_clear_night_100 = '/usr/share/icons/mate/16x16/status/weather-clear-night-100.png'
theme.delightful_weather_clear_night_110 = '/usr/share/icons/mate/16x16/status/weather-clear-night-110.png'
theme.delightful_weather_clear_night_120 = '/usr/share/icons/mate/16x16/status/weather-clear-night-120.png'
theme.delightful_weather_clear_night_130 = '/usr/share/icons/mate/16x16/status/weather-clear-night-130.png'
theme.delightful_weather_clear_night_140 = '/usr/share/icons/mate/16x16/status/weather-clear-night-140.png'
theme.delightful_weather_clear_night_150 = '/usr/share/icons/mate/16x16/status/weather-clear-night-150.png'
theme.delightful_weather_clear_night_160 = '/usr/share/icons/mate/16x16/status/weather-clear-night-160.png'
theme.delightful_weather_clear_night_170 = '/usr/share/icons/mate/16x16/status/weather-clear-night-170.png'
theme.delightful_weather_clear_night_190 = '/usr/share/icons/mate/16x16/status/weather-clear-night-190.png'
theme.delightful_weather_clear_night_200 = '/usr/share/icons/mate/16x16/status/weather-clear-night-200.png'
theme.delightful_weather_clear_night_210 = '/usr/share/icons/mate/16x16/status/weather-clear-night-210.png'
theme.delightful_weather_clear_night_220 = '/usr/share/icons/mate/16x16/status/weather-clear-night-220.png'
theme.delightful_weather_clear_night_230 = '/usr/share/icons/mate/16x16/status/weather-clear-night-230.png'
theme.delightful_weather_clear_night_240 = '/usr/share/icons/mate/16x16/status/weather-clear-night-240.png'
theme.delightful_weather_clear_night_250 = '/usr/share/icons/mate/16x16/status/weather-clear-night-250.png'
theme.delightful_weather_clear_night_260 = '/usr/share/icons/mate/16x16/status/weather-clear-night-260.png'
theme.delightful_weather_clear_night_270 = '/usr/share/icons/mate/16x16/status/weather-clear-night-270.png'
theme.delightful_weather_clear_night_280 = '/usr/share/icons/mate/16x16/status/weather-clear-night-280.png'
theme.delightful_weather_clear_night_290 = '/usr/share/icons/mate/16x16/status/weather-clear-night-290.png'
theme.delightful_weather_clear_night_300 = '/usr/share/icons/mate/16x16/status/weather-clear-night-300.png'
theme.delightful_weather_clear_night_310 = '/usr/share/icons/mate/16x16/status/weather-clear-night-310.png'
theme.delightful_weather_clear_night_320 = '/usr/share/icons/mate/16x16/status/weather-clear-night-320.png'
theme.delightful_weather_clear_night_330 = '/usr/share/icons/mate/16x16/status/weather-clear-night-330.png'
theme.delightful_weather_clear_night_340 = '/usr/share/icons/mate/16x16/status/weather-clear-night-340.png'
theme.delightful_weather_clear_night_350 = '/usr/share/icons/mate/16x16/status/weather-clear-night-350.png'
theme.delightful_weather_few_clouds = '/usr/share/icons/mate/16x16/status/weather-few-clouds.png'
theme.delightful_weather_few_clouds_night = '/usr/share/icons/mate/16x16/status/weather-few-clouds-night.png'
theme.delightful_weather_few_clouds_night_000 = '/usr/share/icons/mate/16x16/status/weather-few-clouds-night-000.png'
theme.delightful_weather_few_clouds_night_010 = '/usr/share/icons/mate/16x16/status/weather-few-clouds-night-010.png'
theme.delightful_weather_few_clouds_night_020 = '/usr/share/icons/mate/16x16/status/weather-few-clouds-night-020.png'
theme.delightful_weather_few_clouds_night_030 = '/usr/share/icons/mate/16x16/status/weather-few-clouds-night-030.png'
theme.delightful_weather_few_clouds_night_040 = '/usr/share/icons/mate/16x16/status/weather-few-clouds-night-040.png'
theme.delightful_weather_few_clouds_night_050 = '/usr/share/icons/mate/16x16/status/weather-few-clouds-night-050.png'
theme.delightful_weather_few_clouds_night_060 = '/usr/share/icons/mate/16x16/status/weather-few-clouds-night-060.png'
theme.delightful_weather_few_clouds_night_070 = '/usr/share/icons/mate/16x16/status/weather-few-clouds-night-070.png'
theme.delightful_weather_few_clouds_night_080 = '/usr/share/icons/mate/16x16/status/weather-few-clouds-night-080.png'
theme.delightful_weather_few_clouds_night_090 = '/usr/share/icons/mate/16x16/status/weather-few-clouds-night-090.png'
theme.delightful_weather_few_clouds_night_100 = '/usr/share/icons/mate/16x16/status/weather-few-clouds-night-100.png'
theme.delightful_weather_few_clouds_night_110 = '/usr/share/icons/mate/16x16/status/weather-few-clouds-night-110.png'
theme.delightful_weather_few_clouds_night_120 = '/usr/share/icons/mate/16x16/status/weather-few-clouds-night-120.png'
theme.delightful_weather_few_clouds_night_130 = '/usr/share/icons/mate/16x16/status/weather-few-clouds-night-130.png'
theme.delightful_weather_few_clouds_night_140 = '/usr/share/icons/mate/16x16/status/weather-few-clouds-night-140.png'
theme.delightful_weather_few_clouds_night_150 = '/usr/share/icons/mate/16x16/status/weather-few-clouds-night-150.png'
theme.delightful_weather_few_clouds_night_160 = '/usr/share/icons/mate/16x16/status/weather-few-clouds-night-160.png'
theme.delightful_weather_few_clouds_night_170 = '/usr/share/icons/mate/16x16/status/weather-few-clouds-night-170.png'
theme.delightful_weather_few_clouds_night_190 = '/usr/share/icons/mate/16x16/status/weather-few-clouds-night-190.png'
theme.delightful_weather_few_clouds_night_200 = '/usr/share/icons/mate/16x16/status/weather-few-clouds-night-200.png'
theme.delightful_weather_few_clouds_night_210 = '/usr/share/icons/mate/16x16/status/weather-few-clouds-night-210.png'
theme.delightful_weather_few_clouds_night_220 = '/usr/share/icons/mate/16x16/status/weather-few-clouds-night-220.png'
theme.delightful_weather_few_clouds_night_230 = '/usr/share/icons/mate/16x16/status/weather-few-clouds-night-230.png'
theme.delightful_weather_few_clouds_night_240 = '/usr/share/icons/mate/16x16/status/weather-few-clouds-night-240.png'
theme.delightful_weather_few_clouds_night_250 = '/usr/share/icons/mate/16x16/status/weather-few-clouds-night-250.png'
theme.delightful_weather_few_clouds_night_260 = '/usr/share/icons/mate/16x16/status/weather-few-clouds-night-260.png'
theme.delightful_weather_few_clouds_night_270 = '/usr/share/icons/mate/16x16/status/weather-few-clouds-night-270.png'
theme.delightful_weather_few_clouds_night_280 = '/usr/share/icons/mate/16x16/status/weather-few-clouds-night-280.png'
theme.delightful_weather_few_clouds_night_290 = '/usr/share/icons/mate/16x16/status/weather-few-clouds-night-290.png'
theme.delightful_weather_few_clouds_night_300 = '/usr/share/icons/mate/16x16/status/weather-few-clouds-night-300.png'
theme.delightful_weather_few_clouds_night_310 = '/usr/share/icons/mate/16x16/status/weather-few-clouds-night-310.png'
theme.delightful_weather_few_clouds_night_320 = '/usr/share/icons/mate/16x16/status/weather-few-clouds-night-320.png'
theme.delightful_weather_few_clouds_night_330 = '/usr/share/icons/mate/16x16/status/weather-few-clouds-night-330.png'
theme.delightful_weather_few_clouds_night_340 = '/usr/share/icons/mate/16x16/status/weather-few-clouds-night-340.png'
theme.delightful_weather_few_clouds_night_350 = '/usr/share/icons/mate/16x16/status/weather-few-clouds-night-350.png'
theme.delightful_weather_fog = '/usr/share/icons/mate/16x16/status/weather-fog.png'
theme.delightful_weather_overcast = '/usr/share/icons/mate/16x16/status/weather-overcast.png'
theme.delightful_weather_showers = '/usr/share/icons/mate/16x16/status/weather-showers.png'
theme.delightful_weather_scattered_showers = '/usr/share/icons/mate/16x16/status/weather-showers-scattered.png'
theme.delightful_weather_snow = '/usr/share/icons/mate/16x16/status/weather-snow.png'
theme.delightful_weather_strom = '/usr/share/icons/mate/16x16/status/weather-storm.png'
theme.delightful_weather_alert = '/usr/share/icons/mate/16x16/status/weather-severe-alert.png'
return theme
| gpl-2.0 |
bryancall/trafficserver | plugins/lua/ci/module_test.lua | 17 | 2097 | -- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you under the Apache License, Version 2.0 (the
-- "License"); you may not use this file except in compliance
-- with the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
_G.ts = { http = {}, client_request = {}, ctx = {} }
_G.TS_LUA_HOOK_TXN_CLOSE = 4
_G.TS_LUA_REMAP_DID_REMAP = 1
describe("Busted unit testing framework", function()
describe("script for ATS Lua Plugin", function()
it("test - module.split", function()
local module = require("module")
local results = module.split('a,b,c', ',')
assert.are.equals('a', results[1])
assert.are.equals('b', results[2])
end)
it("test - module.set_hook", function()
stub(ts, "hook")
local module = require("module")
module.set_hook()
assert.stub(ts.hook).was.called_with(TS_LUA_HOOK_TXN_CLOSE, module.test)
end)
it("test - module.set_context", function()
local module = require("module")
module.set_context()
assert.are.equals('test10', ts.ctx['test'])
end)
it("test - module.check_internal", function()
stub(ts.http, "is_internal_request").returns(0)
local module = require("module")
local result = module.check_internal()
assert.are.equals(0, result)
end)
it("test - module.return_constant", function()
local module = require("module")
local result = module.return_constant()
assert.are.equals(TS_LUA_REMAP_DID_REMAP, result)
end)
end)
end)
| apache-2.0 |
mercury233/ygopro-scripts | c21368442.lua | 2 | 1727 | --S-Force グラビティーノ
function c21368442.initial_effect(c)
--to hand
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(21368442,0))
e1:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetCode(EVENT_SUMMON_SUCCESS)
e1:SetProperty(EFFECT_FLAG_DELAY)
e1:SetCountLimit(1,21368442)
e1:SetTarget(c21368442.thtg)
e1:SetOperation(c21368442.thop)
c:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetCode(EVENT_SPSUMMON_SUCCESS)
c:RegisterEffect(e2)
--redirect
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_FIELD)
e3:SetProperty(EFFECT_FLAG_SET_AVAILABLE+EFFECT_FLAG_IGNORE_IMMUNE)
e3:SetCode(EFFECT_LEAVE_FIELD_REDIRECT)
e3:SetRange(LOCATION_MZONE)
e3:SetTargetRange(0,LOCATION_MZONE)
e3:SetTarget(c21368442.rmtg)
e3:SetValue(LOCATION_REMOVED)
c:RegisterEffect(e3)
end
function c21368442.thfilter(c)
return c:IsSetCard(0x156) and not c:IsCode(21368442) and c:IsAbleToHand()
end
function c21368442.thtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c21368442.thfilter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function c21368442.thop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,c21368442.thfilter,tp,LOCATION_DECK,0,1,1,nil)
if #g>0 then
Duel.SendtoHand(g,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g)
end
end
function c21368442.rmfilter(c,tp)
return c:IsFaceup() and c:IsSetCard(0x156) and c:IsLocation(LOCATION_MZONE) and c:IsControler(tp)
end
function c21368442.rmtg(e,c)
local cg=c:GetColumnGroup()
return cg:IsExists(c21368442.rmfilter,1,nil,e:GetHandlerPlayer())
end
| gpl-2.0 |
mercury233/ygopro-scripts | c20292186.lua | 9 | 1915 | --アーティファクト-デスサイズ
function c20292186.initial_effect(c)
--set
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_MONSTER_SSET)
e1:SetValue(TYPE_SPELL)
c:RegisterEffect(e1)
--spsummon
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(20292186,0))
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e2:SetCode(EVENT_TO_GRAVE)
e2:SetCondition(c20292186.spcon)
e2:SetTarget(c20292186.sptg)
e2:SetOperation(c20292186.spop)
c:RegisterEffect(e2)
--cannot spsummon
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(20292186,1))
e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e3:SetCode(EVENT_SPSUMMON_SUCCESS)
e3:SetCondition(c20292186.dcon)
e3:SetOperation(c20292186.dop)
c:RegisterEffect(e3)
end
function c20292186.spcon(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
return c:IsPreviousLocation(LOCATION_SZONE) and c:IsPreviousPosition(POS_FACEDOWN)
and c:IsReason(REASON_DESTROY) and Duel.GetTurnPlayer()~=tp
end
function c20292186.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0)
end
function c20292186.spop(e,tp,eg,ep,ev,re,r,rp)
if e:GetHandler():IsRelateToEffect(e) then
Duel.SpecialSummon(e:GetHandler(),0,tp,tp,false,false,POS_FACEUP)
end
end
function c20292186.dcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetTurnPlayer()~=tp
end
function c20292186.dop(e,tp,eg,ep,ev,re,r,rp)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON)
e1:SetReset(RESET_PHASE+PHASE_END)
e1:SetTargetRange(0,1)
e1:SetTarget(c20292186.sumlimit)
Duel.RegisterEffect(e1,tp)
end
function c20292186.sumlimit(e,c,sump,sumtype,sumpos,targetp,se)
return c:IsLocation(LOCATION_EXTRA)
end
| gpl-2.0 |
mercury233/ygopro-scripts | c88989706.lua | 2 | 3089 | --大神官デ・ザード
function c88989706.initial_effect(c)
--check
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS)
e1:SetCode(EVENT_BATTLE_DESTROYING)
e1:SetOperation(c88989706.regop)
c:RegisterEffect(e1)
--negate
local e2=Effect.CreateEffect(c)
e2:SetCategory(CATEGORY_DESTROY+CATEGORY_NEGATE)
e2:SetType(EFFECT_TYPE_QUICK_F)
e2:SetCode(EVENT_CHAINING)
e2:SetRange(LOCATION_MZONE)
e2:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DAMAGE_CAL)
e2:SetCondition(c88989706.discon)
e2:SetTarget(c88989706.distg)
e2:SetOperation(c88989706.disop)
c:RegisterEffect(e2)
--special summon
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(88989706,0))
e3:SetCategory(CATEGORY_SPECIAL_SUMMON+CATEGORY_DECKDES)
e3:SetType(EFFECT_TYPE_IGNITION)
e3:SetRange(LOCATION_MZONE)
e3:SetCondition(c88989706.spcon)
e3:SetCost(c88989706.spcost)
e3:SetTarget(c88989706.sptg)
e3:SetOperation(c88989706.spop)
c:RegisterEffect(e3)
end
function c88989706.regop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToBattle() then
c:RegisterFlagEffect(88989707,RESET_EVENT+RESETS_STANDARD,0,0)
end
end
function c88989706.discon(e,tp,eg,ep,ev,re,r,rp)
if e:GetHandler():GetFlagEffect(88989707)==0 then return false end
if not re:IsHasProperty(EFFECT_FLAG_CARD_TARGET) then return false end
local tg=Duel.GetChainInfo(ev,CHAININFO_TARGET_CARDS)
if not tg or not tg:IsContains(e:GetHandler()) then return false end
return re:IsHasType(EFFECT_TYPE_ACTIVATE)
end
function c88989706.distg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_NEGATE,eg,1,0,0)
if re:GetHandler():IsDestructable() and re:GetHandler():IsRelateToEffect(re) then
Duel.SetOperationInfo(0,CATEGORY_DESTROY,eg,1,0,0)
end
end
function c88989706.disop(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetCurrentChain()~=ev+1 then return end
if Duel.NegateActivation(ev) and re:GetHandler():IsRelateToEffect(re) then
Duel.Destroy(eg,REASON_EFFECT)
end
end
function c88989706.spcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetFlagEffect(88989707)>=2
end
function c88989706.spcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsReleasable() end
Duel.Release(e:GetHandler(),REASON_COST)
end
function c88989706.filter(c,e,tp)
return c:IsCode(39711336) and c:IsCanBeSpecialSummoned(e,0,tp,true,false)
end
function c88989706.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>-1
and Duel.IsExistingMatchingCard(c88989706.filter,tp,LOCATION_DECK+LOCATION_HAND,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK+LOCATION_HAND)
end
function c88989706.spop(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c88989706.filter,tp,LOCATION_DECK+LOCATION_HAND,0,1,1,nil,e,tp)
if g:GetCount()>0 and Duel.SpecialSummon(g,0,tp,tp,true,false,POS_FACEUP)>0 then
g:GetFirst():CompleteProcedure()
end
end
| gpl-2.0 |
Firew0lf/ctruLua | sdcard/3ds/ctruLua/examples/example.lua | 2 | 1925 | local gfx = require("ctr.gfx")
local hid = require("ctr.hid")
local ctr = require("ctr")
local x = 50
local y = 50
local dMul = 1
local angle = 0
local texture1 = gfx.texture.load(ctr.root.."icon.png");
if not texture1 then error("Giants ducks came from another planet") end
local tWidth, tHeight = texture1:getSize()
gfx.color.setBackground(gfx.color.RGBA8(200, 200, 200))
gfx.set3D(true)
-- eye : -1 = left, 1 = right
local function drawStuffIn3D(eye)
gfx.text(2, 5, "Depth multiplicator: "..dMul)
-- 3D stuff
local function d(depth) return math.ceil(eye * depth * dMul) end
gfx.color.setDefault(0xFFFFFF00)
gfx.rectangle(240 + d(10), 150, 120, 10)
gfx.point(10 + d(6), 20, 0xFF0000FF)
gfx.color.setDefault(0xFF0000FF)
gfx.rectangle(x + d(10*math.sin(ctr.time()/500)), y, 20, 20, angle)
gfx.line(50 + d(-6), 50, 75 + d(4), 96, 1, gfx.color.RGBA8(52, 10, 65))
gfx.circle(125 + d(-8), 125, 16)
end
while ctr.run() do
hid.read()
local keys = hid.keys()
if keys.down.start then return end
if keys.held.right then x = x + 1 end
if keys.held.left then x = x - 1 end
if keys.held.up then y = y - 1 end
if keys.held.down then y = y + 1 end
dMul = hid.pos3d()
gfx.start(gfx.TOP, gfx.LEFT)
drawStuffIn3D(-1)
gfx.stop()
gfx.start(gfx.TOP, gfx.RIGHT)
drawStuffIn3D(1)
gfx.stop()
gfx.start(gfx.BOTTOM)
gfx.color.setDefault(gfx.color.RGBA8(0, 0, 0))
gfx.text(5, 5, "FPS: "..math.ceil(gfx.getFPS()))
gfx.text(5, 17, "Hello world, from Lua ! éàçù", 20, gfx.color.RGBA8(0, 0, 0))
gfx.text(5, 50, "Time: "..os.date())
texture1:draw(280, 80, angle, tWidth/2, tHeight/2);
local cx, cy = hid.circle()
gfx.rectangle(40, 90, 60, 60, 0, 0xDDDDDDFF)
gfx.circle(70 + math.ceil(cx/156 * 30), 120 - math.ceil(cy/156 * 30), 10, 0xFF000000)
gfx.stop()
angle = angle + 0.05
if angle > 2*math.pi then angle = angle - 2*math.pi end
gfx.render()
end
texture1:unload()
| gpl-3.0 |
mynameiscraziu/carlos | plugins/rss.lua | 700 | 5434 | local function get_base_redis(id, option, extra)
local ex = ''
if option ~= nil then
ex = ex .. ':' .. option
if extra ~= nil then
ex = ex .. ':' .. extra
end
end
return 'rss:' .. id .. ex
end
local function prot_url(url)
local url, h = string.gsub(url, "http://", "")
local url, hs = string.gsub(url, "https://", "")
local protocol = "http"
if hs == 1 then
protocol = "https"
end
return url, protocol
end
local function get_rss(url, prot)
local res, code = nil, 0
if prot == "http" then
res, code = http.request(url)
elseif prot == "https" then
res, code = https.request(url)
end
if code ~= 200 then
return nil, "Error while doing the petition to " .. url
end
local parsed = feedparser.parse(res)
if parsed == nil then
return nil, "Error decoding the RSS.\nAre you sure that " .. url .. " it's a RSS?"
end
return parsed, nil
end
local function get_new_entries(last, nentries)
local entries = {}
for k,v in pairs(nentries) do
if v.id == last then
return entries
else
table.insert(entries, v)
end
end
return entries
end
local function print_subs(id)
local uhash = get_base_redis(id)
local subs = redis:smembers(uhash)
local text = id .. ' are subscribed to:\n---------\n'
for k,v in pairs(subs) do
text = text .. k .. ") " .. v .. '\n'
end
return text
end
local function subscribe(id, url)
local baseurl, protocol = prot_url(url)
local prothash = get_base_redis(baseurl, "protocol")
local lasthash = get_base_redis(baseurl, "last_entry")
local lhash = get_base_redis(baseurl, "subs")
local uhash = get_base_redis(id)
if redis:sismember(uhash, baseurl) then
return "You are already subscribed to " .. url
end
local parsed, err = get_rss(url, protocol)
if err ~= nil then
return err
end
local last_entry = ""
if #parsed.entries > 0 then
last_entry = parsed.entries[1].id
end
local name = parsed.feed.title
redis:set(prothash, protocol)
redis:set(lasthash, last_entry)
redis:sadd(lhash, id)
redis:sadd(uhash, baseurl)
return "You had been subscribed to " .. name
end
local function unsubscribe(id, n)
if #n > 3 then
return "I don't think that you have that many subscriptions."
end
n = tonumber(n)
local uhash = get_base_redis(id)
local subs = redis:smembers(uhash)
if n < 1 or n > #subs then
return "Subscription id out of range!"
end
local sub = subs[n]
local lhash = get_base_redis(sub, "subs")
redis:srem(uhash, sub)
redis:srem(lhash, id)
local left = redis:smembers(lhash)
if #left < 1 then -- no one subscribed, remove it
local prothash = get_base_redis(sub, "protocol")
local lasthash = get_base_redis(sub, "last_entry")
redis:del(prothash)
redis:del(lasthash)
end
return "You had been unsubscribed from " .. sub
end
local function cron()
-- sync every 15 mins?
local keys = redis:keys(get_base_redis("*", "subs"))
for k,v in pairs(keys) do
local base = string.match(v, "rss:(.+):subs") -- Get the URL base
local prot = redis:get(get_base_redis(base, "protocol"))
local last = redis:get(get_base_redis(base, "last_entry"))
local url = prot .. "://" .. base
local parsed, err = get_rss(url, prot)
if err ~= nil then
return
end
local newentr = get_new_entries(last, parsed.entries)
local subscribers = {}
local text = '' -- Send only one message with all updates
for k2, v2 in pairs(newentr) do
local title = v2.title or 'No title'
local link = v2.link or v2.id or 'No Link'
text = text .. "[rss](" .. link .. ") - " .. title .. '\n'
end
if text ~= '' then
local newlast = newentr[1].id
redis:set(get_base_redis(base, "last_entry"), newlast)
for k2, receiver in pairs(redis:smembers(v)) do
send_msg(receiver, text, ok_cb, false)
end
end
end
end
local function run(msg, matches)
local id = "user#id" .. msg.from.id
if is_chat_msg(msg) then
id = "chat#id" .. msg.to.id
end
if matches[1] == "!rss"then
return print_subs(id)
end
if matches[1] == "sync" then
if not is_sudo(msg) then
return "Only sudo users can sync the RSS."
end
cron()
end
if matches[1] == "subscribe" or matches[1] == "sub" then
return subscribe(id, matches[2])
end
if matches[1] == "unsubscribe" or matches[1] == "uns" then
return unsubscribe(id, matches[2])
end
end
return {
description = "Manage User/Chat RSS subscriptions. If you are in a chat group, the RSS subscriptions will be of that chat. If you are in an one-to-one talk with the bot, the RSS subscriptions will be yours.",
usage = {
"!rss: Get your rss (or chat rss) subscriptions",
"!rss subscribe (url): Subscribe to that url",
"!rss unsubscribe (id): Unsubscribe of that id",
"!rss sync: Download now the updates and send it. Only sudo users can use this option."
},
patterns = {
"^!rss$",
"^!rss (subscribe) (https?://[%w-_%.%?%.:/%+=&]+)$",
"^!rss (sub) (https?://[%w-_%.%?%.:/%+=&]+)$",
"^!rss (unsubscribe) (%d+)$",
"^!rss (uns) (%d+)$",
"^!rss (sync)$"
},
run = run,
cron = cron
}
| gpl-2.0 |
focusworld/telemamal | plugins/rss.lua | 700 | 5434 | local function get_base_redis(id, option, extra)
local ex = ''
if option ~= nil then
ex = ex .. ':' .. option
if extra ~= nil then
ex = ex .. ':' .. extra
end
end
return 'rss:' .. id .. ex
end
local function prot_url(url)
local url, h = string.gsub(url, "http://", "")
local url, hs = string.gsub(url, "https://", "")
local protocol = "http"
if hs == 1 then
protocol = "https"
end
return url, protocol
end
local function get_rss(url, prot)
local res, code = nil, 0
if prot == "http" then
res, code = http.request(url)
elseif prot == "https" then
res, code = https.request(url)
end
if code ~= 200 then
return nil, "Error while doing the petition to " .. url
end
local parsed = feedparser.parse(res)
if parsed == nil then
return nil, "Error decoding the RSS.\nAre you sure that " .. url .. " it's a RSS?"
end
return parsed, nil
end
local function get_new_entries(last, nentries)
local entries = {}
for k,v in pairs(nentries) do
if v.id == last then
return entries
else
table.insert(entries, v)
end
end
return entries
end
local function print_subs(id)
local uhash = get_base_redis(id)
local subs = redis:smembers(uhash)
local text = id .. ' are subscribed to:\n---------\n'
for k,v in pairs(subs) do
text = text .. k .. ") " .. v .. '\n'
end
return text
end
local function subscribe(id, url)
local baseurl, protocol = prot_url(url)
local prothash = get_base_redis(baseurl, "protocol")
local lasthash = get_base_redis(baseurl, "last_entry")
local lhash = get_base_redis(baseurl, "subs")
local uhash = get_base_redis(id)
if redis:sismember(uhash, baseurl) then
return "You are already subscribed to " .. url
end
local parsed, err = get_rss(url, protocol)
if err ~= nil then
return err
end
local last_entry = ""
if #parsed.entries > 0 then
last_entry = parsed.entries[1].id
end
local name = parsed.feed.title
redis:set(prothash, protocol)
redis:set(lasthash, last_entry)
redis:sadd(lhash, id)
redis:sadd(uhash, baseurl)
return "You had been subscribed to " .. name
end
local function unsubscribe(id, n)
if #n > 3 then
return "I don't think that you have that many subscriptions."
end
n = tonumber(n)
local uhash = get_base_redis(id)
local subs = redis:smembers(uhash)
if n < 1 or n > #subs then
return "Subscription id out of range!"
end
local sub = subs[n]
local lhash = get_base_redis(sub, "subs")
redis:srem(uhash, sub)
redis:srem(lhash, id)
local left = redis:smembers(lhash)
if #left < 1 then -- no one subscribed, remove it
local prothash = get_base_redis(sub, "protocol")
local lasthash = get_base_redis(sub, "last_entry")
redis:del(prothash)
redis:del(lasthash)
end
return "You had been unsubscribed from " .. sub
end
local function cron()
-- sync every 15 mins?
local keys = redis:keys(get_base_redis("*", "subs"))
for k,v in pairs(keys) do
local base = string.match(v, "rss:(.+):subs") -- Get the URL base
local prot = redis:get(get_base_redis(base, "protocol"))
local last = redis:get(get_base_redis(base, "last_entry"))
local url = prot .. "://" .. base
local parsed, err = get_rss(url, prot)
if err ~= nil then
return
end
local newentr = get_new_entries(last, parsed.entries)
local subscribers = {}
local text = '' -- Send only one message with all updates
for k2, v2 in pairs(newentr) do
local title = v2.title or 'No title'
local link = v2.link or v2.id or 'No Link'
text = text .. "[rss](" .. link .. ") - " .. title .. '\n'
end
if text ~= '' then
local newlast = newentr[1].id
redis:set(get_base_redis(base, "last_entry"), newlast)
for k2, receiver in pairs(redis:smembers(v)) do
send_msg(receiver, text, ok_cb, false)
end
end
end
end
local function run(msg, matches)
local id = "user#id" .. msg.from.id
if is_chat_msg(msg) then
id = "chat#id" .. msg.to.id
end
if matches[1] == "!rss"then
return print_subs(id)
end
if matches[1] == "sync" then
if not is_sudo(msg) then
return "Only sudo users can sync the RSS."
end
cron()
end
if matches[1] == "subscribe" or matches[1] == "sub" then
return subscribe(id, matches[2])
end
if matches[1] == "unsubscribe" or matches[1] == "uns" then
return unsubscribe(id, matches[2])
end
end
return {
description = "Manage User/Chat RSS subscriptions. If you are in a chat group, the RSS subscriptions will be of that chat. If you are in an one-to-one talk with the bot, the RSS subscriptions will be yours.",
usage = {
"!rss: Get your rss (or chat rss) subscriptions",
"!rss subscribe (url): Subscribe to that url",
"!rss unsubscribe (id): Unsubscribe of that id",
"!rss sync: Download now the updates and send it. Only sudo users can use this option."
},
patterns = {
"^!rss$",
"^!rss (subscribe) (https?://[%w-_%.%?%.:/%+=&]+)$",
"^!rss (sub) (https?://[%w-_%.%?%.:/%+=&]+)$",
"^!rss (unsubscribe) (%d+)$",
"^!rss (uns) (%d+)$",
"^!rss (sync)$"
},
run = run,
cron = cron
}
| gpl-2.0 |
alfred-bot/mer2phm | plugins/rss.lua | 700 | 5434 | local function get_base_redis(id, option, extra)
local ex = ''
if option ~= nil then
ex = ex .. ':' .. option
if extra ~= nil then
ex = ex .. ':' .. extra
end
end
return 'rss:' .. id .. ex
end
local function prot_url(url)
local url, h = string.gsub(url, "http://", "")
local url, hs = string.gsub(url, "https://", "")
local protocol = "http"
if hs == 1 then
protocol = "https"
end
return url, protocol
end
local function get_rss(url, prot)
local res, code = nil, 0
if prot == "http" then
res, code = http.request(url)
elseif prot == "https" then
res, code = https.request(url)
end
if code ~= 200 then
return nil, "Error while doing the petition to " .. url
end
local parsed = feedparser.parse(res)
if parsed == nil then
return nil, "Error decoding the RSS.\nAre you sure that " .. url .. " it's a RSS?"
end
return parsed, nil
end
local function get_new_entries(last, nentries)
local entries = {}
for k,v in pairs(nentries) do
if v.id == last then
return entries
else
table.insert(entries, v)
end
end
return entries
end
local function print_subs(id)
local uhash = get_base_redis(id)
local subs = redis:smembers(uhash)
local text = id .. ' are subscribed to:\n---------\n'
for k,v in pairs(subs) do
text = text .. k .. ") " .. v .. '\n'
end
return text
end
local function subscribe(id, url)
local baseurl, protocol = prot_url(url)
local prothash = get_base_redis(baseurl, "protocol")
local lasthash = get_base_redis(baseurl, "last_entry")
local lhash = get_base_redis(baseurl, "subs")
local uhash = get_base_redis(id)
if redis:sismember(uhash, baseurl) then
return "You are already subscribed to " .. url
end
local parsed, err = get_rss(url, protocol)
if err ~= nil then
return err
end
local last_entry = ""
if #parsed.entries > 0 then
last_entry = parsed.entries[1].id
end
local name = parsed.feed.title
redis:set(prothash, protocol)
redis:set(lasthash, last_entry)
redis:sadd(lhash, id)
redis:sadd(uhash, baseurl)
return "You had been subscribed to " .. name
end
local function unsubscribe(id, n)
if #n > 3 then
return "I don't think that you have that many subscriptions."
end
n = tonumber(n)
local uhash = get_base_redis(id)
local subs = redis:smembers(uhash)
if n < 1 or n > #subs then
return "Subscription id out of range!"
end
local sub = subs[n]
local lhash = get_base_redis(sub, "subs")
redis:srem(uhash, sub)
redis:srem(lhash, id)
local left = redis:smembers(lhash)
if #left < 1 then -- no one subscribed, remove it
local prothash = get_base_redis(sub, "protocol")
local lasthash = get_base_redis(sub, "last_entry")
redis:del(prothash)
redis:del(lasthash)
end
return "You had been unsubscribed from " .. sub
end
local function cron()
-- sync every 15 mins?
local keys = redis:keys(get_base_redis("*", "subs"))
for k,v in pairs(keys) do
local base = string.match(v, "rss:(.+):subs") -- Get the URL base
local prot = redis:get(get_base_redis(base, "protocol"))
local last = redis:get(get_base_redis(base, "last_entry"))
local url = prot .. "://" .. base
local parsed, err = get_rss(url, prot)
if err ~= nil then
return
end
local newentr = get_new_entries(last, parsed.entries)
local subscribers = {}
local text = '' -- Send only one message with all updates
for k2, v2 in pairs(newentr) do
local title = v2.title or 'No title'
local link = v2.link or v2.id or 'No Link'
text = text .. "[rss](" .. link .. ") - " .. title .. '\n'
end
if text ~= '' then
local newlast = newentr[1].id
redis:set(get_base_redis(base, "last_entry"), newlast)
for k2, receiver in pairs(redis:smembers(v)) do
send_msg(receiver, text, ok_cb, false)
end
end
end
end
local function run(msg, matches)
local id = "user#id" .. msg.from.id
if is_chat_msg(msg) then
id = "chat#id" .. msg.to.id
end
if matches[1] == "!rss"then
return print_subs(id)
end
if matches[1] == "sync" then
if not is_sudo(msg) then
return "Only sudo users can sync the RSS."
end
cron()
end
if matches[1] == "subscribe" or matches[1] == "sub" then
return subscribe(id, matches[2])
end
if matches[1] == "unsubscribe" or matches[1] == "uns" then
return unsubscribe(id, matches[2])
end
end
return {
description = "Manage User/Chat RSS subscriptions. If you are in a chat group, the RSS subscriptions will be of that chat. If you are in an one-to-one talk with the bot, the RSS subscriptions will be yours.",
usage = {
"!rss: Get your rss (or chat rss) subscriptions",
"!rss subscribe (url): Subscribe to that url",
"!rss unsubscribe (id): Unsubscribe of that id",
"!rss sync: Download now the updates and send it. Only sudo users can use this option."
},
patterns = {
"^!rss$",
"^!rss (subscribe) (https?://[%w-_%.%?%.:/%+=&]+)$",
"^!rss (sub) (https?://[%w-_%.%?%.:/%+=&]+)$",
"^!rss (unsubscribe) (%d+)$",
"^!rss (uns) (%d+)$",
"^!rss (sync)$"
},
run = run,
cron = cron
}
| gpl-2.0 |
rigeirani/pm | plugins/welcome.lua | 190 | 3526 | local add_user_cfg = load_from_file('data/add_user_cfg.lua')
local function template_add_user(base, to_username, from_username, chat_name, chat_id)
base = base or ''
to_username = '@' .. (to_username or '')
from_username = '@' .. (from_username or '')
chat_name = string.gsub(chat_name, '_', ' ') or ''
chat_id = "chat#id" .. (chat_id or '')
if to_username == "@" then
to_username = ''
end
if from_username == "@" then
from_username = ''
end
base = string.gsub(base, "{to_username}", to_username)
base = string.gsub(base, "{from_username}", from_username)
base = string.gsub(base, "{chat_name}", chat_name)
base = string.gsub(base, "{chat_id}", chat_id)
return base
end
function chat_new_user_link(msg)
local pattern = add_user_cfg.initial_chat_msg
local to_username = msg.from.username
local from_username = 'link (@' .. (msg.action.link_issuer.username or '') .. ')'
local chat_name = msg.to.print_name
local chat_id = msg.to.id
pattern = template_add_user(pattern, to_username, from_username, chat_name, chat_id)
if pattern ~= '' then
local receiver = get_receiver(msg)
send_msg(receiver, pattern, ok_cb, false)
end
end
function chat_new_user(msg)
local pattern = add_user_cfg.initial_chat_msg
local to_username = msg.action.user.username
local from_username = msg.from.username
local chat_name = msg.to.print_name
local chat_id = msg.to.id
pattern = template_add_user(pattern, to_username, from_username, chat_name, chat_id)
if pattern ~= '' then
local receiver = get_receiver(msg)
send_msg(receiver, pattern, ok_cb, false)
end
end
local function description_rules(msg, nama)
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
local about = ""
local rules = ""
if data[tostring(msg.to.id)]["description"] then
about = data[tostring(msg.to.id)]["description"]
about = "\nAbout :\n"..about.."\n"
end
if data[tostring(msg.to.id)]["rules"] then
rules = data[tostring(msg.to.id)]["rules"]
rules = "\nRules :\n"..rules.."\n"
end
local sambutan = "Hi "..nama.."\nWelcome to '"..string.gsub(msg.to.print_name, "_", " ").."'\nYou can use /help for see bot commands\n"
local text = sambutan..about..rules.."\n"
local receiver = get_receiver(msg)
send_large_msg(receiver, text, ok_cb, false)
end
end
local function run(msg, matches)
if not msg.service then
return "Are you trying to troll me?"
end
--vardump(msg)
if matches[1] == "chat_add_user" then
if not msg.action.user.username then
nama = string.gsub(msg.action.user.print_name, "_", " ")
else
nama = "@"..msg.action.user.username
end
chat_new_user(msg)
description_rules(msg, nama)
elseif matches[1] == "chat_add_user_link" then
if not msg.from.username then
nama = string.gsub(msg.from.print_name, "_", " ")
else
nama = "@"..msg.from.username
end
chat_new_user_link(msg)
description_rules(msg, nama)
elseif matches[1] == "chat_del_user" then
local bye_name = msg.action.user.first_name
return 'Bye '..bye_name
end
end
return {
description = "Welcoming Message",
usage = "send message to new member",
patterns = {
"^!!tgservice (chat_add_user)$",
"^!!tgservice (chat_add_user_link)$",
"^!!tgservice (chat_del_user)$",
},
run = run
}
| gpl-2.0 |
mercury233/ygopro-scripts | c4417407.lua | 2 | 3141 | --幻獣機ブラックファルコン
function c4417407.initial_effect(c)
--level
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e1:SetRange(LOCATION_MZONE)
e1:SetCode(EFFECT_UPDATE_LEVEL)
e1:SetValue(c4417407.lvval)
c:RegisterEffect(e1)
--
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e2:SetRange(LOCATION_MZONE)
e2:SetCode(EFFECT_INDESTRUCTABLE_BATTLE)
e2:SetCondition(c4417407.indcon)
e2:SetValue(1)
c:RegisterEffect(e2)
local e3=e2:Clone()
e3:SetCode(EFFECT_INDESTRUCTABLE_EFFECT)
c:RegisterEffect(e3)
--token
local e4=Effect.CreateEffect(c)
e4:SetDescription(aux.Stringid(4417407,0))
e4:SetCategory(CATEGORY_SPECIAL_SUMMON+CATEGORY_TOKEN)
e4:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e4:SetCode(EVENT_ATTACK_ANNOUNCE)
e4:SetTarget(c4417407.sptg)
e4:SetOperation(c4417407.spop)
c:RegisterEffect(e4)
--pos
local e5=Effect.CreateEffect(c)
e5:SetDescription(aux.Stringid(4417407,1))
e5:SetCategory(CATEGORY_POSITION)
e5:SetType(EFFECT_TYPE_QUICK_O)
e5:SetRange(LOCATION_MZONE)
e5:SetCode(EVENT_FREE_CHAIN)
e5:SetProperty(EFFECT_FLAG_CARD_TARGET)
e5:SetHintTiming(TIMING_BATTLE_PHASE)
e5:SetCountLimit(1)
e5:SetCost(c4417407.poscost)
e5:SetTarget(c4417407.postg)
e5:SetOperation(c4417407.posop)
c:RegisterEffect(e5)
end
function c4417407.lvval(e,c)
local tp=c:GetControler()
return Duel.GetMatchingGroup(Card.IsCode,tp,LOCATION_MZONE,0,nil,31533705):GetSum(Card.GetLevel)
end
function c4417407.indcon(e)
return Duel.IsExistingMatchingCard(Card.IsType,e:GetHandlerPlayer(),LOCATION_MZONE,0,1,nil,TYPE_TOKEN)
end
function c4417407.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_TOKEN,nil,1,0,0)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,0,0)
end
function c4417407.spop(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
if Duel.IsPlayerCanSpecialSummonMonster(tp,31533705,0x101b,TYPES_TOKEN_MONSTER,0,0,3,RACE_MACHINE,ATTRIBUTE_WIND) then
local token=Duel.CreateToken(tp,4417408)
Duel.SpecialSummon(token,0,tp,tp,false,false,POS_FACEUP)
end
end
function c4417407.poscost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.CheckReleaseGroup(tp,Card.IsType,1,nil,TYPE_TOKEN) end
local g=Duel.SelectReleaseGroup(tp,Card.IsType,1,1,nil,TYPE_TOKEN)
Duel.Release(g,REASON_COST)
end
function c4417407.filter(c)
return c:IsPosition(POS_FACEUP_ATTACK) and c:IsCanChangePosition()
end
function c4417407.postg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsControler(1-tp) and chkc:IsLocation(LOCATION_MZONE) and c4417407.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c4417407.filter,tp,0,LOCATION_MZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_POSCHANGE)
Duel.SelectTarget(tp,c4417407.filter,tp,0,LOCATION_MZONE,1,1,nil)
end
function c4417407.posop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) and not tc:IsPosition(POS_FACEUP_DEFENSE) then
Duel.ChangePosition(tc,POS_FACEUP_DEFENSE)
end
end
| gpl-2.0 |
mercury233/ygopro-scripts | c66078354.lua | 2 | 2855 | --遺跡の魔鉱戦士
function c66078354.initial_effect(c)
aux.AddCodeList(c,3285552)
--spsummon
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_HAND)
e1:SetCountLimit(1,66078354)
e1:SetCondition(c66078354.spcon)
e1:SetTarget(c66078354.sptg)
e1:SetOperation(c66078354.spop)
c:RegisterEffect(e1)
--cannot atk
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_CANNOT_ATTACK)
e2:SetCondition(c66078354.atkcon)
c:RegisterEffect(e2)
--set card
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e3:SetCode(EVENT_PHASE+PHASE_BATTLE)
e3:SetRange(LOCATION_MZONE)
e3:SetCountLimit(1,66078355)
e3:SetCondition(c66078354.setcon)
e3:SetTarget(c66078354.settg)
e3:SetOperation(c66078354.setop)
c:RegisterEffect(e3)
if not c66078354.global_check then
c66078354.global_check=true
local ge1=Effect.CreateEffect(c)
ge1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
ge1:SetCode(EVENT_BATTLED)
ge1:SetOperation(c66078354.checkop)
Duel.RegisterEffect(ge1,0)
end
end
function c66078354.check(c)
return c and aux.IsCodeListed(c,3285552)
end
function c66078354.checkop(e,tp,eg,ep,ev,re,r,rp)
local a,d=Duel.GetBattleMonster(0)
if c66078354.check(a) then Duel.RegisterFlagEffect(0,66078354,RESET_PHASE+PHASE_END,0,1) end
if c66078354.check(d) then Duel.RegisterFlagEffect(1,66078354,RESET_PHASE+PHASE_END,0,1) end
end
function c66078354.cfilter(c)
return c:IsCode(3285552) and c:IsFaceup()
end
function c66078354.spcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.IsExistingMatchingCard(c66078354.cfilter,tp,LOCATION_ONFIELD,0,1,nil)
end
function c66078354.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0)
end
function c66078354.spop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) then
Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP)
end
end
function c66078354.atkcon(e)
return not Duel.IsExistingMatchingCard(c66078354.cfilter,e:GetHandlerPlayer(),LOCATION_ONFIELD,0,1,nil)
end
function c66078354.setcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetFlagEffect(tp,66078354)>0
end
function c66078354.setfilter(c)
return aux.IsCodeListed(c,3285552) and c:IsType(TYPE_TRAP) and c:IsSSetable()
end
function c66078354.settg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c66078354.setfilter,tp,LOCATION_DECK,0,1,nil) end
end
function c66078354.setop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SET)
local g=Duel.SelectMatchingCard(tp,c66078354.setfilter,tp,LOCATION_DECK,0,1,1,nil)
if g:GetCount()>0 then
Duel.SSet(tp,g)
end
end
| gpl-2.0 |
mercury233/ygopro-scripts | c7200041.lua | 6 | 1499 | --メタル・シューター
function c7200041.initial_effect(c)
c:EnableCounterPermit(0x26)
--summon success
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(7200041,0))
e1:SetCategory(CATEGORY_COUNTER)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e1:SetCode(EVENT_SUMMON_SUCCESS)
e1:SetTarget(c7200041.addct)
e1:SetOperation(c7200041.addc)
c:RegisterEffect(e1)
--attackup
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e2:SetRange(LOCATION_MZONE)
e2:SetCode(EFFECT_UPDATE_ATTACK)
e2:SetValue(c7200041.attackup)
c:RegisterEffect(e2)
--destroy replace
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_CONTINUOUS+EFFECT_TYPE_SINGLE)
e3:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e3:SetCode(EFFECT_DESTROY_REPLACE)
e3:SetRange(LOCATION_MZONE)
e3:SetTarget(c7200041.reptg)
c:RegisterEffect(e3)
end
function c7200041.addct(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_COUNTER,nil,1,0,0x26)
end
function c7200041.addc(e,tp,eg,ep,ev,re,r,rp)
if e:GetHandler():IsRelateToEffect(e) then
e:GetHandler():AddCounter(0x26,2)
end
end
function c7200041.attackup(e,c)
return c:GetCounter(0x26)*800
end
function c7200041.reptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsReason(REASON_EFFECT)
and e:GetHandler():IsCanRemoveCounter(tp,0x26,1,REASON_COST) end
e:GetHandler():RemoveCounter(tp,0x26,1,REASON_EFFECT)
return true
end
| gpl-2.0 |
Zenny89/darkstar | scripts/zones/Bearclaw_Pinnacle/Zone.lua | 28 | 1630 | -----------------------------------
--
-- Zone: Bearclaw_Pinnacle (6)
--
-----------------------------------
package.loaded["scripts/zones/Bearclaw_Pinnacle/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Bearclaw_Pinnacle/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
player:setPos(-680,16,-540,129);
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
mercury233/ygopro-scripts | c2851070.lua | 2 | 1700 | --魔鏡導士リフレクト・バウンダー
function c2851070.initial_effect(c)
--damage
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(2851070,0))
e1:SetCategory(CATEGORY_DAMAGE)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e1:SetCode(EVENT_BATTLE_CONFIRM)
e1:SetCondition(c2851070.damcon)
e1:SetTarget(c2851070.damtg)
e1:SetOperation(c2851070.damop)
c:RegisterEffect(e1)
--destroy
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(2851070,1))
e1:SetCategory(CATEGORY_DESTROY)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e1:SetCode(EVENT_BATTLED)
e1:SetTarget(c2851070.destg)
e1:SetOperation(c2851070.desop)
c:RegisterEffect(e1)
end
function c2851070.damcon(e,tp,eg,ep,ev,re,r,rp)
local c=Duel.GetAttackTarget()
return c==e:GetHandler() and c:GetBattlePosition()==POS_FACEUP_ATTACK
end
function c2851070.damtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetTargetPlayer(1-tp)
Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,1-tp,0)
end
function c2851070.damop(e,tp,eg,ep,ev,re,r,rp)
local p=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER)
local lp1=Duel.GetLP(p)
Duel.Damage(p,Duel.GetAttacker():GetAttack(),REASON_EFFECT)
local lp2=Duel.GetLP(p)
if lp2<lp1 then
e:GetHandler():RegisterFlagEffect(2851070,RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_DAMAGE,0,1)
end
end
function c2851070.destg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():GetFlagEffect(2851070)~=0 end
Duel.SetOperationInfo(0,CATEGORY_DESTROY,e:GetHandler(),1,0,0)
end
function c2851070.desop(e,tp,eg,ep,ev,re,r,rp)
if e:GetHandler():IsRelateToEffect(e) then
Duel.Destroy(e:GetHandler(),REASON_EFFECT)
end
end
| gpl-2.0 |
mercury233/ygopro-scripts | c525110.lua | 4 | 1867 | --プチトマボー
function c525110.initial_effect(c)
--special summon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(525110,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetCode(EVENT_BATTLE_DESTROYED)
e1:SetCondition(c525110.condition)
e1:SetTarget(c525110.target)
e1:SetOperation(c525110.operation)
c:RegisterEffect(e1)
end
function c525110.condition(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsLocation(LOCATION_GRAVE) and e:GetHandler():IsReason(REASON_BATTLE)
end
function c525110.filter(c,e,tp)
return c:IsSetCard(0x5b) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c525110.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c525110.filter,tp,LOCATION_DECK,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK)
end
function c525110.operation(e,tp,eg,ep,ev,re,r,rp)
local ft=Duel.GetLocationCount(tp,LOCATION_MZONE)
if ft<=0 then return end
if ft>=2 then ft=2 end
if Duel.IsPlayerAffectedByEffect(tp,59822133) then ft=1 end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c525110.filter,tp,LOCATION_DECK,0,1,ft,nil,e,tp)
if g:GetCount()>0 then
local t1=g:GetFirst()
local t2=g:GetNext()
Duel.SpecialSummonStep(t1,0,tp,tp,false,false,POS_FACEUP)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CANNOT_BE_SYNCHRO_MATERIAL)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetValue(1)
e1:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END)
t1:RegisterEffect(e1)
if t2 then
Duel.SpecialSummonStep(t2,0,tp,tp,false,false,POS_FACEUP)
local e2=e1:Clone()
t2:RegisterEffect(e2)
end
Duel.SpecialSummonComplete()
end
end
| gpl-2.0 |
mercury233/ygopro-scripts | c99789342.lua | 3 | 2137 | --黒魔術のカーテン
function c99789342.initial_effect(c)
aux.AddCodeList(c,46986414)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCost(c99789342.cost)
e1:SetTarget(c99789342.target)
e1:SetOperation(c99789342.activate)
c:RegisterEffect(e1)
end
function c99789342.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetActivityCount(tp,ACTIVITY_SUMMON)==0
and Duel.GetActivityCount(tp,ACTIVITY_FLIPSUMMON)==0 and Duel.GetActivityCount(tp,ACTIVITY_SPSUMMON)==0 end
Duel.PayLPCost(tp,math.floor(Duel.GetLP(tp)/2))
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_OATH)
e1:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON)
e1:SetReset(RESET_PHASE+PHASE_END)
e1:SetTargetRange(1,0)
e1:SetTarget(c99789342.sumlimit)
Duel.RegisterEffect(e1,tp)
local e2=Effect.CreateEffect(e:GetHandler())
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetProperty(EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_OATH)
e2:SetCode(EFFECT_CANNOT_SUMMON)
e2:SetReset(RESET_PHASE+PHASE_END)
e2:SetTargetRange(1,0)
Duel.RegisterEffect(e2,tp)
local e3=e2:Clone()
e3:SetCode(EFFECT_CANNOT_FLIP_SUMMON)
Duel.RegisterEffect(e3,tp)
end
function c99789342.sumlimit(e,c,sump,sumtype,sumpos,targetp,se)
return e:GetHandler()~=se:GetHandler()
end
function c99789342.filter(c,e,tp)
return c:IsCode(46986414) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c99789342.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c99789342.filter,tp,LOCATION_DECK,0,1,nil,e,tp)
end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK)
end
function c99789342.activate(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c99789342.filter,tp,LOCATION_DECK,0,1,1,nil,e,tp)
if g:GetCount()>0 then
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)
end
end
| gpl-2.0 |
mercury233/ygopro-scripts | c59724555.lua | 2 | 2429 | --ドドドドワーフ-GG
function c59724555.initial_effect(c)
--spsummon1
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(59724555,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_MZONE)
e1:SetCountLimit(1,59724555)
e1:SetTarget(c59724555.sptg1)
e1:SetOperation(c59724555.spop1)
c:RegisterEffect(e1)
--spsummon2
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(59724555,1))
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_GRAVE)
e2:SetCountLimit(1,59724556)
e2:SetCondition(c59724555.spcon2)
e2:SetTarget(c59724555.sptg2)
e2:SetOperation(c59724555.spop2)
c:RegisterEffect(e2)
end
function c59724555.spfilter(c,e,tp)
return c:IsSetCard(0x8f,0x54) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c59724555.sptg1(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c59724555.spfilter,tp,LOCATION_HAND,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_HAND)
end
function c59724555.spop1(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c59724555.spfilter,tp,LOCATION_HAND,0,1,1,nil,e,tp)
if g:GetCount()>0 then
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)
end
end
function c59724555.cfilter(c)
return c:IsFaceup() and c:IsSetCard(0x59,0x82) and not c:IsCode(59724555)
end
function c59724555.spcon2(e,tp,eg,ep,ev,re,r,rp)
return Duel.IsExistingMatchingCard(c59724555.cfilter,tp,LOCATION_MZONE,0,1,nil)
end
function c59724555.sptg2(e,tp,eg,ep,ev,re,r,rp,chk)
local c=e:GetHandler()
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,c,1,0,0)
end
function c59724555.spop2(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) and Duel.SpecialSummonStep(c,0,tp,tp,false,false,POS_FACEUP) then
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_LEAVE_FIELD_REDIRECT)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetReset(RESET_EVENT+RESETS_REDIRECT)
e1:SetValue(LOCATION_REMOVED)
c:RegisterEffect(e1,true)
end
Duel.SpecialSummonComplete()
end
| gpl-2.0 |
mercury233/ygopro-scripts | c12571621.lua | 2 | 3268 | --電脳堺豸-豸々
function c12571621.initial_effect(c)
--spsummon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(12571621,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON+CATEGORY_TOGRAVE+CATEGORY_TOHAND+CATEGORY_GRAVE_ACTION)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_HAND)
e1:SetCountLimit(1,12571621)
e1:SetTarget(c12571621.sptg)
e1:SetOperation(c12571621.spop)
c:RegisterEffect(e1)
end
function c12571621.tfilter(c,tp)
local type1=c:GetType()&0x7
return c:IsSetCard(0x14e) and c:IsFaceup() and Duel.IsExistingMatchingCard(c12571621.tgfilter,tp,LOCATION_DECK,0,1,nil,type1)
end
function c12571621.tgfilter(c,type1)
return not c:IsType(type1) and c:IsSetCard(0x14e) and c:IsAbleToGrave()
end
function c12571621.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsOnField() and chkc:IsControler(tp) and c12571621.tfilter(chkc,tp) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false)
and Duel.IsExistingTarget(c12571621.tfilter,tp,LOCATION_ONFIELD,0,1,nil,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP)
local g=Duel.SelectTarget(tp,c12571621.tfilter,tp,LOCATION_ONFIELD,0,1,1,nil,tp)
Duel.SetOperationInfo(0,CATEGORY_TOGRAVE,nil,1,tp,LOCATION_DECK)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0)
end
function c12571621.spop(e,tp,eg,ep,ev,re,r,rp)
local c,tc=e:GetHandler(),Duel.GetFirstTarget()
local type1=tc:GetType()&0x7
if tc:IsRelateToEffect(e) then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE)
local g=Duel.SelectMatchingCard(tp,c12571621.tgfilter,tp,LOCATION_DECK,0,1,1,nil,type1)
local tgc=g:GetFirst()
if tgc and Duel.SendtoGrave(tgc,REASON_EFFECT)~=0 and tgc:IsLocation(LOCATION_GRAVE) and c:IsRelateToEffect(e)
and Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP)~=0 then
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e1:SetCode(EVENT_PHASE+PHASE_END)
e1:SetCountLimit(1)
e1:SetCondition(c12571621.thcon)
e1:SetOperation(c12571621.thop)
e1:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e1,tp)
end
end
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON)
e1:SetTargetRange(1,0)
e1:SetTarget(c12571621.splimit)
e1:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e1,tp)
end
function c12571621.splimit(e,c)
return not (c:IsLevelAbove(3) or c:IsRankAbove(3))
end
function c12571621.thfilter(c)
return c:IsSetCard(0x14e) and c:IsType(TYPE_MONSTER) and not c:IsCode(12571621) and c:IsAbleToHand()
end
function c12571621.thcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.IsExistingMatchingCard(aux.NecroValleyFilter(c12571621.thfilter),tp,LOCATION_GRAVE,0,1,nil)
end
function c12571621.thop(e,tp,eg,ep,ev,re,r,rp)
if Duel.SelectYesNo(tp,aux.Stringid(12571621,1)) then
Duel.Hint(HINT_CARD,0,12571621)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,aux.NecroValleyFilter(c12571621.thfilter),tp,LOCATION_GRAVE,0,1,1,nil)
if g:GetCount()>0 then
Duel.SendtoHand(g,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g)
end
end
end
| gpl-2.0 |
mercury233/ygopro-scripts | c1248895.lua | 9 | 1261 | --連鎖破壊
function c1248895.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_DESTROY)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCode(EVENT_SUMMON_SUCCESS)
e1:SetTarget(c1248895.target)
e1:SetOperation(c1248895.activate)
c:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetCode(EVENT_FLIP_SUMMON_SUCCESS)
c:RegisterEffect(e2)
local e3=e1:Clone()
e3:SetCode(EVENT_SPSUMMON_SUCCESS)
c:RegisterEffect(e3)
end
function c1248895.filter(c,e)
return c:IsFaceup() and c:IsAttackBelow(2000) and c:IsCanBeEffectTarget(e)
end
function c1248895.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return eg:IsContains(chkc) end
if chk==0 then return eg:IsExists(c1248895.filter,1,nil,e) end
if eg:GetCount()==1 then
Duel.SetTargetCard(eg)
else
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TARGET)
local g=eg:FilterSelect(tp,c1248895.filter,1,1,nil,e)
Duel.SetTargetCard(g)
end
end
function c1248895.activate(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
local tpe=tc:GetType()
if bit.band(tpe,TYPE_TOKEN)~=0 then return end
local dg=Duel.GetMatchingGroup(Card.IsCode,tc:GetControler(),LOCATION_DECK+LOCATION_HAND,0,nil,tc:GetCode())
Duel.Destroy(dg,REASON_EFFECT)
end
| gpl-2.0 |
mercury233/ygopro-scripts | c94113093.lua | 2 | 3282 | --らくがきちょう-とおせんぼ
function c94113093.initial_effect(c)
--negate attack
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON+CATEGORY_GRAVE_SPSUMMON)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_BE_BATTLE_TARGET)
e1:SetCountLimit(1,94113093)
e1:SetCondition(c94113093.negcon)
e1:SetOperation(c94113093.negop)
c:RegisterEffect(e1)
--to hand
local e2=Effect.CreateEffect(c)
e2:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH)
e2:SetType(EFFECT_TYPE_QUICK_O)
e2:SetCode(EVENT_FREE_CHAIN)
e2:SetRange(LOCATION_GRAVE)
e2:SetCountLimit(1,94113094)
e2:SetHintTiming(0,TIMINGS_CHECK_MONSTER+TIMING_END_PHASE)
e2:SetCondition(aux.exccon)
e2:SetCost(aux.bfgcost)
e2:SetTarget(c94113093.thtg)
e2:SetOperation(c94113093.thop)
c:RegisterEffect(e2)
end
function c94113093.negcon(e,tp,eg,ep,ev,re,r,rp)
local tc=eg:GetFirst()
return tc:IsControler(tp) and tc:IsFaceup() and tc:IsRace(RACE_DINOSAUR)
end
function c94113093.spfilter(c,e,tp)
return c:IsSetCard(0x1185) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c94113093.negop(e,tp,eg,ep,ev,re,r,rp)
if Duel.NegateAttack() then
local g=Duel.GetMatchingGroup(aux.NecroValleyFilter(c94113093.spfilter),tp,LOCATION_GRAVE,0,nil,e,tp)
local ct=Duel.GetLocationCount(tp,LOCATION_MZONE)
if ct>0 and g:GetCount()>0 and Duel.SelectYesNo(tp,aux.Stringid(94113093,0)) then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local tc=g:Select(tp,1,1,nil):GetFirst()
if tc then
Duel.BreakEffect()
Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP)
local fid=e:GetHandler():GetFieldID()
tc:RegisterFlagEffect(94113093,RESET_EVENT+RESETS_STANDARD,0,1,fid)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetDescription(aux.Stringid(94113093,2))
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_INDESTRUCTABLE_BATTLE)
e1:SetProperty(EFFECT_FLAG_CLIENT_HINT)
e1:SetValue(1)
e1:SetReset(RESET_EVENT+RESETS_STANDARD)
tc:RegisterEffect(e1)
local e2=Effect.CreateEffect(e:GetHandler())
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e2:SetCode(EVENT_PHASE+PHASE_END)
e2:SetProperty(EFFECT_FLAG_IGNORE_IMMUNE)
e2:SetCountLimit(1)
e2:SetLabel(fid)
e2:SetLabelObject(tc)
e2:SetCondition(c94113093.descon)
e2:SetOperation(c94113093.desop)
Duel.RegisterEffect(e2,tp)
end
end
end
end
function c94113093.descon(e,tp,eg,ep,ev,re,r,rp)
local tc=e:GetLabelObject()
if tc:GetFlagEffectLabel(94113093)~=e:GetLabel() then
e:Reset()
return false
else return true end
end
function c94113093.desop(e,tp,eg,ep,ev,re,r,rp)
Duel.Destroy(e:GetLabelObject(),REASON_EFFECT)
end
function c94113093.thfilter(c)
return c:IsRace(RACE_DINOSAUR) and c:IsLevelAbove(5) and c:IsAbleToHand()
end
function c94113093.thtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c94113093.thfilter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function c94113093.thop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,c94113093.thfilter,tp,LOCATION_DECK,0,1,1,nil)
if g:GetCount()>0 then
Duel.SendtoHand(g,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g)
end
end
| gpl-2.0 |
mercury233/ygopro-scripts | c111280.lua | 2 | 3192 | --黒魔導強化
function c111280.initial_effect(c)
aux.AddCodeList(c,46986414,38033121)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_ATKCHANGE)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetProperty(EFFECT_FLAG_DAMAGE_STEP)
e1:SetHintTiming(TIMING_DAMAGE_STEP)
e1:SetCondition(c111280.condition)
e1:SetTarget(c111280.target)
e1:SetOperation(c111280.activate)
c:RegisterEffect(e1)
end
function c111280.cfilter(c)
return c:IsFaceup() and c:IsCode(46986414,38033121)
end
function c111280.condition(e,tp,eg,ep,ev,re,r,rp)
local ct=Duel.GetMatchingGroupCount(c111280.cfilter,tp,LOCATION_ONFIELD+LOCATION_GRAVE,LOCATION_ONFIELD+LOCATION_GRAVE,nil)
return ct>0 and aux.dscon()
end
function c111280.filter(c)
return c:IsFaceup() and c:IsRace(RACE_SPELLCASTER) and c:IsAttribute(ATTRIBUTE_DARK)
end
function c111280.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then
local ct=Duel.GetMatchingGroupCount(c111280.cfilter,tp,LOCATION_ONFIELD+LOCATION_GRAVE,LOCATION_ONFIELD+LOCATION_GRAVE,nil)
if ct<=1 then return Duel.IsExistingMatchingCard(c111280.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil) end
return true
end
end
function c111280.activate(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetMatchingGroup(c111280.cfilter,tp,LOCATION_ONFIELD+LOCATION_GRAVE,LOCATION_ONFIELD+LOCATION_GRAVE,nil)
local ct=g:GetCount()
if ct>=1 then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP)
local g=Duel.SelectMatchingCard(tp,c111280.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil)
local tc=g:GetFirst()
if tc then
Duel.HintSelection(g)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END)
e1:SetValue(1000)
tc:RegisterEffect(e1)
end
end
if ct>=2 then
local e2=Effect.CreateEffect(e:GetHandler())
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e2:SetCode(EVENT_CHAINING)
e2:SetOperation(c111280.chainop)
e2:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e2,tp)
local e3=Effect.CreateEffect(e:GetHandler())
e3:SetType(EFFECT_TYPE_FIELD)
e3:SetCode(EFFECT_INDESTRUCTABLE_EFFECT)
e3:SetProperty(EFFECT_FLAG_SET_AVAILABLE)
e3:SetTargetRange(LOCATION_ONFIELD,0)
e3:SetTarget(c111280.indtg)
e3:SetValue(aux.indoval)
e3:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e3,tp)
end
if ct>=3 then
local g=Duel.GetMatchingGroup(c111280.filter,tp,LOCATION_MZONE,0,nil)
local tc=g:GetFirst()
while tc do
local e4=Effect.CreateEffect(e:GetHandler())
e4:SetType(EFFECT_TYPE_SINGLE)
e4:SetCode(EFFECT_IMMUNE_EFFECT)
e4:SetValue(c111280.efilter)
e4:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END)
e4:SetOwnerPlayer(tp)
tc:RegisterEffect(e4)
tc=g:GetNext()
end
end
end
function c111280.chainop(e,tp,eg,ep,ev,re,r,rp)
if re:IsActiveType(TYPE_SPELL+TYPE_TRAP) and ep==tp then
Duel.SetChainLimit(c111280.chainlm)
end
end
function c111280.chainlm(e,rp,tp)
return tp==rp
end
function c111280.indtg(e,c)
return c:IsType(TYPE_SPELL+TYPE_TRAP)
end
function c111280.efilter(e,re)
return e:GetOwnerPlayer()~=re:GetOwnerPlayer()
end
| gpl-2.0 |
Zenny89/darkstar | scripts/globals/mobskills/Antimatter.lua | 18 | 1115 | ---------------------------------------------------
-- Antimatter
--
-- Description: Single-target ranged Light damage (~700-1500), ignores Utsusemi.
-- Type: Magical
--
---------------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------------
function onMobSkillCheck(target,mob,skill)
local mobID = mob:getID(); --(16908295 ,16908302 ,16908309 =omega , 16928966=proto-ultima )
local mobhp = mob:getHPP();
if (( (mobhp > 80 or (mobhp < 60 and mobhp > 20 ) )and mobID == 16928966) or(mobhp < 20 and(mobID == 16908295 or mobID == 16908302 or mobID == 16908309 ))) then
return 0;
end
return 1;
end;
function onMobWeaponSkill(target, mob, skill)
local dmgmod = 2.5;
local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*3,ELE_LIGHT,dmgmod,TP_MAB_BONUS,1);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_LIGHT,MOBPARAM_IGNORE_SHADOWS);
target:delHP(dmg);
return dmg;
end
| gpl-3.0 |
mercury233/ygopro-scripts | c92958307.lua | 4 | 1337 | --EMショーダウン
function c92958307.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_POSITION)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetHintTiming(TIMING_BATTLE_PHASE,TIMINGS_CHECK_MONSTER+TIMING_BATTLE_PHASE)
e1:SetTarget(c92958307.target)
e1:SetOperation(c92958307.activate)
c:RegisterEffect(e1)
end
function c92958307.cfilter(c)
return c:IsFaceup() and c:IsType(TYPE_SPELL)
end
function c92958307.filter(c)
return c:IsFaceup() and c:IsCanTurnSet()
end
function c92958307.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
local sc=Duel.GetMatchingGroupCount(c92958307.cfilter,tp,LOCATION_ONFIELD,0,nil)
if chkc then return chkc:IsControler(1-tp) and chkc:IsLocation(LOCATION_MZONE) and c92958307.filter(chkc) end
if chk==0 then return sc>0 and Duel.IsExistingTarget(c92958307.filter,tp,0,LOCATION_MZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP)
local g=Duel.SelectTarget(tp,c92958307.filter,tp,0,LOCATION_MZONE,1,sc,nil)
Duel.SetOperationInfo(0,CATEGORY_POSITION,g,g:GetCount(),0,0)
end
function c92958307.activate(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS):Filter(Card.IsRelateToEffect,nil,e)
if g:GetCount()>0 then
Duel.ChangePosition(g,POS_FACEDOWN_DEFENSE)
end
end
| gpl-2.0 |
mercury233/ygopro-scripts | c85852291.lua | 2 | 1047 | --打ち出の小槌
function c85852291.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_TODECK+CATEGORY_DRAW)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetTarget(c85852291.target)
e1:SetOperation(c85852291.activate)
c:RegisterEffect(e1)
end
function c85852291.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsPlayerCanDraw(tp)
and Duel.IsExistingMatchingCard(Card.IsAbleToDeck,tp,LOCATION_HAND,0,1,e:GetHandler()) end
Duel.SetTargetPlayer(tp)
Duel.SetOperationInfo(0,CATEGORY_TODECK,nil,1,tp,LOCATION_HAND)
end
function c85852291.activate(e,tp,eg,ep,ev,re,r,rp)
local p=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER)
Duel.Hint(HINT_SELECTMSG,p,HINTMSG_TODECK)
local g=Duel.SelectMatchingCard(p,Card.IsAbleToDeck,p,LOCATION_HAND,0,1,63,nil)
if g:GetCount()==0 then return end
Duel.SendtoDeck(g,nil,SEQ_DECKSHUFFLE,REASON_EFFECT)
Duel.ShuffleDeck(p)
Duel.BreakEffect()
Duel.Draw(p,g:GetCount(),REASON_EFFECT)
end
| gpl-2.0 |
mercury233/ygopro-scripts | c47247413.lua | 2 | 1039 | --差し戻し
function c47247413.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCategory(CATEGORY_TODECK)
e1:SetCode(EVENT_TO_HAND)
e1:SetCondition(c47247413.condition)
e1:SetTarget(c47247413.target)
e1:SetOperation(c47247413.activate)
c:RegisterEffect(e1)
end
function c47247413.filter(c,e,tp)
return c:IsPreviousLocation(LOCATION_GRAVE) and c:IsControler(tp) and (not e or c:IsRelateToEffect(e))
end
function c47247413.condition(e,tp,eg,ep,ev,re,r,rp)
return eg:IsExists(c47247413.filter,1,nil,nil,1-tp)
end
function c47247413.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetTargetCard(eg)
Duel.SetOperationInfo(0,CATEGORY_TODECK,eg,1,0,0)
end
function c47247413.activate(e,tp,eg,ep,ev,re,r,rp)
local g=eg:Filter(c47247413.filter,nil,e,1-tp)
if g:GetCount()==0 then return end
Duel.Hint(HINT_SELECTMSG,1-tp,HINTMSG_TODECK)
local rg=g:Select(1-tp,1,1,nil)
Duel.ConfirmCards(tp,rg)
Duel.SendtoDeck(rg,nil,SEQ_DECKSHUFFLE,REASON_EFFECT)
end
| gpl-2.0 |
Zenny89/darkstar | scripts/globals/items/m&p_doner_kabob.lua | 36 | 1132 | -----------------------------------------
-- ID: 5717
-- Item: M&P Doner Kabob
-- Food Effect: 5Min, All Races
-----------------------------------------
-- HP 5%
-- MP 5%
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,5717);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HPP, 5);
target:addMod(MOD_MPP, 5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HPP, 5);
target:delMod(MOD_MPP, 5);
end;
| gpl-3.0 |
mercury233/ygopro-scripts | c20584712.lua | 2 | 1399 | --SPYRAL-タフネス
function c20584712.initial_effect(c)
--change name
aux.EnableChangeCode(c,41091257,LOCATION_MZONE+LOCATION_GRAVE)
--destroy
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(20584712,0))
e2:SetCategory(CATEGORY_DESTROY)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET)
e2:SetRange(LOCATION_MZONE)
e2:SetCountLimit(1)
e2:SetTarget(c20584712.destg)
e2:SetOperation(c20584712.desop)
c:RegisterEffect(e2)
end
function c20584712.destg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsOnField() and chkc:IsControler(1-tp) end
if chk==0 then return Duel.IsExistingTarget(nil,tp,0,LOCATION_ONFIELD,1,nil)
and Duel.GetFieldGroupCount(tp,0,LOCATION_DECK)>0 end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_CARDTYPE)
e:SetLabel(Duel.AnnounceType(tp))
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
Duel.SelectTarget(tp,nil,tp,0,LOCATION_ONFIELD,1,1,nil)
end
function c20584712.desop(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetFieldGroupCount(tp,0,LOCATION_DECK)==0 then return end
local dc=Duel.GetFirstTarget()
if not dc:IsRelateToEffect(e) then return end
Duel.ConfirmDecktop(1-tp,1)
local g=Duel.GetDecktopGroup(1-tp,1)
local tc=g:GetFirst()
local opt=e:GetLabel()
if (opt==0 and tc:IsType(TYPE_MONSTER)) or (opt==1 and tc:IsType(TYPE_SPELL)) or (opt==2 and tc:IsType(TYPE_TRAP)) then
Duel.Destroy(dc,REASON_EFFECT)
end
end
| gpl-2.0 |
mrbangi/mrbangii | plugins/all.lua | 1321 | 4661 | do
data = load_data(_config.moderation.data)
local function get_msgs_user_chat(user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info.msgs = tonumber(redis:get(um_hash) or 0)
user_info.name = user_print_name(user)..' ['..user_id..']'
return user_info
end
local function chat_stats(chat_id)
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = 'Chat stats:\n'
for k,user in pairs(users_info) do
text = text..user.name..' = '..user.msgs..'\n'
end
return text
end
local function get_group_type(target)
local data = load_data(_config.moderation.data)
local group_type = data[tostring(target)]['group_type']
if not group_type or group_type == nil then
return 'No group type available.'
end
return group_type
end
local function show_group_settings(target)
local data = load_data(_config.moderation.data)
if data[tostring(target)] then
if data[tostring(target)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local settings = data[tostring(target)]['settings']
local text = "Lock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX
return text
end
local function get_description(target)
local data = load_data(_config.moderation.data)
local data_cat = 'description'
if not data[tostring(target)][data_cat] then
return 'No description available.'
end
local about = data[tostring(target)][data_cat]
return about
end
local function get_rules(target)
local data = load_data(_config.moderation.data)
local data_cat = 'rules'
if not data[tostring(target)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(target)][data_cat]
return rules
end
local function modlist(target)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] or not data[tostring(groups)][tostring(target)] then
return 'Group is not added or is Realm.'
end
if next(data[tostring(target)]['moderators']) == nil then
return 'No moderator in this group.'
end
local i = 1
local message = '\nList of moderators :\n'
for k,v in pairs(data[tostring(target)]['moderators']) do
message = message ..i..' - @'..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function get_link(target)
local data = load_data(_config.moderation.data)
local group_link = data[tostring(target)]['settings']['set_link']
if not group_link or group_link == nil then
return "No link"
end
return "Group link:\n"..group_link
end
local function all(target, receiver)
local text = "All the things I know about this group\n\n"
local group_type = get_group_type(target)
text = text.."Group Type: \n"..group_type
local settings = show_group_settings(target)
text = text.."\n\nGroup settings: \n"..settings
local rules = get_rules(target)
text = text.."\n\nRules: \n"..rules
local description = get_description(target)
text = text.."\n\nAbout: \n"..description
local modlist = modlist(target)
text = text.."\n\nMods: \n"..modlist
local link = get_link(target)
text = text.."\n\nLink: \n"..link
local stats = chat_stats(target)
text = text.."\n\n"..stats
local ban_list = ban_list(target)
text = text.."\n\n"..ban_list
local file = io.open("./groups/all/"..target.."all.txt", "w")
file:write(text)
file:flush()
file:close()
send_document(receiver,"./groups/all/"..target.."all.txt", ok_cb, false)
return
end
function run(msg, matches)
if matches[1] == "all" and matches[2] and is_owner2(msg.from.id, matches[2]) then
local receiver = get_receiver(msg)
local target = matches[2]
return all(target, receiver)
end
if not is_owner(msg) then
return
end
if matches[1] == "all" and not matches[2] then
local receiver = get_receiver(msg)
if not is_owner(msg) then
return
end
return all(msg.to.id, receiver)
end
end
return {
patterns = {
"^[!/](all)$",
"^[!/](all) (%d+)$"
},
run = run
}
end
| gpl-2.0 |
ashkanpj/beny | plugins/all.lua | 1321 | 4661 | do
data = load_data(_config.moderation.data)
local function get_msgs_user_chat(user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info.msgs = tonumber(redis:get(um_hash) or 0)
user_info.name = user_print_name(user)..' ['..user_id..']'
return user_info
end
local function chat_stats(chat_id)
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = 'Chat stats:\n'
for k,user in pairs(users_info) do
text = text..user.name..' = '..user.msgs..'\n'
end
return text
end
local function get_group_type(target)
local data = load_data(_config.moderation.data)
local group_type = data[tostring(target)]['group_type']
if not group_type or group_type == nil then
return 'No group type available.'
end
return group_type
end
local function show_group_settings(target)
local data = load_data(_config.moderation.data)
if data[tostring(target)] then
if data[tostring(target)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local settings = data[tostring(target)]['settings']
local text = "Lock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX
return text
end
local function get_description(target)
local data = load_data(_config.moderation.data)
local data_cat = 'description'
if not data[tostring(target)][data_cat] then
return 'No description available.'
end
local about = data[tostring(target)][data_cat]
return about
end
local function get_rules(target)
local data = load_data(_config.moderation.data)
local data_cat = 'rules'
if not data[tostring(target)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(target)][data_cat]
return rules
end
local function modlist(target)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] or not data[tostring(groups)][tostring(target)] then
return 'Group is not added or is Realm.'
end
if next(data[tostring(target)]['moderators']) == nil then
return 'No moderator in this group.'
end
local i = 1
local message = '\nList of moderators :\n'
for k,v in pairs(data[tostring(target)]['moderators']) do
message = message ..i..' - @'..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function get_link(target)
local data = load_data(_config.moderation.data)
local group_link = data[tostring(target)]['settings']['set_link']
if not group_link or group_link == nil then
return "No link"
end
return "Group link:\n"..group_link
end
local function all(target, receiver)
local text = "All the things I know about this group\n\n"
local group_type = get_group_type(target)
text = text.."Group Type: \n"..group_type
local settings = show_group_settings(target)
text = text.."\n\nGroup settings: \n"..settings
local rules = get_rules(target)
text = text.."\n\nRules: \n"..rules
local description = get_description(target)
text = text.."\n\nAbout: \n"..description
local modlist = modlist(target)
text = text.."\n\nMods: \n"..modlist
local link = get_link(target)
text = text.."\n\nLink: \n"..link
local stats = chat_stats(target)
text = text.."\n\n"..stats
local ban_list = ban_list(target)
text = text.."\n\n"..ban_list
local file = io.open("./groups/all/"..target.."all.txt", "w")
file:write(text)
file:flush()
file:close()
send_document(receiver,"./groups/all/"..target.."all.txt", ok_cb, false)
return
end
function run(msg, matches)
if matches[1] == "all" and matches[2] and is_owner2(msg.from.id, matches[2]) then
local receiver = get_receiver(msg)
local target = matches[2]
return all(target, receiver)
end
if not is_owner(msg) then
return
end
if matches[1] == "all" and not matches[2] then
local receiver = get_receiver(msg)
if not is_owner(msg) then
return
end
return all(msg.to.id, receiver)
end
end
return {
patterns = {
"^[!/](all)$",
"^[!/](all) (%d+)$"
},
run = run
}
end
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.