BotHub Framework

A comprehensive C# .NET 8 game automation framework with 150+ features spanning anti-detection, combat, skilling, market automation, farm management, visual scripting, and analytics. Built with a unified service architecture via BotContext.

143
Source Files
150+
Features
32
Directories
20+
Categories
Visual Script Editor
Drag & drop nodes to build bot logic

Script Creation Tutorial STEP-BY-STEP

A complete walkthrough for creating your first custom C# script, from opening Visual Studio to building, loading in-game, and running via the Script Manager.

Part 1: Setting Up Visual Studio
  1. Open Visual Studio

    Launch Visual Studio 2022 (Community edition or higher). If you don't have it installed, download it from visualstudio.microsoft.com and make sure the .NET desktop development workload is selected during installation.

  2. Create a Class Library Project

    Go to File → New → Project, search for "Class Library", and select the C# one targeting .NET 8.0. Name it something descriptive like MyBotScripts.

    This gives you full IntelliSense, autocomplete, and compile-time error checking. When you build the project, Visual Studio produces a .dll file that BotHub loads directly — no runtime compilation needed.

  3. Add BotCore Reference

    To get autocomplete on AbstractScript, BotContext, Actions, and everything else:

    • Right-click your project in Solution ExplorerAddProject Reference (or Add Reference → Browse)
    • Navigate to BotHub's install directory and select BotCore.dll
    • Click OK — you now have full IntelliSense for the entire framework
    Important: After adding the reference, right-click BotCore under your project's Dependencies → Assemblies, select Properties, and set Copy Local to No. This prevents Visual Studio from copying a second BotCore.dll into your build output, which would cause a type mismatch when loading your script.
    Also add Hexa.NET.ImGui.dll (same folder, also Copy Local = No) if you want to create custom ImGui displays (Part 4).
  4. Rename the Default Class

    Visual Studio automatically creates a file called Class1.cs with a class named Class1 inside it. You need to rename both to something descriptive:

    • In Solution Explorer, right-click Class1.cs and select Rename
    • Type a descriptive name for your script, e.g. WillowChopper.cs
    • Visual Studio will ask "Would you also like to rename all references to Class1?" — click Yes. This renames the class inside the file to match.

    Some examples of good script names:

    • WillowChopper.cs — a woodcutting script
    • CowKiller.cs — a combat script
    • FlaxSpinner.cs — a crafting script
    The file name and class name should always match. Visual Studio handles this for you when you use Rename. Use PascalCase with no spaces (e.g. DraynorWillowChopper, not draynor willow chopper).
