# Example of coding script routines for MUSHclient in Python

# ----------------------------------------------------------
# Error codes returned by various functions
# ----------------------------------------------------------

eOK = 0 # No error
eWorldOpen = 30001 # The world is already open
eWorldClosed = 30002 # The world is closed, this action cannot be performed
eNoNameSpecified = 30003 # No name has been specified where one is required
eCannotPlaySound = 30004 # The sound file could not be played
eTriggerNotFound = 30005 # The specified trigger name does not exist
eTriggerAlreadyExists = 30006 # Attempt to add a trigger that already exists
eTriggerCannotBeEmpty = 30007 # The trigger "match" string cannot be empty
eInvalidObjectLabel = 30008 # The name of this object is invalid
eScriptNameNotLocated = 30009 # Script name is not in the script file
eAliasNotFound = 30010 # The specified alias name does not exist
eAliasAlreadyExists = 30011 # Attempt to add a alias that already exists
eAliasCannotBeEmpty = 30012 # The alias "match" string cannot be empty
eCouldNotOpenFile = 30013 # Unable to open requested file
eLogFileNotOpen = 30014 # Log file was not open
eLogFileAlreadyOpen = 30015 # Log file was already open
eLogFileBadWrite = 30016 # Bad write to log file
eTimerNotFound = 30017 # The specified timer name does not exist
eTimerAlreadyExists = 30018 # Attempt to add a timer that already exists
eVariableNotFound = 30019 # Attempt to delete a variable that does not exist
eCommandNotEmpty = 30020 # Attempt to use SetCommand with a non-empty command window
eBadRegularExpression = 30021 # Bad regular expression syntax
eTimeInvalid = 30022 # Time given to AddTimer is invalid
eBadMapItem = 30023 # Direction given to AddToMapper is invalid
eNoMapItems = 30024 # No items in mapper
eUnknownOption = 30025 # Option name not found
eOptionOutOfRange = 30026 # New value for option is out of range
eTriggerSequenceOutOfRange = 30027 # Trigger sequence value invalid
eTriggerSendToInvalid = 30028 # Where to send trigger text to is invalid
eTriggerLabelNotSpecified = 30029 # Trigger label not specified/invalid for 'send to variable'
ePluginFileNotFound = 30030 # File name specified for plugin not found
eProblemsLoadingPlugin = 30031 # There was a parsing or other problem loading the plugin
ePluginCannotSetOption = 30032 # Plugin is not allowed to set this option
ePluginCannotGetOption = 30033 # Plugin is not allowed to get this option
eNoSuchPlugin = 30034 # Requested plugin is not installed
eNotAPlugin = 30035 # Only a plugin can do this
eNoSuchRoutine = 30036 # Plugin does not support that subroutine (subroutine not in script)
ePluginDoesNotSaveState = 30037 # Plugin does not support saving state
ePluginCouldNotSaveState = 30037 # Plugin could not save state (eg. no state directory)
ePluginDisabled = 30039 # Plugin is currently disabled
eErrorCallingPluginRoutine = 30040 # Could not call plugin routine
eCommandsNestedTooDeeply = 30041 # Calls to "Execute" nested too deeply
eCannotCreateChatSocket = 30042 # Unable to create socket for chat connection
eCannotLookupDomainName = 30043 # Unable to do DNS (domain name) lookup for chat connection
eNoChatConnections = 30044 # No chat connections open
eChatPersonNotFound = 30045 # Requested chat person not connected
eBadParameter = 30046 # General problem with a parameter to a script call
eChatAlreadyListening = 30047 # Already listening for incoming chats
eChatIDNotFound = 30048 # Chat session with that ID not found
eChatAlreadyConnected = 30049 # Already connected to that server/port
eClipboardEmpty = 30050 # Cannot get (text from the) clipboard
eFileNotFound = 30051 # Cannot open the specified file
eAlreadyTransferringFile = 30052 # Already transferring a file
eNotTransferringFile = 30053 # Not transferring a file
eNoSuchCommand = 30054 # There is not a command of that name
eArrayAlreadyExists = 30055 # That array already exists
eBadKeyName = 30056 # That name is not permitted for a key
eArrayDoesNotExist = 30056 # That array does not exist
eArrayNotEvenNumberOfValues = 30057 # Values to be imported into array are not in pairs
eImportedWithDuplicates = 30058 # Import succeeded, however some values were overwritten
eBadDelimiter = 30059 # Import/export delimiter must be a single character, other than backslash
eSetReplacingExistingValue = 30060 # Array element set, existing value overwritten
eKeyDoesNotExist = 30061 # Array key does not exist
eCannotImport = 30062 # Cannot import because cannot find unused temporary character


# ----------------------------------------------------------
# Flags for AddTrigger
# ----------------------------------------------------------

