- Thread Author
- #1
Hi new to scripting and type bots, i would like if someone could use and try my script to see where i can get better and improv it
Its a rev script with prayer flick and anty pk
import com.runemate.game.api.hybrid.entities.*;
import com.runemate.game.api.hybrid.local.hud.Prayer;
import com.runemate.game.api.hybrid.local.hud.interfaces.*;
import com.runemate.game.api.hybrid.region.*;
import com.runemate.game.api.hybrid.location.Area;
import com.runemate.game.api.script.framework.LoopingBot;
import com.runemate.game.api.hybrid.util.Timer;
import java.util.*;
import java.util.function.BooleanSupplier;
public class RevenantAutoBotV2 extends LoopingBot {
// Áreas para roaming entre spots de Revenants
private final Area[] revenantSpots = new Area[]{
new Area(3172, 3840, 3185, 3855),
new Area(3190, 3862, 3205, 3878),
new Area(3210, 3888, 3225, 3900)
};
private int currentSpotIndex = 0;
// Controle para prayer flick
private long lastFlickTime = 0;
private static final long MIN_FLICK_INTERVAL_MS = 2400;
// Controle de loot acumulado
private int totalLootValue = 0;
private static final int LOOT_THRESHOLD = 5_000_000;
// Controle detecção PKer
private boolean pkDetected = false;
private Timer pkTimer = new Timer();
// Tentativas máximas para interação (evitar loop infinito)
private static final int MAX_INTERACTION_ATTEMPTS = 3;
@Override
public void onStart(String... args) {
getLogger().info("Bot automático iniciado: Revenants com melhorias e segurança");
}
@Override
public void onLoop() {
detectPK();
if (pkDetected) {
defensivePreSwitch();
fleeFromPK();
return;
}
if (Inventory.isFull() || totalLootValue >= LOOT_THRESHOLD) {
goToBankAndRestock();
return;
}
if (getPlayers().local().isInCombat()) {
handlePrayerFlick();
} else {
attackNearestRevenant();
}
lootValuableItems();
if (!getPlayers().local().isInCombat() && !isRevenantNearby()) {
roamToNextSpot();
}
}
/**
* Detecta possíveis PKers na área próxima,
* baseando-se em distância, equipamento, combate e nível de combate.
*/
private void detectPK() {
List<Player> nearbyPlayers = Players.newQuery()
.names(p -> !p.equals(getPlayers().local().getName()))
.withinDistance(20)
.results();
pkDetected = false;
for (Player p : nearbyPlayers) {
if (isLikelyPKer(p)) {
pkDetected = true;
pkTimer.reset();
getLogger().info("PKer detectado: " + p.getName());
break;
}
}
// Reseta flag se passou mais de 30s sem detectar PK
if (pkTimer.getElapsed() > 30_000) {
pkDetected = false;
}
}
/**
* Critérios avançados para identificar PKer:
* - Visível e perto
* - Equipamento ofensivo típico de PK
* - Player está em combate ativo
* - Nível de combate >= 50 (exemplo)
*/
private boolean isLikelyPKer(Player p) {
if (!p.isVisible()) return false;
if (p.getPosition().distanceTo(getPlayers().local()) > 20) return false;
if (p.getCombatLevel() < 50) return false;
if (p.isInCombat()) return true;
return p.getEquipment().containsAny(
"Abyssal whip", "Dragon dagger", "Toxic blowpipe", "Armadyl crossbow"
) || p.getPrayer().isAnyActivated();
}
/**
* Ativa pre-switch defensivo de prayer para proteger contra PK.
*/
private void defensivePreSwitch() {
if (!Prayer.PROTECT_FROM_MELEE.isActivated()) {
Prayer.PROTECT_FROM_MELEE.activate();
getLogger().info("Pre-switch defensivo ativado");
}
}
/**
* Executa a fuga contra PK, podendo incluir teleporte ou logout.
* Aqui é um exemplo básico; adapte para seu método de teleporte.
*/
private void fleeFromPK() {
getLogger().info("Fugindo do PK! Executando teleporte para segurança.");
// TODO: substituir pelo seu método de teleporte
// Exemplo: Magic.spell("Varrock teleport").cast();
sleep(7000); // espera simular teleporte
// Também poderia fazer logout, andar para área segura etc.
}
/**
* Ataca o revenant mais próximo que não esteja em combate.
* Tenta a interação com tratamento de erro para evitar travamento.
*/
private void attackNearestRevenant() {
List<String> revenants = Arrays.asList("Revenant demon", "Revenant ork", "Revenant pyrefiend");
Npc target = Npcs.newQuery()
.names(revenants)
.actions("Attack")
.filter(npc -> !npc.isInCombat() && npc.getPosition().distanceTo(getPlayers().local()) < 12)
.results()
.nearest();
if (target != null) {
getLogger().info("Tentando atacar: " + target.getName());
boolean interacted = tryInteract(target, "Attack");
if (interacted) {
sleepUntil(() -> getPlayers().local().isInCombat(), 3000);
}
}
}
/**
* Verifica se existem revenants próximos para farm.
*/
private boolean isRevenantNearby() {
List<String> revenants = Arrays.asList("Revenant demon", "Revenant ork", "Revenant pyrefiend");
return Npcs.newQuery()
.names(revenants)
.actions("Attack")
.results()
.size() > 0;
}
/**
* Roda para o próximo spot de revenants para continuar farmando.
*/
private void roamToNextSpot() {
currentSpotIndex = (currentSpotIndex + 1) % revenantSpots.length;
getLogger().info("Indo para o spot " + (currentSpotIndex + 1));
getWalking().walk(revenantSpots[currentSpotIndex].getCenter());
sleepUntil(() -> getPlayers().local().getPosition().distanceTo(revenantSpots[currentSpotIndex].getCenter()) < 5, 5000);
}
/**
* Controla o prayer flick para economia de pontos de oração.
* Usa timer para evitar flicks muito rápidos.
*/
private void handlePrayerFlick() {
long now = System.currentTimeMillis();
if (now - lastFlickTime >= MIN_FLICK_INTERVAL_MS) {
if (Prayer.getPoints() > 5) {
if (!Prayer.PROTECT_FROM_MELEE.isActivated()) {
Prayer.PROTECT_FROM_MELEE.activate();
}
sleep(80, 120);
Prayer.PROTECT_FROM_MELEE.deactivate();
lastFlickTime = now;
getLogger().info("Prayer flick ativado");
}
}
}
/**
* Coleta loot valioso no chão, garantindo visibilidade e alcance,
* e utiliza Looting Bag para otimizar espaço no inventário.
*/
private void lootValuableItems() {
GroundItem loot = GroundItems.newQuery()
.filter(item -> isLootValuableAndAccessible(item))
.results()
.nearest();
if (loot != null) {
getLogger().info("Tentando coletar loot: " + loot.getName());
boolean success = tryInteract(loot, "Take");
if (success) {
sleepUntil(() -> !loot.isValid(), 3000);
totalLootValue += loot.getDefinition().getPrice();
}
}
// Usar Looting Bag para guardar itens valiosos e liberar inventário
if (Inventory.contains("Looting bag")) {
List<Item> itemsToStore = Inventory.getItems(i -> {
if (i.getDefinition() == null) return false;
return i.getDefinition().getPrice() > 8000 && !i.getName().toLowerCase().contains("potion");
});
for (Item i : itemsToStore) {
boolean used = tryUseOnLootingBag(i);
if (used) sleep(300, 600);
}
}
}
/**
* Verifica se o loot é valioso, visível e próximo o suficiente para coleta.
*/
private boolean isLootValuableAndAccessible(GroundItem item) {
if (item == null || !item.isVisible() || !item.isValid()) return false;
if (item.getPosition().distanceTo(getPlayers().local()) > 7) return false;
if (item.getDefinition() == null) return false;
return item.getDefinition().getPrice() > 10_000;
}
/**
* Vai para o banco, deposita loot e reabastece potes.
* Utiliza sleepUntil para aguardar interfaces.
*/
private void goToBankAndRestock() {
getLogger().info("Indo para banco para depositar loot e reabastecer");
// TODO: substituir por teleporte ao banco no seu client
sleep(7000);
if (Bank.open()) {
Bank.depositAllExcept(i -> i.getName().toLowerCase().contains("prayer potion") || i.getName().toLowerCase().contains("looting bag"));
sleepUntil(() -> Inventory.isEmpty() || !Inventory.isFull(), 3000);
if (!Inventory.contains("Prayer potion(4)")) {
if (Bank.contains("Prayer potion(4)")) {
Bank.withdraw("Prayer potion(4)", 4);
sleepUntil(() -> Inventory.contains("Prayer potion(4)"), 3000);
}
}
Bank.close();
sleep(1000);
} else {
getLogger().warning("Falha ao abrir banco, tentando novamente na próxima iteração");
}
totalLootValue = 0;
// Voltar para o spot atual de revenants
getLogger().info("Retornando ao farming");
getWalking().walk(revenantSpots[currentSpotIndex].getCenter());
sleepUntil(() -> getPlayers().local().getPosition().distanceTo(revenantSpots[currentSpotIndex].getCenter()) < 5, 5000);
}
/**
* Tenta interagir com uma entidade (NPC ou GroundItem) com tratamento de erro e tentativas limitadas.
*/
private boolean tryInteract(Entity entity, String action) {
int attempts = 0;
while (attempts < MAX_INTERACTION_ATTEMPTS) {
if (entity != null && entity.isValid() && entity.interact(action)) {
return true;
}
attempts++;
sleep(200, 400);
}
getLogger().warning("Falha ao tentar interagir com " + (entity != null ? entity.getName() : "entidade desconhecida"));
return false;
}
/**
* Usa um item no inventário na Looting Bag para guardar.
*/
private boolean tryUseOnLootingBag(Item item) {
if (item == null || !Inventory.contains("Looting bag")) return false;
int attempts = 0;
while (attempts < MAX_INTERACTION_ATTEMPTS) {
if (item.interact("Use")) {
sleep(300, 500);
Item bag = Inventory.getItem("Looting bag");
if (bag != null && bag.interact("Use")) {
return true;
}
}
attempts++;
sleep(200, 400);
}
getLogger().warning("Falha ao tentar usar " + (item != null ? item.getName() : "item desconhecido") + " na Looting Bag");
return false;
}
/**
* Sleep com timeout e condição customizada para aguardar estado.
*/
private void sleepUntil(BooleanSupplier condition, int timeoutMs) {
int waited = 0;
int interval = 100;
while (!condition.getAsBoolean() && waited < timeoutMs) {
sleep(interval);
waited += interval;
}
}
}
Its a rev script with prayer flick and anty pk
import com.runemate.game.api.hybrid.entities.*;
import com.runemate.game.api.hybrid.local.hud.Prayer;
import com.runemate.game.api.hybrid.local.hud.interfaces.*;
import com.runemate.game.api.hybrid.region.*;
import com.runemate.game.api.hybrid.location.Area;
import com.runemate.game.api.script.framework.LoopingBot;
import com.runemate.game.api.hybrid.util.Timer;
import java.util.*;
import java.util.function.BooleanSupplier;
public class RevenantAutoBotV2 extends LoopingBot {
// Áreas para roaming entre spots de Revenants
private final Area[] revenantSpots = new Area[]{
new Area(3172, 3840, 3185, 3855),
new Area(3190, 3862, 3205, 3878),
new Area(3210, 3888, 3225, 3900)
};
private int currentSpotIndex = 0;
// Controle para prayer flick
private long lastFlickTime = 0;
private static final long MIN_FLICK_INTERVAL_MS = 2400;
// Controle de loot acumulado
private int totalLootValue = 0;
private static final int LOOT_THRESHOLD = 5_000_000;
// Controle detecção PKer
private boolean pkDetected = false;
private Timer pkTimer = new Timer();
// Tentativas máximas para interação (evitar loop infinito)
private static final int MAX_INTERACTION_ATTEMPTS = 3;
@Override
public void onStart(String... args) {
getLogger().info("Bot automático iniciado: Revenants com melhorias e segurança");
}
@Override
public void onLoop() {
detectPK();
if (pkDetected) {
defensivePreSwitch();
fleeFromPK();
return;
}
if (Inventory.isFull() || totalLootValue >= LOOT_THRESHOLD) {
goToBankAndRestock();
return;
}
if (getPlayers().local().isInCombat()) {
handlePrayerFlick();
} else {
attackNearestRevenant();
}
lootValuableItems();
if (!getPlayers().local().isInCombat() && !isRevenantNearby()) {
roamToNextSpot();
}
}
/**
* Detecta possíveis PKers na área próxima,
* baseando-se em distância, equipamento, combate e nível de combate.
*/
private void detectPK() {
List<Player> nearbyPlayers = Players.newQuery()
.names(p -> !p.equals(getPlayers().local().getName()))
.withinDistance(20)
.results();
pkDetected = false;
for (Player p : nearbyPlayers) {
if (isLikelyPKer(p)) {
pkDetected = true;
pkTimer.reset();
getLogger().info("PKer detectado: " + p.getName());
break;
}
}
// Reseta flag se passou mais de 30s sem detectar PK
if (pkTimer.getElapsed() > 30_000) {
pkDetected = false;
}
}
/**
* Critérios avançados para identificar PKer:
* - Visível e perto
* - Equipamento ofensivo típico de PK
* - Player está em combate ativo
* - Nível de combate >= 50 (exemplo)
*/
private boolean isLikelyPKer(Player p) {
if (!p.isVisible()) return false;
if (p.getPosition().distanceTo(getPlayers().local()) > 20) return false;
if (p.getCombatLevel() < 50) return false;
if (p.isInCombat()) return true;
return p.getEquipment().containsAny(
"Abyssal whip", "Dragon dagger", "Toxic blowpipe", "Armadyl crossbow"
) || p.getPrayer().isAnyActivated();
}
/**
* Ativa pre-switch defensivo de prayer para proteger contra PK.
*/
private void defensivePreSwitch() {
if (!Prayer.PROTECT_FROM_MELEE.isActivated()) {
Prayer.PROTECT_FROM_MELEE.activate();
getLogger().info("Pre-switch defensivo ativado");
}
}
/**
* Executa a fuga contra PK, podendo incluir teleporte ou logout.
* Aqui é um exemplo básico; adapte para seu método de teleporte.
*/
private void fleeFromPK() {
getLogger().info("Fugindo do PK! Executando teleporte para segurança.");
// TODO: substituir pelo seu método de teleporte
// Exemplo: Magic.spell("Varrock teleport").cast();
sleep(7000); // espera simular teleporte
// Também poderia fazer logout, andar para área segura etc.
}
/**
* Ataca o revenant mais próximo que não esteja em combate.
* Tenta a interação com tratamento de erro para evitar travamento.
*/
private void attackNearestRevenant() {
List<String> revenants = Arrays.asList("Revenant demon", "Revenant ork", "Revenant pyrefiend");
Npc target = Npcs.newQuery()
.names(revenants)
.actions("Attack")
.filter(npc -> !npc.isInCombat() && npc.getPosition().distanceTo(getPlayers().local()) < 12)
.results()
.nearest();
if (target != null) {
getLogger().info("Tentando atacar: " + target.getName());
boolean interacted = tryInteract(target, "Attack");
if (interacted) {
sleepUntil(() -> getPlayers().local().isInCombat(), 3000);
}
}
}
/**
* Verifica se existem revenants próximos para farm.
*/
private boolean isRevenantNearby() {
List<String> revenants = Arrays.asList("Revenant demon", "Revenant ork", "Revenant pyrefiend");
return Npcs.newQuery()
.names(revenants)
.actions("Attack")
.results()
.size() > 0;
}
/**
* Roda para o próximo spot de revenants para continuar farmando.
*/
private void roamToNextSpot() {
currentSpotIndex = (currentSpotIndex + 1) % revenantSpots.length;
getLogger().info("Indo para o spot " + (currentSpotIndex + 1));
getWalking().walk(revenantSpots[currentSpotIndex].getCenter());
sleepUntil(() -> getPlayers().local().getPosition().distanceTo(revenantSpots[currentSpotIndex].getCenter()) < 5, 5000);
}
/**
* Controla o prayer flick para economia de pontos de oração.
* Usa timer para evitar flicks muito rápidos.
*/
private void handlePrayerFlick() {
long now = System.currentTimeMillis();
if (now - lastFlickTime >= MIN_FLICK_INTERVAL_MS) {
if (Prayer.getPoints() > 5) {
if (!Prayer.PROTECT_FROM_MELEE.isActivated()) {
Prayer.PROTECT_FROM_MELEE.activate();
}
sleep(80, 120);
Prayer.PROTECT_FROM_MELEE.deactivate();
lastFlickTime = now;
getLogger().info("Prayer flick ativado");
}
}
}
/**
* Coleta loot valioso no chão, garantindo visibilidade e alcance,
* e utiliza Looting Bag para otimizar espaço no inventário.
*/
private void lootValuableItems() {
GroundItem loot = GroundItems.newQuery()
.filter(item -> isLootValuableAndAccessible(item))
.results()
.nearest();
if (loot != null) {
getLogger().info("Tentando coletar loot: " + loot.getName());
boolean success = tryInteract(loot, "Take");
if (success) {
sleepUntil(() -> !loot.isValid(), 3000);
totalLootValue += loot.getDefinition().getPrice();
}
}
// Usar Looting Bag para guardar itens valiosos e liberar inventário
if (Inventory.contains("Looting bag")) {
List<Item> itemsToStore = Inventory.getItems(i -> {
if (i.getDefinition() == null) return false;
return i.getDefinition().getPrice() > 8000 && !i.getName().toLowerCase().contains("potion");
});
for (Item i : itemsToStore) {
boolean used = tryUseOnLootingBag(i);
if (used) sleep(300, 600);
}
}
}
/**
* Verifica se o loot é valioso, visível e próximo o suficiente para coleta.
*/
private boolean isLootValuableAndAccessible(GroundItem item) {
if (item == null || !item.isVisible() || !item.isValid()) return false;
if (item.getPosition().distanceTo(getPlayers().local()) > 7) return false;
if (item.getDefinition() == null) return false;
return item.getDefinition().getPrice() > 10_000;
}
/**
* Vai para o banco, deposita loot e reabastece potes.
* Utiliza sleepUntil para aguardar interfaces.
*/
private void goToBankAndRestock() {
getLogger().info("Indo para banco para depositar loot e reabastecer");
// TODO: substituir por teleporte ao banco no seu client
sleep(7000);
if (Bank.open()) {
Bank.depositAllExcept(i -> i.getName().toLowerCase().contains("prayer potion") || i.getName().toLowerCase().contains("looting bag"));
sleepUntil(() -> Inventory.isEmpty() || !Inventory.isFull(), 3000);
if (!Inventory.contains("Prayer potion(4)")) {
if (Bank.contains("Prayer potion(4)")) {
Bank.withdraw("Prayer potion(4)", 4);
sleepUntil(() -> Inventory.contains("Prayer potion(4)"), 3000);
}
}
Bank.close();
sleep(1000);
} else {
getLogger().warning("Falha ao abrir banco, tentando novamente na próxima iteração");
}
totalLootValue = 0;
// Voltar para o spot atual de revenants
getLogger().info("Retornando ao farming");
getWalking().walk(revenantSpots[currentSpotIndex].getCenter());
sleepUntil(() -> getPlayers().local().getPosition().distanceTo(revenantSpots[currentSpotIndex].getCenter()) < 5, 5000);
}
/**
* Tenta interagir com uma entidade (NPC ou GroundItem) com tratamento de erro e tentativas limitadas.
*/
private boolean tryInteract(Entity entity, String action) {
int attempts = 0;
while (attempts < MAX_INTERACTION_ATTEMPTS) {
if (entity != null && entity.isValid() && entity.interact(action)) {
return true;
}
attempts++;
sleep(200, 400);
}
getLogger().warning("Falha ao tentar interagir com " + (entity != null ? entity.getName() : "entidade desconhecida"));
return false;
}
/**
* Usa um item no inventário na Looting Bag para guardar.
*/
private boolean tryUseOnLootingBag(Item item) {
if (item == null || !Inventory.contains("Looting bag")) return false;
int attempts = 0;
while (attempts < MAX_INTERACTION_ATTEMPTS) {
if (item.interact("Use")) {
sleep(300, 500);
Item bag = Inventory.getItem("Looting bag");
if (bag != null && bag.interact("Use")) {
return true;
}
}
attempts++;
sleep(200, 400);
}
getLogger().warning("Falha ao tentar usar " + (item != null ? item.getName() : "item desconhecido") + " na Looting Bag");
return false;
}
/**
* Sleep com timeout e condição customizada para aguardar estado.
*/
private void sleepUntil(BooleanSupplier condition, int timeoutMs) {
int waited = 0;
int interval = 100;
while (!condition.getAsBoolean() && waited < timeoutMs) {
sleep(interval);
waited += interval;
}
}
}