RGTERM SCRIPTING (RGScript)
===========================

RGTERM can run small scripts that talk to the BBS for you: log in, walk
menus, grab mail, dial a list of boards, and so on. Scripts are plain
text files with the extension .rgs, and they live in the "scripts"
folder next to RGTERM.exe:

    RGTERM\RGTERM.exe
    RGTERM\scripts\example.rgs      <- created the first time RGTERM runs

Edit them with any text editor (Notepad, EDIT, etc).


RUNNING SCRIPTS
---------------

There are three ways to run a script. Either way, scripts are ONLY ever
loaded from RGTERM\scripts.

1) LOGON SCRIPT - the phonebook's Script field

Each phonebook entry has a "Script" field (Alt+E, under DISPLAY & LOGIN).
Type just the script's name - no path:

    Script: titantic          -> runs RGTERM\scripts\titantic.rgs
    Script: titantic.rgs      -> same thing

When that entry connects, RGTERM loads the script from the scripts folder
and runs it. Scripts are ONLY ever loaded from RGTERM\scripts - if you
type a path, the path is ignored and just the file name is used. Leave
the field blank for no script.

A logon script stops when you hang up (or the BBS does). If the script
itself hangs up or dials another board with connect "Name", it keeps
running.

2) ANY TIME - Alt+O

Press Alt+O (in the terminal or the phonebook) to open the script picker
on the scripts folder and run any .rgs file - a door-game helper, a
Trade Wars routine, a mail-reading macro, anything. Press Alt+O again
while a script is running to stop it.

The picker lists each script with a short description next to its name -
the script's first comment line, e.g.

    tw-pairtrade.rgs   Trade Wars 2002 port-pair trading loop
    titantic.rgs       RGTERM auto-login example

so start each script with a comment saying what it does. A leading
"name.rgs - " in that comment is dropped. The picker stays in the scripts
folder (no other folders are shown).

Alt+O scripts aren't tied to the call; they run until they finish or
you stop them. (A waitfor() gives up with 0 if the line drops, so most
scripts end by themselves after a hangup.)

3) HOTKEYS - Shift+F1 .. Shift+F10

