Home API Manuals About Forum
Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Script engines

Overview / Обзор

Stealth can run scripts written in three languages:

  • DWScript (.sc, .pas) — a modern Object Pascal dialect, built into Stealth. The default and recommended Pascal engine.
  • PascalScript (.sc, .pas) — an older Pascal engine, also built in. Kept for compatibility with old scripts; no longer developed.
  • Python (.py, .pyw, .pyc) — a real, full Python interpreter installed on your computer, running the script as a separate process.

The key difference is where the script runs. DWScript and PascalScript are internal engines: the script runs inside Stealth itself, and every API call is an ordinary function call. Python is external: Stealth starts your Python interpreter, and the script talks to Stealth over a local network connection.

Stealth может выполнять скрипты на трёх языках:

  • DWScript (.sc, .pas) — современный диалект Object Pascal, встроен в Stealth. Pascal-движок по умолчанию и рекомендуемый.
  • PascalScript (.sc, .pas) — старый Pascal-движок, тоже встроенный. Оставлен для совместимости со старыми скриптами, больше не развивается.
  • Python (.py, .pyw, .pyc) — настоящий, полноценный интерпретатор Python, установленный на вашем компьютере; скрипт работает в отдельном процессе.

Главное отличие — где выполняется скрипт. DWScript и PascalScript — внутренние движки: скрипт работает внутри самого Stealth, и каждый вызов API — обычный вызов функции. Python — внешний: Stealth запускает ваш интерпретатор Python, и скрипт общается со Stealth через локальное сетевое соединение.


How Stealth picks the engine / Как Stealth выбирает движок

The engine is chosen by the file extension:

Extension Engine
.py, .pyw, .pyc Python
anything else (.sc, .pas, …) The Pascal engine selected in Settings → Script Engine (DWS by default)

So a .sc file is not tied to one Pascal engine: the same file runs in DWScript or PascalScript depending on the setting. The exception is a compiled script (Compile & Save in the editor): its file carries the engine’s signature, and it always runs in the engine it was compiled with, whatever the setting.

Up to 10 scripts can run at the same time for one character, in any mix of engines.

Движок выбирается по расширению файла:

Расширение Движок
.py, .pyw, .pyc Python
всё остальное (.sc, .pas, …) Pascal-движок, выбранный в Настройках → Script Engine (по умолчанию DWS)

То есть .sc-файл не привязан к конкретному Pascal-движку: один и тот же файл выполнится в DWScript или в PascalScript в зависимости от настройки. Исключение — скомпилированный скрипт (Compile & Save в редакторе): в файле записана сигнатура движка, и он всегда выполняется тем движком, которым был скомпилирован, независимо от настройки.

Одновременно на одном персонаже может работать до 10 скриптов, в любом сочетании движков.


Comparison / Сравнение

DWScript PascalScript Python
Where it runs Inside Stealth Inside Stealth Separate process (your Python)
What to install Nothing Nothing Python 3.8+
Cost of an API call Direct call Direct call Request over a local socket
Third-party libraries No (Pascal units / includes only) No (Pascal units / includes only) Yes — anything from pip
Threads inside a script — — Yes (threading, asyncio)
Several characters from one script — — Yes (py_astealth clients)
Debugger in the editor Yes Yes Yes (needs debugpy)
Live error check while typing Yes — —
Compile & Save Yes Yes — (use .pyc)
Windows / Linux / macOS Yes Yes Yes
Android Yes Yes Yes, started outside Stealth
DWScript PascalScript Python
Где выполняется Внутри Stealth Внутри Stealth Отдельный процесс (ваш Python)
Что установить Ничего Ничего Python 3.8+
Цена вызова API Прямой вызов Прямой вызов Запрос через локальный сокет
Сторонние библиотеки Нет (только Pascal-юниты / include) Нет (только Pascal-юниты / include) Да — всё, что есть в pip
Потоки внутри скрипта — — Да (threading, asyncio)
Несколько персонажей из одного скрипта — — Да (клиенты py_astealth)
Отладчик в редакторе Да Да Да (нужен debugpy)
Проверка ошибок на лету Да — —
Compile & Save Да Да — (используйте .pyc)
Windows / Linux / macOS Да Да Да
Android Да Да Да, с запуском вне Stealth

