macro plugin

From OpenKore Wiki
Jump to navigation Jump to search

With this plugin you can predefine command sequences (macros) which are run either manually or by situation-dependent triggers. The latest version is 2.0.3.

Installation

  • Download your Macro plugin. You can get it here or from SVN.
  • Go to your OpenKore main folder (the folder which contains the file openkore.pl) and create a subfolder called plugins, if there isn't already one.
  • Inside the Macro plugin's zipfile, you will find the file macro.pl and the folder Macro. Extract them to your plugins folder.
  • In your OpenKore control folder, create a blank file named macros.txt. In this file you will put your macros/automacros.


After installation, your OpenKore file tree should look like this (ignoring OpenKore's own files):

openkore
|-- openkore.pl
|-- control
|   |-- macros.txt
|-- fields
|-- logs
|-- plugins
|   |-- Macro
|   |   |-- Automacro.pm
|   |   |-- Data.pm
|   |   |-- Parser.pm
|   |   |-- Script.pm
|   |   |-- Utilities.pm
|   |-- macro.pl
|-- src
|-- tables

Console Commands

Syntax

macro <macroname> [options] [-- parameter(s)]


Runs macro <macroname>.

Option Value Description
-repeat n repeat the macro n times
-overrideAI none override openkore's AI
-macro_delay delay override global macro_delay for this macro
-exclusive none do not allow automacros to cancel this macro
-orphan method use method for handling orphaned macros


Parameters for the macro can be specified after a double dash (--). These parameters are saved to the variables $.param1 to $.paramN. Example:

macro foo {
 log Parameter 1 is $.param1
 log Parameter 2 is $.param2
}


When called as macro foo -- foo bar it would print out

[macro] Parameter 1 is foo
[macro] Parameter 2 is bar


macro list
Lists all available macros.
macro stop
Stops current macro.
macro pause
Interrupts the running macro.
macro resume
Resumes an interrupted macro.
macro version
Prints version number.
macro reset [<name(s)>]
Resets all run-once automacros or the specified automacro <name>.
macro status
Shows whether or not a macro is currently running. If that's the case it shows the delay for the next command, the current line, overrideAI setting, whether or not it has finished and whether or not the macro registered to AI queue.

Configuration files

control/macros.txt
Put your macros and automacros in here. You can change the file's name depending on what you configured on config macro_file.
control/timeouts.txt
Add macro_delay and set it to the number of seconds you want the plugin to pause between commands.
control/config.txt
Option Value Description
macro_nowarn 0
1
enable or disable the annoying warnings when not using call in your automacro(s)
macro_orphans terminate
reregister
reregister_safe
override openkore's AI
macro_file file name file containing the macros ("macros.txt" by default)
macro_allowDebug 0
1
console-check also processes openkore's debug messages (default: 0). Warning: slows down the plugin.

Macro Syntax

macro MacroName {
   do this..
   and that..
   yattayatta..
}
  • You can use any name you want for your macro. Be careful not to make two macros with the same name.
  • Macros is executed from top to bottom.
  • Only macro instructions can be used in macros. If you need to use console command, use do.

Macro Instructions

do <command>
Run <command>, as if it was entered in OpenKore terminal. Commands are from Console Commands.
macro foo {
   do move 123 234 prontera
   do sit
   do c hello world
}


log <text>
Prints a text in the console. Can contain macro $variables and @stuff.
macro foo {
  log This line logs a text to console.
  log All your base are belong to us!
}


pause [<n>]
Pauses the macro for n seconds.
macro foo {
   log It's 10:00:00
   pause 10
   log Now it's 10:00:10 
   log 10 seconds have passed after the first print.
}


call <macroname> [<n>]
Calls macro <macroname> [<n> times]. When <macroname> is finished the current macro continues.


release (<name> | all)
Reenables a locked automacro ("run-once" keyword or locked by "lock") or reenables all automacros when using release all.


lock (<name> | all)
Locks an automacro and disables it's checks. To lock all automacros, use lock all.


stop
Immediately terminates the running macro.


set <option> <value>
Sets macro features:
  • orphan method
  • macro_delay timeout
  • overrideAI [0|1]
  • repeat times
  • exclusive [0|1]


Variable declaration and usage

You can work with variables. Variable declaration is not needed. All macro variables are global.

Set a value of variable:

$variable = value

Get a value of variable:

$variable
macro Hello {
   $var = Hello
   $var1 = World!
   log $var $var1
}

This would print in the console:

[log] Hello World!


If you want to use the $ symbol you should escape it with \.

macro money {
   log I have a lot of \$
}


It is possible to increment and to decrement a variable using $variable++ or $variable--.

macro Counter {
    $counter = 0
    log Counter is at $counter
    $counter++
    log Now it's $counter
    $counter--
    log It's back to $counter
}

The result is:

log Counter is at 0
log Now it's 1
log It's back to 0

You can also unset/vanish the existing variable using 'undef' or 'unset':

$x = 1
log \$x is $x
$x = undef  # or you can use 'unset'
log \$x now vanished: $x

Variable assignment doesn't evaluate, it only does macro substitutions, so use @eval for calculations.

macro math {
    $num = 2
    $num2 = 3
    $result = @eval($num+$num2)
    log sum of $num and $num2 is $result
}

The result is:

log sum of 2 and 3 is 5

You can extract the first element from a comma-separated list using like this:

macro foo {
  $list = banana, apple, strawberry, grape
  $var = [$list]
  log The first element of \$list is $var
  log Now \$list contains $list
}

The result is:

log The first element from \$list is banana
log Now $list contains apple, strawberry, grape

Note: Variable names may only contain letters and numbers.

Nested Variables

You can define dynamic or nested variables.

macro foo {
    $name = Camila
    ${$name} = Brazil   # Note: ${name} is equal to $Camila now
    log $name lives on ${$name}
}

The result is:

log Camila lives on Brazil

Special Variables

There are special read-only variables which begin with a dot. They are pre-defined with the macro plugin.

  • $.map - the map you're on ("prontera")
  • $.pos - your current position ("123 234")
  • $.time - current time as unix timestamp ("1131116304")
  • $.datetime - current date and time ("Fri Nov 4 15:59:36 2005")
  • $.hour - current hour time in 24h format
  • $.minute - current minute time
  • $.second - current second time
  • $.hp - current hp
  • $.sp - current sp
  • $.lvl - current base level
  • $.joblvl - current job level
  • $.spirits - current number of spirit spheres
  • $.zeny - current amount of zeny
  • $.status - current statuses in a comma-separated list
  • $.paramN - command line parameters (see Commands)
  • $.caller - name of the last triggered automacro
  • $.weight - returns the current weight of the character
  • $.maxweight - returns the maximum weight of the character

Special Keywords

They are used to return values depending on the parameters given.

@npc (<x> <y> | /regexp/i | "<name>")
Return NPC's ID which location is <x> <y> or NPC's name match regexp or NPC's name is equal to <name> . Returns -1 if no NPC was found.
@inventory (<item>)
Returns Inventory Item ID of <item>. If <item> doesn't exist, it returns -1.
@Inventory (<item>)
Same as @inventory but returns all matching IDs as a comma-separated list or -1 if the item was not found.
@invamount (<item>)
Returns the amount of the given <item> in inventory.
@cart (<item>)
Returns cart item ID of <item>. If <item> doesn't exist, it returns -1.
@Cart (<item>)
Same as @cart but returns all matching IDs as a comma-separated list or -1 if the item was not found.
@cartamount (<item>)
Returns the amount of the given <item> in cart.
@storage (<item>)
Returns storage item ID of <item>. If <item> doesn't exist, it returns -1.
@Storage (<item>)
Same as @storage but returns all matching IDs as a comma-separated list or -1 if the item was not found.
@storamount (<item>)
Returns the amount of the given <item> in storage.
@player (<name>)
Returns player ID of player <name>. If player <name> is not found, it returns -1.
@vender (<name>)
Returns vender ID of vender <name>. If vender <name> is not found, it returns -1.
@store (<name>)
Looks for an item in a store and returns ID or -1 if the item was not found.
@shopamount (<item>)
Returns the amount of the given <item> in shop.
@random ("<argument1>", "<argument2>", ...)
Returns randomly one of the given arguments .
@rand (<n>, <m>)
Returns a random number between (and including) <n> and <m>.
@eval (<argument>)
Evaluates the given <argument>. Contents of @eval is Perl and does NOT have macro plugin syntax, except for variables and @() substitution.
@arg ("<argument>", <n>)
Returns the <n>th word of <argument> or an empty string if the word index is out of range.
Note: <n> could also be a variable that contains a round number/s greater than zero.
@config (<variable>)
Returns the value of <variable> specified in config.txt.
@venderitem (<name>)
Looks for an item in a player's shop and returns ID or -1 if the item was not found.
@venderprice (<indexID>)
Looks for an item in a player's shop and returns its price.
@nick (<word>)
Escapes all the regexp metacharacters and some of the perl special characters with \ (a backslash). Especially for player's name.

Chaining commands

You can run multiple commands one after another without having to wait for openkore's AI or macro_delay or whatever. Just enclose these commands with [ and ].

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 }

