eventMacro — различия между версиями

Материал из Руководство по OpenKore
Перейти к: навигация, поиск
(Автомакросы: Следующий параметр - exclusive.)
Строка 903: Строка 903:
  
  
'''''Note²:''''' Внутри скобок можно использовать неограниченное количество сравнений.
+
'''''Примечание:''''' Внутри скобок можно использовать неограниченное количество сравнений.
 
  if (arg1 <[[eventMacro#Operators|Operators]]> arg2 || arg3 <[[eventMacro#Operators|Operators]]> arg4 || ... || arg'''''N''''' <[[eventMacro#Operators|Operators]]> arg'''''N+1''''') (goto <label> | call <macro> <parameters> | stop)
 
  if (arg1 <[[eventMacro#Operators|Operators]]> arg2 || arg3 <[[eventMacro#Operators|Operators]]> arg4 || ... || arg'''''N''''' <[[eventMacro#Operators|Operators]]> arg'''''N+1''''') (goto <label> | call <macro> <parameters> | stop)
  
Строка 937: Строка 937:
 
     commandN
 
     commandN
 
  } else {
 
  } else {
     command1
+
     command3
     command2
+
     command4
 
     ...
 
     ...
 
     commandN
 
     commandN
 
  }
 
  }
 +
В этом случае если условие в круглых скобках истинно, то выполнятся только команды 1 и 2, если условие ложное, то выполнятся только команды 3 и 4.
  
  
'''''Note:''''' В фигурных скобках можно использовать сколько угодно команд.<br>
+
'''''Примечание:''''' в фигурных скобках можно использовать неограниченное количество команд.<br>
'''''Note:''''' Ветка '''else''' - не обязательна.
+
'''''Примечание:''''' ветка '''else''' - не обязательна.
  
 
----
 
----
  
 
===== Elsif =====
 
===== Elsif =====
Это как else + if одновременно. Оператор '''elsif''' нужен для проверки следующего условия. Оператор '''else''' срабатывает, когда ни одно условие не выполнилось.
+
Этот оператор работает как else + if одновременно. Оператор '''elsif''' нужен для проверки следующего условия. Оператор '''else''' срабатывает, когда ни одно условие не выполнилось.
  
 
  if (arg1 <[[eventMacro#Operators|Operators]]> arg2) {
 
  if (arg1 <[[eventMacro#Operators|Operators]]> arg2) {
Строка 958: Строка 959:
 
     comandoN
 
     comandoN
 
  } elsif (arg1 <[[eventMacro#Operators|Operators]]> arg2) {
 
  } elsif (arg1 <[[eventMacro#Operators|Operators]]> arg2) {
     command1
+
     command3
     command2
+
     command4
 
     ...
 
     ...
 
     commandN
 
     commandN
 
  } else {
 
  } else {
     command1
+
     command5
     command2
+
     command6
 
     ...
 
     ...
 
     commandN
 
     commandN
 
  }
 
  }
 +
В этом случае если первое условие истинно, то будут выполнены только команды 1 и 2, если оно ложное, то далее идёт проверка второго условия. Если второе условие истинно, то будут выполнены только команды 3 и 4. Если оба условия ложные, то будут выполнены только команды 5 и 6.
 +
  
 +
'''''Примечание:''''' ветки '''elsif''' и '''else''' - не обязательны.
 
----
 
----
  
 
===== Switch/case =====
 
===== Switch/case =====
Этот оператор напоминает ''if'' с кучей последующих ''elseif'', пригождается для проверки одной переменной на разные условия.
+
Этот оператор напоминает ''if'' с кучей последующих ''elseif''. Данный оператор будет полезным, когда необходимо проверить одну переменную на разные условия.
  
 
  switch (arg1) {
 
  switch (arg1) {
 
     case (<[[eventMacro#Operators|Operators]]> arg2) (goto <label> | call <macro> <parameters> | stop | {)
 
     case (<[[eventMacro#Operators|Operators]]> arg2) (goto <label> | call <macro> <parameters> | stop | {)
         (If you use "{", the commands should be used here and in a separated line that should be closed with the block "}")
+
         (Если вы используете "{", то команды для выполнения должна находиться здесь. Каждая команда должна быть написана в новой строчке. В конце обязательно должна быть закрывающая скобка "}")
 
     case (<[[eventMacro#Operators|Operators]]> arg2) (goto <label> | call <macro> <parameters> | stop | {)
 
     case (<[[eventMacro#Operators|Operators]]> arg2) (goto <label> | call <macro> <parameters> | stop | {)
         (If you use "{", the commands should be used here and in a separated line that should be closed with the block "}")
+
         (Если вы используете "{", то команды для выполнения должна находиться здесь. Каждая команда должна быть написана в новой строчке. В конце обязательно должна быть закрывающая скобка "}")
 
     ...
 
     ...
 
     else (goto <label> | call <macro> <parameters> | stop | {)
 
     else (goto <label> | call <macro> <parameters> | stop | {)
         (If you use "{", the commands should be used here and in a separated line that should be closed with the block "}")
+
         (Если вы используете "{", то команды для выполнения должна находиться здесь. Каждая команда должна быть написана в новой строчке. В конце обязательно должна быть закрывающая скобка "}")
 
  }
 
  }
  
'''''Note:''''' Использовать ''else'' не обязательно.
+
'''''Примечание:''''' если не сработал ни один ''case'', тогда отработает ''else''.<br>
'''''Note:''''' Если не сработал ни один ''case'', тогда отработает ''else''.
+
'''''Примечание:''''' использовать ''else'' не обязательно.
  
 
----
 
----
  
 
===== Примеры с условными операторами =====
 
===== Примеры с условными операторами =====
Давайте напишем макрос, который двигает персонажа в выбранном случайно направлении, на север, юг, восток или запад.
+
Этот макрос двигает персонажа в случайном направлении: на север, юг, восток или запад.
 +
 
 
  macro walk {
 
  macro walk {
 
     $num = &rand(1, 4)
 
     $num = &rand(1, 4)
 
     if ($num == 1) {
 
     if ($num == 1) {
         do c I will follow the path 1
+
         do [[c]] я пойду в сторону 1 (на север)
         do north
+
         do [[north]]
 
     }
 
     }
 
     if ($num == 2) {
 
     if ($num == 2) {
         do c I will follow the path 2
+
         do [[c]] я пойду в сторону 2 (на юг)
         do south
+
         do [[south]]
 
     }
 
     }
 
     if ($num == 3) {
 
     if ($num == 3) {
         do c I will follow the path 3
+
         do [[c]] я пойду в сторону 3 (на восток)
         do east
+
         do [[east]]
 
     }
 
     }
 
     if ($num == 4) {
 
     if ($num == 4) {
         do c I will follow the path 4
+
         do [[c]] я пойду в сторону 4 (на запад)
         do west
+
         do [[west]]
 
     }
 
     }
 
  }
 
  }
  
Давайте перепишем этот макрос с постфиксным if.
+
Давайте перепишем этот макрос с постфиксным if:
 +
 
 
  macro walk {
 
  macro walk {
 
     $num = &rand(1, 4)
 
     $num = &rand(1, 4)
     do c I will follow the path $num
+
     do [[c]] я пойду в сторону $num
     do north if ($num == 1)
+
     do [[north]] if ($num == 1)
     do south if ($num == 2)
+
     do [[south]] if ($num == 2)
     do east  if ($num == 3)
+
     do [[east]] if ($num == 3)
     do west  if ($num == 4)
+
     do [[west]] if ($num == 4)
 
  }
 
  }
  
 
Следующий макрос использует конструкцию if/else, чтобы определить, есть ли у персонажа больше 1000 зени или нет.
 
Следующий макрос использует конструкцию if/else, чтобы определить, есть ли у персонажа больше 1000 зени или нет.
 +
 
  macro checkZeny {
 
  macro checkZeny {
 
     if ($.zeny > 1000) {
 
     if ($.zeny > 1000) {
       do c I've over 1.000z!  
+
       do [[c]] У меня больше 1.000z!  
 
     } else {
 
     } else {
       do c I've 1.000z or less...
+
       do [[c]] у меня 1.000z или меньше...
 
     }
 
     }
 
  }
 
  }
  
 
Чуть усложнённый пример, чтобы узнать сколько зени в кармане: больше тысячи, ровно тысяча или меньше. В зависимости от этого выдаются разные смайлики.
 
Чуть усложнённый пример, чтобы узнать сколько зени в кармане: больше тысячи, ровно тысяча или меньше. В зависимости от этого выдаются разные смайлики.
 +
 
  macro checkZeny {
 
  macro checkZeny {
 
     if ($.zeny > 1000) {
 
     if ($.zeny > 1000) {
       do c I've over 1.000z!  
+
       do [[c]] у меня больше 1.000z!  
       do e money
+
       do [[e]] money
 
     } elsif ($.zeny == 1000) {
 
     } elsif ($.zeny == 1000) {
       do c I have exactly 1.000z.
+
       do [[c]] у меня ровно 1.000z.
       do e !
+
       do [[e]] !
 
     } else {
 
     } else {
       do c I've 1.000z or less...
+
       do [[c]] у меня меньше 1.000z
       do e panic
+
       do [[e]] panic
 
     }
 
     }
 
  }
 
  }
  
Переработаем предыдущий макрос, чтобы показать switch/case:
+
Переработаем предыдущий макрос, с использованием switch/case:
 +
 
 
  macro checkZeny {
 
  macro checkZeny {
 
     switch ($.zeny) {
 
     switch ($.zeny) {
 
         case (> 1000) {
 
         case (> 1000) {
             do c I've over 1.000z!  
+
             do [[c]] у меня больше 1.000z!  
             do e money
+
             do [[e]] money
 
         }
 
         }
 
         case (== 1000) {
 
         case (== 1000) {
             do c I have exactly 1.000z.
+
             do [[c]] у меня ровно 1.000z.
             do e !
+
             do [[e]] !
 
         }
 
         }
 
         else {
 
         else {
             do c I've 1.000z or less...
+
             do [[c]] у меня меньше 1.000z
             do e panic
+
             do [[e]] panic
 
         }
 
         }
 
     }
 
     }
 
  }
 
  }
  
Следующий макрос показывает использование if вместе с goto.
+
Следующий макрос показывает использование if вместе с goto:
 +
 
 
  macro checknum {
 
  macro checknum {
 
     $num = &rand(1, 3)
 
     $num = &rand(1, 3)
Строка 1069: Строка 1079:
 
     if ($num == 3) goto three
 
     if ($num == 3) goto three
 
     :one
 
     :one
     log \$num is 1
+
     log \$num = 1
 
     stop
 
     stop
 
     :two
 
     :two
     log \$num is 2
+
     log \$num = 2
 
     stop
 
     stop
 
     :three
 
     :three
     log \$num is 3
+
     log \$num = 3
    stop
 
 
  }
 
  }
  
Предыдущий макрос можно написать с использованием '''call''' вместо '''goto'''.
+
Переработаем предыдущий макрос, с использованием '''call''' вместо '''goto'''.
  
 
  macro checknum {
 
  macro checknum {
Строка 1088: Строка 1097:
 
  }
 
  }
 
  macro one {
 
  macro one {
     log $num is 1
+
     log $num = 1
 
  }
 
  }
 
  macro two {
 
  macro two {
     log $num is 2
+
     log $num = 2
 
  }
 
  }
 
  macro three {
 
  macro three {
     log $num is 3
+
     log $num = 3
 
  }
 
  }
  
  
 
Сложный макрос, где переменная $i, равная 1, подвергается изощрённым проверкам и так и сяк.
 
Сложный макрос, где переменная $i, равная 1, подвергается изощрённым проверкам и так и сяк.
 +
 
  macro if {
 
  macro if {
 
   $i = 1
 
   $i = 1
Строка 3033: Строка 3043:
 
  Math_condition < $variable # Only true if lower than $variable value
 
  Math_condition < $variable # Only true if lower than $variable value
  
:* Note2: <value> can be a percentage (even if it is a variable).
+
:* Note: <value> can be a percentage (even if it is a variable).
 
Examples:
 
Examples:
 
  Math_condition <= 10% # Only true if lower or equal to 10%
 
  Math_condition <= 10% # Only true if lower or equal to 10%

Версия 14:27, 20 мая 2023

Описание

  • Этот плагин представляет собой переделанный и обновлённый macro плагин, написанный таким образом, чтобы потреблять меньше процессорной мощности. Имеет более расширенный функционал по сравнению со своим предшественником.
  • С помощью этого плагина, Вы сможете составлять блоки с условиями, называемые автомакросами (automacro) и блоки исполняемых инструкций, называемые макросами (macro).
  • Автомакросы срабатывают при достижении условий, описанных в блоке (например, появление определённого слова в чате, или достижение определённого уровня, и т.д.). По результату срабатывания выполняется один или несколько макросов.
  • Макросы могут быть простыми (например, «сказать что-то в чате» или «сохранить предметы в кафре»), или сложными (например, «выполнить полный квест»). Макросы вызываются несколькими способами: автомакросами, вручную консольной командой eventMacro <название_макроса>, либо инструкцией call <название_макроса>.

* Старые макросы не совместимы с эвент-макросами! Их следует переписать, используя новый синтаксис эвент-макросов.

Установка

  • eventMacro по умолчанию включён в стандартную версию OpenKore.
  • Чтобы начать использовать плагин, просто создайте в папке control файл eventMacros.txt и наполните файл эвент-макросами.

Консольные команды

Синтаксис

eventMacro [MACRO|auto|list|status|check|stop|pause|unpause|var_get|var_set|enable|disable|include] [extra]
eventMacro <MACRO>
  • Запустить макрос с названием <MACRO>. При запуске можно использовать предустановленные опции, либо произвольные параметры.
Опция Значение Описание
-repeat | -r n (целое_число) Повторяет выполнение макроса n раз
-overrideAI игнорирует ИИ (см. описание ниже)
-macro_delay секунды задержка между выполняемыми командами в макросе
-exclusive Запрещает прерывать выполнение макроса другими автомакросами
-orphan terminate
reregister
reregister_safe
terminate_last_call
Что делать с макросами которые были удалены из очереди ИИ (AI queue)

Макросы можно запускать с произвольными параметрами. Они указываются с помощью двойной черты +пробел -- , либо просто через пробел. Эти параметры сохраняются в массиве @.param. Пример:

macro showParam {
 log Parameter 1 is $.param[0]
 log Parameter 2 is $.param[1]
}

Если запустить макрос с помощью консольной команды eventMacro showParam -- foo bar (либо eventMacro showParam foo bar), то он выведет в консоль:

[eventmacro log] Parameter 1 is foo
[eventmacro log] Parameter 2 is bar
eventMacro auto <AUTOMACRO>
Получить информацию об автомакросе с названием <AUTOMACRO> и его условиях
eventMacro list
Получить список доступных макросов и автомакросов
eventMacro status [macro|automacro]
Получить текущее состояние макросов или автомакросов
eventMacro check (force_stop|force_start|resume)
Указать состояние проверки автомакросов:
  • eventMacro check force_stop - принудительно остановить проверку условий автомакросов
  • eventMacro check force_start - принудительно остановить проверку условий автомакросов
  • eventMacro check resume - вернуть проверку условий автомакросов в нормальное состояние
eventMacro stop
Отменить выполнение текущего макроса
eventMacro pause
Поставить на паузу текущий макрос
eventMacro unpause
Возобновить выполнение текущего макроса
eventMacro var_get [<var_name>]
Показать значение переменной <var_name>, либо если параметр не указан, всех переменных. С помощью этой команды можно посмотреть значения следующих переменных: скаляра ($var_name), массива (@var_name) или хэша (%var_name)
eventMacro var_set <var_name> <value>
Присвоить значение <value> переменной <var_name>
eventMacro enable [automacro]
Включить один, либо если параметр не указан, все автомакросы
eventMacro disable [automacro]
Выключить один, либо если параметр не указан, все автомакросы
eventMacro include (on | off | list) [filename or pattern]
Включить или отключить дополнительный файл, подключенный с помощью !include, в файле eventMacros.txt

Примечание. Консольную команду "eventMacro" писать очень долго и не удобно. В конфиге OpenKore можно назначить синоним на эту команду, например: " alias_em eventMacro".

Файлы настроек

control/eventMacros.txt
Поместите свои эвент-макросы и автомакросы в этот файл. Вы можете изменить имя файла в настройке конфига eventMacro_file.
control/timeouts.txt
Добавтьте параметр eventMacro_delay и укажите количество секунд которые плагин должен подождать между выполнением команд.
control/config.txt
Параметр Значение По умолчанию Описание
eventMacro_orphans terminate
reregister
reregister_safe
terminate_last_call
terminate Что делать с макросами которые были удалены из очереди ИИ (AI queue)
eventMacro_file имя файла eventMacros.txt файл с эвент-макросами и автомакросами
eventMacro_CheckOnAI список 'auto', 'manual' и\или 'off' auto При каких значениях ИИ должны проверяться автомакросы

Синтаксис эвент-макросов

macro MacroName {
   do this..
   and that..
   yattayatta..
}
  • Вы можете использовать любое имя для макроса (кроме символа "пробел"). Следите, чтобы макросы не назывались одинаково, иначе ни один из этих макросов не будет загружен.
  • Команды в макросе выполняются по порядку сверху вниз.
  • В теле макроса можно использовать ТОЛЬКО специальные макро-команды. Чтобы вызвать в теле макроса консольную команду, следует использовать макро-команду do.

Макро-команды

do <команда>
выполняет <команду>, как будто она была набрана в консоли OpenKore. См. список консольных команд.
macro foo {
   do move 123 234 prontera
   do sit
   do c привет!
}

Команда ai clear по умолчанию выключена в плагине, т.е. её не удастся выполнить через макрос.
Если выполнится команда do ai off, то макрос остановит своё выполнение. Также после команды do ai manual может остановиться проверка условий автомакросов (см. параметр eventMacro_CheckOnAI)

log <текст>
warning <текст>
error <текст>
выводит <текст> в консоль. В тексте можно использовать переменные эвент-макроса ($var_name), специальные переменные ($.***) а также специальные ключевые слова (&config, &rand и т.д.). Эту макро-команду удобно использовать для отладки своих эвент-макросов.
macro foo {
  log Эта строка записывает текст в консоль.
  warning Бот достиг $.lvl уровня
}
pause <секунды>
останавливает эвент-макрос на указанное количество секунд.
macro foo {
   log сейчас 10:00:00
   pause 10
   log теперь 10:00:10 
   log после первого сообщения прошло 10 секунд.
}

макро-команда pause останавливает не только выполнение эвент-макроса, но и все действия OpenKore.

call <MACRO> [<параметры>]
выполняет другой макрос с произвольным именем <MACRO>, также можно указать произвольные <параметры>. После выполнения эвент-макроса <MACRO> продолжится выполняться текущий макрос.
В имени <MACRO> можно использовать переменные (например: call $killmacro)
macro foo {
   $killmacro = bar
   log сейчас будет выполняться макрос bar
   call $killmacro
}
lock (<AUTOMACRO> | all)
выключает автомакрос с произвольным именем <AUTOMACRO> (т.е. прекращается проверка его условий срабатывания). Выключенный автомарос никогда не выполнится. Команда lock all выключает все автомакросы. Включить автомакрос обратно можно с помощью команды code>release</code>.
release (<AUTOMACRO> | all)
включает обратно заблокированный автомакрос с произвольным именем <AUTOMACRO> или включает все автомакросы при использовании release all (Автомакрос может быть заблокирован условием run-once 1 или командой lock). Включённый автомакрос может повторно запуститься если выполнятся все условия его срабатывания.
stop
немедленно прерывает выполнение текущего макроса.
include (on | off | list) [<имя_файла или шаблон_имени>]
включает или выключает строчки !include в файле eventMacros.txt.
set <опция> <значение>
устанавливает значения следующим опциям:

Переменные

  • В эвент-макросе есть возможность работать с переменными. Объявлять переменные не нужно. Все переменные макросов - глобальные, т.е. переменная из одного макроса может быть использована в другом макросе.
  • Система переменных в eventMacro основывается на типах данных языка Perl. Переменные могут быть скалярами, массивами и хешами.
  • В названии переменной можно использовать только буквы и цифры.
  • Если Вы хотите использовать какую-либо переменную без подстановки её значения, то следует экранировать её с помощью "\" (например, \$var).

Типы переменных

Скаляр
  • Скалярная переменная содержит только одну величину, например, число и\или текст.
  • Скалярные переменные начинаются со знака $.
Массив
  • Переменная массив содержит список величин (элементов).
  • У каждого элемента в массиве есть свой индекс, который указывает на позицию в списке.
  • Первый элемент массива имеет индекс 0, а последний - длина массива минус один.
  • Массивы начинаются со знака @.
Хэш
  • Переменная хэш содержит пары величин.
  • Каждая пара состоит из ключа и значения.
  • Каждый ключ имеет только одно значение, но несколько ключей могут иметь одинаковые значения.
  • Хэши начинаются со знака %.

Объявление и использование

Скаляр
  • Присвоить переменной значение: $variable = значение
  • Получить значение переменной (НО это касается только макросов, для автомакросов есть другой синтаксис, как и для параметров конфига и т.п.): $variable
macro Hello {
   $var = Hello
   $var1 = World!
   log $var $var1
}
Данный макрос выведет на консоль:
[eventmacro message] Hello World!
  • Увеличить на 1 значение переменной: $variable++ или уменьшить $variable--
macro Counter {
    $counter = 0
    log Значение счётчика: $counter
    $counter++
    log Новое значение: $counter
    $counter--
    log Прежнее значение: $counter
}
В консоли увидим:
[eventmacro message] Значение счётчика: 0
[eventmacro message] Новое значение: 1
[eventmacro message] Прежнее значение: 0
  • Переменную можно удалить, присвоив ей специальное значение undef или unset:
macro undef {
    $counter = 0
    $x = 1
    log \$x = $x
    $x = undef  # также можно использовать 'unset'
    log \$x теперь уничтожена: $x
}
В консоли увидим:
[eventmacro message] $x = 1
[eventmacro message] $x теперь уничтожена:
  • Операция присвоения не вычисляет значение справа от знака равно, а тупо подставляет вместо переменных их величины. Для расчетов нужно вызывать функцию &eval().
macro math {
    $num = 2
    $num2 = 3
    $result = $num+$num2
    $result2 = &eval($num+$num2)
    log обычная подстановка значений переменных \$result = $result
    log сумма $num и $num2 равна $result2
}
В консоли увидим:
[eventmacro message] обычная подстановка значений переменных $result = 2+3
[eventmacro message] сумма 2 и 3 равна 5


У скаляров есть следующая функция:

&defined($<переменная>})
Функции &defined требуется указать <переменную>, существование которой следует проверить. Если <переменная> существует, то функция вернёт 1, в противном случае - 0.
Примечание: если значение переменной =0, то считается, что она существует, т.е. функция &defined вернёт "1".
macro defined {
  $var = 0;
  @array = (a, b)
  %hash = (a => 1, b => 2)
  log переменная \$var существует: &defined($var)
  log элемент 1 в массиве \@array - существует: &defined($array[1])
  log ключа "с" в хэше \%hash - не существует: &defined($hash{c})
}
В консоли увидим:
[eventmacro message] переменная $var существует: 1
[eventmacro message] элемент 1 в массиве @array - существует: 1
[eventmacro message] ключа "с" в хэше %hash - не существует: 0

Массив
  • Присвоить массиву несколько значений можно указав их в скобках через запятую: @variable = (member0, member1, member2)
  • Получить доступ к конкретному элементу массива можно по его индексу. Для этого нужно вместо знака @ подставить $ и в квадратных скобках [...] указать индекс элемента: $variable[0]
  • Узнать длину массива: @variable
macro Hello {
   @var = (drops, poring)
   log Кол-во элементов в массиве \@var = @var, первый элемент: $var[0], второй элемент: $var[1]
}
В консоли увидим:
[eventmacro message] Кол-во элементов в массиве @var = 2, первый элемент: drops, второй элемент: poring
  • Отдельные элементы массива - это скалярные переменные.
Элементам массива можно присвоить значение:
$myarray[0] = Гарри
$myarray[1] = Поттер
Увеличить\уменьшить элемент массива на единицу:
macro Counter {
    $counterArray[1] = 0
    log Значение элемента \$counterArray[1]: $counterArray[1]
    $counterArray[1]++
    log Новое значение: $counterArray[1]
    $counterArray[1]--
    log Прежнее значение: $counterArray[1]
}
В консоли увидим:
[eventmacro message] Значение элемента $counterArray[1]: 0
[eventmacro message] Новое значение: 1
[eventmacro message] Прежнее значение: 0
Удаление элемента массива:
macro undef {
    $var[5] = 1
    log значение элемента \$var[5]: $var[5]
    $var[5] = undef  # также можно использовать 'unset'
    log значение элемента \$var[5] теперь уничтожено: $var[5]
}
В консоли увидим:
[eventmacro message] значение элемента $var[5]: 1
[eventmacro message] значение элемента $var[5] теперь уничтожено:
Функции для работы с массивами
Существует четыре функции, которые предназначены для работы с массивами:
  1. &push: добавляет элемент в конец массива, увеличивая таким образом длину массива на единицу.
  2. &pop: убирает элемент из конца массива, уменьшая таким образом длину массива на единицу.
  3. &shift: убирает первый элемент массива, сдвигая таким образом все остальные элементы массива влево, ближе к началу и уменьшает на единицу длину массива.
  4. &unshift: добавляет новый элемент в начало массива и сдвигает все остальные элементы вправо, ближе к концу массива, увеличивает длину массива на 1.
&push(@array, newmember)
Функции &push требуется два аргумента: массив и его новый элемент.
Пример создания массива с помощью функции &push:
macro push {
    &push(@monsters, Поринг)
    &push(@monsters, Волк)
    &push(@monsters, Мая)
    log Массив \@monsters состоит из @monsters элементов: $monsters[0], $monsters[1] и $monsters[2]
}
В консоли увидим:
[eventmacro message] Массив @monsters состоит из 3 элементов: Поринг, Волк и Мая
&pop(@array)
Функции &pop нужен только один аргумент - массив, из которого надо вытолкнуть последний элемент.
Пример массива в котором сначала было три элемента, потом из него вытолкнули два последних элемента и остался только один:
macro pop {
    @jobs = (нуб, вор, охотник)
    log Массив \@jobs состоит из @jobs элементов: $jobs[0], $jobs[1] и $jobs[2]
    &pop(@jobs)
    log Теперь массив \@jobs состоит из @jobs элементов: $jobs[0], $jobs[1]
    &pop(@jobs)
    log Теперь массив \@jobs состоит из @jobs элемента: $jobs[0]
}
В консоли увидим:
[eventmacro message] Массив @jobs состоит из 3 элементов: нуб, вор и охотник
[eventmacro message] Теперь массив @jobs состоит из 2 элементов: нуб, вор
[eventmacro message] Теперь массив @jobs состоит из 1 элемента: нуб
&shift(@array)
Функции &shift нужен только один аргумент - массив, из которого надо вытолкнуть первый элемент.
Пример массива в котором сначала было три элемента, потом из него вытолкнули два первых элемента и остался только один:
macro shift {
    @jobs = (нуб, вор, охотник)
    log Массив \@jobs состоит из @jobs элементов: $jobs[0], $jobs[1] и $jobs[2]
    &shift(@jobs)
    log Теперь массив \@jobs состоит из @jobs элементов: $jobs[0] и $jobs[1]
    &shift(@jobs)
    log Теперь массив \@jobs состоит из @jobs элемента: $jobs[0]
}
В консоли увидим:
[eventmacro message] Массив @jobs состоит из 3 элементов: нуб, вор и охотник
[eventmacro message] Теперь массив @jobs состоит из 2 элементов: вор и охотник
[eventmacro message] Теперь массив @jobs состоит из 1 элемента: охотник
Обратите внимание, что функция &shift сдвигает весь массив влево, т.е. после первого сдвига элемент 'охотник' переместится с индекса 2 на 1, а после второго сдвига получит индекс 0.
&unshift(@array, newmember)
Функция &unshift требует два аргумента - массив и его новый элемент, который после сдвига массива вправо попадёт на освободившееся место в начале.
Пример создания массива с помощью функции &unshift:
macro unshift {
    &unshift(@monsters, Поринг)
    &unshift(@monsters, Волк)
    &unshift(@monsters, Мая)
    log Массив \@monsters состоит из @monsters элементов: $monsters[0], $monsters[1] и $monsters[2]
}
В консоли увидим:
[eventmacro message] Массив \@monsters состоит из @monsters элементов: Мая, Волк, Поринг
Обратите внимание, что функция &unshift сдвигает весь массив вправо, т.е. последний добавленный элемент 'Мая', оказывается на первом месте.

Хэш
  • Чтобы инициализировать переменную типа хэш, нужно в круглых скобках прописать через запятую список пар: "ключ => значение": %variable = (key1 => value1, key2 => value2)
  • Чтобы обратиться к элементу хэша, нужно использовать знак $ вместо % и в фигурных скобках { } написать ключ: $variable{key1}
  • Ключ может состоять из букв и цифр.
  • Получить количество элементов (т.е. пар) в хеше: %variable
macro Hello {
   %ages = (Kaya => 25, Namrok => 32)
   log Возраст Каи: $ages{Kaya} лет, а Намрока: $ages{Namrok} года
}
В консоли увидим:
[eventmacro message] Возраст Каи: 25 лет, а Намрока: 32 года
  • значения ключей хеша - это обычные скаляры.
Значениям хеша можно присвоить данные:
$name{first} = Гарри
$name{last} = Поттер
Числовые значения хеша можно увеличить\уменьшить на единицу:
macro Counter {
    $hash{monterskilled} = 0
    log Значение \$hash{monterskilled}: $hash{monterskilled}
    $hash{monterskilled}++
    log Новое значение: $hash{monterskilled}
    $hash{monterskilled}--
    log Прежнее значение: $hash{monterskilled}
}
Значение ключа хеша можно уничтожить, присвоив ему специальное слово undef или unset:
macro undef {
    $myhash{value} = 1
    log Значение \$myhash{value}: $myhash{value}
    $myhash{value} = undef  # также можно использовать 'unset'
    log \$myhash{value} теперь уничтожена: $myhash{value}
}
В консоли увидим:
[eventmacro message] Значение $myhash{value}: 1
[eventmacro message] $myhash{value} теперь уничтожена:
Функции для работы с хэшами
Существует две функции, которые предназначены для работы с хэшами:
  1. &delete: удаляет пару ключ\значение
  2. &exists: проверяет существует ли значение у заданного ключа
&delete($<хэш>{<ключ>})
Функции &delete требуется указать ключ хэша, который следует удалить, например: &delete ( $hash{key} )
&exists($<хэш>{<ключ>})
Функции &exists требуется указать ключ хэша, который следует проверить. Если у заданного <ключа>есть значение, то функция вернёт 1, в противном случае - 0. Например: &exists ( $hash{key} )
Пример
macro hash {
   %fruitsprice = (apple => 1000, banana => 700)
   log Хэш \%fruitsprice состоит из  %fruitsprice элементов
   log Цена на яблоки: $fruitsprice{apple}, а на бананы: $fruitsprice{banana}
   &delete($fruitsprice{apple})
   log Хэш \%fruitsprice состоит из %fruitsprice элемента
     if ( &exists($fruitsprice{apple}) ) {
       log Цена на яблоки: $fruitsprice{banana}
     } else {
       log В хэше нет яблок
     }
     if ( &exists($fruitsprice{banana}) ) {
       log Цена на бананы: $fruitsprice{banana}
     } else {
       log В хэше нет бананов
     }
}
В консоли увидим:
[eventmacro message] Хэш %fruitsprice состоит из 2 элементов
[eventmacro message] Цена на яблоки: 1000, а на бананы: 700
[eventmacro message] Хэш %fruitsprice состоит из 1 элемента
[eventmacro message] В хэше нет яблок
[eventmacro message] Цена на бананы: 700

Особые переменные

В эвент-макросе есть особые переменные, названия которых начинаются с точки. Они автоматически создаются плагином eventMacro.

Переменная Описание Пример
$.time текущее время в виде unix timestamp 1482275422
$.datetime текущая дата и время Tue Dec 20 21:22:34 2016
$.second текущее значение секунд (0 - 59) 53
$.minute текущее значение минут (0 - 59) 34
$.hour текущее значение часов в 24-х часовом формате 14
$.dayofmonth день месяца 19
$.dayofweek день недели (Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday) Wednesday
$.map местонахождение персонажа, локация prontera
$.incity булев_флаг, 1 если персонаж в городе, иначе 0 1
$.inlockmap булев_флаг, 1 если персонаж на lockMap, иначе 0 1
$.job профессия персонажа Swordman
$.pos координаты персонажа 123 234
$.name имя персонажа ya4ept
$.hp значение HP (жизнь) 2304
$.sp значение SP (мана) 345
$.lvl значение базового уровня 175
$.joblvl значение профессионального уровня 60
$.spirits количество сферок у монка или монеток у ганса 3
$.zeny количество денег (зени) 8478341
$.weight вес инвентаря персонажа 1948
$.weightpercent загруженность персонажа в процентах 81.5
$.maxweight максимальная грузоподъемность персонажа 2400
$.status список висящих на персонаже статусов (см. файл statusnametable.txt) Attention Concentrate,Endure,Two-Hand Quicken
$.statushandle список висящих на персонаже статусов, в виде констант SM_ENDURE,KN_TWOHANDQUICKEN
$.inventoryitems количество предметов в инвентаре 13
$.cartweight вес предметов в телеге 800
$.cartweightpercent загруженность телеги в процентах 10
$.cartmaxweight максимальная грузоподъемность телеги 8000
$.cartitems количество предметов в телеге 21
$.cartmaxitems максимально возможное количество предметов в телеге 100
$.shopopen булев_флаг, 1 если магазин открыт, иначе 0 0
$.storageopen булев_флаг, 1 если открыт склад, иначе 0 1
$.storageitems количество предметов на складе 432
$.storagemaxitems максимально возможное количество предметов на складе 600
$.param[N] аргументы командной строки (см. Синтаксис) -
$.caller название последнего сработавшего автомакроса -

Функции эвент-макроса

Функции макро-языка имеют вид &<название> (<аргументы>). Функциями можно пользоваться почти везде внутри блока macro (кроме goto, end, названиях меток (label), названиях макроса в конструкциях call и set). Все функции кроме &nick() могут принимать переменные в качестве аргументов.

&questStatus (<questID>)
Вернёт статус квеста по его <questID>, возможные значения: "inactive", "incomplete" или "complete".
&questInactiveCount (<questID1>,<questID2>,<questID3>,etc)
Вернёт количество взятых, но не активных (т.е. "inactive"), квестов.
&questIncompleteCount (<questID1>,<questID2>,<questID3>,etc)
Вернёт количество взятых, но незавершенных (т.е. "incomplete"), квестов.
&questCompleteCount (<questID1>,<questID2>,<questID3>,etc)
Вернет количество завершенных квестов, т.е. со статусом "complete".


&inventory (<имя_предмета> | <ID_предмета>)
Вернёт индекс предмета в инвентаре. В качестве аргумента принимает имя предмета или его ИД. Если такого предмета нет, то возвращает -1.
&Inventory (<имя_предмета> | <ID_предмета>)
Как и &inventory вернёт индекс предмета в инвентаре, но если таких предметов несколько - вернёт список их индексов через запятую. Если такого предмета нет, то возвращает -1.
&invamount (<имя_предмета> | <ID_предмета>)
Вернёт количество указанного предмета в инвентаре. Если такого предмета нет, то возвращает 0.
&InventoryType (usable|equip|card|etc)
Вернёт список индексов предметов заданного типа (через запятую), находящихся в инвентаре. Если таких предметов нет, то вернёт -1.


&cart (<имя_предмета> | <ID_предмета>)
Вернёт индекс указанного предмета в телеге. Если такого предмета нет, то возвращает -1.
&Cart (<имя_предмета> | <ID_предмета>)
Как и &cart вернёт индекс предмета в телеге, но если таких предметов несколько - вернёт список их индексов через запятую. Если такого предмета нет, то возвращает -1.
&cartamount (<имя_предмета> | <ID_предмета>)
Вернёт количество предмета в телеге. Если такого предмета нет, то возвращает 0.


&storage (<имя_предмета> | <ID_предмета>)
Вернёт индекс указанного предмета на складе. Если такого предмета на складе нет, то возвращает -1.
&Storage (<имя_предмета> | <ID_предмета>)
Как и &storage вернёт индекс предмета на складе, но если таких предметов несколько - вернёт список их индексов через запятую. Если такого предмета нет, то возвращает -1.
&storamount (<имя_предмета> | <ID_предмета>)
Вернёт количество предмета на складе. Если такого предмета нет, то возвращает 0.


&vender (<name>)
Вернёт индекс продавца (игрока) с именем <name>. Если такого продавца нет в пределах видимости, то возвращает -1.
&venderitem (<имя_предмета | <ID_предмета>)
Вернёт индекс предмета в магазине у торгаша (игрока). Если такого предмета в магазине нет, то возвращает -1.
&venderprice (<имя_предмета> | <indexID>)
Вернёт цену предмета в магазине у торгаша (игрока). В качестве аргумента принимает имя предмета или его индекс (который можно получить через функцию выше &venderitem).
&venderamount (<индекс_предмета>)
Вернёт количество предметов у торгаша (игрока). Если такого предмета в магазине нет, то возвращает -1.


&store (<имя_предмета> | <ID_предмета>)
Ищёт заданный предмет в открытом магазине (НЦП) и возвращает его индекс. Если такого предмета нет, то возвращает -1.
&shopamount (<имя_предмета> | <ID_предмета>)
Вернёт количество предметов, продающихся в магазине (НПЦ).


&npc (<x> <y> | "<NPC_name>" | /regexp/i)
Вернёт индекс неписи, стоящей на заданных координатах <x> <y> или с именем <NPC_name> или если имя НПЦ соответствует шаблону regexp. Если непись найти не удалось, то возвращает -1.
&player (<name>)
Вернёт индекс игрока с именем <name>. Если такого игрока нет в пределах видимости, то возвращает -1.
&monster (<имя_моба> | <ID>)
Вернёт индекс моба. В качестве аргумента принимает имя моба или его ИД. Если такого моба нет в пределах видимости, то возвращает -1.


&config (<параметр>)
Вернёт значение <параметра> из config.txt
&random ("<параметр 1>", "<параметр 2>", $var, ...)
Вернёт один из перечисленных в скобках параметров. Параметры необходимо указывать в кавычках. В качестве параметров можно указывать переменные.
&rand (<n>, <m>)
Вернёт случайное число в диапазоне от <n> до <m> включительно.
&eval (<параметр>)
Вычисляет значение <параметра>. Например, если "$v = 8", то результатом функции &eval ($v + 2) будет число 10. Параметр функции &eval - это выражение на языке Perl, и оно не имеет ничего общего с синтаксисом эвент-макроса. В <параметре> можно использовать переменные эвент-макроса вида $var и результаты других &<функций>, например: warning &eval(&rand(0,5) + 1)
&arg ("<строка>", <n>)
Вернёт <n>-ое слово из <строки>. Слова в строке разделяются знаками: ,.:;\"\'!?\r\n. Если <n> больше количества слов в строке, то возвращается пустая строка. Аргумент <n> может быть как целым числом, так и целочисленной переменной. Например:
$n = 3
log &arg("aa ! bb : cc . dd",$n)
&nick (<строка>)
Экранирует все метасимволы regexp и некоторые специальные символы perl с помощью \ (обратного слэша). Придуман специально для экранирования некоторых имён персонажей. Например, ник "}|{oJIA" будет преобразован в "\}|\{oJIA"
&split (<разделитель>, <переменная>)
Создаёт массив из <переменной> на основе <разделителя>. Вывод этой функции обязательно должен присваиваться массиву. Например:
macro split {
  $list = a~b~c
  log переменная: $list
  @array = &split('~', $list)
  log размер массива: @array, array[1]=$array[1]
}
&keys (<%хэш>)
Создаёт массив из ключей <хэша>. Вывод этой функции обязательно должен присваиваться массиву. Например:
macro split {
  %hash = (a => "foo", b => "bar")
  log размер хэша: %hash
  @array = &keys (%hash)
  log размер массива: @array, array[1]=$array[1]
}
&values (<%хэш>)
Создаёт массив из ключей <хэша>. Вывод этой функции обязательно должен присваиваться массиву.
&listlength (<список_разделённый_запятой>)
Вернёт количество элементов в списке разделённом запятой, например:
macro listlength {
   log количество элементов: &listlength(a, b, c)
}
&strip (<текст>)
Удаляет из <текста> круглые скобки ( ), например:
macro strip {
   $text = (привет))))) мир)
   log текст без скобок: "&strip($text)"
}

Цепочка команд

Несколько команд выполняются друг за другом без задержки, если они объединены в цепочку команд квадратными скобками [ и ].

0 macro foo {
1  do whatever
2  log yet another line
3  [
4     do something
5     do something else
6     log foo
7  ]
8  log done
9 }

Строка 3 начинает цепочку команд и сама по себе не вносит никакой задержки. Строки 4, 5 и 6 выполняются сразу же, как только предыдущая команда завершится. В цепочке команд нет задержек и выполнение команд не может быть прервано. Строка 7 завершает цепочку команд и строка 8 будет выполнятся через положенную задерку в $macro_delay секунд.


Подстроки

Вместо использования по одной команде на строку, можно отделять команды между собой символом точки с запятой ";" и располагать их в одной строке.

macro foo {
    $i = 1; pause 5; log \$i = $i; $ii = 2; $iii = 3; $i++; $ii--; lock automacroName; release automacroName; set overrideAI 1
}

Разделенные точкой с запятой ";" команды будут выполняться с обычной задержной macro_delay.


Операторы сравнения

Плагин eventMacro предлагает следующие операторы сравнения:

Оператор Описание
< меньше
<= меньше, либо равно
== или = равенство, см. (link)
> больше
>= больше, либо равно
 != неравенство
~ <леваячасть> есть элемент <праваячасть>, где <праваячасть> список, разделенный символом запятой ","
=~ <леваячасть> подпадает под регулярное выражение - regexp из <праваячасть>. Подробнее: Forums
arg .. arg2 диапазон значений между arg и arg2, где arg число, процент или переменная.

Управление потоком и метки

  • Как и в большинстве языков программирования, в плагине eventMacro реализованы привычные конструции типа "if .. else", "while", "foreach", "for .. next", "do .. while" и некоторые другие.
  • Кроме того есть операции "if", "else", "elsif", "switch", "case", "goto" и "while". При помощи label можно ставить метки в коде.

Синтаксис условных операторов

If

Right now, macro if conditions are very close to the perl if statements. It accepts unlimited number of statements in just one if condition line, regexp matching is allowed (unfortunately, no backreference using parenthesis) and the use of && for and meaning and || for or meaning.

Можно использовать простое выражение, которое проверяет одно условие:

if (arg1 <Operators> arg2) (goto <label> | call <macro> [<parameters>] | stop | { )

Проверка двух условий, объединённых оператором или, хотя бы одно условие должно быть истинным:

if (arg1 <Operators> arg2 || arg3 <Operators> arg4) (goto <label> | call <macro> <parameters> | stop | { )

Проверка двух условий, объединённых оператором и, оба условия должны быть истинными:

if (arg1 <Operators> arg2 && arg3 <Operators> arg4) (goto <label> | call <macro> <parameters> | stop | { )

Примеры использования обоих операторов:

if ((arg1 <Operators> arg2 || arg3 <Operators> arg4) && arg5 <Operators> arg6) (goto <label> | call <macro> <parameters> | stop | { )
if ((arg1 <Operators> arg2 && arg3 <Operators> arg4) || arg5 <Operators> arg6) (goto <label> | call <macro> <parameters> | stop | { )
if ((arg1 <Operators> arg2 && arg3 <Operators> arg4) || (arg5 <Operators> arg6 && arg7 <Operators> arg8)) (goto <label> | call <macro> <parameters> | stop | { )
if ((arg1 <Operators> arg2 || arg3 <Operators> arg4) && (arg5 <condition> arg6 || arg7 <condition> arg8)) (goto <label> | call <macro> <parameters> | stop | { )
  • Notice inside of each brackets containing the AND and OR symbols.

причём

  • arg может быть переменной, a nested variable, a special keyword, &eval, текстом или числом или даже Perl Subroutines функцией.
  • <label>, название метки в коде, может быть только из букв и цифр.
  • <macro>, название макроса
  • <parameters> параметры макроса, внутри макроса можно к ним обратиться как $.param[0], $param[1] и т.д.
  • < { >, начало блока команд, которые запустятся, если условие истинно. Блок команд закрывается соответствующей фигурной скобкой }.


Примечание: Внутри скобок можно использовать неограниченное количество сравнений.

if (arg1 <Operators> arg2 || arg3 <Operators> arg4 || ... || argN <Operators> argN+1) (goto <label> | call <macro> <parameters> | stop)

Where;

  • arg can be a variable, a nested variable, a special keyword, &eval or letters and numbers.
  • All the conditions is up to the Nth argument <Operators> N+1th argument.
  • While N is an integer number/s which is greater than zero.

Постфиксный if

Кроме того, можно использовать if после команды.

<command> if (arg1 <Operators> arg2)

Т.е. команда перед if запустится только тогда, когда условие истинно. Условие пишется по точно таким же правилам, как было сказано выше.

В следующем примере обе команды равнозначны и делают одно и то же:

call buy if ($.zeny > 1000)
if ($.zeny > 1000) call buy

Else

В случае, если if использовался с фигурными скобками ( { ), то можно использовать else после закрывающей фигурной скобки ( } ).

if (arg1 <Operators> arg2) {
   command1
   command2
   ...
   commandN
} else {
   command3
   command4
   ...
   commandN
}

В этом случае если условие в круглых скобках истинно, то выполнятся только команды 1 и 2, если условие ложное, то выполнятся только команды 3 и 4.


Примечание: в фигурных скобках можно использовать неограниченное количество команд.
Примечание: ветка else - не обязательна.


Elsif

Этот оператор работает как else + if одновременно. Оператор elsif нужен для проверки следующего условия. Оператор else срабатывает, когда ни одно условие не выполнилось.

if (arg1 <Operators> arg2) {
   command1
   command2
   ...
   comandoN
} elsif (arg1 <Operators> arg2) {
   command3
   command4
   ...
   commandN
} else {
   command5
   command6
   ...
   commandN
}

В этом случае если первое условие истинно, то будут выполнены только команды 1 и 2, если оно ложное, то далее идёт проверка второго условия. Если второе условие истинно, то будут выполнены только команды 3 и 4. Если оба условия ложные, то будут выполнены только команды 5 и 6.


Примечание: ветки elsif и else - не обязательны.


Switch/case

Этот оператор напоминает if с кучей последующих elseif. Данный оператор будет полезным, когда необходимо проверить одну переменную на разные условия.

switch (arg1) {
    case (<Operators> arg2) (goto <label> | call <macro> <parameters> | stop | {)
        (Если вы используете "{", то команды для выполнения должна находиться здесь. Каждая команда должна быть написана в новой строчке. В конце обязательно должна быть закрывающая скобка "}")
    case (<Operators> arg2) (goto <label> | call <macro> <parameters> | stop | {)
        (Если вы используете "{", то команды для выполнения должна находиться здесь. Каждая команда должна быть написана в новой строчке. В конце обязательно должна быть закрывающая скобка "}")
    ...
    else (goto <label> | call <macro> <parameters> | stop | {)
        (Если вы используете "{", то команды для выполнения должна находиться здесь. Каждая команда должна быть написана в новой строчке. В конце обязательно должна быть закрывающая скобка "}")
}

Примечание: если не сработал ни один case, тогда отработает else.
Примечание: использовать else не обязательно.


Примеры с условными операторами

Этот макрос двигает персонажа в случайном направлении: на север, юг, восток или запад.

macro walk {
   $num = &rand(1, 4)
   if ($num == 1) {
       do c я пойду в сторону 1 (на север)
       do north
   }
   if ($num == 2) {
       do c я пойду в сторону 2 (на юг)
       do south
   }
   if ($num == 3) {
       do c я пойду в сторону 3 (на восток)
       do east
   }
   if ($num == 4) {
       do c я пойду в сторону 4 (на запад)
       do west
   }
}

Давайте перепишем этот макрос с постфиксным if:

macro walk {
   $num = &rand(1, 4)
   do c я пойду в сторону $num
   do north if ($num == 1)
   do south if ($num == 2)
   do east  if ($num == 3)
   do west  if ($num == 4)
}

Следующий макрос использует конструкцию if/else, чтобы определить, есть ли у персонажа больше 1000 зени или нет.

macro checkZeny {
   if ($.zeny > 1000) {
      do c У меня больше 1.000z! 
   } else {
      do c у меня 1.000z или меньше...
   }
}

Чуть усложнённый пример, чтобы узнать сколько зени в кармане: больше тысячи, ровно тысяча или меньше. В зависимости от этого выдаются разные смайлики.

macro checkZeny {
   if ($.zeny > 1000) {
      do c у меня больше 1.000z! 
      do e money
   } elsif ($.zeny == 1000) {
      do c у меня ровно 1.000z.
      do e !
   } else {
      do c у меня меньше 1.000z
      do e panic
   }
}

Переработаем предыдущий макрос, с использованием switch/case:

macro checkZeny {
    switch ($.zeny) {
        case (> 1000) {
            do c у меня больше 1.000z! 
            do e money
        }
        case (== 1000) {
            do c у меня ровно 1.000z.
            do e !
        }
        else {
            do c у меня меньше 1.000z
            do e panic
        }
    }
}

Следующий макрос показывает использование if вместе с goto:

macro checknum {
    $num = &rand(1, 3)
    if ($num == 1) goto one
    if ($num == 2) goto two
    if ($num == 3) goto three
    :one
    log \$num = 1
    stop
    :two
    log \$num = 2
    stop
    :three
    log \$num = 3
}

Переработаем предыдущий макрос, с использованием call вместо goto.

macro checknum {
    $num = &rand(1, 3)
    if ($num == 1) call one
    if ($num == 2) call two
    if ($num == 3) call three
}
macro one {
    log $num = 1
}
macro two {
    log $num = 2
}
macro three {
    log $num = 3
}


Сложный макрос, где переменная $i, равная 1, подвергается изощрённым проверкам и так и сяк.

macro if {
 $i = 1
 log \$i = $i
 if (((($i = 1 || $i < 5 || $i ~ 0 .. 5) && &eval(&eval($i - 1) - &eval($i - 0)) = -1) && ($i != 2 && $i > 0 && &eval($i - 1) = 0) && ($i != 2 && $i > 0 && &eval($i - 1) = 0)) && $i = 1) goto somewhere
 if (($i = 1 || $i < 5 || $i ~ 0 .. 5) && ($i != "" && $i > 0 && &eval($i - 1) = 0)) goto somewhere
 if (&eval (&eval($i-1) - 1) != "") goto somewhere
 if ((($i = 1) || ($i < 5 && $i ~ 0 .. 5)) && ($i != "" && $i > 0 && &eval($i - 1) > 0)) goto somewhere
 log ko
 stop
:somewhere
 log OK
}

Цикл while

Цикл по условию while запускает команды раз за разом до тех пор, пока условие не перестанет быть истинным.

Синктаксис
while (arg <condition> arg) {
    do bla bla
    ...
}

причём

  • arg - может переменной, вложенной переменной, ключевым словом, &eval, числом или строкой.

Операторы сравнения смотри тут: Operators.

Пример

Пробежим цикл десять раз, от $i равного 0 до 9.

macro while {
    $i = 0
    while ($i < 10) {
    log \$i = $i
    $i++
    }
}

Вывод на консоль:

[eventmacro log] \$i = 0
[eventmacro log] \$i = 1
[eventmacro log] \$i = 2
[eventmacro log] \$i = 3
[eventmacro log] \$i = 4
[eventmacro log] \$i = 5
[eventmacro log] \$i = 6
[eventmacro log] \$i = 7
[eventmacro log] \$i = 8
[eventmacro log] \$i = 9

Автомакросы

На данный момент вы научились объявлять макросы и вызывать их, набирая в консоли OpenKore 'eventMacro <macro name>'.

Автомакрос нужен для того, чтобы автоматически запускать макрос при срабатывании некоторых условий.

Автомакрос состоит из:

  • одного или нескольких параметров (параметр call среди них единственный обязательный).
  • одного или нескольких условий.

Автомакрос не сработает, если в данный момент исполняется макрос в т.н. эксклюзивном режиме. В любом другом случае очередь макросов очищается (другими словами, всё останавливается) и уже тогда запускается нужный макрос.

Ещё раз - мы используем автомакрос для проверки неких условий, если они выполняются, то автомакрос срабатывает и запускает указанный макрос.

Параметры

  • Каждый параметр упоминается не больше одного раза.
  • Параметры определяют, каким образом будет работать автомакрос или вызванный им макрос.
  • У большинства параметров есть значение по умолчанию.
call
  • call - это единственный обязательный параметр в каждом автомакросе.
  • call определяет, какой макрос будет запущен.
  • call может быть названием макроса или блоком команд.

Пример с использованием названия макроса:

automacro <название автомакроса> {
    <тут только условия и параметры автомакроса>
    call myMacro
}
macro myMacro {
    <тут обычные инструкции макроса>
    # например:
    do move prontera
    do move payon
}

Пример с использованием блока команд:

automacro <название автомакроса> {
    <тут только условия и параметры автомакроса>
    call {
        <тут обычные инструкции макроса>
        # например:
        do move prontera
        do move payon
    }
}


  • Оба примера выше равнозначны и делают то же самое.
  • Обратите внимание, что блок команд в параметре call подчиняется тем же правилам что и обычный macro-блок.

Синтаксис первого автомакроса удобен, когда у вас есть несколько автомакросов, которые могут вызывать один и тот же макрос:

automacro First {
    <одни условия> 
    call print
}
automacro Second {
    <другие условия> 
    call print
}
macro print {
    log $.caller triggered
}


delay
  • delay - необязательный параметр.
  • delay определяет время в секундах, которое пройдёт перед тем, как запустится макрос из параметра call.
  • Значение по умолчанию: 0.
  • Значением параметра может быть только число.
automacro <название автомакроса> {
    <тут только условия и параметры автомакроса>
    delay 5
    call myMacro
}
macro myMacro {
    <тут обычные инструкции макроса>
    log Текст будет напечатан через 5 секунд, после того, как сработает автомакрос.
}
run-once
  • run-once - необязательный параметр.
  • run-once определяет, сколько раз может сработать автомакрос - только один раз или неограниченное количество раз.
  • Значение по умолчанию: 0.
  • Если 1 , то автомакрос сработает лишь однажды, если 0, то может сработать много раз.
  • Чтобы уже сработавшему автомакросу с run-once 1 разрешить сработать ещё раз, можно использовать команду 'release' Macro Syntax.
automacro myautomacro {
    <тут только условия и параметры автомакроса>
    run-once 1
    call myMacro
}
automacro myaotherauto {
    <тут только условия и параметры автомакроса>
    run-once 0
    call myMacro
}
macro myMacro {
    <тут обычные инструкции макроса>
    log Данный макрос может быть вызван из myautomacro только один раз,
    log но из myaotherauto он может быть вызван много раз.
}
CheckOnAI
  • CheckOnAI - необязательный параметр.
  • CheckOnAI определяет, в каком режиме AI может сработать автомакрос.
  • Значение по умолчанию можно установить в параметре конфига eventMacro_CheckOnAI Configuration files.
  • Если не указать данный параметр в автомакросе, то будет использовано значение по умолчанию, которое берётся из параметра конфига eventMacro_CheckOnAI.
  • Если в конфиге не прописано значение по умолчанию eventMacro_CheckOnAI, то используется: auto
  • Значение параметра - список через запятую следующих слов: auto, manual и off.
automacro MyAuto {
    <тут только условия и параметры автомакроса>
    CheckOnAI manual
    call myMacro
}
macro myMacro {
    <тут обычные инструкции макроса>
    log Автомакрос MyAuto сработает только в ручном режиме бота (manual)
}

automacro MyAuto2 {
    <тут только условия и параметры автомакроса>
    CheckOnAI manual, off
    call myMacro
}
macro myMacro2 {
    <тут обычные инструкции макроса>
    log Автомакрос MyAuto2 сработает в режимах manual или off.
}
disabled
  • disabled - необязательный параметр.
  • disabled определяет, активен ли автомакрос.
  • Значение по умолчанию: 0.
  • Если 1, то автомакрос не активен и не сможет сработать. Если 0, то сработает при наступлении условий.
automacro MyAuto {
    <тут только условия и параметры автомакроса>
    disabled 1
    call myMacro
}
macro myMacro {
    <тут обычные инструкции макроса>
    log Автомакрос MyAuto никогда не сработает, он выключен.
}

automacro MyAuto2 {
    <тут только условия и параметры автомакроса>
    disabled 0
    call myMacro
}
macro myMacro2 {
    <тут обычные инструкции макроса>
    log Автомакрос MyAuto2 сработает как положено при наступлении условий.
}
overrideAI
  • overrideAI - необязательный параметр.
  • overrideAI определяет, занесёт ли плагин eventMacro макро-команды в очередь задач AI.
  • Значение по умолчанию: 0.
  • Если 0, то команды макроса попадают в очередь задач AI как 'eventMacro' и каждая команда сработает только тогда, когда до неё дойдёт очередь, т.е. AI переключится на задачу 'eventMacro'.
  • Если 1, то команды макроса не попадут в очередь задач AI и не будут управляться ею. Команды тупо выполняются одна за другой с интервалом macro_delay.
  • It's important to note that when it's value is 1 since it won't be put into AI queue normal AI functions will continue as normal, like mob hunting or autostorage.
automacro MyAuto {
    <тут только условия и параметры автомакроса>
    overrideAI 0
    call myMacro
}
macro myMacro {
    <тут обычные инструкции макроса>
    do move prontera
    log До этой строки макроса дело дойдёт только тогда, когда бот дойдёт до Пронтеры, т.е. довольно длительная команда 'move prontera' выполнится. Ибо в списке задач AI команда 'move' стоит первая в очереди.
}

automacro MyAuto2 {
    <тут только условия и параметры автомакроса>
    overrideAI 1
    call myMacro
}
macro myMacro2 {
    <тут обычные инструкции макроса>
    do move prontera
    log До этой строки макроса дело дойдёт практически сразу, через короткий промежуток macro_delay, потому что оно работает без оглядки на очередь команд AI.
}
exclusive
  • exclusive is an optional parameter.
  • exclusive defines if the macro can be interrupted or not.
  • If not used in the automacro the default value will be used, which is: 0.
  • When it's value is 0 the macro can be interrupted by other automacros.
  • When it's value is 1 the macro can not be interrupted by other automacros.
automacro MyAuto {
    <automacro conditions and parameters (and only them)>
    exclusive 0
    call myMacro
}
macro myMacro {
    <macro instructions (and only them, as this is regular macro)>
    log This would probably cause a bug because the automacro would activate every AI cycle since the macro is interruptible.
}

automacro MyAuto2 {
    <automacro conditions and parameters (and only them)>
    exclusive 1
    call myMacro
}
macro myMacro2 {
    <macro instructions (and only them, as this is regular macro)>
    log Since exclusive is 1 the macro is now uninterruptible and will work properly.
}
priority
  • priority is an optional parameter.
  • priority defines the priority for activation the automacro has between all automacros, the lower the priority, the sooner ir will be checked.
  • If not used in the automacro the default value will be used, which is: 0.
  • Must have a numeric value.
automacro MyAuto {
    <automacro conditions and parameters (and only them)>
    priority 5
    call {
        log This automacro will be checked after MyAuto2 because it's priority is higher
    }
}

automacro MyAuto2 {
    <automacro conditions and parameters (and only them)>
    priority 2
    call {
        log This automacro will be checked before MyAuto because it's priority is lower
    }
}
macro_delay
  • macro_delay is an optional parameter.
  • macro_delay defines the time in seconds to wait between macro commands.
  • If not used in the automacro the default value will be used, which is: 1.
  • Must have a numeric value.
automacro MyAuto {
    <automacro conditions and parameters (and only them)>
    macro_delay 2
    call {
        log This will be printed at the macro execution
        log This will be printed 2 seconds after
    }
}

automacro MyAuto2 {
    <automacro conditions and parameters (and only them)>
    macro_delay 5
    call {
        log This will be printed at the macro execution
        log This will be printed 5 seconds after
    }
}
orphan
  • orphan is an optional parameter.
  • orphan defines how will eventMacro deal with macros when 'eventMacro' is cleaned out of AI queue.
  • The default value for this parameter can be set in the config key eventMacro_orphans Configuration files.
  • If not used in the automacro the default value will be used, which is the config key eventMacro_orphans.
  • If eventMacro_orphans is not set in the config the default value will be used, which is: terminate
  • The valid values and their descriptions are the following:
Value Description
terminate terminates the macro (equivalent to eventMacro stop)
terminate_last_call terminates only the last call of the queue, this means that if macro 'mac1' called 'mac2' which called 'mac3', who got orphaned, only 'mac3' gets terminated, and queue returns to 'mac2'.
reregister re-registers to AI queue, overriding other entries. This means to force the continuation of the macro.
reregister_safe re-registers to AI queue when AI gets idle. This means the macro will continue when all other tasks are done.
repeat
  • repeat is an optional parameter.
  • repeat defines how many times the macro defined by call will be called.
  • If not used in the automacro the default value will be used, which is: 1.
  • Must have a numeric value.
automacro <automacro name> {
    <automacro conditions and parameters (and only them)>
    repeat 3
    call myMacro
}
macro myMacro {
    <macro instructions (and only them, as this is regular macro)>
    log This message will be printed 3 times, because the macro will be called 3 times
}
timeout
  • timeout is an optional parameter.
  • timeout defines the time in seconds before this automacro can activate again after an activation.
  • If not used in the automacro the default value will be used, which is: 0.
  • Must have a numeric value.
automacro <automacro name> {
    <automacro conditions and parameters (and only them)>
    timeout 60
    call myMacro
}
macro myMacro {
    <macro instructions (and only them, as this is regular macro)>
    log This macro will only be called every 60 seconds
}

Conditions

  • Conditions are separated into 2 categories: state and event.
  • Most conditions set special variables when the automacro activates.
  • Most conditions accept variables in their code.
  • Each automacro can only have one event condition.
  • Most state conditions can be used more than once in each automacro.
  • Each condition will have it's detailed explanation below.
  • eventMacro has a modular condition system, each file inside eventMacro/Condition is a condition.

State

  • State conditions have a defined status of true or false.
  • An automacro will only activate when all of it's state conditions are true.


BaseLevel
  • Description: Checks the player base level.
  • Does not support percentages.
Syntax:
BaseLevel <Math condition operators>
Example:
BaseLevel >= 30
Set variables:
$.BaseLevelLast => Saves the last level that made BaseLevel become true


JobLevel
  • Description: Checks the player job level.
  • Does not support percentages.
Syntax:
JobLevel <Math condition operators>
Example:
JobLevel = 70
Set variables:
$.JobLevelLast => Saves the last job level that made JobLevel become true


CartCurrentWeight
  • Description: Checks the player's cart current weight.
  • Supports percentages.
Syntax:
CartCurrentWeight <Math condition operators>
Example:
CartCurrentWeight > 80%
CartCurrentWeight > 4000
Set variables:
$.CartCurrentWeightLast => Saves the last cart weight that made CartCurrentWeight become true
$.CartCurrentWeightLastPercent => Saves the last cart weight percentage that made CartCurrentWeight become true


CartMaxWeight
  • Description: Checks the player's cart max weight.
  • Does not support percentages.
Syntax:
CartMaxWeight <Math condition operators>
Example:
CartMaxWeight > 4000
Set variables:
$.CartMaxWeightLast => Saves the last cart max weight that made CartMaxWeight become true


CartCurrentSize
  • Description: Checks the player's cart current item quantity.
  • Supports percentages.
Syntax:
CartCurrentSize <Math condition operators>
Example:
CartCurrentSize > 80%
CartCurrentSize > 4000
Set variables:
$.CartCurrentSizeLast => Saves the last cart item quantity that made CartCurrentSize become true
$.CartCurrentSizeLastPercent => Saves the last cart item quantity percentage that made CartCurrentSize become true


CartMaxSize
  • Description: Checks the player's cart max item quantity.
  • Does not support percentages.
Syntax:
CartMaxSize <Math condition operators>
Example:
CartMaxSize > 4000
Set variables:
$.CartMaxSizeLast => Saves the last cart max item quantity that made CartMaxSize become true


CharCurrentWeight
  • Description: Checks the player's current weight.
  • Supports percentages.
Syntax:
CharCurrentWeight <Math condition operators>
Example:
CharCurrentWeight > 80%
CharCurrentWeight > 4000
Set variables:
$.CharCurrentWeightLast => Saves the last player weight that made CharCurrentWeight become true
$.CharCurrentWeightLastPercent => Saves the last player weight percentage that made CharCurrentWeight become true


CharMaxWeight
  • Description: Checks the player's max weight.
  • Does not support percentages.
Syntax:
CharMaxWeight <Math condition operators>
Example:
CharMaxWeight > 4000
Set variables:
$.CharMaxWeightLast => Saves the last player max weight that made CharMaxWeight become true


FreeStatPoints
  • Description: Checks the player's free stat points.
  • Does not support percentages.
Syntax:
FreeStatPoints <Math condition operators>
Example:
FreeStatPoints > 20
Set variables:
$.FreeStatPointsLast => Saves the last amount of free stat points that made FreeStatPoints become true


FreeSkillPoints
  • Description: Checks the player's free skill points.
  • Does not support percentages.
Syntax:
FreeSkillPoints <Math condition operators>
Example:
FreeSkillPoints > 20
Set variables:
$.FreeSkillPointsLast => Saves the last amount of free skill points that made FreeSkillPoints become true


CurrentHP
  • Description: Checks the player's current hp.
  • Supports percentages.
Syntax:
CurrentHP <Math condition operators>
Example:
CurrentHP > 80%
CurrentHP > 4000
Set variables:
$.CurrentHPLast => Saves the last player hp that made CurrentHP become true
$.CurrentHPLastPercent => Saves the last player hp percentage that made CurrentHP become true


MaxHP
  • Description: Checks the player's max hp.
  • Does not support percentages.
Syntax:
MaxHP <Math condition operators>
Example:
MaxHP > 4000
Set variables:
$.MaxHPLast => Saves the last player max hp that made MaxHP become true


CurrentSP
  • Description: Checks the player's current sp.
  • Supports percentages.
Syntax:
CurrentSP <Math condition operators>
Example:
CurrentSP > 80%
CurrentSP > 4000
Set variables:
$.CurrentSPLast => Saves the last player sp that made CurrentSP become true
$.CurrentSPLastPercent => Saves the last player sp percentage that made CurrentSP become true


MaxSP
  • Description: Checks the player's max sp.
  • Does not support percentages.
Syntax:
MaxSP <Math condition operators>
Example:
MaxSP > 4000
Set variables:
$.MaxSPLast => Saves the last player max sp that made MaxSP become true


InInventory
  • Description: Checks if the player has a certain quantity of an item in the inventory, uses item name.
  • Does not support percentages.
Syntax:
InInventory "<item name>" <Math condition operators>
Note the quotation marks.
Example:
InInventory "Red Potion" < 10
Set variables:
$.InInventoryLast => Saves the name of the last item that made InInventory become true
$.InInventoryLastAmount => Saves the amount in inventory of the last item that made InInventory become true


InInventoryID
  • Description: Checks if the player has a certain quantity of an item in the inventory, uses item ID.
  • Does not support percentages.
Syntax:
InInventoryID <item ID> <Math condition operators>
Example:
InInventoryID 501 < 10
Set variables:
$.InInventoryIDLast => Saves the ID of the last item that made InInventoryID become true
$.InInventoryIDLastAmount => Saves the amount in inventory of the last item that made InInventoryID become true


InStorage
  • Description: Checks if the player has a certain quantity of an item in the storage, uses item name.
  • Does not support percentages.
Syntax:
InStorage "<item name>" <Math condition operators>
Note the quotation marks.
Example:
InStorage "Blue Potion" > 100
Set variables:
$.InStorageLast => Saves the name of the last item that made InStorage become true
$.InStorageLastAmount => Saves the amount in storage of the last item that made InStorage become true


InStorageID
  • Description: Checks if the player has a certain quantity of an item in the storage, uses item ID.
  • Does not support percentages.
Syntax:
InStorageID <item ID> <Math condition operators>
Example:
InStorageID 507 100..500
Set variables:
$.InStorageIDLast => Saves the ID of the last item that made InStorageID become true
$.InStorageIDLastAmount => Saves the amount in storage of the last item that made InStorageID become true


InCart
  • Description: Checks if the player has a certain quantity of an item in the cart, uses item name.
  • Does not support percentages.
Syntax:
InCart "<item name>" <Math condition operators>
Note the quotation marks.
Example:
InCart "Blue Potion" > 100
Set variables:
$.InCartLast => Saves the name of the last item that made InCart become true
$.InCartLastAmount => Saves the amount in cart of the last item that made InCart become true


InCartID
  • Description: Checks if the player has a certain quantity of an item in the cart, uses item ID.
  • Does not support percentages.
Syntax:
InCartID <item ID> <Math condition operators>
Example:
InCartID 507 100..500
Set variables:
$.InCartIDLast => Saves the ID of the last item that made InCartID become true
$.InCartIDLastAmount => Saves the amount in cart of the last item that made InCartID become true


InventoryCurrentSize
  • Description: Checks the player current item count.
  • Supports percentages. (but it won't change anything since you can have 100 items max)
Syntax:
InventoryCurrentSize <Math condition operators>
Example:
InventoryCurrentSize > 70%
InventoryCurrentSize > 30
Set variables:
$.InventoryCurrentSizeLast => Saves the last player item count that made InventoryCurrentSize become true


SkillLevel
  • Description: Checks if the player has a certain level of a certain skill, uses skill Id or Handle.
  • Does not support percentages.
Syntax:
SkillLevel "<skill ID or Handle>" <Math condition operators>
Note the quotation marks.
Example:
SkillLevel NV_FIRSTAID = 0
SkillLevel 10 > 5
Set variables:
$.SkillLevelLastName => Saves the name of the last skill that made SkillLevel become true
$.SkillLevelLastID => Saves the ID of the last skill that made SkillLevel become true
$.SkillLevelLastHandle => Saves the Handle of the last skill that made SkillLevel become true
$.SkillLevelLastLevel => Saves the level of the last skill that made SkillLevel become true


Zeny
  • Description: Checks the player current zeny.
  • Does not support percentages.
Syntax:
Zeny <Math condition operators>
Example:
Zeny > 500000
Set variables:
$.ZenyLast => Saves the last zeny amount that made Zeny become true


StorageOpened
  • Description: Is true if storage is opened and it is set to 1 or storage is not opened and it is set to 0.
Syntax:
StorageOpened <1|0>
Example:
StorageOpened 1


ShopOpened
  • Description: Is true if your vending shop is opened and it is set to 1 or your vending shop is not opened and it is set to 0.
Syntax:
ShopOpened <1|0>
Example:
ShopOpened 1


InChatRoom
  • Description: Is true if you are in a chat room and it is set to 1 or you are not in a chat room and it is set to 0.
Syntax:
InChatRoom <1|0>
Example:
InChatRoom 0


ChatRoomNear
  • Description: Checks if there is a npc near which name matches the given regex.
Syntax:
NpcNear <Regex>
Example:
NpcNear /kafra/
NpcNear /special agent/
Set variables:
$.ChatRoomNearLastID => Saves the ID of the last chat room that made ChatRoomNear become true
$.ChatRoomNearLastOwnerID => Saves the ID of the owner of the last chat room that made ChatRoomNear become true
$.ChatRoomNearLastOwnerName => Saves the name of the owner of the last chat room that made ChatRoomNear become true
$.ChatRoomNearLastTitle => Saves the title of the last chat room that made ChatRoomNear become true


InMap
  • Description: Checks if the current map match one of the given maps.
Syntax:
InMap <comma separated list of maps>
Map can be a variable.
Example:
InMap prontra, geffen, gef_fild10
Set variables:
$.InMapLast => Saves the last map that made InMap become true


InLockMap
  • Description: Is true if you are in lockmap and it is set to 1 or you are not in lockmap and it is set to 0.
Syntax:
InLockMap <1|0>
Example:
InLockMap 1


InSaveMap
  • Description: Is true if you are in savemap and it is set to 1 or you are not in savemap and it is set to 0.
Syntax:
InSaveMap <1|0>
Example:
InSaveMap 0


IsInCoordinate
  • Description: Checks if the current coordinates match one of the given ones.
Syntax:
IsInCoordinate <comma separated list of pairs of x and y coordinates>
It also accepts ranges in place of coordinates. (like 100..200 for x and 50..100 for y)
Example:
IsInCoordinate 100 150
IsInCoordinate 120 100, 115 289, 158 236
IsInCoordinate 20..80 200, 50 60, 80 90..150, 100..200 150..200
IsInCoordinate 30..35 40..45
Set variables:
$.IsInCoordinateLast => Saves the last coordinate that made IsInCoordinate become true
$.IsInCoordinateLastMemberIndex => Saves the list index in condition that made IsInCoordinate become true


IsInMapAndCoordinate
  • Description: Checks if the current map and/or coordinates match one of the given maps.
Syntax:
IsInMapAndCoordinate <comma separated list of pairs of x and y coordinates and/or maps>
It also accepts ranges in place of coordinates. (like 100..200 for x and 50..100 for y)
You can use map, coordinates or map with coordinates
Example:
IsInMapAndCoordinate 100 150
IsInMapAndCoordinate prontera
IsInMapAndCoordinate prontra, geffen, gef_fild10
IsInMapAndCoordinate 120 100, 115 289, 158 236
IsInMapAndCoordinate prontera, 100 200, gef_fild10 100..150 250
IsInMapAndCoordinate gef_fild10 20..80 200, payon 50 60
Set variables:
$.IsInMapAndCoordinateLast => Saves the last coordinate that made IsInMapAndCoordinate become true
$.IsInMapAndCoordinateLastMemberIndex => Saves the list index in condition that made IsInMapAndCoordinate become true


InPvP
  • Description: Checks if the current pvp type of the map matches the given type.
Syntax:
InPvP <comma separated list of pvp types>
Valid pvp types: pvp, gvg and battleground
Example:
InPvP battleground, pvp
Set variables:
$.InPvPLast => Saves the last pvp type that made InPvP become true


InCity
  • Description: Checks if the player is in a city or not.
Syntax:
InCity <0 | 1>
When value is 0: Only true if map is not a city
When value is 1: Only true if map is a city
Example:
InCity 1
Set variables:
$.InCityLast => Saves the name of the last map that made InCity become true


InMapRegex
  • Description: Checks if the current map matches the given regex.
Syntax:
InMapRegex <Regex>
Example:
InMapRegex /field\d+$/
InMapRegex /^pay/
Set variables:
$.InMapRegexLast => Saves the name of the last map that made InMapRegex become true


NpcNear
  • Description: Checks if there is a npc near which name matches the given regex.
Syntax:
NpcNear <Regex>
Example:
NpcNear /kafra/
NpcNear /special agent/
Set variables:
$.NpcNearLast => Saves the name of the last npc that made NpcNear become true
$.NpcNearLastPos => Saves the position of the last npc that made NpcNear become true (can be used for 'talknpc' command)
$.NpcNearLastBinId => Saves the openkore ID of the last npc that made NpcNear become true (can be used for 'talk' command)
$.NpcNearLastDist => Saves the distance of the last npc that made NpcNear become true


NpcNearDist
  • Description: Checks if there is a npc in a given distance which name matches the given regex.
Syntax:
NpcNearDist <Regex> <Math condition operators>
Example:
NpcNearDist /kafra/ <= 4
NpcNearDist /special agent/ >= 5
Set variables:
$.NpcNearDistLast => Saves the name of the last npc that made NpcNearDist become true
$.NpcNearDistLastPos => Saves the position of the last npc that made NpcNearDist become true (can be used for 'talknpc' command)
$.NpcNearDistLastBinId => Saves the openkore ID of the last npc that made NpcNearDist become true (can be used for 'talk' command)
$.NpcNearDistLastDist => Saves the distance of the last npc that made NpcNearDist become true


NpcNotNear
  • Description: Checks if there's no npc near which name matches the given regex.
Syntax:
NpcNotNear <Regex>
Example:
NpcNotNear /kafra/
NpcNotNear /special agent/
Sets no variables


PlayerNear
  • Description: Checks if there is a player near which name matches the given regex.
Syntax:
PlayerNear <Regex>
Example:
PlayerNear /john/
PlayerNear /henry the best TM/i
Set variables:
$.PlayerNearLast => Saves the name of the last player that made PlayerNear become true
$.PlayerNearLastPos => Saves the position of the last player that made PlayerNear become true
$.PlayerNearLastBinId => Saves the openkore ID of the last player that made PlayerNear become true
$.PlayerNearLastDist => Saves the distance of the last player that made PlayerNear become true


PlayerNearDist
  • Description: Checks if there is a player in a given distance which name matches the given regex.
Syntax:
PlayerNearDist <Regex> <Math condition operators>
Example:
PlayerNearDist /bad gm/ < 10
PlayerNearDist /good guy healer/ <5
Set variables:
$.PlayerNearDistLast => Saves the name of the last player that made PlayerNearDist become true
$.PlayerNearDistLastPos => Saves the position of the last player that made PlayerNearDist become true
$.PlayerNearDistLastBinId => Saves the openkore ID of the last player that made PlayerNearDist become true
$.PlayerNearDistLastDist => Saves the distance of the last player that made PlayerNearDist become true


PlayerNotNear
  • Description: Checks if there's no player near which name matches the given regex.
Syntax:
PlayerNotNear <Regex>
Example:
PlayerNotNear /the guy I need to see/
PlayerNotNear /^(john|george|paul|ringo)$/i
Sets no variables


MobNear
  • Description: Checks if there is a mob near which name matches the given regex.
Syntax:
MobNear <Regex>
Example:
MobNear /(edga|maya|ifrit|bad mvps)/i
MobNear /oring/
Set variables:
$.MobNearLast => Saves the name of the last mob that made MobNear become true
$.MobNearLastPos => Saves the position of the last mob that made MobNear become true
$.MobNearLastBinId => Saves the openkore ID of the last mob that made MobNear become true
$.MobNearLastDist => Saves the distance of the last mob that made MobNear become true


MobNearDist
  • Description: Checks if there is a mob in a given distance which name matches the given regex.
Syntax:
MobNearDist <Regex> <Math condition operators>
Example:
MobNearDist /(Poporing|Drops|Poring|Marin)/ < 3
Set variables:
$.MobNearDistLast => Saves the name of the last mob that made MobNearDist become true
$.MobNearDistLastPos => Saves the position of the last mob that made MobNearDist become true
$.MobNearDistLastBinId => Saves the openkore ID of the last mob that made MobNearDist become true
$.MobNearDistLastDist => Saves the distance of the last mob that made MobNearDist become true


MobNotNear
  • Description: Checks if there's no mob near which name matches the given regex.
Syntax:
MobNotNear <Regex>
Example:
MobNotNear /mvp I am look for/
MobNotNear /edga/i
Sets no variables


JobID
  • Description: Checks if the Job ID of the current player job matches one of the given ones.
Syntax:
JobID <job ID 1>, <job ID 2>, <job ID 3>, etc
Example:
JobID 6, 4053
Set variables:
$.JobIDLast => Saves the ID of the last job that made JobID become true


JobIDNot
  • Description: Checks if the Job ID of the current player job does not match the given one.
Syntax:
JobIDNot <job ID>
Example:
JobIDNot 6
Set variables:
$.JobIDNotLast => Saves the ID of the condition that made JobIDNot become true


IsEquippedID
  • Description: Checks if the player has an item equipped which ID matches the given one.
Syntax:
IsEquippedID <comma separated list of pairs of equip place and ID>
Example:
IsEquippedID topHead 5055
IsEquippedID rightHand 13040, topHead 5055
IsEquippedID topHead 5055, leftHand 2112, robe 2510, shoes 2414, armor 2352, rightHand 1243
Set variables:
$.IsEquippedIDLastID => Saves the id of the last equip which made IsEquippedID become true
$.IsEquippedIDLastName => Saves the name of the last equip which made IsEquippedID become true
$.IsEquippedIDLastSlot => Saves the slot of the last equip which made IsEquippedID become true
$.IsEquippedIDLastListIndex => Saves the index in the condition list of the last equip which made IsEquippedID become true


IsNotEquippedID
  • Description: Checks if the player doesn't have an item equipped which ID matches the given one.
Syntax:
IsNotEquippedID <comma separated list of pairs of equip place and ID>
Example:
IsNotEquippedID topHead 5055
IsNotEquippedID rightHand 13040, topHead 5055
IsNotEquippedID topHead 5055, leftHand 2112, robe 2510, shoes 2414, armor 2352, rightHand 1243
Set variables:
$.IsNotEquippedIDLastIsEmpty => Saves wheter the slot was empty ot not
$.IsNotEquippedIDLastSlot => Saves the slot which made IsNotEquippedID become true


ConfigKey
  • Description: Checks if the one or more of the given config keys match it's desired value.
Syntax:
ConfigKey <comma separated list of pairs of config key and value>
Config key and config value can be variables. (as in ConfigKey attackAuto $myattack or ConfigKey $vars{atk} 2)
Example:
ConfigKey attackAuto 2, itemsTakeAuto 2
Set variables:
$.ConfigKeyLastKey => Saves the key of the last config key that made ConfigKey become true
$.ConfigKeyLastValue => Saves the value of the last config key that made ConfigKey become true
$.ConfigKeyLastMemberIndex => Saves the list index in condition list that made ConfigKey become true


ConfigKeyNot
  • Description: Checks if the at least one of the config key pairs doesn't match their desired value.
Syntax:
ConfigKeyNot <comma separated list of pairs of config key and value>
Config key and config value can be variables. (as in ConfigKeyNot attackAuto $myattack or ConfigKeyNot $vars{atk} 2)
Example:
ConfigKeyNot $vars{atk} 2
ConfigKeyNot itemsTakeAuto 1, attackAuto 2
Set variables:
$.ConfigKeyNotLastKey => Saves the key of the last config key that made ConfigKeyNot become true
$.ConfigKeyNotLastWantedValue => Saves the desired value specified in the condifion of the last config key that made ConfigKeyNot become true
$.ConfigKeyNotLastKeyValue => Saves the value of the last config key that made ConfigKeyNot become true
$.ConfigKeyNotLastMemberIndex => Saves the list index in condition list that made ConfigKeyNot become true
Note: Good to be sure your keys are the way you want, example below.
automacro ConfigWasWrong {
    exclusive 1
    timeout 10
    overrideAI 1
    ConfigKeyNot itemsTakeAuto 2, attackAuto 2
    call {
        log There is a config key with the wrong configuration
        log The key is $.ConfigKeyNotLastKey
        log The wanted value is $.ConfigKeyNotLastWantedValue
        log The current key Value is $.ConfigKeyNotLastKeyValue
        log The Index is $.ConfigKeyNotLastMemberIndex
        log Changing value of key $.ConfigKeyNotLastKey from $.ConfigKeyNotLastKeyValue to $.ConfigKeyNotLastWantedValue
        do conf $.ConfigKeyNotLastKey $.ConfigKeyNotLastWantedValue
    }
}

This macro will make sure all config keys specified in ConfigKeyNot have the desired value.


ConfigKeyNotExist
  • Description: Checks if the at least one of the config keys doesn't exist in config.txt.
Syntax:
ConfigKeyNotExist <comma separated list config keys>
Config key can be a variable
Example:
ConfigKeyNotExist gameGuard, saveMap
Set variables:
$.ConfigKeyNotExistLastKey => Saves the last config key that made ConfigKeyNotExist become true
$.ConfigKeyNotExistLastMemberIndex => Saves the list index in condition list that made ConfigKeyNotExist become true
Note: Good to be sure your custom config keys were added (can auto-configure plugins), example below with perl sub to add missing keys:
automacro AddgameGuardMissingKey {
    exclusive 1
    timeout 10
    overrideAI 1
    CheckOnAI auto, manual, off
    ConfigKeyNotExist gameGuard
    call {
        $wantedkey = $.ConfigKeyNotExistLastKey
        $wantedvalue = 1
        call AddMissingKey
    }
}

automacro AddcmdOnLoginMissingKey {
    exclusive 1
    timeout 10
    overrideAI 1
    CheckOnAI auto, manual, off
    ConfigKeyNotExist cmdOnLogin
    call {
        $wantedkey = $.ConfigKeyNotExistLastKey
        $wantedvalue = c \@autoloot
        call AddMissingKey
    }
}

macro AddMissingKey {
    log There is a missing key in config.txt
    log The key is $wantedkey
    log The wanted value for it is is $wantedvalue
    log Adding key $wantedkey with value $wantedvalue with perl sub 'add_key'
    add_key("$wantedkey","$wantedvalue")
}

sub add_key {
    my ($key, $value) = @_;
    configModify($key, $value);
}

This macro will make sure you added the config keys for gameGuard and cmdOnLogin plugin.


InProgressBar
  • Description: Checks if the player is waiting for a progress bar to end.
Syntax:
InProgressBar <0 | 1>
When value is 0: Only true if not waiting for a progress bar
When value is 1: Only true if waiting for a progress bar
Example:
InProgressBar 1
Sets no variables


StatusActiveHandle
  • Description: Checks if the player has one of the given status, uses status HANDLE.
Syntax:
StatusActiveHandle <comma separated list of status handles>
Status handle can be a variable
Example:
StatusActiveHandle EFST_INC_AGI, EFST_IMPOSITIO
Set variables:
$.StatusActiveHandleLastName => Saves the name of the last stauts that made StatusActiveHandle become true
$.StatusActiveHandleLastHandle => Saves the handle of the last stauts that made StatusActiveHandle become true
$.StatusActiveHandleLastListIndex => Saves the list index in condition of the last stauts that made StatusActiveHandle become true


StatusInactiveHandle
  • Description: Checks if the player doesn't have one of the given status, uses status HANDLE.
Syntax:
StatusInactiveHandle <comma separated list of status handles>
Status handle can be a variable
Example:
StatusInactiveHandle EFST_BLESSING, EFST_CONCENTRATION
Set variables:
$.StatusInactiveHandleLastName => Saves the name of the last stauts that made StatusInactiveHandle become true
$.StatusInactiveHandleLastHandle => Saves the handle of the last stauts that made StatusInactiveHandle become true
$.StatusInactiveHandleLastListIndex => Saves the list index in condition of the last stauts that made StatusInactiveHandle become true


QuestActive
  • Description: Checks if the player has one of the given quests active, uses quest ID (use command 'quest list' to see ID).
Syntax:
QuestActive <comma separated list of quests ID>
Quest ID can be a variable
Example:
QuestActive 7121, 7122
Set variables:
$.QuestActiveLastID => Saves the ID of the last quest that made QuestActive become true
$.QuestActiveLastListIndex => Saves the list index in condition of the last quest that made QuestActive become true


QuestInactive
  • Description: Checks if the player has of the given quests inactive, uses quest ID (use command 'quest list' to see ID).
Syntax:
QuestInactive <comma separated list of quests ID>
Quest ID can be a variable
Example:
QuestInactive 7121, 7122
Set variables:
$.QuestInactiveLastID => Saves the ID of the last quest that made QuestInactive become true
$.QuestInactiveLastListIndex => Saves the list index in condition of the last quest that made QuestInactive become true


QuestOnTime
  • Description: Checks if the player has one of the given quests active, and this quest has a timer that hasn't ended yet, uses quest ID (use command 'quest list' to see ID).
Syntax:
QuestOnTime <comma separated list of quests ID>
Quest ID can be a variable
Example:
QuestOnTime 7121, 7122
Set variables:
$.QuestOnTimeLastID => Saves the ID of the last quest that made QuestOnTime become true
$.QuestOnTimeLastListIndex => Saves the list index in condition of the last quest that made QuestOnTime become true


QuestTimeOverdue
  • Description: Checks if the player has one of the given quests active, and this quest has a timer that has already ended, uses quest ID (use command 'quest list' to see ID).
Syntax:
QuestTimeOverdue <comma separated list of quests ID>
Quest ID can be a variable
Example:
QuestTimeOverdue 7121, 7122
Set variables:
$.QuestTimeOverdueLastID => Saves the ID of the last quest that made QuestTimeOverdue become true
$.QuestTimeOverdueLastListIndex => Saves the list index in condition of the last quest that made QuestTimeOverdue become true


QuestHuntCompleted
  • Description: Checks if the player has one of the given quests active, and this quest has a hunt mission which wasn't completed yet, uses quest ID and Mob ID (use command 'quest list' to see ID).
Syntax:
QuestHuntCompleted <comma separated list of pairs of quests ID and Mob ID>
Quest ID and/or Mob ID can be variables
Example:
QuestHuntCompleted 7122 1002, 7127 1004
Set variables:
$.QuestHuntCompletedLastQuestID => Saves the Quest ID of the last quest that made QuestHuntCompleted become true
$.QuestHuntCompletedLastMobID => Saves the Mob ID of the last quest that made QuestHuntCompleted become true
$.QuestHuntCompletedLastListIndex => Saves the list index in condition of the last quest that made QuestHuntCompleted become true


QuestHuntOngoing
  • Description: Checks if the player has one of the given quests active, and this quest has a hunt mission which has not been completed yet, uses quest ID and Mob ID (use command 'quest list' to see ID).
Syntax:
QuestHuntOngoing <comma separated list of pairs of quests ID and Mob ID>
Quest ID and/or Mob ID can be variables
Example:
QuestHuntOngoing 7122 1002, 7127 1004
Set variables:
$.QuestHuntOngoingLastQuestID => Saves the Quest ID of the last quest that made QuestHuntOngoing become true
$.QuestHuntOngoingLastMobID => Saves the Mob ID of the last quest that made QuestHuntOngoing become true
$.QuestHuntOngoingLastListIndex => Saves the list index in condition of the last quest that made QuestHuntOngoing become true


NoPlayerNear
  • Description: Checks if there are any players near, it's true when there's none.
Syntax:
NoPlayerNear 1
Example:
NoPlayerNear 1
Sets no variables.


NoPortalNear
  • Description: Checks if there are any portals near, it's true when there's none.
Syntax:
NoPortalNear 1
Example:
NoPortalNear 1
Sets no variables.


NoMobNear
  • Description: Checks if there are any mobs near, it's true when there's none.
Syntax:
NoMobNear 1
Example:
NoMobNear 1
Sets no variables.


NoNpcNear
  • Description: Checks if there are any npcs near, it's true when there's none.
Syntax:
NoNpcNear 1
Example:
NoNpcNear 1
Sets no variables.


PlayerNearCount
  • Description: Checks if the number of players near match the given math condition.
Syntax:
PlayerNearCount <Math condition operators>
Example:
PlayerNearCount > 5
Set variables:
$.PlayerNearCountLast => Saves the number of players that made PlayerNearCount become true


NpcNearCount
  • Description: Checks if the number of npcs near match the given math condition.
Syntax:
NpcNearCount <Math condition operators>
Example:
NpcNearCount > 5
Set variables:
$.NpcNearCountLast => Saves the number of npcs that made NpcNearCount become true


MobNearCount
  • Description: Checks if the number of mobs near match the given math condition.
Syntax:
MobNearCount <Math condition operators>
Example:
MobNearCount > 10
Set variables:
$.MobNearCountLast => Saves the number of mobs that made MobNearCount become true


PortalNearCount
  • Description: Checks if the number of portals near match the given math condition.
Syntax:
PortalNearCount <Math condition operators>
Example:
PortalNearCount > 5
Set variables:
$.PortalNearCountLast => Saves the number of portals that made PortalNearCount become true

Event

  • Event conditions don't have a defined status of true or false, they are only checked once an event happens.
  • When this event happens, the condition is checked, if it is true, and all the state conditions are also true, the automacro activates.
  • You can only have one event condition in each automacro.


PubMsg
  • Description: Is checked on public messages, is true when the message matches the given regex.
Syntax:
PubMsg <Regex>
Example:
PubMsg /(buff|bless)/
Set variables:
$.PubMsgLastName => Saves the name of the player which message activated PubMsg
$.PubMsgLastMsg => Saves the message which activated PubMsg


PubMsgDist
  • Description: Is checked on public messages, is true when the message matches the given regex and the distance match the given condition.
Syntax:
PubMsgDist <Regex> <Math condition operators>
Example:
PubMsgDist /(buff|bless)/ < 5
Set variables:
$.PubMsgDistLastName => Saves the name of the player which message activated PubMsgDist
$.PubMsgDistLastMsg => Saves the message which activated PubMsgDist
$.PubMsgDistLastPos => Saves the position of the player which message activated PubMsgDist
$.PubMsgDistLastDist => Saves the distance to the player which message activated PubMsgDist
$.PubMsgDistLastID => Saves the openkore ID of the player which message activated PubMsgDist


PubMsgName
  • Description: Is checked on public messages, is true when the message matches the given regex and the name of the player which sent it also matches it's given regex.
Syntax:
PubMsgName <Regex> <Regex>
The first regex is for the message, the second one is for the player name
Example:
PubMsgName /(buff|bless)/ /Player to buff/
PubMsgName /stop/ /GM/
Set variables:
$.PubMsgNameLastName => Saves the name of the player which message activated PubMsgName
$.PubMsgNameLastMsg => Saves the message which activated PubMsgName


PubMsgNameDist
  • Description: Is checked on public messages, is true when the message matches the given regex and the name of the player which sent it also matches it's given regex and the distance matches the condition.
Syntax:
PubMsgNameDist <Regex> <Regex> <Math condition operators>
The first regex is for the message, the second one is for the player name
Example:
PubMsgNameDist /(buff|bless)/ /Player to buff/ < 3
PubMsgNameDist /stop/ /GM/ >= 4
Set variables:
$.PubMsgNameDistLastName => Saves the name of the player which message activated PubMsgNameDist
$.PubMsgNameDistLastMsg => Saves the message which activated PubMsgNameDist
$.PubMsgNameDistLastPos => Saves the position of the player which message activated PubMsgNameDist
$.PubMsgNameDistLastDist => Saves the distance to the player which message activated PubMsgNameDist
$.PubMsgNameDistLastID => Saves the openkore ID of the player which message activated PubMsgNameDist


PrivMsg
  • Description: Is checked on private messages, is true when the message matches the given regex.
Syntax:
PrivMsg <Regex>
Example:
PrivMsg /(buff|bless)/
Set variables:
$.PrivMsgLastName => Saves the name of the player which message activated PrivMsg
$.PrivMsgLastMsg => Saves the message which activated PrivMsg


PrivMsgDist
  • Description: Is checked on private messages, is true when the message matches the given regex and the distance match the given condition.
Syntax:
PrivMsgDist <Regex> <Math condition operators>
Example:
PrivMsgDist /(buff|bless)/ < 5
Set variables:
$.PrivMsgDistLastName => Saves the name of the player which message activated PrivMsgDist
$.PrivMsgDistLastMsg => Saves the message which activated PrivMsgDist
$.PrivMsgDistLastPos => Saves the position of the player which message activated PrivMsgDist
$.PrivMsgDistLastDist => Saves the distance to the player which message activated PrivMsgDist
$.PrivMsgDistLastID => Saves the openkore ID of the player which message activated PrivMsgDist


PrivMsgName
  • Description: Is checked on private messages, is true when the message matches the given regex and the name of the player which sent it also matches it's given regex.
Syntax:
PrivMsgName <Regex> <Regex>
The first regex is for the message, the second one is for the player name
Example:
PrivMsgName /(buff|bless)/ /Player to buff/
PrivMsgName /stop/ /GM/
Set variables:
$.PrivMsgNameLastName => Saves the name of the player which message activated PrivMsgName
$.PrivMsgNameLastMsg => Saves the message which activated PrivMsgName


PrivMsgNameDist
  • Description: Is checked on private messages, is true when the message matches the given regex and the name of the player which sent it also matches it's given regex and the distance matches the condition.
Syntax:
PrivMsgNameDist <Regex> <Regex> <Math condition operators>
The first regex is for the message, the second one is for the player name
Example:
PrivMsgNameDist /(buff|bless)/ /Player to buff/ < 3
PrivMsgNameDist /stop/ /GM/ >= 4
Set variables:
$.PrivMsgNameDistLastName => Saves the name of the player which message activated PrivMsgNameDist
$.PrivMsgNameDistLastMsg => Saves the message which activated PrivMsgNameDist
$.PrivMsgNameDistLastPos => Saves the position of the player which message activated PrivMsgNameDist
$.PrivMsgNameDistLastDist => Saves the distance to the player which message activated PrivMsgNameDist
$.PrivMsgNameDistLastID => Saves the openkore ID of the player which message activated PrivMsgNameDist


PartyMsg
  • Description: Is checked on party messages, is true when the message matches the given regex.
Syntax:
PartyMsg <Regex>
Example:
PartyMsg /(buff|bless)/
Set variables:
$.PartyMsgLastName => Saves the name of the player which message activated PartyMsg
$.PartyMsgLastMsg => Saves the message which activated PartyMsg


PartyMsgDist
  • Description: Is checked on party messages, is true when the message matches the given regex and the distance match the given condition.
Syntax:
PartyMsgDist <Regex> <Math condition operators>
Example:
PartyMsgDist /(buff|bless)/ < 5
Set variables:
$.PartyMsgDistLastName => Saves the name of the player which message activated PartyMsgDist
$.PartyMsgDistLastMsg => Saves the message which activated PartyMsgDist
$.PartyMsgDistLastPos => Saves the position of the player which message activated PartyMsgDist
$.PartyMsgDistLastDist => Saves the distance to the player which message activated PartyMsgDist
$.PartyMsgDistLastID => Saves the openkore ID of the player which message activated PartyMsgDist


PartyMsgName
  • Description: Is checked on party messages, is true when the message matches the given regex and the name of the player which sent it also matches it's given regex.
Syntax:
PartyMsgName <Regex> <Regex>
The first regex is for the message, the second one is for the player name
Example:
PartyMsgName /(buff|bless)/ /Player to buff/
PartyMsgName /stop/ /GM/
Set variables:
$.PartyMsgNameLastName => Saves the name of the player which message activated PartyMsgName
$.PartyMsgNameLastMsg => Saves the message which activated PartyMsgName


PartyMsgNameDist
  • Description: Is checked on party messages, is true when the message matches the given regex and the name of the player which sent it also matches it's given regex and the distance matches the condition.
Syntax:
PartyMsgNameDist <Regex> <Regex> <Math condition operators>
The first regex is for the message, the second one is for the player name
Example:
PartyMsgNameDist /(buff|bless)/ /Player to buff/ < 3
PartyMsgNameDist /stop/ /GM/ >= 4
Set variables:
$.PartyMsgNameDistLastName => Saves the name of the player which message activated PartyMsgNameDist
$.PartyMsgNameDistLastMsg => Saves the message which activated PartyMsgNameDist
$.PartyMsgNameDistLastPos => Saves the position of the player which message activated PartyMsgNameDist
$.PartyMsgNameDistLastDist => Saves the distance to the player which message activated PartyMsgNameDist
$.PartyMsgNameDistLastID => Saves the openkore ID of the player which message activated PartyMsgNameDist


GuildMsg
  • Description: Is checked on guild messages, is true when the message matches the given regex.
Syntax:
GuildMsg <Regex>
Example:
GuildMsg /(buff|bless)/
Set variables:
$.GuildMsgLastName => Saves the name of the player which message activated GuildMsg
$.GuildMsgLastMsg => Saves the message which activated GuildMsg


GuildMsgDist
  • Description: Is checked on guild messages, is true when the message matches the given regex and the distance match the given condition.
Syntax:
GuildMsgDist <Regex> <Math condition operators>
Example:
GuildMsgDist /(buff|bless)/ < 5
Set variables:
$.GuildMsgDistLastName => Saves the name of the player which message activated GuildMsgDist
$.GuildMsgDistLastMsg => Saves the message which activated GuildMsgDist
$.GuildMsgDistLastPos => Saves the position of the player which message activated GuildMsgDist
$.GuildMsgDistLastDist => Saves the distance to the player which message activated GuildMsgDist
$.GuildMsgDistLastID => Saves the openkore ID of the player which message activated GuildMsgDist


GuildMsgName
  • Description: Is checked on guild messages, is true when the message matches the given regex and the name of the player which sent it also matches it's given regex.
Syntax:
GuildMsgName <Regex> <Regex>
The first regex is for the message, the second one is for the player name
Example:
GuildMsgName /(buff|bless)/ /Player to buff/
GuildMsgName /stop/ /GM/
Set variables:
$.GuildMsgNameLastName => Saves the name of the player which message activated GuildMsgName
$.GuildMsgNameLastMsg => Saves the message which activated GuildMsgName


GuildMsgNameDist
  • Description: Is checked on guild messages, is true when the message matches the given regex and the name of the player which sent it also matches it's given regex and the distance matches the condition.
Syntax:
GuildMsgNameDist <Regex> <Regex> <Math condition operators>
The first regex is for the message, the second one is for the player name
Example:
GuildMsgNameDist /(buff|bless)/ /Player to buff/ < 3
GuildMsgNameDist /stop/ /GM/ >= 4
Set variables:
$.GuildMsgNameDistLastName => Saves the name of the player which message activated GuildMsgNameDist
$.GuildMsgNameDistLastMsg => Saves the message which activated GuildMsgNameDist
$.GuildMsgNameDistLastPos => Saves the position of the player which message activated GuildMsgNameDist
$.GuildMsgNameDistLastDist => Saves the distance to the player which message activated GuildMsgNameDist
$.GuildMsgNameDistLastID => Saves the openkore ID of the player which message activated GuildMsgNameDist


NpcMsg
  • Description: Is checked on npc conversation messages, is true when the message matches the given regex.
Syntax:
NpcMsg <Regex>
Example:
NpcMsg /your return point was saved/
Set variables:
$.NpcMsgLastName => Saves the name of the npc which message activated NpcMsg
$.NpcMsgLastMsg => Saves the message which activated NpcMsg


NpcMsgDist
  • Description: Is checked on npc conversation messages, is true when the message matches the given regex and the distance match the given condition.
Syntax:
NpcMsgDist <Regex> <Math condition operators>
Example:
NpcMsgDist /please come near to me/ > 5
Set variables:
$.NpcMsgDistLastName => Saves the name of the npc which message activated NpcMsgDist
$.NpcMsgDistLastMsg => Saves the message which activated NpcMsgDist
$.NpcMsgDistLastPos => Saves the position of the npc which message activated NpcMsgDist
$.NpcMsgDistLastDist => Saves the distance to the npc which message activated NpcMsgDist
$.NpcMsgDistLastID => Saves the openkore ID of the npc which message activated NpcMsgDist


NpcMsgName
  • Description: Is checked on npc conversation messages, is true when the message matches the given regex and the name of the npc which sent it also matches it's given regex.
Syntax:
NpcMsgName <Regex> <Regex>
The first regex is for the message, the second one is for the npc name
Example:
NpcMsgName /You don't have zeny/ /kafra/
Set variables:
$.NpcMsgNameLastName => Saves the name of the npc which message activated NpcMsgName
$.NpcMsgNameLastMsg => Saves the message which activated NpcMsgName


NpcMsgNameDist
  • Description: Is checked on npc conversation messages, is true when the message matches the given regex and the name of the npc which sent it also matches it's given regex and the distance matches the condition.
Syntax:
NpcMsgNameDist <Regex> <Regex> <Math condition operators>
The first regex is for the message, the second one is for the npc name
Example:
NpcMsgNameDist /You need to be closer to punch me/ /punchable npc/ > 5
Set variables:
$.NpcMsgNameDistLastName => Saves the name of the npc which message activated NpcMsgNameDist
$.NpcMsgNameDistLastMsg => Saves the message which activated NpcMsgNameDist
$.NpcMsgNameDistLastPos => Saves the position of the npc which message activated NpcMsgNameDist
$.NpcMsgNameDistLastDist => Saves the distance to the npc which message activated NpcMsgNameDist
$.NpcMsgNameDistLastID => Saves the openkore ID of the npc which message activated NpcMsgNameDist


LocalMsg
  • Description: Is checked on local broadcast messages, is true when the message matches the given regex.
Syntax:
LocalMsg <Regex>
Example:
LocalMsg /airship is arriving/
Set variables:
$.LocalMsgLastMsg => Saves the message which activated LocalMsg


BusMsg
  • Description: Is checked on bus system messages, is true when the message matches the given regex.
Syntax:
BusMsg <Regex>
Example:
BusMsg /gm near/
Set variables:
$.BusMsgLastMsg => Saves the message which activated BusMsg


MapLoaded
  • Description: Is checked everytime a map change event occur (teleport, map changes), is true if the current map match one of the given ones.
Syntax:
MapLoaded <comma separated list of maps>
Map can be a variable.
Example:
MapLoaded prontra, geffen, gef_fild10
Set variables:
$.MapLoadedLast => Saves the last map that made MapLoaded become true


OnCharLogIn
  • Description: Is always true, activates everytime the character logs into the game.
Syntax:
OnCharLogIn 1
Example:
OnCharLogIn 1
Sets no variables


ZenyChanged
  • Description: Is checked everytime the amount of zeny changes, is true if the math condition is true.
  • Supports percentages. (based on total zeny before change and change amount)
Syntax:
ZennyChanged <Math condition operators>
Example:
ZennyChanged > 10%
ZennyChanged >= 1000
Set variables:
$.ZennyChangedLastChange => Saves the amount of zenny changed that made ZennyChanged activate
$.ZennyChangedLastZennyAfter => Saves the amount of zenny left after the change that made ZennyChanged activate


SimpleHookEvent
  • Description: Is checked every time the hook you set, is triggered.
Syntax:
SimpleHookEvent <hook name>
Example:
SimpleHookEvent target_died
Set all variables the hook have as:
$.SimpleHookEventLast<capitalized variable name>
Example:
$.SimpleHookEventLastMonster => monster ID in target_died hook

Extras

Math condition operators

(<|<=|=|==|!=|!|>=|>|)\s*($number_qr%?|$general_wider_variable_qr)(?:\s*\.\.\s*($number_qr%?|$general_wider_variable_qr))

Operator Description Example
< <value> lower than <value> < 50
> <value> higher than <value> > 20
<= <value> lower or equal to <value> <= 10
>= <value> higher or equal to <value> >= 25
= <value> | == <value> | <value> equal to <value> = 150 | == 150 | 150
!= <value> | ! <value> not equal to <value> ! 1000 | != 1000
<value1>..<value2> between <value1> and <value2> 20..80
  • Note: <value> can be a number or a variable.

Examples:

Math_condition >= 50 # Only true if higher or equal to 50
Math_condition < $variable # Only true if lower than $variable value
  • Note: <value> can be a percentage (even if it is a variable).

Examples:

Math_condition <= 10% # Only true if lower or equal to 10%
Math_condition != $variable # $variable value can be something like '50%', in which case it would only be true if different than 50%


Regex

To learn about regex plese refer to this link: regexp tutorial
Note: Regex in conditions support all types of variables

Perl Subroutines

eventMacro plugin support Perl subroutines in macros. You can now create any simple Perl function without limitations from the eval command.

Example No.1 - how to create a Perl Subroutine function in Macro

macro sub {
    $list = Orange, Milk, Soya, Peach
    if (existsInList("$list", "PeAch")) goto ok 
    log Not Match!!!; stop
    :ok
    log Match!!!
    $x = &eval(existsInList("$list", "PeAch"))
    log \$x = $x   # $x here is 1
}
sub existsInList {
    my ($list, $val) = @_;
    return 0 if ($val eq "");
    my @array = split / *, */, $list;
    $val = lc($val);
    foreach (@array) {
        s/^\s+//;
        s/\s+$//;
        s/\s+/ /g;
        next if $_ eq "";
        return 1 if lc eq $val;
    }
    return 0;
}


Example No.2 - how to create a re-writable file function using Perl Subroutine in Macro

automacro confHP1 {
    CurrentHP > 85%
    exclusive 1
    run-once 1
    call {
        $setting = Demon Pungus #becareful on your case, its case sensitive
        $attack = 1
        $teleport = 0
        $telesearch = 1
        call HP
    }
}

automacro confHP2 {
    CurrentHP < 75%
    exclusive 1
    run-once 1
    call {
        $setting = Demon Pungus #becareful on your case, its case sensitive
        $attack = 1
        $teleport = 2
        $telesearch = 1
        call HP
    }
}

macro HP {
    #Getting the value of the $setting monster name Ex: $setting $exist1 $exist2 $exist3
    $exist1 = &eval (defined Misc::mon_control("$setting")?Misc::mon_control("$setting")->{attack_auto}:"None")
    $exist2 = &eval (defined Misc::mon_control("$setting")?Misc::mon_control("$setting")->{teleport_auto}:"None")
    $exist3 = &eval (defined Misc::mon_control("$setting")?Misc::mon_control("$setting")->{teleport_search}:"None")
    log Old Values are $setting $exist1 $exist2 $exist3
    log Changing the values to $setting $attack $teleport $telesearch
    do eval Misc::mon_control("$::Macro::Data::varStack{setting}")->{attack_auto} = $attack; Misc::mon_control("$::Macro::Data::varStack{setting}")->{teleport_auto} = $teleport; Misc::mon_control("$::Macro::Data::varStack{setting}")->{teleport_search} = $telesearch
    log Writting mon_control.txt with new values
    rewrite()  # see the sub-routine function below
    log Reloading mon_control.txt
    do reload mon_control
    $exist1 = &eval (defined Misc::mon_control("$setting")?Misc::mon_control("$setting")->{attack_auto}:"None")
    $exist2 = &eval (defined Misc::mon_control("$setting")?Misc::mon_control("$setting")->{teleport_auto}:"None")
    $exist3 = &eval (defined Misc::mon_control("$setting")?Misc::mon_control("$setting")->{teleport_search}:"None")
    log New mon_control.txt Setting: $setting $exist1 $exist2 $exist3
    log Macro done
    #if $teleport = 0 ; means the Higher automacro HP is currently triggered
    #if $teleport = 2 ; means the Lower automacro HP is currently triggered
    if ($teleport < 2) goto releaseHighHp
    :releaseLowHp
        release confHP1
        stop
    :releaseHighHp
        release confHP2
        stop
}

sub rewrite {
    my $monster = Misc::mon_control("$::Macro::Data::varStack{setting}");
    my @lines = ();
    if (open(FILE, "<:utf8", Settings::getControlFilename("mon_control.txt"))) {
        while (<FILE>) {
            s/\x{FEFF}//g; chomp;
            if (/^#/ || /^\n/ || /^\r/) {
                push @lines,$_;
                next
            }
            /^(\d+|([a-zA-Z' ]+)*) -?\d/;
            if ("$::Macro::Data::varStack{setting}" eq $1 && defined $monster) {
                $_ = $1; s/\s+$//;
                push(@lines, ($_ . " $monster->{attack_auto} $monster->{teleport_auto} $monster->{teleport_search} $monster->{attack_lvl} $monster->{attack_jlvl} $monster->{attack_hp} $monster->{attack_sp} $monster->{weight}"));
            } else {
                push(@lines, $_);
            }
        }
        close FILE
    }
    open(FILE, ">:utf8", Settings::getControlFilename("mon_control.txt"));
    print FILE join "\n", @lines;
    close FILE;
}

Comments

The macro files allow comments, i.e. lines that are ignored by the eventMacro plugin.

  • Lines starting with a # will be treated as a comment.
  • Everything after a space and followed by a # will also be ignored.
macro happy {
    #this is a comment line
    log I'm Happy # this is also a comment
}

Will print:

[eventmacro log] I'm Happy

Examples with Explanations

I assume you already know how to use Console Commands and understand how they work. If not, before going further, read through all Console Commands and try out ones like a, ai, move, cart get, storage add, talk, deal, take, direction commands, sl, sm, relog, pm and others.

Keep another page with this manual open for cross reference.


Okay, so there are 2 types of blocks

  1. automacros – these trigger automatically
  2. macros – these do not trigger automatically but need to be called manually or by an automacro


Automacros

Automacros automatically trigger when certain conditions are met, just like how blocks in config.txt trigger depending on the conditions set in them.

The point of automacros is that you use them to check for conditions. When the condition is fulfilled, you can either respond to it in the automacro or call a macro to do it. The format for automacro is...

automacro <name> {
        condition 1
        condition 2
        …...
        …...
        call {
                command 1
                command 2
                …..
                …..
        }
        timeout <n seconds> #(if necessary)
}


For example, suppose you're playing manually but your slave priest is on Kore, and you want it to warn you if it's running out of sp, you can use an automacro like this....

automacro sp {
   CurrentSP < 200
   timeout 10
   call {
      do c sp low
   }
}


Taking it line by line,

  1. automacro sp { - you need to put automacro to tell kore that its an automacro. Then you put the name of the macro, in this case its “sp”. Then you need to put an opening bracket “{“ which tells Kore that the automacro's code begins there.
  2. CurrentSP < 200 – After the “{“, you put the conditions on successive lines. Here, there is only one condition and I think its clear that the condition is that sp should be below 200.
  3. timeout 10 – This isn't a condition or a command, it works the same way it works in normal Kore blocks, so this automacro cannot trigger within 10 seconds of it already having been triggered. I ALWAYS put timeouts, so even if my conditions are faulty, the automacro doesn't spam and mess up whatever my bot is doing. Otherwise if your automacro is messed up then you could die or something, so its better to put an appropriate timeout.
  4. call { – The word “call” tells Kore that now you're going to be putting commands, not conditions. The opening bracket “{“ tells Kore that the commands will start now. These commands are the ones that will get carried out when the conditions are met, here when sp goes below 200.
  5. do c sp low – “do” tells Kore that this is a command, something to be done. After “do”, just leave a space and type in the console command you want to execute exactly the way you do in the Kore console.
  6. } – This closing bracket “}” tells Kore that the commands have ended.
  7. } – This closing bracket “}” tells Kore that your automacro code has ended.

So basically whenever, the bot's sp goes below 200, it says in public chat “sp low”. This also has the advantage of making your bot not look like a bot =p.


Here's another macro which illustrates how you can use macros to handle weird situations which Kore is not equipped to deal with. When fighting against metalings, they often strip you and then your oh-so-smart bot punches! To get around this, put the weapon you use in default auto equip and use this macro.

automacro strip {
   StatusActiveHandle EFST_NOEQUIPWEAPON
   timeout 10
   call {
      do tele
      do relog 10
   }
}


Taking it line by line....

  1. automacro strip { - Tell Kore this is an automacro, and it's name is "strip". The '{' tells Kore the code of the automacro starts here.
  2. StatusActiveHandle EFST_NOEQUIPWEAPON - The only condition in this macro. This checks your list of statuses for the status handle "EFST_NOEQUIPWEAPON". Thus, when you are stripped by a Metaling, you get the "EFST_NOEQUIPWEAPON" status and this condition will be fulfilled.
  3. timeout 10 - Ensures automacro is not spammed, and 10 seconds is enough time to execute the automacro. So after 10 seconds, if for some reason you are still stripped, this automacro will trigger again. However, if you re-login and are stripped within 10 seconds, then macro will not trigger again untill the 10 seconds are up.
  4. call { - The word "call" and "{" tells Kore that the commands to be executed start after the '{'
  5. do tele - "do" tells Kore that what comes after is a console command to be carried out. Here, the command is "tele" so you teleport away from the Metaling, so that in case you lag or something, you aren't killed while executing the next instruction which is.....
  6. do relog 10 - Tells Kore to relogin in 10 seconds, because when you login again, your "strip weapon" status is cleared.
  7. } - The closing bracket '}' tells Kore the commands have ended.
  8. } - The closing bracket '}' tells Kore the macro code has ended.

Summarising, on being stripped, you teleport away from the monster and then relogin, with a timeout of 10 seconds to ensure that the automacro is not spammed. Since the weapon you're using is filled in the default weapon option, after re-logging in, Kore will automatically re-equip that weapon.


Let's try a more complicated macro. If you have a priest, you would want it to warp back to its lockmap or the nearest warp-able map near its lockmap. This macro does it. From the savemap, the bot takes the same route to the lockmap each time. So in the first map outside the town, just set it to move to a designated tile, and cast warp on a nearby tile, and then move to that tile. You will need delays to allow the spell to be cast and commands to be completed.

automacro warp {
    InMap gef_fild07
    InInventory "Blue Gemstone" > 0
    timeout 20
    call {
        do ai manual
        pause 1
        do move 319 187
        do sl 27 316 188
        pause 2
        do warp 1
        pause 1
        do move 316 188
        do ai on
    }
}


Taking it line by line,

  1. automacro warp { - As explained, the automacro's name is warp, and “{“ indicates that the automacro begins.
  2. InMap get_fild07 - The first condition, the automacro will only trigger if the map is gef_fild07.
  3. InInventory “Blue Gemstone” > 0 - Second condition, ensures there is atleast one blue gemstone in the inventory so that warp portal can be cast. Obviously you need a getAuto in config.txt for the gemstones.
  4. timeout 20 - Ensures that the bot does not spam the automacro. The timeout should be large enough to allow the completion of the automacro, so that the automacro does not trigger again while it is in execution.
  5. call { - Tells Kore that the commands start here.
  6. do ai manual - Frequently, I use this command in the more complicated and longer macros, so that Kore doesn't get diverted into doing something else while your macro is running, for example, attacking a monster or gathering up an item. In this case I'm using it so that the bot doesn't continue walking.
  7. pause 1 - Inserts a delay of 1 second before the next command is carried out, VERY IMPORTANT. If you don't use delays then Kore can and will miss steps in the macro and the result is a mess.
  8. do move 319 187 - The “move” console command is used to move your bot to a set location.
  9. do sl 27 316 188 - The “sl” console command is used to make your priest cast warp portal on a convenient spot near your location, in this case (316,188).
  10. pause 2 - Very Important. A delay of 2 seconds is put, allowing enough time to cast warp portal. If you priest has low dex, this delay should be increased.
  11. do warp 1 - Console command “warp” is used to select memo location 1.
  12. pause 1 - 1 second delay to allow the portal to form.
  13. do move 316 188 - Move to the portal and Voila! You have been warped to the map.
  14. do ai on - You set ai to manual at the beginning of this macro, so now you need to turn it back on.
  15. } - Closing bracket indicates end of commands.
  16. } - Closing bracket indicates end of automacro code.

Note the use of appropriate delays and timeouts in this automacro.


The EventMacro plugin also has many useful built-in variables which give you your position for example. It's all listed in the eventMacro manual. I just want to show how to extract your position from these variables.

$.pos gives you your position. Now to get your x and y coordinates the code is,

  $px = &arg ("$.pos", 1)
  $py = &arg ("$.pos", 2)

Here, the x coordinate is the 1st value in $.pos so we have a '1'. Similarly, the y coordinate is the second value in $.pos so we have a '2'.

If you have a “MobNear” condition in your automacro, $.MobNearLastPos gives the position of that monster. To extract the x and y coordinates the code is,

  $mx = &arg ("$.MobNearLastPos", 1)
  $my = &arg ("$.MobNearLastPos", 2)

"run-once"

Frequently, the run-once condition is used instead of a timeout. It allows the automacro to run only once so that the automacro isn't spammed. To get the automacro to run again, a release command needs to be executed. However, due to a rogue situation that the macro hangs and the release macro isn't executed, your automacro is effectively stuck. To get around this, use a timeout instead of using run-once.


How to write a macro

Now that you have some idea of what a macro is, try writing one

  • Figure out under exactly what conditions you want your automacro to trigger
  • Logically think out the steps your bot needs to perform in the automacro. Go step by step over this carefully.
  • Ensure you have inserted appropriate pauses between the steps.
  • Ensure you have a timeout or a run-once in your macro to prevent spamming of it.
  • Now put the code in eventMacros.txt and start the bot or reload eventMacros.txt. If all is fine you won't get any error messages. But if there is a problem in the syntax, say you missed out a “}”, then you will get an error message and the macro won't work. Figure out what the error is, correct it, and reload eventMacros.txt again to check if you corrected it properly or not.

Collected Macros

I would like to share some useful macros, hopefully not angering anyone here.

Identify with Magnifier

You got unidentified Items in your inventory and want to identify them using magnifiers? Use "eventMacro id" on console until all items are identified. You don't have to type anything else, the macro will identify the first item found, after that the second and so on.

macro id {
    $id = &inventory(Magnifier)
    do is $id
    pause 1
    do identify 0
}

Automatically refine Rough Stones (Ori / Elu)

This macro, once called, will automatically walk to the prontera forge and refine Rough Ori / Elu as long as there are more than 5 in your inventory. I did not find something like that yet, please post everything (better) I may have missed.

Just fire eventMacro ref to start. To stop manually, type eventMacro stop.

macro ref {
    do move prt_in 59 60
    call ref-while
}

macro ref-while {
    log start refining with
    $ori = &invamount(Rough Oridecon)
    $elu =  &invamount(Rough Elunium)
    log I have $ori Rough Oridecons
    log I have $elu Rough Eluniums
    while (&invamount(Rough Oridecon) > 4) {
        do talk 0
        pause 0.8
        do talk resp 0
        call ref-while
    }
    while (&inventory(Rough Elunium) > 4) {
        do talk 0
        pause 0.8
        do talk resp 1
        call ref-while
    }
    stop
}

FAQ

I get disconnected from map server when running a macro!
The commands are sent too fast. Increase macro_delay or add pause lines between your do commands


I'm getting Malformed UTF-8 character (fatal), what is this?
This error happens when your eventMacros.txt is not saved in UTF-8 encoding.
To solve it, open your eventMacros.txt and if you're using Notepad, when you are going to save, change Encoding to UTF-8. (If that does not help - do not use Notepad.)
If you're using Notepad++ or other text editor, go to Format > UTF-8 (without BOM) and save.

Author

EventMacro was written by Henrybk.
EventMacro was based on macro plugin which was first written by arachno has various contributors like ezza, daigaku, keplerbr, eternalhavest and technologyguild.
EventMacro was beta tested by emjustin.
Some of the most important ideas and functions were developed by allanon.