Python

Is it “real” Python? / Это «настоящий» Python?

Yes. Stealth does not contain its own Python. It runs the Python interpreter installed on your computer — the same one you use for anything else. Everything that works in Python works in a Stealth script: the whole standard library, any package installed with pip (requests, numpy, databases, GUIs…), threads, asyncio, your own modules next to the script.

The Stealth API is provided by the py_astealth package, which ships with Stealth (the py_astealth folder in the Stealth directory; see below about the older py_stealth). When Stealth starts a script, all API functions (Self(), FindType(), Wait(), …) are already available — no import is needed. Constants and enums are imported from py_astealth.stealth_enums.

Да. Внутри Stealth нет своего Python. Он запускает интерпретатор Python, установленный на вашем компьютере, — тот же, которым вы пользуетесь для всего остального. В скрипте Stealth работает всё, что работает в Python: вся стандартная библиотека, любые пакеты, установленные через pip (requests, numpy, базы данных, GUI…), потоки, asyncio, ваши собственные модули рядом со скриптом.

API Stealth предоставляет пакет py_astealth, который поставляется вместе со Stealth (папка py_astealth в каталоге Stealth; о старом py_stealth — ниже). Когда Stealth запускает скрипт, все функции API (Self(), FindType(), Wait(), …) уже доступны — импорт не нужен. Константы и перечисления импортируются из py_astealth.stealth_enums.

py_stealth and py_astealth / py_stealth и py_astealth

For many years Stealth’s Python API was py_stealth — a simple module that worked on both Python 2 and Python 3. It has since been replaced by py_astealth, a new, much faster API wrapper with many more features (thread-safe connections, asyncio clients, several characters per script).

Old scripts keep working without changes. The classic first lines from stealth import * and from py_stealth import * are still supported: stealth.py and the py_stealth folder are now just thin compatibility shims that load py_astealth. The only thing that is gone is Python 2 — an old script still run on Python 2 has to move to Python 3.8+.

For new scripts started from Stealth you need no import at all; for scripts started outside Stealth, use from py_astealth.stealth import *.

Много лет Python-API Stealth был py_stealth — простым модулем, работавшим и на Python 2, и на Python 3. Сейчас его заменил py_astealth — новая, гораздо более быстрая обёртка API с множеством новых возможностей (потокобезопасные соединения, клиенты на asyncio, несколько персонажей в одном скрипте).

Старые скрипты продолжают работать без изменений. Классические первые строки from stealth import * и from py_stealth import * по-прежнему поддерживаются: stealth.py и папка py_stealth теперь — лишь тонкие прослойки совместимости, загружающие py_astealth. Ушёл только Python 2 — старый скрипт, который до сих пор запускался на Python 2, нужно перевести на Python 3.8+.

Новым скриптам, запускаемым из Stealth, импорт вообще не нужен; для скриптов, запускаемых вне Stealth, используйте from py_astealth.stealth import *.

Requirements / Требования

  • Python 3.8 or newer. Python 2 is not supported.

  • Windows: Python is found through the registry, so install it from python.org (a normal install registers itself). If several versions are installed, pick one in Settings → Python Version, or let Stealth ask on the first start.

  • Linux / macOS: Stealth uses python3 (or python) from PATH.

  • Debugging additionally needs the debugpy package: pip install debugpy.

  • Python 3.8 или новее. Python 2 не поддерживается.

  • Windows: Python ищется через реестр, поэтому ставьте его с python.org (обычная установка сама регистрируется). Если установлено несколько версий — выберите нужную в Настройках → Python Version, либо Stealth спросит при первом запуске.

  • Linux / macOS: Stealth использует python3 (или python) из PATH.

  • Для отладки дополнительно нужен пакет debugpy: pip install debugpy.

How it works / Как это устроено