Line 3 starts the chaining mode. This line has no delay. Lines 4, 5 and 6 are run as soon as the previous command has finished with no delay and they cannot be interrupted. Line 7 stops the chaining mode and line 8 will be run $macro_delay seconds after that.

Sub-lines

Instead of using one command/var assigments per line, you can separate them using a semi-colon ";". There were few syntaxes that you could use it to minimize the lines with this function such as Var Assignment ($var), Double/Nested Var (${$var}), Increase(++) or Decrease(--) Var or Double/Nested Var, Set, Lock, Release, Log (Use separate line if you want to use ";" in the log message), Pause, Do and Perl Sub-Routine Macro Command. Further info: Forums

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

Commands separated by a semi-colon ";" will have no delay between them, just like the Chaining commands, unless on certain commands such as pause and log.

Conditions

Supported conditions in macro plugin are:

Operator Description
< less than
<= less or equal to
== equal to
> greater than
>= greater or equal to
!= not equal to
~ <left part> is element of <right part (comma-separated list)>
=~ <left part> matches regular expression <right part>

Further Discussion: Forums

arg .. arg2 Between arg and arg2. Where arg can be a number, a % or a variable.

Flow control and labels

While all high-level programming languages have constructs like "if .. else", "while", "foreach", "for .. next", "do .. while" and function calls, their common denominators are "if", "goto" and "while". That's why the macro plugin only supports these three keywords. Since there are no (visible) line numbers, you'll need to use labels which can be defined by a colon followed by the name of the label.