Part 2: Writing Your Script
  1. Replace the Default Code

    After renaming, your file will look something like this — an empty class inside the namespace Visual Studio created from your project name:

    namespace MyBotScripts { public class WillowChopper { } }

    Replace the entire contents of the file with the template below. Notice we keep the same namespace and class name — just add the BotHub imports, extend AbstractScript, and fill in the required properties:

    using System.Threading.Tasks; using BotCore.Engine; using BotCore.API; namespace MyBotScripts { public class WillowChopper : AbstractScript { public override string Name => "Willow Chopper"; public override string Description => "Chops willows and banks logs"; public override string Author => "YourName"; public override string Version => "1.0.0"; public override string Category => "Woodcutting"; protected override async Task Run() { while (!ShouldStop) { // Your logic goes here await Delay(500); } } } }
    What changed? We added three using imports at the top, made the class extend AbstractScript, added the five required properties (Name, Description, Author, Version, Category), and added the Run() method. The namespace and class name stay the same as what Visual Studio gave you.
  2. Customize Your Script Metadata

    Now update the five properties at the top of the class to match your script. These are what users see in the Script Manager panel:

    • Name — Human-readable name shown in the UI. Change "Willow Chopper" to whatever fits your script.
    • Description — Short summary of what the script does
    • Author — Replace "YourName" with your username or alias
    • Version — Semantic version string, start with "1.0.0"
    • Category — One of: Combat, Skilling, MoneyMaking, Minigame, Questing, Utility, AIO, Prayer, Magic, Agility, Mining, Fishing, Woodcutting, Farming, Hunter, Slayer, Thieving, Other
  3. Write the Main Loop

    The Run() method is your script's main loop. Use the while (!ShouldStop) pattern so the framework can cleanly stop your script. Here's a real example — a tree chopper with banking:

    protected override async Task Run() { while (!ShouldStop) { await CheckBreak(); // Auto break scheduling await CheckRandomEvents(); // Handle genie, etc. await MaybeMistake(); // Anti-detection misclicks if (InventoryFull) { Log("Inventory full, banking..."); await WalkTo(2886, 3534); // InteractObject(action, objectId, tileX, tileY, offset) await Actions.InteractObject(46, 134036, 2886, 3535, 3808); await Actions.WaitUntilIdle(1500); Interface.Interact(-1, 1, 1, 517, 39, -1, 80); await WalkTo(2882, 3532); } else { Log("Chopping tree..."); await Actions.InteractObject(59, 38785, 2881, 3534, 3712); await Actions.WaitUntilIdle(10000); } await Delay(300); // 300ms base mean - actual wait varies (e.g. 150-500ms) } }
    About Delay(): The number you pass (e.g. 300) is NOT a fixed wait — it's a base mean in milliseconds. Under the hood, Delay() calls Ctx.SmartDelay() which applies Gaussian randomization, fatigue scaling, circadian rhythm, and entropy matching. So Delay(300) might actually wait 180ms, 420ms, 350ms, or 510ms — never the same value twice.
  4. Use Built-in Convenience Methods

    AbstractScript gives you these methods out of the box — no extra imports needed:

    • Log("message") / LogWarn("msg") / LogError("msg") — Structured logging
    • Delay(baseMeanMs) — Randomized humanized delay (NOT a fixed wait)
    • WalkTo(x, y) — Pathfind and walk to a tile
    • IsNear(x, y, radius) — Check proximity to a tile
    • InventoryFull / HasItem(id) / InvCount — Inventory checks
    • CheckBreak() — Handles break scheduling automatically
    • CheckRandomEvents() — Solves genies, strange plants, etc.
    • MaybeMistake() — Injects humanized misclicks
    • RecordAction("what") — Anti-AFK activity recording
    • ShouldStop — True when user clicks Stop or cancellation is requested
    Access the full framework via Ctx — e.g. Ctx.Combat, Ctx.Banking, Ctx.Stats, Ctx.WorldState, and 40+ more systems.
Part 3: Finding Action & Object IDs

Every in-game object (trees, banks, NPCs) has a unique ID that can change between game patches. You need the correct IDs for your script to interact with objects. There are two ways to find them:

  1. Method 1: Use the Console Log

    With BotHub injected, manually click on the object you want to interact with (e.g. click a tree to chop it). Watch the BotHub console window — it logs every action the game processes:

    ** OBJECT INTERACTION DETECTED id=0x3B at (2881,3534) ** Sending to C#: OBJECT(action: 59 id: 38785 x: 2881 y: 3534 offset: 3712)

    This tells you exactly what to put in your script:

    • action: 59 — the action code (e.g. "Chop down")
    • id: 38785 — the object ID for that specific tree
    • x: 2881, y: 3534 — the tile coordinates
    • offset: 3712 — the action queue offset

    Use these values in your script:

    await Actions.InteractObject(59, 38785, 2881, 3534, 3712);
    Common mistake: Object IDs can differ between seemingly identical objects. A willow tree on one tile may have id 38785 while the same-looking willow one tile over has id 38783. Always verify the ID by clicking the exact object you want your script to use.
  2. Method 2: Use Record New Script

    Click the "Record New Script" button in the Script Manager. This starts recording your clicks and captures all the action codes, object IDs, and tile coordinates automatically. When you stop recording, the captured data can be used to generate a script or just to copy the correct IDs into your own code.

Part 4: Build Your Project
  1. Build the DLL

    In Visual Studio, press Ctrl+Shift+B (or Build → Build Solution). This compiles your script into a DLL file. Look for:

    MyBotScripts/ bin/ Debug/ net8.0/ MyBotScripts.dll ← THIS is what you load in-game BotCore.dll ← delete this (or set Copy Local = No)

    Check the Output window at the bottom of Visual Studio — it should show "Build succeeded" with 0 errors.

    Important: If you see a BotCore.dll in your output folder, delete it. If the bot loads YOUR copy of BotCore alongside the real one, types won't match and loading will fail with "No IScript class found". Prevent this permanently by setting Copy Local = No on the BotCore reference (see Part 1 Step 3).
  2. Verify Build Output

    Make sure your DLL exists and has a recent timestamp. The file path will be something like:

    C:\Users\YourName\source\repos\MyBotScripts\bin\Debug\net8.0\MyBotScripts.dll

    Remember this path — you'll navigate to it in the next step.

Part 5: Loading Your Script In-Game
  1. Open the Script Manager In-Game

    With BotHub injected into the game client, open the Script Manager panel from the in-game toolbar.

  2. Click "Load Script"

    At the top of the Script Manager, click the blue "Load Script" button. This opens a file browser with:

    • Drive buttons (C:, D:, etc.) for quick navigation
    • Desktop / Documents shortcut buttons
    • ".." (up) to go to the parent folder
    • [FolderName] entries (blue) to navigate into folders
    • FileName.dll / FileName.cs entries (green) to select a script

    Navigate to your Visual Studio project's build output folder (e.g. MyBotScripts\bin\Debug\net8.0\) and click on MyBotScripts.dll.

  3. Click "Compile & Load"

    With your DLL selected, click the green "Compile & Load" button. The loader:

    • Loads the assembly directly into memory (reads bytes, no file lock)
    • Discovers scripts — finds all classes that extend AbstractScript
    • Registers them in the local library (Scripts/library.json) with the full file path

    The status line shows: "Loaded 1 script(s): WillowChopper"

    Your script now appears in the Installed Scripts list below.

    Persisted across restarts: The DLL path is saved in library.json. Next time you inject, the script stays in the Installed list. Clicking Run re-loads the DLL from the same path — so if you rebuild in Visual Studio, the next Run picks up your changes automatically.
  4. Run Your Script

    In the Installed Scripts list, click the green Run button next to your script. The status shows "Running WillowChopper" and your script's Run() method starts executing.

    To stop: click the red Stop button (same position). This sets ShouldStop = true, which exits your while (!ShouldStop) loop cleanly.

  5. Update Your Script

    The edit-test cycle is simple:

    • Edit your code in Visual Studio
    • Press Ctrl+Shift+B to rebuild
    • In-game, click Stop (if running) then Run again — it reloads the latest DLL automatically

    No need to click "Load Script" again — the path is already saved. Just rebuild and re-run.

Part 6: Adding a Custom ImGui Display

Scripts can draw custom in-game UI by implementing the IScriptPainter interface. Your OnPaintImGui() method is called every frame while the script is running. Add Hexa.NET.ImGui.dll as a reference (Copy Local = No) to use this feature.

  1. Implement IScriptPainter

    Add IScriptPainter to your class declaration and implement OnPaintImGui():

    using System.Numerics; using System.Threading.Tasks; using Hexa.NET.ImGui; using BotCore.Engine; using BotCore.API; namespace MyBotScripts { public class WillowChopper : AbstractScript, IScriptPainter { public override string Name => "Willow Chopper"; // ... other properties ... private int _logsChopped = 0; public void OnPaintImGui() { ImGui.SetNextWindowSize(new Vector2(250, 120), ImGuiCond.FirstUseEver); if (ImGui.Begin("Willow Chopper")) { ImGui.Text($"Logs: {_logsChopped}"); float inv = InvCount / 28f; ImGui.ProgressBar(inv, new Vector2(-1, 18), $"Inventory: {InvCount}/28"); var col = InventoryFull ? new Vector4(1f,0.4f,0.4f,1f) : new Vector4(0.3f,1f,0.3f,1f); ImGui.TextColored(col, InventoryFull ? "Banking..." : "Chopping..."); } ImGui.End(); } protected override async Task Run() { while (!ShouldStop) { _logsChopped++; await Delay(300); } } } }
    Registration is automatic. AbstractScript registers your painter on start and unregisters on stop.
  2. Important Rules

    • Thread safetyOnPaintImGui() runs on the render thread. Use simple types (int, bool) for shared state.
    • Always call ImGui.End() after every ImGui.Begin()
    • No heavy work — runs every frame (~16ms). Just read state and draw.
Tips & Best Practices
Script Structure
  • Always use while (!ShouldStop) as your main loop guard
  • Always use Delay(baseMean) instead of Task.Delay() — SmartDelay adds Gaussian noise, fatigue, circadian, and entropy variation so the actual wait is different every time
  • Call await CheckBreak() at the top of each loop iteration
  • Use RecordAction() to prevent anti-AFK timeouts
  • Use Log() generously for debugging
Building & Loading
  • Build with Ctrl+Shift+B in Visual Studio to produce your .dll
  • Load via Load Script in the in-game Script Manager — navigate to your bin/Debug/net8.0/ folder
  • The DLL path is saved — after rebuild, just click Run again (no need to re-load)
  • Set Copy Local = No on BotCore.dll reference to prevent type identity mismatches
  • Delete any stale BotCore.dll from your build output folder if loading fails
Anti-Detection
  • Call await MaybeMistake() periodically to inject humanized misclicks and pauses
  • Don't hard-code exact delays — always use Delay(baseMean) which adds Gaussian noise
  • Use Ctx.BanRisk.GetScore() to monitor your ban risk score and adjust behavior
  • Access the full humanization suite via Ctx.Fatigue, Ctx.Circadian, Ctx.Entropy, Ctx.Mistakes
Troubleshooting
  • "No IScript class found" — You're loading the wrong DLL (e.g. BotCore.dll instead of your script DLL), OR a stale BotCore.dll sits next to your DLL causing a type mismatch. Fix: delete the extra BotCore.dll from your output folder.
  • Action queued but nothing happens — The object ID is wrong. Manually click the object and check the console log for the correct ID. IDs can differ between identical-looking objects.
  • Script loads but crashes immediately — Check the status bar for the error. Common: NullReferenceException from calling Ctx methods before Run() is entered.
  • Script not in Installed list after load — The load may have silently failed. Check the status line at the bottom of the Script Manager for diagnostic messages.

Architecture

All systems are accessed through BotContext, wired together via SystemWiring, and fed live data by GameStatePoller. Scripts extend AbstractScript and get the full framework for free.

BotHubInject_Load() | +--> BotRuntime.Initialize() | +--> new BotContext() | +--> Constructs ALL 60+ subsystems +--> SystemWiring.WireAll() connects events +--> CrashDump.Install() +--> .Start() launches background services: | +--> GameStatePoller -> publishes to EventBus +--> AntiAFK heartbeat +--> AntiCrashRecovery monitor EventBus receives: PlayerMoved, HealthChanged, LevelUp, CombatStarted... +--> SessionStats auto-tracks XP/GP/kills +--> NotificationSystem fires toasts +--> ScreenshotCapture grabs on death +--> DiscordWebhook sends alerts +--> ProfitTracker records GP flow Scripts run via: BotRuntime.StartScript(new MyScript()) +--> AbstractScript.Run() has access to: +--> Ctx.Combat, Ctx.Banking, Ctx.AutoEat... +--> Delay() (fatigue + circadian + entropy) +--> CheckBreak() (auto scheduling) +--> MaybeMistake() (anti-detection)

Quick Start

Create a script by extending AbstractScript. You get access to every system through Ctx.

using System.Threading.Tasks; using BotCore.Engine; using BotCore.API; namespace MyBotScripts { public class MyGatherer : AbstractScript { public override string Name => "My Gatherer"; public override string Category => "Skilling"; protected override async Task Run() { while (!ShouldStop) { await CheckBreak(); // Auto break scheduling await MaybeMistake(); // Anti-detection mistakes if (InventoryFull) await Ctx.Banking.DepositAll(CT); else await Actions.InteractObject(62, 11360, 3285, 3365); await Delay(300); // 300ms base mean - actual wait varies } } } }

BotContext CORE

Central service container that constructs, holds, and exposes every subsystem. Script authors get ONE object that provides access to the entire framework. Handles lifecycle (start/stop), background service management, and cross-system wiring.

BotContext.csEngine/BotContext.cs
Properties: Events, Pipeline, Logger, Poller, Combat, Rotation, AutoEat, Deaths, Stats, BanRisk, Banking, Chat, WorldHop, Plugins, and 40+ more. Methods: Start(), Stop(), GetDelay(), SmartDelay(), CheckBreak().
BotContext

BotRuntime

Static bridge between BotHubInject (entry point) and BotContext (framework). Call BotRuntime.Initialize() once to make the entire framework live.

BotRuntime.csEngine/BotRuntime.cs
Static methods: Initialize(), StartScript(), StopScript(), PauseScript(), ResumeScript(), Shutdown(). Global access via BotRuntime.Ctx.
BotRuntime (static)

IScript / AbstractScript

Standard contract for all bot scripts with proper lifecycle management. AbstractScript provides convenience methods for logging, delays, inventory checks, breaks, and random events.

IScript.csEngine/IScript.cs
Interface: Name, Description, Author, Version, Category, OnStart(), OnStop(), OnPause(), OnResume(). Base class: Log(), Delay(), WalkTo(), IsNear(), InventoryFull, HasItem(), CheckBreak(), MaybeMistake().
IScriptAbstractScript

EventBus

Central pub/sub event system. Any component can publish events and any component can subscribe to them by type. 15+ built-in event types.

EventBus.csEngine/EventBus.cs
Events: PlayerMovedEvent, PlayerDiedEvent, InventoryChangedEvent, CombatStartedEvent, CombatEndedEvent, LevelUpEvent, HealthChangedEvent, LowHealthEvent, NPCSpawnedEvent, ItemDroppedEvent, ScriptStateChangedEvent, BotPausedEvent, BotResumedEvent, BreakStartedEvent, BreakEndedEvent, PlayerIdleEvent.
EventBusGameEventPlayerMovedEventLevelUpEventHealthChangedEvent

GameStatePoller

Background loop that polls game state every 600ms and publishes events to the EventBus. This is the heartbeat that makes the entire event-driven architecture work.

GameStatePoller.csEngine/GameStatePoller.cs
Detects: position changes, health changes, combat start/end, idle state, inventory changes, skill XP gains, level ups. Pushes all changes to EventBus automatically.
GameStatePoller

SystemWiring

Wires cross-system event subscriptions so all 150+ systems work together as an integrated platform. Called once from BotContext constructor.

SystemWiring.csEngine/SystemWiring.cs
Connects: Combat kills -> Stats, Deaths -> Screenshots + Discord, LevelUp -> Stats + Discord + Screenshots, Health -> AutoEat, Inventory -> ProfitTracker, Breaks -> Stats + Fatigue. Wires 30+ Log events to StructuredLogger.
SystemWiring (static)

TaskPipeline

Async task pipeline with proper cancellation, pause/resume, and state tracking. Replaces ad-hoc while(true) loops with structured execution.

TaskPipeline.csEngine/TaskPipeline.cs
States: Idle, Running, Paused, Stopping, Stopped. Methods: RunLoop(), RunQueue(), Pause(), Resume(), Stop(), SafeDelay(). Events: TaskStarted, TaskCompleted, TaskFailed, StateChanged.
TaskPipelinePipelineState

Resilience

Retry with backoff, safe wrappers for memory reads, and circuit breaker for APIs that start failing. Prevents a single failed memory read from crashing scripts.

Resilience.csEngine/Resilience.cs
Static methods: RetryAsync(), Retry(), SafeRead(), SafeReadAsync(), SafeExecute(), SafeExecuteAsync(). Class: CircuitBreaker with Execute(), ExecuteAsync(), Reset().
Resilience (static)CircuitBreaker

ScriptChainer

Chains multiple scripts with conditions. "Mine 1000 ores, then smith, then bank." Scripts execute in sequence with completion conditions, skip conditions, repeat counts, and timeouts.

ScriptChainer.csEngine/ScriptChainer.cs
Fluent API: Then(), ThenIf(), ThenRepeat(), ThenWait(). Events: ScriptStarted, ScriptCompleted, ScriptSkipped, ChainCompleted.
ScriptChainerChainedScript

ScriptHotReload

Hot-reload for bot scripts using Roslyn. Edit .cs files and they recompile at runtime without restart. FileSystemWatcher triggers recompilation on save.

ScriptHotReload.csEngine/ScriptHotReload.cs
Methods: StartWatching(), StopWatching(), CompileScript(), GetTypes<T>(), CreateInstance<T>(). Events: ScriptCompiled, CompilationFailed.
ScriptHotReload

BehaviorTree

12 node types for hierarchical behavior composition: Sequence, Selector, Repeater, Inverter, Parallel, Cooldown, TimeLimit, RandomSelector, ConditionalGuard, AlwaysSucceed, ActionNode, ConditionNode.

BehaviorTree.csEngine/BehaviorTree/BehaviorTree.cs
All nodes extend BTNode with async Tick() and Reset(). NodeStatus: Success, Failure, Running.
BTNodeSequenceSelectorRepeaterInverterParallelCooldownTimeLimitActionNodeConditionNodeNodeStatus

OffsetHealer

When the game updates and memory offsets break, this system detects invalid reads, re-scans for known signatures, validates against invariants, and hot-patches the offset table without restart.

OffsetHealer.csEngine/OffsetHealer.cs
Methods: RegisterOffset(), RegisterPointerChain(), StartMonitoring(), ForceRescanAll(), GetStatus(). Events: OffsetPatched, HealFailed.
OffsetHealerOffsetEntry

Actions (High-Level API) NEW

High-level action facade wrapping low-level API calls with proper error handling, humanized delays, and event publishing. Use these instead of raw Interface.Interact() calls.

Actions.csAPI/Actions.cs
Methods: Eat(), UseItemOnItem(), EquipItem(), DropItem(), DropAll(), WaitUntilIdle(), WaitForAnimation(), TalkToNpc(), ContinueDialogue(), SelectDialogueOption(), InteractObject(), InteractNpc().
Actions (static)

Humanization Suite 11 SYSTEMS

The most comprehensive anti-detection layer of any botting framework. Covers mouse movement, timing, attention, fatigue, circadian rhythms, click patterns, entropy matching, and deliberate mistakes.

BezierMouse.csHumanization/BezierMouse.cs
Cubic Bezier curves with Gaussian noise, variable speed profiles, overshoot, and correction. Also includes WindMouse algorithm for long-distance movement.
BezierMouse
HumanizedTiming.csHumanization/HumanizedTiming.cs
Gaussian reaction times with 4 profiles (Fast/Normal/Relaxed/Fatigued). Includes micro-pauses, typing delays, decision delays, batch delays with rhythm.
HumanizedTimingProfile
FatigueSimulation.csHumanization/FatigueSimulation.cs
Sigmoid fatigue curve from 0.0 (fresh) to 1.0 (exhausted). Affects timing, mistakes, and breaks. Break recovery partially resets fatigue.
FatigueSimulation
CameraSimulation.csHumanization/CameraSimulation.cs
Random camera rotations/zooms at natural intervals. Configurable intensity and frequency. Real players constantly adjust camera.
CameraSimulation
ActivityRandomizer.csHumanization/ActivityRandomizer.cs
Shuffles action order, random side activities (check skills, hover random UI), varied thresholds, waypoint jitter.
ActivityRandomizerSideActivity
CircadianEngine.csHumanization/Advanced/CircadianEngine.cs
Time-of-day behavior variation with player archetypes (NightOwl, EarlyBird, Average, NoLife, CasualEvening). Models alertness dips at 4AM and post-lunch 2PM.
CircadianEnginePlayerArchetype
EntropyMatcher.csHumanization/Advanced/EntropyMatcher.cs
Matches Shannon entropy of input timing to human range (2.5-3.5 bits). Pure random is 4.5+ bits - too high. Injects rhythm bursts to lower entropy.
EntropyMatcher
ClickHeatmap.csHumanization/Advanced/ClickHeatmap.cs
Records where humans click per activity, builds KDE distributions, samples from them. Clicks cluster naturally instead of uniform scatter.
ClickHeatmapKDE2D
MouseFingerprint.csHumanization/Advanced/MouseFingerprint.cs
Each account gets a unique mouse "personality" - velocity, wobble, overshoot probability, click hold time, idle drift. Persistent per account.
MouseFingerprint
AttentionDrift.csHumanization/Advanced/AttentionDrift.cs
Markov chain: Focused -> Wandering -> Distracted -> MicroAFK -> Exploring. Fatigue shifts probabilities away from Focused state.
AttentionDriftAttentionState
MistakeInjector.csHumanization/Advanced/MistakeInjector.cs
Deliberately injects: misclicks, wrong tabs, overshoots, accidental right-clicks, double-clicks, cancelled actions, hover-without-click, typo corrections.
MistakeInjectorMistakeType

Combat Suite 8 SYSTEMS

Complete combat automation: FSM, ability rotation, auto-eat, death handling, boss mechanics, PvP escape, prayer switching, tick manipulation.

CombatStateMachine.csCombat/CombatStateMachine.cs
States: Idle, SearchingTarget, Approaching, Fighting, Eating, Looting, Fleeing, WaitingForRespawn, Dead. Integrates with AutoConsumable, EventBus.
CombatStateMachineCombatStateTargetDefinition
AbilityRotation.csCombat/AbilityRotation.cs
Priority-based ability system with cooldowns, conditions, keybind/interface firing. Supports Basic/Threshold/Ultimate/Special/Defensive/Prayer/Potion types.
AbilityRotationAbilityAbilityType
AutoConsumable.csCombat/AutoConsumable.cs
Monitors HP/prayer and auto-uses food/potions at thresholds. Priority-ordered consumable list with cooldown tracking.
AutoConsumableConsumableDefinition
DeathHandler.csCombat/DeathHandler.cs
Death detection, respawn waiting, grave recovery, re-equip callback, max death limits.
DeathHandler
BossMechanics.csCombat/Boss/BossMechanics.cs
Phase-aware boss fight engine with attack patterns, safe tiles, counter-actions. Profiles for Jad, Vorkath. Includes GearSwitcher, SpellCaster, TickPerfectQueue, PatternRecognizer.
BossFightEngineGearSwitcherSpellCasterTickPerfectQueuePatternRecognizer
WildernessEscape.csCombat/PvP/WildernessEscape.cs
PKer detection, threat assessment, teleblock/freeze tracking, escape route execution (seed pod, glory, logout).
WildernessEscapeThreatLevelEscapeRoute
CombatUtilities.csCombat/PvP/CombatUtilities.cs
OverheadSwitcher (prayer swapping per-tick), ComboEatEngine (food+karambwan+brew in one tick), SpecialAttackTimer, VengeanceTimer (30s cooldown), LureDetector, RingOfLifeManager.
OverheadSwitcherComboEatEngineSpecialAttackTimerVengeanceTimerLureDetectorRingOfLifeManager
TickManipulation.csSkills/TickManip/TickManipulation.cs
3-tick and 2-tick skilling engines for fishing/mining/woodcutting with precise 600ms interval management.
ThreeTickEngineTwoTickEngine

Skills Suite 8 SYSTEMS

Skill-specific automation modules: XP calculator, prayer flicking, potion timers, farming planner, agility courses, clue scrolls, smart alching, herblore, hunter traps, bone burying.

SkillCalculator.csSkills/SkillCalculator.cs
XPForLevel(), LevelForXP(), XPRemaining(), ActionsToLevel(), TimeToLevel(), GetProgressReport(), VirtualLevel(). Full RS XP table built-in.
SkillCalculator
PrayerFlicker.csSkills/PrayerFlicker.cs
1-tick and lazy prayer flicking. Toggles protection prayers on exact game tick to conserve prayer points.
PrayerFlickerPrayerType
PotionTimer.csSkills/PotionTimer.cs
Tracks potion/buff durations with countdown. Built-in presets: Antifire, Overload, Stamina, Antivenom, Divine, Prayer Renewal.
PotionTimerActiveBuff
FarmingPlanner.csSkills/FarmingPlanner.cs
Patch definitions, growth timers, run order optimization, required items list, standard herb run presets.
FarmingPlannerFarmingPatch
AgilityCourseRunner.csSkills/AgilityCourseRunner.cs
Agility course framework with obstacle sequences, success/failure detection, lap counting. Includes Seers Village course definition.
AgilityCourseRunnerAgilityCourseObstacle
ClueScrollHelper.csSkills/ClueScrollHelper.cs
Anagram answers, coordinate locations, cipher solutions, puzzle box IDA* solver. 18+ built-in anagram solutions.
ClueScrollHelperClueSolution
SkillAutomation.csSkills/SkillAutomation.cs
SmartAlcher (profit calculation, auto-alch), HerbloreMixer (potion mixing), HunterTrapManager (grid traps), BoneAutomation (bury/altar).
SmartAlcherHerbloreMixerHunterTrapManagerBoneAutomation

Items & Market

Loot management, equipment loadouts, drop tables, price caching, GE tracking, and autonomous flipping.

LootPriority.csItems/LootPriority.cs
Value-based loot scoring with always/never-loot lists and max loot per kill.
LootPriorityLootEntryGroundItem
EquipmentManager.csItems/EquipmentManager.cs
Named loadout presets, save/load/swap gear setups, capture current equipment, missing item checker.
EquipmentManagerLoadout
DropTableDatabase.csItems/DropTableDatabase.cs
NPC drop tables with rates, quantities, values. GP/kill estimates. Built-in Zulrah, Abyssal demon tables.
DropTableDatabaseNPCDropTableDropEntry
ItemPriceCache.csItems/ItemPriceCache.cs
Local cache over OSRS wiki prices API with configurable TTL. Buy/sell/avg price per item ID.
ItemPriceCacheCachedPrice
GrandExchangeTracker.csMarket/GrandExchangeTracker.cs
Real-time price polling, margin calculation, volume analysis, flip opportunity scoring with risk assessment.
GrandExchangeTrackerItemPriceFlipOpportunity
GEAutoFlipper.csMarket/GEAutoFlipper.cs
Autonomous 8-slot flipping with buy/sell FSM, portfolio P&L tracking, stop-loss protection.
GEAutoFlipperFlipSlotFlipSlotState

Interaction Handlers

Banking, dialogue, random events, auto-login, player interaction policies.

BankingAutomation.csInteraction/BankingAutomation.cs
Bank presets, deposit-all, withdraw-X, quick bank trips. Supports game preset slots 1-9.
BankingAutomationBankPreset
DialogueHandler.csInteraction/DialogueHandler.cs
Multi-step NPC conversation handler with decision tables and auto-continue.
DialogueHandler
RandomEventSolver.csInteraction/RandomEventSolver.cs
Genie, Strange Plant, Rick Turpentine, Drunken Dwarf solvers with extensible registration.
RandomEventSolver
AutoLogin.csInteraction/AutoLogin.cs
Login screen detection, credential entry, world full/already logged in handling, retry logic.
AutoLoginLoginState
PlayerInteractionGate.csInteraction/PlayerInteractionGate.cs
Policies for player interactions: Ignore, HopWorld, LogOut, Pause, Respond.
PlayerInteractionGateInteractionPolicy

Analytics & Monitoring

Session stats, structured logging, SQLite database, profit tracking, ban risk scoring, screenshots, Discord integration.

SessionStats.csAnalytics/SessionStats.cs
XP/hr per skill, GP/hr, kills/hr, per-skill progress, JSON export for historical analysis.
SessionStats
StructuredLogger.csAnalytics/StructuredLogger.cs
Debug/Info/Warn/Error/Fatal levels, file rotation, TextBox sink, auto-flush.
StructuredLoggerFileLogSinkTextBoxLogSinkILogSink
ActivityDatabase.csAnalytics/ActivityDatabase.cs
SQLite tables: Actions, XpSnapshots, LootLog, Sessions. Queryable for historical analysis.
ActivityDatabase
ProfitTracker.csAnalytics/ProfitTracker.cs
Per-source GP tracking, cumulative P&L, real-time GP/hr, breakdown by activity.
ProfitTracker
BanRiskScorer.csAnalytics/BanRiskScorer.cs
Weighted risk analysis across 10 factors with actionable recommendations. Score 0-100 with risk levels.
BanRiskScorerRiskFactor
ScreenshotCapture.csAnalytics/ScreenshotCapture.cs
Auto-screenshot on death/levelup/rare drops. Window capture, organized by trigger type.
ScreenshotCaptureScreenshotTrigger
DiscordWebhook.csAnalytics/DiscordWebhook.cs
Rich embeds, rate limiting, auto-notify via EventBus, session stats reporting.
DiscordWebhook

Scheduling

Session scheduler, break generator, anti-AFK, crash recovery.

SessionScheduler.csScheduling/SessionScheduler.cs
Day/time play windows with presets: AddWeekdayEvenings(), AddWeekends(). Auto start/stop scripts.
SessionSchedulerPlayWindow
BreakGenerator.csScheduling/BreakGenerator.cs
Gaussian break schedules. Mean 45 min play / 8 min break with configurable variance.
BreakGeneratorScheduledBreak
AntiAFK.csScheduling/AntiAFK.cs
Detects idle and performs subtle camera nudges, tab clicks, or escape taps before 5-min logout.
AntiAFK
AntiCrashRecovery.csScheduling/AntiCrashRecovery.cs
Detects game crashes/disconnects, restarts client, re-logins, resumes scripts.
AntiCrashRecovery

Rules Engine

Declarative condition-action rules, priority action queuing, goal planning, config profiles.

ConditionEngine.csRules/ConditionEngine.cs
When(condition).Then(action) with priority ordering, cooldowns, and else-actions.
ConditionEngineRule
ActionQueue.csRules/ActionQueue.cs
Priority queue with preemption. Urgent actions (eat, random event) interrupt lower priority actions.
ActionQueueGameAction
GoalPlanner.csRules/GoalPlanner.cs
Define goals with prerequisites, auto-decompose into sub-tasks, recommend next optimal action.
GoalPlannerGoal
ConfigProfiles.csRules/ConfigProfiles.cs
Per-script settings profiles. Save/load/switch configurations as JSON files.
ConfigProfiles

Farm Management

Multi-account lifecycle, world hopping, proxy rotation, trade coordination, progression optimization.

AccountManager.csFarm/AccountManager.cs
Lifecycle: Fresh -> Tutorial -> Leveling -> Production -> Flagged -> Muling -> Retired. Risk monitoring.
AccountManagerBotAccountAccountPhase
WorldHopper.csFarm/WorldHopper.cs
Strategies: LeastCrowded, BestPing, FarmDistributed, Random. Farm coordination to avoid bot clustering.
WorldHopperHopStrategy
ProxyPool.csFarm/ProxyPool.cs
SOCKS5/HTTP proxy management, health monitoring, latency checks, sticky per-account binding.
ProxyPoolProxyEntry
TradeCoordinator.csFarm/TradeCoordinator.cs
Automated muling with randomized split trades, supply chains, anti-pattern trade timing.
TradeCoordinatorTradeRequest
ProgressionTracker.csFarm/Progression/ProgressionTracker.cs
Milestone dependency graph, diary tracker, slayer task manager, collection log, multi-account sync.
AccountProgressionOptimizerDiaryTrackerSlayerTaskManagerCollectionLogTrackerMultiAccountSync

Vision & Detection

Pixel scanning, template matching, animation detection, orb reading - pure visual detection without memory reading.

PixelScanner.csVision/PixelScanner.cs
GetPixelAt(), PixelMatches(), WaitForColor(), FindColor(), GetDominantColor(), ReadBarPercent(), CaptureRegion().
PixelScannerPixelColor
TemplateMatcher.csVision/TemplateMatcher.cs
NCC-based image matching. LoadTemplate(), FindTemplate(), FindAllTemplates(), CaptureTemplate().
TemplateMatcherTemplateMatch
AnimationDetector.csVision/AnimationDetector.cs
Detects animation start/stop by hashing screen regions over time. No memory reading needed.
AnimationDetector
OrbReader.csVision/OrbReader.cs
Reads HP, Prayer, Run Energy, Special Attack from minimap orbs via pixel color analysis.
OrbReader

World Systems

WorldStateCache.csWorld/WorldStateCache.cs
Cached game state with auto-update, stale entity pruning. GetNearbyNPCs(), GetNearbyObjects().
WorldStateCacheCachedEntityCachedPlayerState
ChatMonitor.csWorld/ChatMonitor.cs
Regex-based chat rules, danger keyword detection, auto-respond with randomized messages.
ChatMonitorChatRuleChatMessage
WaypointRecorder.csWorld/WaypointRecorder.cs
Record/playback paths with variation, reverse play, JSON persistence.
WaypointRecorderRecordedPath
ResourceTimer.csWorld/ResourceTimer.cs
Track deplete/respawn, learn actual timings from observations, optimal gathering routes.
ResourceTimerResourceNode

Security

ConfigVault.csSecurity/ConfigVault.cs
AES-256-GCM encrypted vault with PBKDF2 key derivation, master password, auto-lock timeout.
ConfigVault
FingerprintRandomizer.csSecurity/FingerprintRandomizer.cs
Unique HWID/MAC/disk serial per account. Prevents hardware-based ban linking across accounts.
FingerprintRandomizerClientFingerprint

UI & Overlay 10 SYSTEMS

Paint overlay API, live stats HUD, mouse trail, tile highlighting, global hotkeys, notifications, script selector, session history.

PaintSystem.csUI/PaintSystem.cs
IPaintable interface, PaintContext with DrawText/DrawRect/DrawProgressBar/DrawTable/DrawCircle, PaintManager.
IPaintablePaintContextPaintManager
StatsHUD.csUI/StatsHUD.cs
Semi-transparent overlay: script name, runtime, GP/hr, kills/deaths, ban risk bar, fatigue bar, active potions.
StatsHUD
MouseTrail.csUI/MouseTrail.cs
Fading polyline trail from ring buffer of recent positions. Visual proof of humanization.
MouseTrail
TileHighlighter.csUI/TileHighlighter.cs
MarkSafe(), MarkDanger(), MarkTarget(), MarkPath(), MarkArea() with WorldToScreen projection.
TileHighlighterTileMarker
HotkeyManager.csUI/HotkeyManager.cs
Win32 RegisterHotKey: F5 Start, F6 Stop, F7 Pause, F8 Overlay, F12 Emergency. Works when game focused.
HotkeyManager
NotificationSystem.csUI/NotificationSystem.cs
Windows toast + system sounds + in-client feed. Auto-subscribes to EventBus for level ups, deaths, breaks.
NotificationSystemNotificationEntryNotificationSeverity
ScriptSelector.csUI/ScriptSelector.cs
Discovers IScript types, search/filter by name/category, favorites, recent history, run counts.
ScriptSelectorScriptInfo
SessionHistoryViewer.csUI/SessionHistoryViewer.cs
Past session summaries, daily GP/hr trends, total runtime, average rates. JSON persistence.
SessionHistoryViewerSessionRecord

Diagnostics

CrashDump.csDiagnostics/CrashDump.cs
Global exception handler. Hooks UnhandledException + UnobservedTaskException. Writes full state dump with logs, events, bot state.
CrashDump
GameStateSnapshot.csDiagnostics/GameStateSnapshot.cs
Capture() full game state, Diff() between snapshots, ToJson() for serialization.
GameStateSnapshotStateSnapshotStateDiff
LatencyMonitor.csDiagnostics/LatencyMonitor.cs
Measures round-trip latency, jitter, lag spikes. GetAdjustedTickMs(), CanDoTickPerfect().
LatencyMonitor
ResourceBudget.csDiagnostics/ResourceBudget.cs
CPU/memory monitoring with auto-throttle for non-critical background tasks.
ResourceBudget
InputRecorder.csDiagnostics/InputRecorder.cs
Records raw keyboard/mouse inputs with timestamps. Replay with speed control. Export to JSON.
InputRecorderRecordedInput

Plugins

PluginSystem.csPlugins/PluginSystem.cs
DLL-based plugin discovery and lifecycle. IBotPlugin, IScriptPlugin, INodePlugin interfaces. Load/unload/query.
PluginSystemIBotPluginIScriptPluginINodePluginPluginInfo

Quest Automation

QuestFramework.csQuests/QuestFramework.cs
Quest step framework: WalkStep, TalkStep, UseItemStep. QuestRunner with precondition checks, requirement validation.
QuestRunnerQuestDefinitionQuestStepWalkStepTalkStep

Debug Tools

ApiReplay.csDebug/ApiReplay.cs
Record live sessions, replay offline for testing. Compare recordings for regression detection.
ApiReplayApiCall
NodeDebugger.csDebug/NodeDebugger.cs
Breakpoints on nodes, step-through execution, variable inspection, execution history.
NodeDebuggerNodeBreakpointNodeDebugState

Node Editor

Visual scripting with 16+ node types, graph serialization, and in-game ImGui rendering.

BaseNode.csNodeEditor/Nodes/BaseNode.cs
Abstract base: Id, Title, Position, InputPins, OutputPins, Params, Draw(), Execute(), TypeName.
BaseNodePinPinKind
ExpandedNodes.csNodeEditor/Nodes/ExpandedNodes.cs
IfConditionNode, LoopNode, InteractNPCNode, InteractObjectNode, InventoryCheckNode, InterfaceClickNode, KeyPressNode, WaitForIdleNode, HealthCheckNode, RandomDelayNode, SkillCheckNode.
IfConditionNodeLoopNodeInteractNPCNodeInteractObjectNodeInventoryCheckNodeInterfaceClickNodeKeyPressNodeWaitForIdleNodeHealthCheckNodeRandomDelayNodeSkillCheckNode
NodeGraph.csNodeEditor/NodeGraph.cs
Graph data structure: AddNode(), RemoveNode(), AddLink(), GetOutputs(), GetInputs().
NodeGraphLink
NodeExecutor.csNodeEditor/NodeExecutor.cs
Executes node graphs with async support and cancellation token.
NodeExecutor
NodeGraphSerializer.csNodeEditor/NodeGraphSerializer.cs
JSON serialization/deserialization for node graphs. Save/Load with type preservation.
NodeGraphSerializer

Core API (Memory Reading)

Low-level game interaction through memory reading and DLL injection. These are the foundational APIs that everything else builds on.

Player.csAPI/Player.cs
ReadPlayerData(): name, coords, combat, animation, health, game status. IsMoving(), GetCoordinates(), GetGameStatus().
PlayerGameStatus
Inventory.csAPI/Inventory.cs
GetInventory(), InventoryFull(), InventoryCount(), Contains(), GetSlotInfo(), GetItemIdAsync(), GetItemNameByIdAsync().
Inventory
Traversal.csAPI/Traversal.cs
WalkTo(), WalkToWaypoint(), FindPath(), FindPathSegmented(), WalkPath(), WalkPathFull(). Transport-aware navigation.
TraversalPathSegment
NPC.csAPI/NPC.cs
Interact(action, id, x, y, offset) via GameHook.dll P/Invoke.
NPC
GameObject.csAPI/GameObject.cs
Interact(action, id, x, y, offset) via GameHook.dll P/Invoke.
GameObject
Interface.csAPI/Interface.cs
Interact(action, command, id, id1, id2, id3, offset) via GameHook.dll P/Invoke.
Interface
Keyboard.csAPI/Keyboard.cs
sendKey(string key) - simulates keyboard input to the game window.
Keyboard
Skills.csAPI/Skills.cs
GetSkills() returns list of 29 skills with Name, XP, CurrentLevel, MaxLevel.
Skills
ImGuiBridge.csAPI/ImGuiBridge.cs
PushPlayerInfo(), PushTileInfo(), PushBotStatus(), PushPath(), Toast(). Bridge to C++ ImGui renderer.
ImGuiBridge
PathFinder.csAPI/PathFinder.cs
WASM-based A* pathfinder with collision data. FindPath(), FindPathSegmented().
PathFinder
WorldToScreen.csAPI/WorldToScreen.cs
TileToScreenF() projects world tiles to screen coordinates using the game's view matrix.
WorldToScreen
Heatmap.csAPI/Heatmap.cs
Records tile visit frequency. RecordTile(), SaveToFile(), LoadFromFile().
Heatmap
BreakScheduler.csAPI/BreakScheduler.cs
Legacy break scheduling (superseded by BotContext.Breaks). Static singleton pattern.
BreakSchedulerBotStatus
Headless.csAPI/Headless.cs
Toggle headless rendering mode to reduce GPU/memory usage.
Headless
GameTick.csAPI/GameTick.cs
Game tick timing system (600ms cycle).
GameTick
Hardware.csAPI/Hardware.cs
Win32 P/Invoke wrappers for mouse and keyboard input simulation.
HardwareMouse
BotHub Framework Documentation — 143 Source Files — 150+ Features — .NET 8.0
Generated from source code analysis