Scripting
Prev
Next

Chapter 3. Scripting

Internal Scripting

Using aliases

Aliases are a very useful function that KMuddy provides to help you do everything from save on repetitive typing of the same, or similar commands, to making complete combat systems. For example, you may want to type light and let it be replaced with cast light on torch, or type walkaround and let KMuddy replace it with .nsewsnwe.

Aliases are only available for profile-based connections in Profile / Aliases - that is also where you can manage them.

To add a new alias, simply click the Add button. If you want to chage an existing alias, then select the alias, and click the Modify button. To delete an alias, simply select it, and press the Delete button. You can also change the order the aliases are matched in my simply moving them up or down the list.

Let's create a new alias and see what options we have. For example, we'll create an alias called hi that'll instead cause KMuddy to send hello. Clicking on the Add button, we get another window (titled Edit alias), and here is where we'll be adding the alias.

First off, there is the alias text line - it's where we'll type in the alias name. So we'll simply type hi in here. For more advanced aliases, you can also define multi-line aliases with the command-separator character (which is a ; by default), or with the the \n sequence.

Next is the comparison type option. For our purposes, the default option of Begins with is okay, so leave it as it is. Comparison type just means how KMuddy will be matching the text you typed to your alias, and there are several options for that:

Exact match - as the name suggests, the alias will only be matched sucsessfuly if the command you enter is exactly the alias. So if we would have typed hi there, our alias would not have matched.

Sub-string - this one is a bit trickier. With this option, the alias name can be anywhere in the command that we entered - so for example, if we typed say oh, hi! How are you?, the hi in our command would get matched.

Begins with - this will only match the alias if our command begins with it. So if we did hi there, our alias then would match, since it begins with our hi.

Ends with - similar to the above option, our alias will only match if our commands ends with it - for example, say no, not hi would work, since it ends with hi.

Regular expression - this is useful for advanced users who want to use regular expressions in their alias matching. If you want to read up on how those work, look here.

Next is the condition field. Again, for our purposes, just leave it as it is. This is used if you only want your alias to go off when a certain condition is true - so you'd put a logical statement here (for example, $variable == 1). If that statement is true, then the alias will go off.

The replacement text(s) field is next, and is just what we want. Here, we'll type in the things we want the alias to do - and since we want our alias to send hello, we'll just type hello in here. You can also use KMuddy's internal scripting engine in here to build your scripts, or call your external scripts with the /notify command, or run a script /exec scriptname command. More information can be found in the More advanced alias/trigger issues section.

So now that we typed in the alias name (hi), and also our replacement text (hello), the alias is fully functional. Just click Ok and Done, and you're all set.

However, for advanced scripting purposes, KMuddy also offers you a testing area where you can test the aliases as you're making them.

In the text field, you can type in sample commands, and below that in the commands: field, KMuddy will echo how it will execute those commands.

Below that is a table with all pseudo-variables that matched, and their respective data. But be aware that they only work if you select a regex match. To read up on how they work, click here.

If desired, it is possible to disable aliases entirely, by using Profile / Macro keys enabled.

There is also an options tab for more advanced settings on how aliases are handled:

Send original command - sends the original command you sent first, along with any commands that your replacement script executes.

Case sensitive - if checked, KMuddy will differentiate between upper- and lower-case letters, otherwise it'll treat them as the same character.

Global matching - with this on, a single pattern can match multiple times on a single line, if the line contains the pattern multiple times (for example, a pattern of abc and sub-string matching selected, will match on a line abc-abc-abc three times).

Whole words only - if enabled, KMuddy will only match the alias if there are no extra spaces before/after the alias. This option if useful if you want to avoid alias matching when it's not neeeded.

Include prefix/suffix - with this option on, KMuddy will append prefixes and suffixes (if any are avialable) to all lines your script sends. For example, if your alias is abc and you select sub-string matching, along with this option, and have the alias do someone, and you do tell abc bye, KMuddy will send tell someone bye - as you can see, it effectively functions as a variable.

Group - select which group this alias belongs to. See alias groups for more information.

Aliases are expanded in the order you specify - so keep this in mind when ordering aliases, so you aren't surprised if another form of expansion takes place. Aliases are not yet expanded recursively, there is only one expansion per command.

Using triggers