IF statement

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.

Syntax

You can use a simple statement;

if (arg1 <Conditions> arg2) (goto <label> | call <macro> [<n>] | stop)

A simple statement with OR condition;

if (arg1 <Conditions> arg2 || arg3 <Conditions> arg4) (goto <label> | call <macro> <n> | stop)

A simple statement with AND condition;

if (arg1 <Conditions> arg2 && arg3 <Conditions> arg4) (goto <label> | call <macro> <n> | stop)

Or with both;

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

Where;

  • arg can be a variable, a nested variable, a special keyword, @eval, letters and numbers or even a Perl Subroutines function.
  • <label>, the name of an existing label, can only contain letters and numbers
  • <macro>, the name of a existing macro, and
  • <n>, the number of times it will call the macro.


Note:

  • If <n> is defined as 0 or even if it is undefined, the called macro name will run at once and then stop, not continuing the previous macro caller at a run time.
  • If <n> is greater than 0, the called macro name will run at n time/s and then continuing the previous macro caller line at a run time.


Note²: If statements are unlimited, you can use as many statements as you want.

if (arg1 <Conditions> arg2 || arg3 <Conditions> arg4 || ... || argN <Conditions> argN+1) (goto <label> | call <macro> <n> | 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 <Conditions> N+1th argument.
  • While N is an integer number/s which is greater than zero.

Examples

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

The above macro will print \$num is 1 if $num == 1, \$num is 2 if $num == 2, \$num is 3 if $num == 3. The same macro can be written using call instead of 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 is 1
}
macro two {
    log $num is 2
}
macro three {
    log $num is 3
}


A more complicated macro

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 Loop

A while in macros means that certain commands will be ran while the defined conditions are met.

Syntax

while (arg <condition> arg) as <loop>
    do bla bla
    ...
end <loop>

Where;

  • arg can be a variable, a nested variable, a special keyword, @eval or letters and numbers. And
  • <loop> is the name of the loop. You can give any name you want.

Conditions can be found on Conditions.

Examples

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

The result is

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

Automacros

Automacros are triggers which 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, your macros is called.

Syntax

