macro plugin: Difference between revisions

From OpenKore Wiki
Jump to navigation Jump to search
Line 720: Line 720:


; spell [party] <''spell''> [, ...]
; spell [party] <''spell''> [, ...]
: Triggers when someone casts <''spell''> on you or you are in it's scope.  
: 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"
: 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.  
: Comma-separated arguments are treated as '''OR''' conditions.  

Revision as of 09:03, 16 November 2009

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

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. All the Console Commands can be used in macros.


do <command>
Run <command>. Commands from Console Commands.
macro foo {
   do move 123 234 prontera
   do sit
   do c hello world
}


log <text>
Prints a text in the console.
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 locks 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 define and work with own variables. To set a variable use $variable = value, to recall the value use $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


For calculation use @eval .

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

The result is:

log 2 + 3 = 5


You can also use @eval inside @eval

macro math {
    $num = 2
    $num2 = 3
    $result = @eval(@eval($num+$num2) - @eval($num+$num2))
    log ($num + $num2) - ($num + $num2) = $result
}


Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division


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 \$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
    log $name lives on ${$name}
}

The result is:

log Camila lives on Brazil


Special Variables

There are special readonly 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 is equal to <name> . If no NPC is found, it returns -1.
@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>.
@arg ("<argument>", <n>)
Returns the <n>th word of <argument> or an empty string if the word index is out of range.

Note: <n> can also be a variable.

@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 players shop and returns its price.
@nick (<word>)
Escape all the regexp characters with \.

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 ;.

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 ; will have no delay between them, just like the Chaining commands, unless on commands 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)>
=~ Check for regexp
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

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

Syntax

You can use a simple statement;

if (arg <condition> arg2) (goto <label> | call <macro> [<n>])

A simple statement with OR condition;

if (arg <condition> arg2 || arg3 <condition> arg4) (goto <label> | call <macro> <n>)

A simple statement with AND condition;

if (arg <condition> arg2 && arg3 <condition> arg4) (goto <label> | call <macro> <n>)

Or with both;

if ((arg <condition> arg2 || arg3 <condition> arg4) && arg5 <condition> arg6) (goto <label> | call <macro> <n>)

Where;

  • arg can be a variable, a nested variable, a special keyword, @eval or letters and numbers.
  • <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.

Conditions can be found on Conditions.


Note: if <n> is not defined or it's 0, it will call the macro once and stop, not continuing the first macro. If it's 1 it will run the called macro and continue the first macro. If it's bigger than 1 it will call the macro n' times and continue the first macro.


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

if (arg <condition> arg2 || arg3 <condition> arg4 || ... || argN <condition> argN+1) (goto <label> | call <macro> <n>)

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
    :one
    log \$num is 2
    stop
    :one
    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> 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 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.

Syntax

automacro <name> {
    <conditions> <values>
    call <macro>
}

Or you can omit the call <macro>

automacro <name> {
    <condition> <values>
    call {
          <commands>
        }
}

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

automacro First {
    <conditions> 
    call print
}
 automacro Seconds {
    <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 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 baselevel 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 partychat 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 guildchat 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


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 defined the conditions for <time> mets.
Time is on 24h format.


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>
Wait 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>
Choose which automacros should be checked before others. The smaller <num> is 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 use Perl without all the limitations from eval command.

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;
}

Comments

The macro files allow comments, i.e. lines that are ignored by the macro plugin. Lines starting with a # will be treated as comment.

macro happy {
     # this is a comment line
    log I'm Happy
}

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

-automacros – these trigger automatically
-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,

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.


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.


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.


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.


} – This closing bracket “}” tells Kore that the commands have ended.


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.


} – 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....

automacro strip { - Tell Kore this is an automacro, and it's name is "strip". The '{' tells Kore the code of the automacro starts here.


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.


call { - The word "call" and "{" tells Kore that the commands to be executed start after the '{'


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.....


do relog 10 - Tells Kore to relogin in 10 seconds, because when you login again, your "strip weapon" status is cleared.


} - The closing bracket '}' tells Kore the commands have ended.


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.


} - 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,

automacro warp { - As explained, the automacro's name is warp, and “{“ indicates that the automacro begins.


map get_fild07 - The first condition, the automacro will only trigger if the map is gef_fild07.


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.


call { - Tells Kore that the commands start here.


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.


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.


do move 319 187 - The “move” console command is used to move your bot to a set location.


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).


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.


do warp 1 - Console command “warp” is used to select memo location 1.


pause 1 - 1 second delay to allow the portal to form.


do move 316 188 - Move to the portal and Voila! You have been warped to the map.


do ai on - You set ai to manual at the beginning of this macro, so now you need to turn it back on.


} - Closing bracket indicates end of commands.


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.


} - 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 automacro isn't spammed. To get the automacro to run again, a release command needs to be executed. However, due to a rogue situation the macro hangs and the release macro isn't executed, your automacro is effectively stuck. To get around this, I use a timeout instead of using run-once.


The normal macros

In the 2 examples above, I've done everything 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, I don't think you can use macro variables such as $.pos in an automacro. So, if you get errors like “not an automacro variable” it means that cannot be done in an automacro and has to be done in 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 its 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 can use /(a+|A+)uto (S|s)torage/. Notice I've used a '+'. This tells Kore that the character it is directly after, here '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 eg: /(a*|A*)uto Storage/ so "uto storage" will also work
  • + - matches 1 or more times eg: as above
  • ? - matches 1 or 0 times eg: /(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 you used some special character on some of your macros. 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 you're using Notepad++, go to Format > UTF-8 without BOM and save.

Author

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