Triggers are commands that are executed when some specific text arrives from the MUD. For example, triggers can check for the text You are hungry. and issue the command eat bread.

Triggers are only available for profile-based connections in Profile / Triggers. Here you can manage your triggers.

Triggers are dealt with the same way aliases are - you can Add, Modify, Delete, and move them about in the order that they're being matched.

Triggers are similar to aliases, with the exception that they match text from the server and not from your commands. See the above section for the explanation of the Basic and the Options tabs. Besides that, KMuddy can also do color, rewrite, gag, and output windows triggers.

Triggers can be used execute simple actions for you (as the above hungry example), or for executing complex scripts. For the latter, see the internal scripting commands or the external scripting section.

You can test your trigger when you're editing it in the test area, to be sure that it does what you expect. Especially useful with regular expressions and pseudo-variables - see the next section for that.

If desired, it is possible to disable triggers entirely, by using Profile / Triggers enabled.

Variables

Variable basics

Basically, variables are special data types that store whatever you want them to. Variable names always begin with "$". The name of a variable may only contain letters and numbers. Therefore, possible legal variable names are $a, $variable, $bah44, and so on. Whenever KMuddy executes a command, it looks to see if a variable with that name exists. If so, the variable name (including the $ prefix) is replaced by the variable value.

For example, assume that you have variables called $enemy and $weapon, and an alias called hh that expands into hit $enemy with $weapon. We assume that the variable $enemy contains orc and $weapon contains sword. Then, whenever you send hh, the actual command sent will read hit orc with sword. Variables allow you to change the value at any time, and allow your alias to expand into something different. The variable can be changed within the GUI or by using the /set function - for example, /set enemy zombie. All further hh aliases will now expand into hit zombie with sword, unless of course, the value of the variable is changed again :).

The real power of variables becomes visible when calling /set commands in aliases and/or triggers. Thus, you can have a trigger that updates $weapon when the mud outputs "You wield ...", and another trigger that updates the value of $enemy when you receive something like "... attacks you!". Then you can have your triggers decide to take appropriate action depending on the values in the variables.

Variables are only available for profile-based connections. There is a GUI for managing variables available at Profile / Variables. You can also use the following commands to manage the variables. These commands can be entered at the input-line, or can be embedded within a trigger or an alias.

Types of variables

Variables are automatically re-typed between numeric and string values as necessary, so you can perform usual arithmetical operations on them. Have a look at expressions for more information.

There are three types of variables. Regular variables, sets (lists) and arrays.

  • Regular variables can be accessed using the standard methods described in the expressions section.

  • Sets are manipulated using /additem, /delitem and contains(). Sets are meant to hold an unordered list of values, and the contains() function queries whether a particular value is held within the set. Sets have no ordering. Set manipulation functions do not work on arrays.

  • Arrays work like regular arrays in programming languages. They allow to hold multiple values within one variable, each stored in one position. The positions are numbered, and their amount is not restricted - the array will automatically grow to hold all the values that you want to keep in it.They are manipulated using /arrayset, /arraydel and item(). With arrays, you can maintain an ordering, as you specify the position where you want to place a given item to. Array manipulation functions do not work on sets.

Have a look at the Internal scripting and Functions section for a more detailed description of the aforementioned macros and functions.

Internal scripting

KMuddy contains its own parsing engine, which allows you to write simple scripts. The engine is far from being complete, and we're always looking to integrate new features into it..

Two core features exist, which form the internal scripting. Internal scripting commands and expressions.

Internal commands are denoted with the "/" character (can be overridden in preferences).

The following macros are available:

/set varname value - set a variable

/unset varname - delete a variable

/inc varname number - increase variable value by certain number

/dec varname number - decrease variable value by certain number

/provide-res varname - provide a resource (increases variable by 1); usable in scripts

/request-res varname - request a resource (decreases by 1, fails if current value is 0); usable in scripts

/setval variable expression - evaluates the expression and puts the result into the given variable. Do not use "[","]" in the expression, it is assumed automatically. The purpose of this command is to allow placing lists and arrays into variables.

/lset varname value - like /set, but the variable is local - exists only within the local script.

/lunset varname - unsets a local variable.

/linc varname value - increases a local variable.

/ldec varname value - decreases a local variable.