When you start a .py script, Stealth opens a local port for it and runs pythonw -B -u py_stealth <your script> <port>. The script connects back to that port, and every API call becomes a request–response over the socket.

Practical consequences:

  • API calls are slower than in Pascal. An internal engine calls the API directly; Python pays a network round-trip for every call. py_astealth handles a few thousand calls per second, which is plenty for normal scripts — but a tight loop of thousands of tiny calls will be noticeably slower than the same loop in DWScript. Pure Python computation is not affected.
  • On Windows there is no console window (pythonw). print() and error tracebacks go to the Stealth system journal.
  • Each Python thread gets its own connection, so API calls from several threads do not block each other.
  • Events work the same as in Pascal (Events), plus a Python-only polling mode.
  • Stopping, pausing and resuming the script from the Stealth UI work as for any other script.

Когда вы запускаете .py-скрипт, Stealth открывает для него локальный порт и выполняет pythonw -B -u py_stealth <ваш скрипт> <порт>. Скрипт подключается к этому порту, и каждый вызов API превращается в запрос-ответ через сокет.

Практические следствия:

  • Вызовы API медленнее, чем в Pascal. Внутренний движок вызывает API напрямую, а Python за каждый вызов платит сетевым round-trip’ом. py_astealth выдаёт несколько тысяч вызовов в секунду — для обычных скриптов этого с запасом, но плотный цикл из тысяч мелких вызовов будет заметно медленнее, чем тот же цикл в DWScript. Чистые вычисления на Python это не затрагивает.
  • В Windows нет консольного окна (pythonw). print() и трейсбеки ошибок выводятся в системный журнал Stealth.
  • У каждого Python-потока своё соединение, поэтому вызовы API из разных потоков не блокируют друг друга.
  • События работают так же, как в Pascal (Events), плюс есть режим polling, доступный только в Python.
  • Остановка, пауза и продолжение скрипта из интерфейса Stealth работают как для любого другого скрипта.

Running a script outside Stealth / Запуск скрипта вне Stealth

A Python script does not have to be started by Stealth. You can run it from a terminal or from your IDE (PyCharm, VS Code…) with its own debugger: on startup py_astealth connects to Stealth on port 47602, asks for a script port, and from then on the script appears in Stealth’s script list like any other.

  • py_astealth must be importable — run the script from the Stealth directory or add that directory to PYTHONPATH.
  • In this mode the API is not injected automatically: import it explicitly, e.g. from py_astealth.stealth import *.
  • The script binds to the currently selected character. To bind to a specific one, pass --profile=<profile name>.

Python-скрипт не обязательно запускать из Stealth. Его можно запустить из терминала или из своей IDE (PyCharm, VS Code…) с её собственным отладчиком: при старте py_astealth подключается к Stealth на порт 47602, запрашивает порт для скрипта, и дальше скрипт появляется в списке скриптов Stealth, как любой другой.

  • py_astealth должен импортироваться — запускайте скрипт из каталога Stealth или добавьте этот каталог в PYTHONPATH.
  • В этом режиме API не подставляется автоматически: импортируйте его явно, например from py_astealth.stealth import *.
  • Скрипт привязывается к текущему выбранному персонажу. Чтобы привязать к конкретному — передайте --profile=<имя профиля>.

Python on Android / Python на Android

On Android, Stealth cannot start a .py script by itself: the phone has no system Python, and a Python app’s interpreter is private to that app. Instead, run the script outside Stealth, from a Python app on the same phone — Termux, Pydroid 3 or QPython. The script connects to Stealth on port 47602 exactly as described above.

  1. Install a Python app (for Termux: pkg install python).
  2. Copy the py_astealth folder from the Stealth directory on your PC into the folder where your scripts live in that app.
  3. Start the script with from py_astealth.stealth import * as its first line, while Stealth is running.