eEnabled = 1 # enable trigger 
eOmitFromLog = 2 # omit from log file 
eOmitFromOutput = 4 # omit trigger from output 
eKeepEvaluating = 8 # keep evaluating 
eIgnoreCase = 16 # ignore case when matching 
eTriggerRegularExpression = 32 # trigger uses regular expression 
eExpandVariables = 512 # expand variables like @direction 
eReplace = 1024 # replace existing trigger of same name 
eLowercaseWildcard = 2048 # wildcards forced to lower-case
eTemporary = 16384 # temporary - do not save to world file 

# ----------------------------------------------------------
# Colours for AddTrigger
# ----------------------------------------------------------

NOCHANGE = -1
custom1 = 0
custom2 = 1
custom3 = 2 
custom4 = 3
custom5 = 4
custom6 = 5
custom7 = 6
custom8 = 7
custom9 = 8
custom10 = 9
custom11 = 10
custom12 = 11
custom13 = 12
custom14 = 13
custom15 = 14
custom16 = 15

# ----------------------------------------------------------
# Flags for AddAlias
# ----------------------------------------------------------

# eEnabled = 1 # same as for AddTrigger 
eIgnoreAliasCase = 32 # ignore case when matching 
eOmitFromLogFile = 64 # omit this alias from the log file 
eAliasRegularExpression = 128 # alias is regular expressions 
# eExpandVariables = 512 # same as for AddTrigger 
# eReplace = 1024 # same as for AddTrigger 
eAliasSpeedWalk = 2048 # interpret send string as a speed walk string 
eAliasQueue = 4096 # queue this alias for sending at the speedwalking delay interval 
eAliasMenu = 8192 # this alias appears on the alias menu 
# eTemporary = 16384 # same as for AddTrigger

# ----------------------------------------------------------
# Flags for AddTimer
# ----------------------------------------------------------

# eEnabled = 1 # same as for AddTrigger
eAtTime = 2 # if not set, time is "every" 
eOneShot = 4 # if set, timer only fires once 
eTimerSpeedWalk = 8 # timer does a speed walk when it fires 
eTimerNote = 16 # timer does a world.note when it fires 
eActiveWhenClosed = 32  # timer fires even when world is disconnected
# eReplace = 1024 # same as for AddTrigger
# eTemporary = 16384 # same as for AddTrigger


# ----------------------------------------------------------
# Example showing iterating through all triggers 
# ----------------------------------------------------------

def showtriggers ():
 triggerlist = world.GetTriggerList
 if (triggerlist):
   for t in triggerlist : world.Note (t)


# -----------------------------------------------
# Example showing iterating through all variables
# ------------------------------------------------

def showvariables ():
  variablelist = world.GetVariableList
  if (variablelist ):
    for v in variablelist : world.Note (v + " = " +
                    world.GetVariable(v))

# ----------------------------------------------------------
# Example showing iterating through all aliases
# ----------------------------------------------------------

def showaliases ():
  aliaslist = world.GetAliasList
  if (aliaslist ):
    for a in aliaslist : world.Note (a)


# ---------------------------------------------------------
# Example showing running a script on world open
# ---------------------------------------------------------
def OnWorldOpen ():
  world.Note ("---------- World Open ------------")

# ---------------------------------------------------------
# Example showing running a script on world close
# ---------------------------------------------------------
def OnWorldClose ():
  world.Note ("---------- World Close ------------")

# ---------------------------------------------------------
# Example showing running a script on world connect
# ---------------------------------------------------------
def OnWorldConnect ():
  world.Note ("---------- World Connect ------------")

# ---------------------------------------------------------
# Example showing running a script on world disconnect
# ---------------------------------------------------------
def OnWorldDisconnect ():
  world.Note ("---------- World Disconnect ------------")

# ---------------------------------------------------------
# Example showing running a script on an alias
#
#  This script is designed to be called by the alias below:
#
#
# <aliases>
#   <alias
#    script="OnTeleport"
#    match="^teleport(.*)$"
#    enabled="y"
#    regexp="y"
#    sequence="100"
#   >
#   </alias>
# </aliases>
#
#  (remove the leading #'s and paste into the alias configuration screen)
#
#  It is for teleporting (going to) a room by number
#
#  The room is entered by name and looked up in the variables
#  list.
# ---------------------------------------------------------
def OnTeleport (thename, theoutput, wildcards):
  sHelp = "";
  sDestination = wildcards [0]

  # remove leading spaces from destination
  if len(sDestination) > 0:
    while sDestination [0] == " ":
      sDestination = sDestination [1:]

  # if nothing entered echo possible destinations
  if len(sDestination) == 0:
    world.note ("-------- TELEPORT destinations ----------")
    roomlist = world.GetVariableList

  # find list of all variables
    if roomlist :
    # loop through each variable, and add to help if it starts with "teleport_"
      for room in roomlist:
         if room [:9] == "teleport_":
            if len (sHelp) > 0:
               sHelp += ", "       
            sHelp = sHelp + room [9:]

    # if no destinations found, tell them
    if sHelp == "":
      sHelp = "<no rooms in teleport list>"
    world.note (sHelp)
    return


  # get contents of the destination variable 

  iRoom = world.GetVariable ("teleport_" + sDestination)

  # if not found, or invalid name, that isn't in the list
  if not iRoom:
    world.note ("******** Destination " + sDestination + " unknown *********")
    return

  world.note ("------> Teleporting to " + sDestination)
  world.send ("@teleport #" + iRoom)



