Ir para conteúdo
  • Cadastre-se
  1. Lurk

    Lurk

  • Quem Está Navegando   0 membros estão online

    Nenhum usuário registrado visualizando esta página.


  • Conteúdo Similar

    • Por Imperius
      O propósito é criar uma nova função em creaturescripts que será acionada toda vez que um novo report (CTRL + R) for aberto.
       
      Eu implementei para enviar uma notificação no grupo do Telegram, contendo os dados do report.
       
      Isso garantirá que os GMs tenham acesso aos reports dos jogadores mesmo quando não estiverem logados, e também evitará que algum report seja perdido caso o jogador saia do servidor.
      A parte do Telegram é apenas um exemplo. Você pode ajustar o script para executar outras ações desejadas.
       
      creatureevent.cpp:
      Dentro deste arquivo, localize a função:
       
      uint32_t CreatureEvent::executeChannelLeave(Player* player, uint16_t channelId, UsersMap usersMap)  
      abaixo dela, adicione:
       
      uint32_t CreatureEvent::executeOpenRuleViolation(Player* player, std::string message) { if (!m_interface->reserveEnv()) { std::clog << "[Error - CreatureEvent::executeOpenRuleViolation] Call stack overflow." << std::endl; return 0; } ScriptEnviroment* env = m_interface->getEnv(); env->setScriptId(m_scriptId, m_interface); lua_State* L = m_interface->getState(); m_interface->pushFunction(m_scriptId); lua_pushnumber(L, env->addThing(player)); lua_pushstring(L, message.c_str()); bool result = m_interface->callFunction(2); m_interface->releaseEnv(); return result; }  
      Após, procure por:
       
      std::string CreatureEvent::getScriptEventName() const  
      abaixo de:
       
      case CREATURE_EVENT_CHANNEL_LEAVE: return "onLeaveChannel";  
      adicione:
       
      case CREATURE_EVENT_OPEN_RULE_VIOLATION: return "onOpenRuleViolation";  
      Agora, procure por:
       
      std::string CreatureEvent::getScriptEventParams() const  
      abaixo de:
       
      case CREATURE_EVENT_CHANNEL_LEAVE: return "cid, channel, users";  
      adicione:
       
      case CREATURE_EVENT_OPEN_RULE_VIOLATION: return "cid, message";  
      Procure por:
       
      bool CreatureEvent::configureEvent(xmlNodePtr p)  
      abaixo de:
       
      else if(tmpStr == "leavechannel") m_type = CREATURE_EVENT_CHANNEL_LEAVE;  
      adicione:
       
      else if(tmpStr == "openruleviolation") m_type = CREATURE_EVENT_OPEN_RULE_VIOLATION;  
       
      creatureevent.h:
      Dentro deste arquivo, localize:
       
      enum CreatureEventType_t  
      adicione "CREATURE_EVENT_OPEN_RULE_VIOLATION" como o último item de enum CreatureEventType_t
       
      Exemplo:
       
      enum CreatureEventType_t { // ... CREATURE_EVENT_OPEN_RULE_VIOLATION };  
      Agora, procure por:
       
      uint32_t executeChannelLeave(Player* player, uint16_t channelId, UsersMap usersMap);  
      abaixo dela, adicione:
       
      uint32_t executeOpenRuleViolation(Player* player, std::string message);  
      game.cpp:
      Dentro deste arquivo, localize:
       
      bool Game::playerReportRuleViolation(Player* player, const std::string& text)  
      e substitua por:
       
      bool Game::playerReportRuleViolation(Player* player, const std::string& text) { //Do not allow reports on multiclones worlds since reports are name-based if(g_config.getNumber(ConfigManager::ALLOW_CLONES)) { player->sendTextMessage(MSG_INFO_DESCR, "Rule violation reports are disabled."); return false; } cancelRuleViolation(player); boost::shared_ptr<RuleViolation> rvr(new RuleViolation(player, text, time(NULL))); ruleViolations[player->getID()] = rvr; ChatChannel* channel = g_chat.getChannelById(CHANNEL_RVR); if(!channel) return false; for(UsersMap::const_iterator it = channel->getUsers().begin(); it != channel->getUsers().end(); ++it) it->second->sendToChannel(player, SPEAK_RVR_CHANNEL, text, CHANNEL_RVR, rvr->time); CreatureEventList joinEvents = player->getCreatureEvents(CREATURE_EVENT_OPEN_RULE_VIOLATION); for(CreatureEventList::iterator it = joinEvents.begin(); it != joinEvents.end(); ++it) (*it)->executeOpenRuleViolation(player, text); return true; }  
      Agora é só compilar a source.
       
      depois em "data > creaturescripts > creaturescripts.xml", adicione:
       
      <event type="login" name="loginNotifyRuleViolation" script="notifyRuleViolation.lua"/> <event type="openruleviolation" name="openNotifyRuleViolation" script="notifyRuleViolation.lua"/>  
      em "data > creaturescripts > scripts", crie um arquivo notifyRuleViolation.lua e adicione:
       
      function onOpenRuleViolation(cid, message) local config = { token = "", -- Token do seu BOT no Telegram chatId = "" -- ID do chat do Telegram que será enviado a notificação. } local message = "Player: "..getCreatureName(cid).."\n\nReport:\n"..message.."" message = string.gsub(message, "\n", "%%0A") local url = "https://api.telegram.org/bot"..config.token.."/sendMessage" local data = "chat_id="..config.chatId.."&text="..message.."" local curl = io.popen('curl -d "'..data..'" "'..url..'"'):read("*a") return true end function onLogin(cid) registerCreatureEvent(cid, "openNotifyRuleViolation") return true end  
       
      Demonstração:
      1. Jogador abre um novo report (CTRL + R)

      2. notifyRuleViolation.lua, definido em creaturescripts.xml, é acionado para enviar uma notificação ao grupo do Telegram.
       

       
    • Por Underewar
      Precisei dessa função e não achei em lugar nem um aqui está uma versão funcional para tfs 1.2 +.
      Listando o monstro ou player que o jogador morreu.

      Data/Creaturescript/XML
      <event type="login" name="LoginDeath" script="death_tp.lua" /> <event type="preparedeath" name="DeathTeleport" script="death_tp.lua"/> Data/Creaturescript/death_tp.lua
      function onLogin(player) player:registerEvent("DeathTeleport") return true end local maxDeathRecords = 5 -- By Underewar function onPrepareDeath(player, killer) -- Update Death DB local byPlayer = 0 local killerName if killer ~= nil then if killer:isPlayer() then byPlayer = 1 else local master = killer:getMaster() if master and master ~= killer and master:isPlayer() then killer = master byPlayer = 1 end end killerName = killer:getName() else killerName = "field item" end local byPlayerMostDamage = 0 local mostDamageKillerName if mostDamageKiller ~= nil then if mostDamageKiller:isPlayer() then byPlayerMostDamage = 1 else local master = mostDamageKiller:getMaster() if master and master ~= mostDamageKiller and master:isPlayer() then mostDamageKiller = master byPlayerMostDamage = 1 end end mostDamageName = mostDamageKiller:getName() else mostDamageName = "field item" end local playerGuid = player:getGuid() db.query("INSERT INTO `player_deaths` (`player_id`, `time`, `level`, `killed_by`, `is_player`, `mostdamage_by`, `mostdamage_is_player`, `unjustified`, `mostdamage_unjustified`) VALUES (" .. playerGuid .. ", " .. os.time() .. ", " .. player:getLevel() .. ", " .. db.escapeString(killerName) .. ", " .. byPlayer .. ", " .. db.escapeString(mostDamageName) .. ", " .. byPlayerMostDamage .. ", " .. (unjustified and 1 or 0) .. ", " .. (mostDamageUnjustified and 1 or 0) .. ")") local resultId = db.storeQuery("SELECT `player_id` FROM `player_deaths` WHERE `player_id` = " .. playerGuid) local deathRecords = 0 local tmpResultId = resultId while tmpResultId ~= false do tmpResultId = result.next(resultId) deathRecords = deathRecords + 1 end if resultId ~= false then result.free(resultId) end local limit = deathRecords - maxDeathRecords if limit > 0 then db.asyncQuery("DELETE FROM `player_deaths` WHERE `player_id` = " .. playerGuid .. " ORDER BY `time` LIMIT " .. limit) end if byPlayer == 1 then local targetGuild = player:getGuild() targetGuild = targetGuild and targetGuild:getId() or 0 if targetGuild ~= 0 then local killerGuild = killer:getGuild() killerGuild = killerGuild and killerGuild:getId() or 0 if killerGuild ~= 0 and targetGuild ~= killerGuild and isInWar(playerId, killer:getId()) then local warId = false resultId = db.storeQuery("SELECT `id` FROM `guild_wars` WHERE `status` = 1 AND ((`guild1` = " .. killerGuild .. " AND `guild2` = " .. targetGuild .. ") OR (`guild1` = " .. targetGuild .. " AND `guild2` = " .. killerGuild .. "))") if resultId ~= false then warId = result.getDataInt(resultId, "id") result.free(resultId) end if warId ~= false then db.asyncQuery("INSERT INTO `guildwar_kills` (`killer`, `target`, `killerguild`, `targetguild`, `time`, `warid`) VALUES (" .. db.escapeString(killerName) .. ", " .. db.escapeString(player:getName()) .. ", " .. killerGuild .. ", " .. targetGuild .. ", " .. os.time() .. ", " .. warId .. ")") end end end end -- teleportando o player para o templo player:teleportTo(player:getTown():getTemplePosition()) -- enchenco life e mana player:addHealth(player:getMaxHealth()) player:addMana(player:getMaxMana()) -- Remove EXP local level = player:getLevel() player:removeExperience(level * 10 * 100, true) -- DEATH MSG player:sendTextMessage(MESSAGE_EVENT_ADVANCE, "You are dead.") -- criando efeito de teleport player:getPosition():sendMagicEffect(CONST_ME_TELEPORT) return false end  
    • Por Ghaz
      Fala pessoal tudo bem?
       
      Estou com dificuldades em um script e preciso da ajuda dos magos do LUA rs.
       
      Tenho um script que quando o player morre (onDeath), ele faz algumas coisas e depois ele chama uma função que deveria retornar uma table (array) para eu fazer o for com o ipairs certinho. Segue abaixo o código:
       
       
      Segue abaixo a função getPlayersInArea:
       
       
      Acontece que no código de cima (do primeiro spoiler) eu dou um print no retorno da função getPlayersInArea, porém ela não tá me retornando a table, tá me retornando só: 2
       
       
       
      Alguém consegue me ajudar em, como raios eu faço a função retornar a lista de players ao invés da quantidade? Acredito que ta retornando o count da table, e não os itens do array.
       
       
      Agradeço desde já, valeu tchurma!
    • Por FeeTads
      salve rapaziada, estou fazendo uma quest no meu OT que é necessário faze-la durante 10 dias consecutivos, porém caso o player perca um dia, a storage da quest reseta.
      Já tenho esses scripts prontos de 2 formas: global event que checa a storage de todos os player online no momento e caso ja tenha passado 24h ele tira a storage do player que está entre os 10 dias de quest.
      E também tenho um creatureScript de onLogin() que quando o player loga, ele entra num loop de verificação a cada 60s

      minha duvida: globalEvents vai checar todos os players online de uma só vez e fazer as alterações necessarias, isso pode lagar a distro, ou até mesmo crashar?
      o creatureScript vai entrar num loop até o player deslogar, isso numa média de 250 pessoa são diversas verificações em momentos diferentes, pode acabar lagando ou crashando?

      meu OT possui uma media de 300 pessoas online.

      Script globalEvents é esse:

      function onThink(interval, lastExecution)
          local players = {}
          local timer = os.time()
          for _, pid in pairs (getPlayersOnline()) do
              local storage = getPlayerStorageValue(pid, 1231234)
              if getPlayerStorageValue(pid,888251) > 0 and getPlayerStorageValue(pid,888251) <= 9 then
                  if storage - timer <= 1  then
                      table.insert(players, pid)
                  end
              end
          end
          
          if #players > 0 then
              for i = 1, #players do
                  doPlayerSendTextMessage(players[i],22,"seu dano voltou ao normal por vc nao ter feito a quest!")
                  setPlayerStorageValue(players[i],888251,0)
              end
          end
      return true
      end

      Script do Creature é esse:
      local storage = getPlayerStorageValue(cid,1231234)
              function checkStorage(cid) local timer = os.time()
                     if not isPlayer(cid) then return true end
                     if getPlayerStorageValue(cid,888251) > 0 and getPlayerStorageValue(cid, 888251) <= 9 then
                             if storage - timer <= 1 then
                                     setPlayerStorageValue(cid,888251,0)
                             end
                   end
                   addEvent(function()
                              checkStorage(cid)
                    end, 60000)
      end
      function onLogin(cid)
              checkStorage(cid)
      return true
      end
      function onLogout(cid)
             stopEvent(checkStorage[cid])
      return true
      end


      caso os códigos nao estejam legiveis me avisem como arrumar em .lua pf

      se quiserem usar os códigos podem usar a vontade kkkkkkk
    • Por Underewar
      O sistema funciona pelo Target do Monstro, e Regenera Stamina Points.
      Em  events/scripts/creature.lua
      Vamos Adicionar a função a Baixo.
      No mesmo script vamos procurar por
      Creature:onTargetCombat(target) E colocar logo a baixo o seguinte script
      Onde está == "Trainer" Coloque o nome do trainer do seu servidor.
×
×
  • Criar Novo...

Informação Importante

Confirmação de Termo