Alt+C, then PgDn to page 4 ("Script Keys" - or pick "-> Shift+F1-F10
Script Keys" on page 1). Give each key a script name, again just the
name:

    Shift+F1:  tw-pairtrade
    Shift+F2:  readmail

Pressing the key in the terminal runs scripts\<name>.rgs. Pressing the
same key again while that script is running stops it. Hotkey scripts
behave like Alt+O scripts (not tied to the call).

Only one script runs at a time - starting another one (Alt+O or a
hotkey) stops whatever was running, including a logon script.


RECORDING A SCRIPT - Ctrl+O
---------------------------

Ctrl+O starts the recorder ("learn mode"), Ctrl+O again stops it. While
it's recording the status bar shows *REC*. Just use the board normally -
RGTERM watches what the BBS shows and what you type, and writes a script
that does it again:

    expect "Press <ESC> twice to continue..."
    send "\e\e"

    expect "Login:"
    sendln username()        // the phonebook entry's Username field

    expect "Password:"
    sendln password()        // the entry's Password - never written to the file

    expect "mins left):"
    send "M"

How it decides what to write:
  - Each thing you type at a prompt is one step. Pressing Enter makes it
    a sendln; single-key menu picks (the BBS reacts without Enter)
    become send.
  - The prompt for a step is the last line the BBS showed before you
    started typing. expect waits up to 30 seconds for it and stops the
    script with a message if it never shows up.
  - Prompts with numbers that change every call (time left, node, dates)
    are cut down to the part after the last number:
    "Main Menu (45 mins left):" -> "mins left):".
  - If what you typed matches the entry's Username or Password, the
    script uses username() / password() instead of the text, so your
    password never ends up in the .rgs file. (A password you typed that
    ISN'T stored in the entry is written as-is, with a comment.)

Where it's saved: scripts\<entry name>.rgs (Titantic BBS.rgs, or
Titantic BBS-2.rgs if that already exists). The status row tells you the
name. Recording also stops and saves by itself when the call ends.

Record a LOGON script: press Ctrl+O in the phonebook, connect, log in,
press Ctrl+O. If that entry's Script field is empty, RGTERM fills it in
with the new script so it runs on every connect from then on.

Record anything else (a door, a mail run): press Ctrl+O while online,
do it, press Ctrl+O. Run it later with Alt+O or put it on a Shift+F key.

The result is a normal .rgs file - open it in a text editor to tidy it
up, lengthen a timeout, or add loops.

The status row shows "Script xxx running", then "finished" - or the error
and the line number it happened on. A missing file shows "Script not
found: scripts\xxx.rgs". print() messages show up in the same place, and
errors are also written to the debug log.

The old "Auto-login script" lines in the phonebook still work the same
as before; RGScript is separate and more capable.


THE LANGUAGE
------------

Comments:        // to end of line, or # to end of line

Values:          whole numbers (64-bit) and strings. Numbers and strings
                 convert as needed. "True" is any non-zero number or a
                 non-empty string; true = 1, false = 0.

Strings:         "double quotes". Escapes:
                   \r  CR      \n  LF      \t  tab     \e  ESC
                   \b  BS      \0  NUL     \\  \       \"  "
                   \xHH  any byte in hex (e.g. \x1B)
                   ^M  control characters in caret form (^M = CR, ^[ = ESC,
                       ^C = Ctrl+C ...). Use \^ for a literal ^.

Variables:       x = 5            (created on first assignment)
                 var name = "T.J."
                 Names are not case sensitive. Variables set at the top of
                 the script are global; inside a function, new variables
                 are local to that function.

Operators:       + - * / %        (+ joins strings when either side is a
                                   string: "Node " + 3 = "Node 3")
                 = <> < > <= >=   (== and != also work; strings compare
                                   alphabetically)
                 and  or  not

Statements are one per line (or separated by ;). Blocks end with END:

  if n = 1 then
    ...
  elseif n = 2 then
    ...
  else
    ...
  end

  while x < 10          (DO is optional)
    x = x + 1
  end

  for i = 1 to 10       (optional: step 2 / step -1)
    ...
  end

  repeat
    ...
  until done

  break                 leave the loop
  continue              next pass of the loop
  exit                  stop the script (normally - not an error)

Functions:

  function greet(name)
    return "Hello, " + name
  end

  print greet("T.J.")

Parentheses are optional when a call is a statement by itself:
    send "hello"      is the same as      send("hello")


BUILT-IN FUNCTIONS
------------------

Talking to the BBS

  send a, b, ...           Send text (all arguments joined together).
  sendln a, b, ...         Same, followed by a CR (Enter).
  waitfor(p1, p2, ..., secs)
                           Wait until one of the patterns shows up in text
                           from the BBS. Returns which one matched (1, 2,
                           ...) or 0 on timeout / line dropped / script
                           stopped. The last argument, if it is a number,
                           is the timeout in seconds; with no timeout it
                           waits for as long as the line stays up.
                           Matching ignores upper/lower case and ANSI color
                           codes. Text is used up as it is matched, so the
                           next waitfor only sees newer text.
                           ("wait" is the same thing.)
  clear                    Throw away text received so far, so the next
                           waitfor only sees what arrives from now on.
  delay ms                 Pause in milliseconds ("pause" is the same).
  sleep secs               Pause in seconds.

Connection

  connected()              1 if online, 0 if not.
  connect "name"           Dial a phonebook entry by name (exact match
                           first, then partial; also searches the BBS Guide
                           list). Waits until online and returns 1, or 0 if
                           the entry isn't found or the connection fails.
                           Hangs up the current call first. ("dial" is the
                           same.)
  hangup                   Hang up.
  entry()                  Name of the connected phonebook entry ("" if
                           none).
  username()  password()   The connected entry's Username / Password
                           fields - sendln password() logs in without the
                           password being in the script.

Screen

  getline(row)             Text of a screen row (1 = top), trailing blanks
                           removed.
  screen()                 The whole screen, rows joined with \n.
  rows()  cols()           Screen size.
  cursorx()  cursory()     Cursor position (1-based).

Asking you something

  input("question" [, "default"])
                           Shows the question on the bottom row and waits
                           for you to type an answer and press Enter.
                           The default is already typed in (Enter takes
                           it; Esc also gives it back). Returns text - use
                           val() for a number:
                             n = val(input("How many trips?", "10"))
                           While the question is up, your typing goes to
                           the answer, not the BBS; Ctrl+V pastes; Alt+O
                           still stops the script. ("ask" is the same.)

Messages

  print a, b, ...          Show a message on the status row ("message" is
                           the same).
  beep                     Windows beep.

Strings

  len(s)                   Length.
  upper(s)  lower(s)  trim(s)
  left(s, n)  right(s, n)  mid(s, start [, count])   (start is 1-based)
  pos(find, s)             Position of find in s (0 = not found).
  contains(s, find)        1 if s contains find.
  replace(s, old, new)     Replace every occurrence.
  str(x)  val(s)           Number to string / string to number ("num" =
                           val).
  chr(n)  asc(s)           Byte value to character and back.

Other

  random(n)                0 .. n-1
  tick()                   Milliseconds counter (for timing).
  time()  date()           "hh:mm:ss" and "yyyy-mm-dd".
  hour()  minute()  dow()  Current hour, minute, day of week (1=Mon..7=Sun).
  scriptname()             This script's file name without .rgs.
  lastline()               The whole line the last successful waitfor()
                           matched on - handy for reading numbers out of
                           a prompt: after waitfor("(?=Help)? :") on
                           "Command [TL=00:00:00]:[1234] (?=Help)? :"
                           lastline() is that whole line.
  number(s)                The first whole number in s, commas ignored:
                           number("We'll buy them for 1,390 credits.")
                           = 1390. 0 if there's no number.

Predefined variables

  bbsname                  Entry name at the moment the script started.
  scriptdir                The scripts folder (with trailing \).


EXAMPLES
--------

Log in to a board (save as scripts\titantic.rgs, and put "titantic" in
the entry's Script field):

  // Titantic BBS auto-login
  if waitfor("name:", "handle:", 30) then
    sendln "T.J."
    if waitfor("password:", 15) then
      sendln "MySecret"
    end
  end
  // Skip the "press any key" pauses until the main menu shows
  while true
    n = waitfor("[Hit a key]", "more?", "Main Menu", 20)
    if n = 1 or n = 2 then
      send "\r"
    else
      break
    end
  end
  print "Logged in to " + entry()


Check several boards for new mail (put this in the Script field of the
first board - connect "Name" hangs up and dials the next one):

  function check(board)
    if not connect(board) then
      print "Could not reach " + board
      return 0
    end
    got = 0
    if waitfor("new mail", "no new mail", 60) = 1 then got = 1 end
    hangup
    return got
  end

  total = 0
  for i = 1 to 3
    if i = 1 then b = "Titantic BBS" end
    if i = 2 then b = "Another BBS" end
    if i = 3 then b = "Third BBS" end
    total = total + check(b)
    delay 2000
  end
  print "Boards with new mail: " + total


Wait for a door prompt and answer with a random choice:

  while connected()
    if waitfor("Your move", 120) = 0 then break end
    send chr(asc("1") + random(3))
  end


Door games - Trade Wars 2002 port-pair trading (tw-pairtrade.rgs, run
with Alt+O from the TW2002 Command prompt). Shows functions, lastline()
and number(). Abbreviated - the full file is in the scripts pack:

  var sectorA = 1234
  var sectorB = 1235
  var PROMPT = "(?=Help)? :"         // end of the Command prompt

  function trade()
    send "P"
    while true
      n = waitfor("Enter your choice", "want to sell [", "want to buy [", "Your offer [", PROMPT, 20)
      if n = 1 then send "T"
      elseif n >= 2 and n <= 4 then send "\r"   // take the defaults
      elseif n = 5 then return 1
      else return 0
      end
    end
  end

  function move(asector)
    sendln asector
    if waitfor(PROMPT, 30) = 0 then return 0 end
    line = lastline()                  // "Command [TL=...]:[1235] (?=Help)? :"
    return number(mid(line, pos("]:[", line) + 3)) = asector
  end

  for i = 1 to 10
    if not trade() then exit end
    if not move(sectorB) then exit end
    if not trade() then exit end
    if not move(sectorA) then exit end
  end