automacro <automacro name> {
	<conditions>
	call myMacro
}
macro myMacro {
	move prontera
	move payon
}

Or you can omit the call <macro> and put macro instructions inside a call block (it's still a normal macro, just semi-anonymous):

automacro <automacro name> {
	<conditions>
	call {
		move prontera
		move payon
	}
}

The first syntax is useful if you want more than one automacro to call one simple macro.

automacro First {
    <conditions> 
    call print
}
 automacro Second {
    <conditions> 
    call print
}
macro print {
    log $.caller triggered
}

Conditions

An automacro needs to have at least 1 condition or it will loop forever. It can have as many conditions as you want. Also, some conditions automatically set some variables so you can use them in your macros.


map <mapname>
Triggers when your current map is <mapname>.


location [not] <mapname [<x1> <y1> [<x2> <y2>]] [, ...]
Triggers when you are [not] at the specified location.
When neither <x1> <y1> nor <x2> <y2> are given, it triggers when you are [not] on <mapname>.
When <x2> <y2> are not given, it triggers when you are [not] on <mapname> at (<x1>,<x2>).
When both <x1> <y1> and <x2> <y2> are defined it triggers when you are on <mapname> somewhere between <x1>, <y1> (upper left) and <x2>, <y2> (lower right, where <x1> < <x2> and <y1> > <y2>
Comma-separated arguments are treated as OR conditions:
location geffen, prontera 123 234
Triggers when you are either in geffen or in prontera at 123 234.
Multiple lines are treated as AND conditions:
location not geffen
location not prontera
Triggers when you are neither in geffen nor in prontera.


mapchange ( <mapname> | any | * ) [, ...]
Triggers when changing map to <mapname>. If the argument is any or * (asterisk or star) then it triggers on any map change.
Comma-separated arguments are treated as OR conditions.


hp <condition> <amount>[%]
Triggers when your hp matches the defined condition.
Multiple lines are treated as AND Conditions.


sp <condition> <amount>[%]
Triggers when your sp matches the defined condition.
Multiple lines are treated as AND conditions.


spirit <condition> <amount>
Triggers when your spirits match <condition> <amount>.
Multiple lines are treated as AND conditions.


weight <condition> <amount>[%]
Triggers when your weight matches <condition> <amount> (absolute value) or <condition> <amount> percent (relative value).
Multiple lines are treated as AND conditions.


cartweight <condition> <amount>[%]
Triggers when your cart weight matches <condition> <amount> (absolute value) or <condition> <amount> percent (relative value).
Multiple lines are treated as AND conditions.


zeny <condition> <amount>
Triggers when your zeny amount matches <condition> <amount>.
Multiple lines are treated as AND conditions.


soldout <condition> <slots>
Triggers when the amount of sold out item slots in your shop matches <condition> <slots>.
Multiple lines are treated as AND conditions.


status [not] <status> [, ...]
Triggers when you are [not] <status>.
The statuses "dead" and "muted" are supported additionally.
Comma-separated arguments are treated as OR conditions.
Multiple lines are treated as AND conditions.


inventory "<item>" <condition> <amount> [, ...]
Triggers when you have <condition> <amount> of <item> in your inventory.
Comma-separated arguments are treated as OR conditions.
Multiple lines are treated as AND conditions.


storage "<item>" <condition> <amount> [, ...]
Triggers when you have <condition> <amount> of <item> in your storage.
Comma-separated arguments are treated as OR conditions.
Multiple lines are treated as AND conditions.


cart "<item>" <condition> <amount> [, ...]
Triggers when you have <condition> <amount> of <item> in your cart.
Comma-separated arguments are treated as OR conditions.
Multiple lines are treated as AND conditions.


shop "<item>" <condition> <amount> [, ...]
Triggers when you have <condition> <amount> of <item> in your shop.
Comma-separated arguments are treated as OR conditions.
Multiple lines are treated as AND conditions.


base <condition> <level>
Triggers when your base level matches <condition> <level>.
Multiple lines are treated as AND conditions.


job <condition> <level>
Triggers when your job level matches <condition> <level>.
Multiple lines are treated as AND conditions.


class <job>
Triggers when your job is <job>


spell [party] <spell> [, ...]
Triggers when someone casts <spell> on you or you are in its scope.
Party support syntax is included (optional). Also trigger on party member (as a target) by other party or monster. Ex: "spell party Lord of Vermilion"
Comma-separated arguments are treated as OR conditions.
Set variables:
  • $.caster - returns the actor (by player/monster) which triggered the last spell syntax on you/party member/in range spell.
  • $.casterName - returns the name of player/monster which triggered the last spell syntax on you/party member/in range spell.
  • $.casterID - returns the ID of player/monster which triggered the last spell syntax on you/party member/in range spell.
  • $.casterPos - returns the last position of player/monster which triggered the last spell syntax on you/party member/in range spell (x y).
  • $.casterSkill - returns the skill name which triggered the last spell syntax on you/party member/in range spell.
  • $.casterTarget - returns the "location of spell" which triggered the last spell syntax on you/party member/in range spell.
  • $.casterTargetName - returns the name of the party member that is in the range of the triggered (as a target) last spell syntax.
  • $.casterDist - returns the distance (between the caster and YOU) which triggered the last spell syntax on you/party member/in range sp


monster [not] <monster(s) name> <condition> [<distance>]
Triggers when <monster(s) name> is near. If <distance> is not set, it will consider the value from clientSight.
Comma-separated arguments are treated as OR conditions.
Multiple lines are treated as AND conditions.
Set variables:
  • $.lastMonster - name of the last monster that triggered the automacro.
  • $.lastMonsterPos - triggered monster position. Ex: x, y map_name
  • $.lastMonsterDist - distance between the triggered monster and you.
  • $.lastMonsterID - the ID of the triggered monster.
  • $.lastMonsterCount - risk point (available only for monster syntax)


aggressives <condition> <number>
Triggers at <number> of aggressives.
Multiple lines are treated as AND conditions.


player ("<player name>" | /<regexp>/[i]) [, <distance> ]
Triggers when <player name> is on screen and not more than <distance> blocks away.
Multiple lines are treated as AND conditions.


equipped [<slot>] (<item> | none) [, ...]
Triggers when <item> or none is equipped [in slot <slot>]
Slots are topHead, midHead, lowHead, leftHand, rightHand, robe, armor, shoes, leftAccessory, rightAccessory and arrow.
Comma-separated arguments are treated as OR conditions.
Multiple lines are treated as AND conditions.


var <variable> (unset | <condition> <value>)
Triggers when <variable> is either unset or matches <condition> <value>.
Multiple lines are treated as AND conditions.


varvar <nested variable> (unset | <condition> <value>)
Triggers when <nested variable> is either unset or matches <condition> <value>.
Multiple lines are treated as AND conditions.


console ("<text>" | /<regexp>/[i])
Triggers when <text> is received on console or the text received matches <regexp>.
The i switch means the regexp is case-insensitive.
Set variables:
  • $.lastLogMsg - the console text that trigerred the automacro.
  • $.lastMatchN - backreference from regexp.


pm ("<text>" | /<regexp>/[i]) [, <player>]
Triggers when <text> is received by PM [from <player>] or the text received matches <regexp>.
The i switch means the regexp is case-insensitive.
Set variables:
  • $.lastpm - the name of the player who PMed you
  • $.lastpmMsg - the message


pubm ("<text>" | /<regexp>/[i]) [, <distance>]
Triggers when a public message [within a distance of <distance>] is received and it is <text> or matches <regexp>
The i switch means the regexp is case-insensitive.
Set variables:
  • $.lastpub - player's name
  • $.lastpubMsg - player's message


party ("<text>" | /<regexp>/[i])
Triggers when <text> is received by party chat or the text received matches <regexp>.
The i switch means the regexp is case-insensitive.
Set variables:
  • $.lastparty - player's name
  • $.lastpartyMsg - player's message


guild ("<text>" | /<regexp>/[i])
Triggers when <text> is received by guild chat or the text received matches <regexp>.
The i switch means the regexp is case-insensitive.
Set variables:
  • $.lastguild - player's name
  • $.lastguildMsg - player's message


playerguild (<guild list> [, ...] | <guild.txt>) [, <distance>]
Trigers when guild list (guild1, guild2, ..., guildN) or lists of guilds inside control/guild.txt matches player's guild name when charNameUpdate or player hook-on-demand packets is received. Further discussion could be found at Forums.
If <distance> is not defined, clientSight value will be considered.
Comma-separated guild list are treated as OR conditions.
Set variables:
  • $.lastPlayerID - return the account ID of the player that trigger the syntax
  • $.lastGuildName - return the guild name of the player that trigger the syntax
  • $.lastGuildNameBinID - return the ID of the player that trigger the syntax
  • $.lastGuildNameBinIDDist - return the distance(from you) of the player that trigger the syntax
  • $.lastGuildNameBinIDName - return the player's name that trigger the syntax
  • $.lastGuildNameBinIDJobName - return the job class of the player that trigger the syntax


hook <hookname>
Triggers when openkore calls <hookname>.


save <hash key> (use in combination with hook)
Saves the value of <hash key> in a variable $.hooksaveN.
automacro hook {
   hook packet_privMsg
   save MsgUser
   save Msg
   call {
         log Player $.hooksave1 said $.hooksave2
         }
}


whenGround [not] <spell>
Triggers when we are in the effect of ground status.
Comma-separated list will be treated as OR condition


areaSpell <spell> [<distance>]
Triggers when someone uses an area of spell (centre) that is in the scope of the distance condition from you. If <distance> is not defined, it will consider clientSight value.
Comma-separated arguments are treated as OR conditions.


localtime <condition> <time>
Triggers when CPU clock time matches the given <condition> <time>.
Time is on 24h format. Ex: 11:22:33 (hour:minute:second)
Multiple lines are treated as AND conditions.


eval <perl expression>
Triggers when <perl expression> is true.
run-once (0 | 1)
When set to 1 the automacro will be locked after being triggered.
Use the macro command release to unlock this automacro.


overrideAI (0 | 1)
When set to 1, the macro ignores openkore's AI. This means it won't pause upon "move" or "status dead".


delay <n>
Waits for <n> seconds before calling the corresponding macro.


timeout <n>
Waits at least for <n> seconds before this automacro can be triggered again.


macro_delay <n>
Overrides the global macro delay setting for the called macro.


priority <num>
Chooses which automacros should be checked before others. The smaller the <num> is, the sooner the automacro gets checked. If priority is not given, the priority is assumed to be 0. (zero: check first).


exclusive (0 | 1)
Automacros which have exclusive set cannot be interrupted by other automacros.


set <variable> <value>
Sets variable <variable> to <value>. You can have multiple set lines per automacro.


orphan <method>
Sets the method of how to deal with orphaned macros.

Example

automacro sp {
   location prontera
   run-once 1
   call {
       log i'm on prontera o/
   }
}


Always remember, when opening a {, always close it with a }.

Orphaned Macros

It may happen - for example by using ai clear while a macro is running - that a macro becomes orphaned. That means the macro object exists but cannot continue because it requires the AI queue to contain the entry "macro" (or "deal") at the first place. When the AI queue gets cleared, the "macro" entry vanishes. There are three methods:

terminate terminates the macro (equivalent to macro stop)
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.


Perl Subroutines

Macro 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 {
   hp > 85%
   exclusive 1
   run-once 1
   set setting Demon Pungus   #becareful on your case, its case sensitive
   set attack 1
   set teleport 0
   set telesearch 1
   call HP
}
automacro confHP2 {
   hp < 75%
   exclusive 1
   run-once 1
   set setting Demon Pungus
   set attack 1
   set teleport 2
   set 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 macro 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:

[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 macros

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


Automacros

Automacros are macros which 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 {
   sp < 200
   call {
      do c sp low
   }
   timeout 10
}


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. sp < 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. 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.
  4. 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.
  5. } – This closing bracket “}” tells Kore that the commands have ended.
  6. 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.
  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 {
   status Strip Weapon
   call {
      do tele
      do relog 10
   }
   timeout 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. status Strip Weapon - The only condition in this macro. This checks your list of statuses for the status "Strip Weapon". Thus, when you are stripped by a Metaling, you get the "Strip Weapon" status and this condition will be fulfilled.
  3. call { - The word "call" and "{" tells Kore that the commands to be executed start after the '{'
  4. 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.....
  5. do relog 10 - Tells Kore to relogin in 10 seconds, because when you login again, your "strip weapon" status is cleared.
  6. } - The closing bracket '}' tells Kore the commands have ended.
  7. 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.
  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 {
   map gef_fild07
   inventory "Blue Gemstone" > 0
   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
   }
   timeout 20
}


Taking it line by line,

  1. automacro warp { - As explained, the automacro's name is warp, and “{“ indicates that the automacro begins.
  2. map get_fild07 - The first condition, the automacro will only trigger if the map is gef_fild07.
  3. inventory “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. call { - Tells Kore that the commands start here.
  5. 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.
  6. 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.
  7. do move 319 187 - The “move” console command is used to move your bot to a set location.
  8. 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).
  9. 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.
  10. do warp 1 - Console command “warp” is used to select memo location 1.
  11. pause 1 - 1 second delay to allow the portal to form.
  12. do move 316 188 - Move to the portal and Voila! You have been warped to the map.
  13. do ai on - You set ai to manual at the beginning of this macro, so now you need to turn it back on.
  14. } - Closing bracket indicates end of commands.
  15. 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.
  16. } - Closing bracket indicates end of automacro code.

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


The macro plugin also has many useful built-in variables which give you your position for example. It's all listed in the macro 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 “monster” condition in your automacro, $.lastmonsterpos gives the position of that monster. To extract the x and y coordinates the code is,

  $mx = @arg ("$.lastMonsterPos", 1)
  $my = @arg ("$.lastMonsterPos", 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.


The normal macros

In the 3 examples given, everything was done using automacros. So you're probably wondering what the point of macros is if everything can be done using automacros. Well, not everything can be done using automacros. For example, it is not possible to use macro variables such as $.pos in an automacro. So, if you get errors like “not an automacro variable”, it means that it cannot be done in an automacro but has to be done using a macro. In such a case, the automacro needs to call a macro.


Regular Expressions

Sometimes, in a macro, you need to compare, say the names of characters near you to see if it matches a certain name. This is where regular expressions come in handy. If you're new to macros, you can read this later as it can be a bit complicated, the more advanced regexps can look hellish =P Visit http://www.regular-expressions.info/quickstart.html where it's explained fairly well. I'm just going to put down some basics here.

$.lastpubMsg = /(A|a)uto (S|s)torage/

Here, $.lastpubMsg is your macro variable holding the last public chat message. A regular expression can just be plain text so it could have been /auto storage/ or /auto/ and Kore would have checked if the public chat contained "auto storage" or "auto".

However, here we have used the "|" symbol which means "or". Notice 'A' and 'a' are contained in brackets with a '|' between them. It means both 'auto' and 'Auto' are checked for. Similarly, both 'storage' and 'Storage' are checked for.


Now suppose you want to check for repetition, say 'aauto storage' also, then you may use:

/(a+|A+)uto (S|s)torage/ 

Notice I've used a '+'. This tells Kore that the character it is directly after, in this instance 'a' or 'A', should be present one or more times. So even if someone says "aaaaaaaaaauto storage', it will be valid. Other checks like the '+' are:

  • * matches 0 or more times e.g. /(a*|A*)uto Storage/ so "uto storage" will also work.
  • + matches 1 or more times e.g. as above.
  • ? matches 1 or 0 times e.g. /(a?|A?)uto Storage/ so "uto storage" and "auto storage" work but "aaaauto storage" won't.


So if you want to check for "Kobold" just do /Kobold/ and if "Kobold" is anywhere in the string, it will be valid. For Kobold-1 and Kobold-2 only it will be /Kobold-(1|2)/.

Regexps may also come in handy when you're using the "console /<regexp>/" condition in automacros, if you need to check for a variety of trigger texts.

These are just the basics. I recommend referring to the link provided above if you need to make a more complicated regexp.

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 macros.txt and start the bot or reload macros.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 macros.txt again to check if you corrected it properly or not.

FAQ

I have an automacro that checks for the amount of an item in my inventory / cart to be less than a given value or equal to zero (e.g. inventory "red potion" <= 30) but that automacro triggers also on map change. Why is that so and what should I do?
When you're changing the map all items vanish from your inventory for a short time. That happens with the official client, too. To avoid this, add an additional check for an item that you always carry with you, like inventory "Jellopy" > 0


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 macros.txt is not saved in UTF-8 encoding.
To solve it, open your macros.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.


I dont understand english. Where is ru-version?
Вот ссылка на перевод данного мануала на русский.

Author

The macro plugin was written by arachno. Special thanks to ezza who is updating the macro plugin now.

Related tools and resources