/echo params - echos its parameters. Useful to display variables and output from aliases/triggers.

/agroupon group - enables an alias group.

/agroupoff group - disables an alias group.

/tgroupon group - enables a trigger group.

/tgroupoff group - disables a trigger group.

/tick - displays time until tick of the tick timer.

/ticknow - resets the tick timer.

/additem set value - adds a new item to a list variable.

/delitem set value - removes an item from a list variable.

/arrayset variable index value - sets an array item at position index.

/arraydel variable index - removes the value at the given index from the array.

/if [expression] value - the commands following the /if will only get executed if the value is non-zero. You will usually want to use an expression here. Each /if must have its matching /endif, and, optionally, an /else. Ifs can be nested.

A sample if statement can be the following:

/if [$i_can_sip == 1 && ($myhealth > 100 || $mymana > 80)]

sip health

/endif

/else - reserves the effect of the last /if - if it matched, then commands after /else will not be executed, and vice versa.

/endif - Ends a if-else-endif block.

/exec script params - execute an external script. Part of the Scripting plugin.

/notify port params - send out a notification to the given port. Part of the Scripting plugin.

Expression syntax

Expressions can be used in any command, be it a command that is to be sent to the server, or a internal scripting command. The expression is denoted in "[" and "]" characters. The string within these characters gets evaluated and the result is inserted to the command instead of the expression.

For example, executing /set $x [2+2] will first evaluate the 2+2 expression, then insert the result to the command - so the command will be /set $x 4, which will set the x variable to 4.

The expression engine supports the following:

$variable - variable value. Types get auto-converted as needed. Arrays and lists don't get auto-converted to strings if not necessary, hence, these variables can be used like this, unlike standard variable expansion outside expressions.

+, -, *, / - arithmetic operations

parentheses can be used to change operator priorities, as usual

conditional operators - && (AND), || (OR), >, >=, <, <=, == (equal), != (not equal) - these return 1 when true, 0 when not. Suitable to be used within the /if command, or the conditional triggers.

FUNCTION(PARAM1,...,PARAMn) - a function, see below for list. Note that for the function to be evaluated properly, you need to enclose it as an expression - for example, [strlen("hi")]. And lastly, enclose strings in quotes (as the previous example shows).

Functions

Built-in functions:

contains(variable,item) - returns 1 if the given list variable contains a given item

item(variable,index) - returns value stored in the given array variable at position index.

count(variable) - returns count of a provided array or list variable.

global(variable) - returns value of a global variable with the given name.

local(variable) - returns value of a local variable with the given name.

attrib(object, name) - attribute of a KMuddy object. Not usable at the moment.

strattrib(object, name) - string attribute of a KMuddy object. Not usable ta the moment.

Functions available in the STRINGS plug-in:

IMPORTANT: these functions do NOT modify the original variable, they return the modified result for you to work with. If you want to modify the value, you need to do something like: /set $var [lower($var)]

lower(string) - returns string value converted to lowercase.

upper(string) - returns string value converted to uppercase.

caps(string) - returns string value where first letter of each word is uppercase, and the rest lowercase

left(string,c) - returns first c letters of the string

right(string,c) - returns last c letters of the string

mid(string,c,len) - returns len letters from the string, starting at position c. Positions are indexed from 0. For example, mid("abcdef",2,2)="cd"

strlen(string) - returns length of a given string.

trim(string) - removes spaces from beginning and end of the string.

strpos(haystack,needle) - searches for needle in haystack, returns position if found, -1 if not.

strfill(string,len) - if the string's length is less then len, append spaces to the string and return the result. Otherwise return the unmodified string.

strleftfill(string,len) - like strfill, but spaces get prepended to the beginning.

strcat(str1,str2,...strn) - concatenate strings and return the result as one string.

join(list,sep) - converts a list/array to a string, with the given separator. Separator defaults to "|".

explode(list,sep) - fills a list from a string, using sep as separator ("|" by default)

replace(str,from,to) - replaces all occurences of string "from" in the string "str" to string "to" and returns the result.

More advanced alias/trigger issues

There are also some more advanced options for aliases/triggers. These include regular expressions, pseudo-variables and back-references.

Regular expressions and back-references