# ---------------------------------------------------------
# Example showing running a script on an alias
#
#  This script is designed to be called by an alias:  
#
# <aliases>
#   <alias
#    script="OnAddTeleport"
#    match="^add_teleport(|\s*(\w*)\s*(\d*))$"
#    enabled="y"
#    regexp="y"
#    sequence="100"
#   >
#   </alias>
# </aliases>
#
#  (remove the leading #'s and paste into the alias configuration screen)
#
#  It is for adding a room to the list of rooms to teleport to (by
#  the earlier script).
#
#  eg.  ADD_TELEPORT dungeon 1234
#
# ---------------------------------------------------------
def OnAddTeleport (thename, theoutput, wildcards):
  
  # wildcard one is the destination
  sDestination = wildcards [1]

  # remove leading spaces from destination
  if len(sDestination) > 0:
    while sDestination [0] == " ":
      sDestination = sDestination [1:]

  # if nothing entered tell them command syntax
  if len (sDestination) == 0:
    world.note ("Syntax: add_teleport name dbref")
    world.note ("    eg. add_teleport LandingBay 4421")
    return
  

  # wildcard 2 is the room to go to
  iRoom= wildcards [2]

  # add room and destination location to variable list
  iStatus = world.SetVariable ("teleport_" + sDestination, int(iRoom))

  if iStatus != 0:
    world.note ("Room name must be alphabetic, you entered: " + sDestination)
    return

  world.note ("Teleport location " + sDestination + "(#" 
             + iRoom + ") added to teleport list")



# ------------------------------------------
# Example showing a script called by a timer
# -------------------------------------------
def OnTimer (strTimerName):
  world.note ("Timer " + strTimerName + " has fired!")


# --------------------------------------------
# Example showing a script called by a trigger
#  Should be connected to a trigger matching on: <*hp *m *mv>*
#   (the above example will work for SMAUG default prompts (eg. <100hp 10m 40mv>)
#    it may need to be changed depending on the MUD prompt format).
# --------------------------------------------
def OnStats (strTriggerName, trig_line, wildcards):
  iHP = wildcards [0]
  iMana = wildcards [1]
  iMV = wildcards [2]

  world.Note ("Your HP are " + iHP)
  world.Note ("Your Mana is " + iMana)
  world.Note ("Your movement points are " + iMV)



# --------------------------------------------
# Subroutine to be called to repeat a command.
#
#  Call from the alias:
#
# <aliases>
#   <alias
#    script="OnRepeat"
#    match="^#(\d+)\s+(.+)$"
#    enabled="y"
#    regexp="y"
#    sequence="100"
#   >
#   </alias>
# </aliases>
#
#  (remove the leading #'s and paste into the alias configuration screen)
#
#  Example of use:  #10 give sword to Trispis
#  This would send "give sword to Trispis" 10 times
# --------------------------------------------
def OnRepeat (strAliasName, strOutput, wildcards):
  for i in range (int (wildcards [0])):
    world.Send (wildcards [1])


# --------------------------------------------
# Example showing iterating through all worlds
# --------------------------------------------

def showworlds ():
  worldlist = world.GetworldList
  if (worldlist ):
    for w in worldlist : world.Note (w)


# --------------------------------------------------
# Example showing sending a message to another world
# --------------------------------------------------

def SendToWorld (name, message):
  otherworld = world.getworld (name);
  if otherworld:
    otherworld.Send (message)
  else:
    world.note ("World " + name + " is not open")
    return


# --------------------------------------------
# Example trigger routine that just shows what was passed to it
# --------------------------------------------

def ExampleTrigger (thename, theoutput, wildcards):
  world.note ("Trigger " + thename + " fired.");
  world.note ("Matching line was: " + theoutput);
  for i in range (10):
    if wildcards [i]:
       world.note ("Wildcard " + str(i) + " = " + wildcards [i])

world.note ("Scripting enabled - script file processed")
                                                          