На Android Stealth не может сам запустить .py-скрипт: системного Python на телефоне нет, а интерпретатор Python-приложения закрыт внутри этого приложения. Вместо этого запускайте скрипт вне Stealth, из Python-приложения на том же телефоне — Termux, Pydroid 3 или QPython. Скрипт подключается к Stealth на порт 47602 ровно так, как описано выше.

  1. Установите Python-приложение (для Termux: pkg install python).
  2. Скопируйте папку py_astealth из каталога Stealth на ПК в папку, где лежат ваши скрипты в этом приложении.
  3. При запущенном Stealth запустите скрипт, первой строкой которого стоит from py_astealth.stealth import *.

Several characters from one script / Несколько персонажей из одного скрипта

Besides the classic module-style API, py_astealth offers client objects (sync and asyncio). Each client is its own connection, so one script can drive several characters at once. See the examples in py_astealth/examples (multiclient.py, multifollower.py).

Помимо классического API в стиле модуля, py_astealth предоставляет объекты-клиенты (синхронные и на asyncio). Каждый клиент — отдельное соединение, поэтому один скрипт может управлять несколькими персонажами одновременно. Примеры — в py_astealth/examples (multiclient.py, multifollower.py).

Differences from the Pascal API / Отличия от Pascal API

  • Method names are the same, but parameter types can differ. Always check the ### Python signature on the method’s page — for example, WaitGump takes a string in Pascal and an int in Python.

  • A few methods exist only in Python — see PythonMethods. A few exist only in Pascal — see PascalMethods (mostly things Python already has in its standard library).

  • Имена методов те же, но типы параметров могут отличаться. Всегда сверяйтесь с сигнатурой ### Python на странице метода — например, WaitGump в Pascal принимает строку, а в Python — int.

  • Несколько методов есть только в Python — см. PythonMethods. Несколько — только в Pascal, см. PascalMethods (в основном то, что в Python и так есть в стандартной библиотеке).


DWScript and PascalScript / DWScript и PascalScript

Both are built into Stealth, need nothing installed, and work on every platform including Android. Scripts are plain Pascal; the whole Stealth API is available directly, without uses.

DWScript is a modern Object Pascal: classes, records with methods, interfaces, lambdas, dynamic and associative arrays, and more. The editor checks DWScript code for errors while you type, and the AI assistant can compile its drafts before showing them. Use DWScript for new Pascal scripts.

PascalScript is an older and simpler engine (for example, you cannot declare your own classes). It stays in Stealth so that old scripts keep working, but it is no longer developed.

Both engines support:

  • Units and includes. uses MyUnit; and {$I file.inc} are looked up next to the script (and in its Include / Uses subfolders), in Scripts\Include / Scripts\Uses of the Stealth folder, and in the folder set in Settings → Include&Uses Path.
  • The debugger in the script editor: breakpoints, step into / step over, and a variables view.
  • Compile & Save — save a script in compiled form; it then runs in the engine it was compiled with.

Оба движка встроены в Stealth, ничего не требуют устанавливать и работают на всех платформах, включая Android. Скрипт — обычный Pascal; весь API Stealth доступен сразу, без uses.

DWScript — современный Object Pascal: классы, записи с методами, интерфейсы, лямбды, динамические и ассоциативные массивы и многое другое. Редактор проверяет код DWScript на ошибки прямо во время набора, а AI-ассистент может компилировать свои черновики перед показом. Для новых Pascal-скриптов используйте DWScript.

PascalScript — более старый и простой движок (например, в нём нельзя объявлять собственные классы). Он остаётся в Stealth, чтобы старые скрипты продолжали работать, но больше не развивается.

Оба движка поддерживают:

  • Юниты и include. uses MyUnit; и {$I file.inc} ищутся рядом со скриптом (и в его подпапках Include / Uses), в Scripts\Include / Scripts\Uses папки Stealth и в папке, заданной в Настройках → Include&Uses Path.
  • Отладчик в редакторе скриптов: точки останова, step into / step over и окно переменных.
  • Compile & Save — сохранение скрипта в скомпилированном виде; такой скрипт выполняется тем движком, которым был скомпилирован.

Other languages / Другие языки