Regular expressions are special expressions that allow advanced searching of certain patterns. Complete documentation of these is beyond the scope of this manual, please refer to regexp manpage or to KRegExpEditor documentation. Here I'll only include some basics to get you started.

Matching with regular expressions works like standard matching, only that some characters have special meaning. For example, regular expression "hello" will match anything that INCLUDES the hello string as a substring.

Character '.' matches one character. For example, "he.." matches hell or help or hello (substring, remember?).

Character '*' says: previous character may appear any number times (including zero). For example, hel*o matches Theo, helo, hello, hhhhhhhhellllllllloooo, but not hell. Special combination .* matches anything.

Similarly, character '+' says: previous character may appear any number of times, but at least once.

Characters '^' and '$' mean beginning and ending of a string, respectively.

Parentheses ('(' and ')') specify sections in the regular expression. They have two common uses - they can be used to specify a part of expression, that then become an argument to '+' and '*' operators (and to another ones not mentioned here). For example, ^(d.)+$ can match do, dodo, dude, dadhdudjdldodqdbdcdu, but not dfd or dffd. Parentheses are also used as back-references.

If you want to use any of special characters as a part of the text, you have to place a backslash ('\') in front of it. (e.g., Hu\. matches anything that contains Hu.)

Regular expressions have much more possibilities, but this should be enough to get you started. Below is a quick cheat sheet of regex patterns:

  • ^ - matches the beginning of a line. Use this whenever possible.

  • $ - matches the ending of a line. Use this whenever possible.

  • () - makes regex remember what it matched, and assign into an appropriate $(number) variable.

  • [A-Za-z] or \w - matches any word.

  • [0-9] or \d - matches any numbers.

  • ? - a quantifier, makes it so the previous thing may, or may not match. For example, ^You( happily)? jump\.$ will match both "You happily jump." and "You jump." (remember your spaces also).

  • + - another quantifier, matches the previous item one or more times.

  • * - another quantifier, matches the previous item none or more times.

  • | - special characeter, which means "or". For example, "^You take (his|her) stuff\.$" will match "You take his stuff." and "You take her stuff."

Back-references are parts of a regular expression that are in parentheses. They are counted in the order in which they appear. For example, consider the regular expression a((b)+)c . Back-reference 0 is the whole expression. Backreference 1 is (b)+ and backreference 2 is b . If matching text is abbbbcdd, then backref 0 is abbbbc (matching part), backref 1 is bbbb, backref 2 is b. Easy, isn't it?

Pseudo-variables

Pseudo-variables are special strings that expand into parts of text being matched. Pseudo-variables are most useful in conjunction with regular expressions. The following pseudo-variables are available:

$matched - part of the string that matched the alias/trigger text or expression.

$prefix - everything that is before the matching part.

$suffix - everything that is after the matching part.

$prefixtrim - $prefix with leading/trailing spaces omitted.

$suffixtrim - $suffix with leading/trailing spaces omitted.

$0, $1, $2, ... - back-reference with that number. See previous section for more information on back-references. These pseudo-variables only exist if you use regular expression matching.

$line - a special variable that always contains the current line number at the point where the trigger or alias was executed. It does NOT require the use of regular expressions as it is a variable in its own right and is always available.

Pseudo-variables can be used in the alias replacement text and in the triggered command; they will expand to the value that they hold.

IMPORTANT: Note that an improper setting of this may allow other players to make you execute any command they want, so be prepared for this. The best way to prevent this is to disallow matching when separator character (';') is in the text (in some trigger that gets matched before the critical one, maybe?).

Remember that you can experiment with all these in the alias/trigger test area. There you can also look at which pseudo-variables are available and what value they will have for the text you've entered.

Global matching and conditional triggers

Normally, each trigger only matches once per line. This sometimes isn't desirable, especially with colorization triggers, where you often want to have all occurences of a certain word colored. In this situation, you can enable the "Global matching" option. This will make the trigger execute multiple times on one line, if there are multiple matches of the trigger pattern within said line.

Conditional triggers allow you to specify a condition that must be met for the trigger to execute. You can use pseudo-variables within the condition. For more information regarding the condition syntax, refer to section about expressions. Note that you must not include the "[" and "]" separators for the condition - these are assumed automatically.

Special-purpose triggers

In addition to its standard trigger, each trigger can also have a specialized function(s):

Color triggers

Color triggers can be used to colorize text that's received from the server. When a trigger match occurs, instead of sending some text, you can have the matched text colorized any way you want. Of course, you can also do both - send a command and colorize the text.

The colorization dialog itself should be pretty self-explanatory. You simply enter a list of items that should be re-colorized and the desired colors. Some parts may be overlapping; in that case, these parts are colorized in order in which they are specified. "Keep" means keep original color, neutralizing effect of previous colorization entries on the appropriate portion of the string (useful for things like colorize backref1 but not backref2 that's a substring of backref1). If you want to select a custom color, select the "Other" option, and then click on the little color box below to select your color. Once you're done picking what colors you want, click on the Add button to add the colorization.

You will usually want to enable the Global matching option for colorization triggers, so that other non-colotization triggers can still match on that line.

Gagging

Gagging is a feature that allows you to have some text not displayed at all. But you should be careful when setting up a gagging trigger, so that it doesn't hide more than you expect. Information is power, you know. :P. To select the gagging option for a trigger, check off the "Don't show (gag) the line" option under the Special trigger tab in the edit trigger dialog.

Notification triggers

Notification triggers are useful, if you want to have notification support, but only for certain events. You need to have Always notify disabled for this to work. Then, when KMuddy and/or the connection is inactive, and the notification trigger matches, a notification event will occur.

Prompt-detection triggers

Since version 0.5.1, incoming lines are only displayed after a newline character has been received. This makes problems when a prompt arrives, because it won't be displayed until next end-line character, but it won't be received until you send another command. To have a prompt displayed, two possible approaches are available. First of them is the Go-Ahead signal; if your MUD supports it, you can ask it to send you the GA signal after each prompt; KMuddy will detect this and display the prompt correctly.

The GA signal is a great thing, however, lots of MUDs just don't support it properly or not at all. The prompt-detection triggers exist to handle this problem. When an unfinished line is received, it's matched against all P-D triggers; if some trigger matches, then the text is considered a prompt and displayed as such.

Most other trigger options don't take effect for P-D triggers. Also, standard lines don't get matched against P-D triggers.

The prompt will be displayed even if none of these mechanisms are used, because KMuddy automatically assumes that a string that remains in the buffer for at least one second, without anything more received, is treated as a prompt and displayed as such. This is helpful in case of various unpredictable prompts - when creating a new character, for example -- you'll see the prompt, but you'll have to wait a bit for it.

Please note that there can be only one prompt per line. Thus, when something was considered a prompt and some more text is received (without end-of-line char), it will not be tested if it's a prompt (even if the GA signal arrives), so be careful when writing these triggers.

Example of a prompt-detecting trigger, that should be enough to get you started:

Let the prompt look like this: [50hp 50mp 50mv] (with one trailing space). Then the trigger that detects this type of prompt, but nothing else, will look like this (using regexp matching): ^\[[0-9]+hp [0-9]+mp [0-9]+mv\] $. The [0-9]+ sequence matches any number, ^, $ characters mean that nothing more is allowed on the line, backslashes are needed before [] chars, so that they're not interpreted by the regexp matcher.

Sound triggers

Sound triggers allow you to have a sound played on certain events. Note that this has nothing to do with the MSP protocol; this is handled completely on the client-side. Also note that sound triggers are only available is you have sound support built in.

Rewrite triggers

Rewrite triggers allow you to alter how text received from the MUD is displayed to you. So if your MUD sends "You fall over and end up on the ground" you could change it to appear as "You stumble and fall". To use this option, head over to the Rewrite text tab of the edit trigger dialog, and enable the "Text rewrite trigger." option. Then simply select what part of the line you want to change (if it's a backreference - $1-9 regex things - then select it's number below), write the new text you want the line to be replaced with, and select Ok!

Alias/trigger groups

The purpose of alias/trigger groups is to split all aliases and triggers into several manageable groups, with the possibility to activate and deactivate individual groups. The groups can be administered in View / Show alias groups and View / Show trigger groups. These dialogs are non-modal, so you can keep them open and activate/deactivate groups as needed.

Please Note that alias and trigger groups are completely separate. You can have different groups of each type. They are documented together, as their principle and usage is the same.

By default, there is a single group called BASE. This group contains aliases or triggers that are not allocated anywhere else. It can not be removed nor renamed.

By un-checking the checkbox next to a group name, you deactivate that group. By checking it you re-activate it. The add/rename/delete buttons can be used to manipulate the list of groups.

Adding an alias/trigger to a group is simple - just go to the Aliases or Triggers dialog box, and change the group of the relevant appropriate alias/trigger.

Action toolbar

Actions let you define buttons on a toolbar that execute a command when clicked. Handy if you don't like typing much.

Actions are only available for profile-based connections in Profile / Actions. Here you can manage your actions.

Note that you can show/hide the action toolbar with View / Show action toolbar

Output Windows

Output windows are external windows that can store various text from the MUD - like tells, channels, or anything else.

To view which output windows do you currently have, and to show/hide/delete any, go to Profile - Output Windows.... From there, you can either delete them, hide them (so they aren't shown, but still exist), or show them (if they were hidden).

You can create a new output window via the Edit Trigger dialog. Simply create a new trigger, or modify an existing one, and click the Output Windows tab on top. Select the Send output to a separate window option, then fill in the desired window name, and click Create window.

To be able to actually use the output windows though, you need to make a trigger that'll send the text to your window. For that to work, select the Send output to a separate window and pick a window to which you want the text to be sent to under Select window. Optionally, you can select the Gag output in main window option if you want the text to be only displayed in the output window, and not in the main KMuddy window also.

Sample output window:

Let's say you want to have an output window that'll store all information about people coming into your room, with a sample entrance being the following: Anna arrives from north..

To start, create a new trigger, with regex (regular expression) pattern of ^[A-Za-z]+ arrives from [a-z]+\.$. This trigger will match any lines where people come in. Next, head over to the Output windows tab. Check off the Send output to a separate window box, and create a new output window - type in it's name in the Window name box, and click the Create window button. After that, you can select the newly-created window in the Select window drop-down box. Now, all lines will be directed to the output window also. You can optionally check off the Gag output in main window option if you want the line to only appear in the output window, and not in both the output and main windows.

Timers

Timers allow you to schedule a command to be run periodically, or once at some time in the future (well, provided that we define future as "anything that will happen in less that one hour", for that's the limit).

Timers are only available for profile-based connections in Profile / Timers. Here you can add, modify, delete, activate or deactivate your timers.

To add a new timer, click the Add button. Type the command you want the timer to execute in the Command field. Optionally, you can also use the \n string to separate your commands, or have the timer call an alias you made for more advanced scripting abilities. Select the interval at which you want the timer to fire, and if you want the timer to go off only once, select the 'Single-shot' option.

It's also possible to disable timers entirely, if desired, by unselecting Profile / Timers enabled.

Tick timer

Some MUDs have a single timer, upon which a number of events happen (such as mobs respawning, weather changes, etc.). A tick timer helps you approximate when that time comes, and KMuddy provides and helps you with that.

To get started, go to Profile - Tick timer.... The Tick interval option sets the time (in seconds) at which the tick timer expires and starts counting down again, and the Timeout margin option sets time, at which when the timer reaches it it'll execute the Command.

Macro keys

Macro keys allow you to define a command that will be sent to the MUD (or placed in the input-line) whenever a key or a combination of keys are pressed. Macro's are often used for things like numpad walking (assigning direction commands to the numpad keys).

Note: avoid assigning Macro keys that are used for actions in menu or elsewhere. Macro keys are evaluated before actions, so you would be unable to use the key combination for that purpose (you'll still be able to use the mouse to access the actions, of course). Also, assigning a character is not very wise, as you'll be unable to type text that includes that character. It is generally recommended to add a modifier such as Alt or Ctrl to avoid clashes.

Macro keys are only available for profile-based connections in Profile / Macro keys. Here you can manage your macro keys.

It's also possible to disable macro keys entirely, if desired, by using Profile / Macro keys enabled.

Variable triggers

Variable triggers lets you create a monitoring condition for a variable, such that when it is changed, the command you set to be executed will be called.

Status variables

They're variables who's status can be displayed at the bottom of the status bar.

Gauges

Fun things like health gauges and all.

Prev
Next
Home


Would you like to make a comment or contribute an update to this page?
Send feedback to the KDE Docs Team