Scripts in other languages (for example C#) use a wrapper library that speaks the same protocol as py_astealth. For Stealth such a script is no different from a Python script started outside Stealth: you start the program yourself, it connects to Stealth on port 47602, and from then on it appears in the script list like any other script. The only difference from Python is that Stealth cannot start such a program for you.

Скрипты на других языках (например, C#) используют библиотеку-обёртку, которая говорит на том же протоколе, что и py_astealth. Для Stealth такой скрипт ничем не отличается от Python-скрипта, запущенного вне Stealth: вы запускаете программу сами, она подключается к Stealth на порт 47602 и дальше появляется в списке скриптов, как любой другой. Единственное отличие от Python — Stealth не умеет запускать такую программу сам.


Which one to choose / Что выбрать

  • You already know Python, or need libraries (HTTP, databases, math, a GUI) → Python.

  • One script must control several characters → Python (py_astealth clients).

  • Nothing to install, maximum speed of API calls → DWScript.

  • You have old PascalScript scripts → keep running them with PascalScript; write new ones in DWScript.

  • Вы уже знаете Python или нужны библиотеки (HTTP, базы данных, математика, GUI) → Python.

  • Один скрипт должен управлять несколькими персонажами → Python (клиенты py_astealth).

  • Ничего не устанавливать, максимальная скорость вызовов API → DWScript.

  • Есть старые скрипты на PascalScript → продолжайте запускать их в PascalScript, новые пишите на DWScript.


FAQ

Is Python in Stealth full Python? / Python в Stealth — полноценный? Yes — it is your own installed Python 3.8+, with the full standard library and any pip packages. See Is it “real” Python? Да — это ваш собственный установленный Python 3.8+, со всей стандартной библиотекой и любыми пакетами из pip.

Is a Python script slower than the same Pascal script? / Python-скрипт медленнее такого же на Pascal? Only in some cases. Every API call goes over a local socket, so a script that makes thousands of API calls in a tight loop is slower in Python. Most scripts spend their time waiting for the game, and there the difference is not noticeable; pure computation is not affected at all. If a loop is slow, reduce the number of calls in it: for example, fetch a list once instead of querying item by item. Только в некоторых случаях. Каждый вызов API идёт через локальный сокет, поэтому скрипт, который делает тысячи вызовов API в плотном цикле, на Python будет медленнее. Большинство скриптов основное время ждут игру, и там разницы не заметно; чистые вычисления это вообще не затрагивает. Если цикл тормозит — сократите в нём число вызовов: например, получите список один раз, а не опрашивайте предметы по одному.

Stealth says “Python Interpreter not found”. / Stealth пишет «Python Interpreter not found». On Windows install Python from python.org (it must be registered in the system). On Linux / macOS make sure python3 is in PATH. В Windows установите Python с python.org (он должен быть зарегистрирован в системе). В Linux / macOS убедитесь, что python3 есть в PATH.

Can I use Python on Android? / Можно ли использовать Python на Android? Yes, but Stealth cannot start a Python script on Android by itself — run it from a Python app on the phone. See Python on Android. Да, но на Android Stealth не может сам запустить Python-скрипт — запускайте его из Python-приложения на телефоне. См. Python на Android.

My old script starts with from stealth import * (or from py_stealth import *). Will it still work? / Мой старый скрипт начинается с from stealth import * (или from py_stealth import *). Он будет работать? Yes, both lines are still supported. The script has to run on Python 3.8+, though — Python 2 is no longer supported. See py_stealth and py_astealth. Да, обе строки по-прежнему поддерживаются. Но скрипт должен работать на Python 3.8+ — Python 2 больше не поддерживается.

Where does print() go? / Куда выводится print()? To the Stealth system journal. В системный журнал Stealth.

Will my old PascalScript script run in DWScript? / Запустится ли старый скрипт PascalScript в DWScript? Usually yes, since both are Pascal, but the dialects differ in details. If it does not compile in DWScript, switch the engine to PS in Settings, or fix the differences. Обычно да, ведь оба — Pascal, но диалекты различаются в деталях. Если скрипт не компилируется в DWScript — переключите движок на PS в Настройках или исправьте различия.