Пример #1
0
def play_prop_sound(a, b, enemy=False):
    if enemy:
        base = 6000
    else:
        base = 6100
    ratio = divmod(a * 10, b)[0]
    exported.lyntin_command("#sound %s.ogg" % (ratio + base), internal=1)
Пример #2
0
    def put(self, cmd, non_blocking=False):
        if non_blocking:
            exported.lyntin_command(cmd.command())
            return

        if self._running:
            self._queue.put((cmd, time.time()))
Пример #3
0
def look_fortarget(args):
    global target
    text = args["data"]
    if target in text:
        if timed():
            exported.lyntin_command("kill " + target)
    return args["data"]
Пример #4
0
  def checkActions(self, text):
    """
    Checks to see if text triggered any actions.  Any resulting 
    actions will get added as an InputEvent to the queue.

    @param text: the data coming from the mud to check for triggers
    @type  text: string
    """
    # FIXME - make sure this works even when lines are broken up.

    actionlist = self._actionlist
    if not actionlist:
      actionlist = [x for x in list(self._actions.values()) if x[6] not in self._disabled]
      actionlist.sort(key = lambda x:x[3])
      self._actionlist = actionlist

    colorline = utils.filter_cm(text)
    nocolorline = ansi.filter_ansi(colorline)

    # go through all the lines in the data and see if we have
    # any matches
    for (action, actioncompiled, response, color, priority, onetime, tag) in actionlist:
      if color:
        match = actioncompiled.search(colorline)
        line = colorline
      else:
        match = actioncompiled.search(nocolorline)
        line = nocolorline

      if match:
        # for every match we figure out what the expanded response
        # is and add it as an InputEvent in the queue.  the reason
        # we do a series of separate events rather than one big
        # event with ; separators is due to possible issues with 
        # braces and such in malformed responses.

        # get variables from the action
        actionvars = get_ordered_vars(action)

        # fill in values for all the variables in the match
        varvals = {}
        for i in range(len(actionvars)):
          varvals[actionvars[i]] = match.group(i+1)

        # add special variables
        varvals['a'] = line.replace(';', '_')
            
        # fill in response variables from those that
        # matched on the trigger
        response = utils.expand_vars(response, varvals)

        # event.InputEvent(response, internal=1, ses=self._ses).enqueue()
        try:
          exported.lyntin_command(response, internal=1, session=self._ses)
        except:
          exported.write_traceback()

        if onetime and action in self._actions:
          del self._actions[action]
          self._actionlist = None           # invalidate the list
Пример #5
0
def handle_timer(args):
	# tick tock
	global ticks
	
	for session in ticks.keys():
		ticks[session] += 1
		
		if ticks[session] >= 200:
			exported.write_message("You have been idle.", ses=session)
			exported.lyntin_command("#raw", internal=1, session=session)
			ticks[session] = 0
Пример #6
0
def loop_cmd(ses, args, input):
    """
  Executes a given command replacing %0 in the command with
  the range of numbers specified in <from> and <to>.

  example:
    #loop {1,4} {reclaim %0.corpse}

  will execute:
    reclaim 1.corpse
    reclaim 2.corpse
    reclaim 3.corpse
    reclaim 4.corpse

  A better way to execute a command a number of times without regard
  to an index, would be:

    #4 {reclaim corpse}

  which will send "reclaim corpse" to the mud 5 times.

  category: commands
  """
    loop = args["fromto"]
    command = args["comm"]

    # split it into parts
    looprange = loop.split(',')

    if len(looprange) != 2:
        exported.write_error("syntax: #loop <from,to> <command>", ses)
        return

    # remove trailing and leading whitespace and convert to ints
    # so we can use them in a range function
    ifrom = int(looprange[0].strip())
    ito = int(looprange[1].strip())

    # we need to handle backwards and forwards using the step
    # and need to adjust ito so the range is correctly bounded.
    if ifrom > ito:
        step = -1
    else:
        step = 1

    if ito > 0:
        ito = ito + step
    else:
        ito = ito - step

    for i in range(ifrom, ito, step):
        loopcommand = command.replace("%0", repr(i))
        exported.lyntin_command(loopcommand, internal=1, session=ses)
Пример #7
0
def loop_cmd(ses, args, input):
  """
  Executes a given command replacing %0 in the command with
  the range of numbers specified in <from> and <to>.

  example:
    #loop {1,4} {reclaim %0.corpse}

  will execute:
    reclaim 1.corpse
    reclaim 2.corpse
    reclaim 3.corpse
    reclaim 4.corpse

  A better way to execute a command a number of times without regard
  to an index, would be:

    #4 {reclaim corpse}

  which will send "reclaim corpse" to the mud 5 times.

  category: commands
  """
  loop = args["fromto"]
  command = args["comm"]

  # split it into parts
  looprange = loop.split(',')

  if len(looprange) != 2:    
    exported.write_error("syntax: #loop <from,to> <command>", ses)
    return

  # remove trailing and leading whitespace and convert to ints
  # so we can use them in a range function
  ifrom = int(looprange[0].strip())
  ito = int(looprange[1].strip())

  # we need to handle backwards and forwards using the step
  # and need to adjust ito so the range is correctly bounded.
  if ifrom > ito:
    step = -1
  else:
    step = 1

  if ito > 0:
    ito = ito + step
  else:
    ito = ito - step

  for i in range(ifrom, ito, step):
    loopcommand = command.replace("%0", repr(i))
    exported.lyntin_command(loopcommand, internal=1, session=ses)
Пример #8
0
def find_nmes(args):
    global targets,immd_tars,taking_inputs,exits,combat
    text= args['data']
    if taking_inputs == 'yes':
        for tar in targets:
            if tar in text:
                immd_tars.append(tar)
    if ">" in text and taking_inputs == 'yes':
        exported.write_message('\n these are my current targs'+ str(immd_tars))
        taking_inputs = 'no'
    if 'Exits' in text:
        found = re.search('\[ Exits: ([\w\s]+) \]',text)

        if found:
            exported.write_message('found exits are ' +found.group(0))
            exits.extend(found.group(1).split())
    health =re.search('(\d+/\d+)hp',text)
    if health:
        health = int(health.group(1).split('/')[0])

    if 'Fighting:' in text:
        if random.choice(range(3)) == 1:
            exported.lyntin_command('kick' if random.choice('kb')== 'k' else 'bash')
            exported.lyntin_command('dirt' if random.choice('es') == 'e' else 'stun')
        if random.choice(range(4)) == 1:
            exported.lyntin_command('intimidate')
        if health < 300 :
            exported.write_message('trying to flee \n')
            exported.lyntin_command('fle')
    return args['data']
Пример #9
0
    def timeUpdate(self, args):
        """
    This gets called by the timer_hook in the engine every
    second.  It goes through and executes all the events for this
    Lyntin tick as well as events who are supposed to execute at
    this seconds since the epoch or before.

    It also handles tossing events back in the schedule if they
    need repeating.
    """
        tick = args["tick"]

        events = []

        if self._events.has_key(tick):
            for mem in self._events[tick]:
                events.append(mem)

            del self._events[tick]

        self._current_tick = tick

        # we want to execute for this second and any previous seconds
        # that have been missed.
        sec = int(time.time())
        keys = self._tevents.keys()
        keys = [mem for mem in keys if mem < sec]
        for key in keys:
            for mem in self._tevents[key]:
                events.append(mem)
            del self._tevents[key]

        # go through and execute all the events we've found
        for mem in events:
            if not mem._quiet:
                exported.write_message("Executing %r." % mem)

            if not callable(mem._cmd):
                exported.lyntin_command(mem._cmd, internal=1, session=mem._ses)
            else:
                try:
                    mem._cmd(*mem._args, **mem._xargs)
                except:
                    exported.write_traceback(
                        "exception kicked up while trying to execute event.")

            # handles repeating events
            if mem._repeat == 1:
                self.addEvent(tick + mem._offset, mem, id=mem._id)
Пример #10
0
    def _main(self):
        while self._running:
            try:
                cmd = self._queue.get()
            except KeyboardInterrupt:
                self._running = False

            self._queue.task_done()
            if not self._running:
                self._clear()
                break

            self._sent.append((cmd[0], cmd[1], time.time()))
            exported.lyntin_command(cmd[0].command(), internal=1)
            self.clear_sent()
Пример #11
0
  def timeUpdate(self, args):
    """
    This gets called by the timer_hook in the engine every
    second.  It goes through and executes all the events for this
    Lyntin tick as well as events who are supposed to execute at
    this seconds since the epoch or before.

    It also handles tossing events back in the schedule if they
    need repeating.
    """
    tick = args["tick"]

    events = []

    if self._events.has_key(tick):
      for mem in self._events[tick]:
        events.append(mem)

      del self._events[tick]

    self._current_tick = tick

    # we want to execute for this second and any previous seconds
    # that have been missed.
    sec = int(time.time())
    keys = self._tevents.keys()
    keys = [mem for mem in keys if mem < sec]
    for key in keys:
      for mem in self._tevents[key]:
        events.append(mem)
      del self._tevents[key]

    # go through and execute all the events we've found
    for mem in events:
      if not mem._quiet:
        exported.write_message("Executing %r." % mem)

      if not callable(mem._cmd):
        exported.lyntin_command(mem._cmd, internal=1, session=mem._ses)
      else:
        try:
          mem._cmd(*mem._args, **mem._xargs)
        except:
          exported.write_traceback("exception kicked up while trying to execute event.")

      # handles repeating events
      if mem._repeat == 1:
        self.addEvent(tick + mem._offset, mem, id=mem._id)
Пример #12
0
 def receiver(self, sock):
     #session = exported.get_current_session()
     while True:
         try:
             data = sock.recv(4096)
             #session.handle_user_data(data.decode(settings.PROXY_ENCODING))
             if len(data) == 0:
                 exported.write_message(
                     "SowMud Proxy: DEBUG: client lost in receive")
                 return
             data = data.strip()
             exported.lyntin_command(data.decode(settings.PROXY_ENCODING))
         except:
             exported.write_message(
                 "SowMud Proxy: DEBUG: client lost in receive")
             self.remove_client(sock)
             return
Пример #13
0
def find_nmes(args):
    global exits_line,targets
    text= args['data']
    if "[ Exits:" in text:
        exits_line = 1
    if exits_line == 1:
        found = re.search('A (\w+ )',text)
        if found:
            targets.append(found.group(1))


    if '>' in text:
        exported.write_message('my targets: '+''.join(targets))
        exits_line = 0
    if '[Fighting: ' in text:
        exported.lyntin_command('kick' if random.choice('kb')== 'k' else 'bash')
    return args['data']
def find_nmes(args):
    global conned,targets
    text= args['data']
    if conned ==1:
        found = re.search('A|An (\w+ )',text)
        if found:
            targets.append(found.group(1))
            exported.write_message(str(targets))

    if targets:
        if '>' in text:
            exported.write_message('my targets: '+''.join(targets))
            conned = 0
    if '[Fighting: ' in text:
        exported.write_message('trying move')
        exported.lyntin_command('kick' if random.choice('kb')== 'k' else 'bash')
    return args['data']
Пример #15
0
  def userfilter(self, args):
    """
    user_filter_hook for handling incoming user data.
    """
    ses = args["session"]
    internal = args["internal"]
    verbatim = args["verbatim"]
    text = args["dataadj"]

    if verbatim == 1:
      return text

    varexpansion = self.expand_command(ses, text)

    if varexpansion == text:
      return text
    else:
      exported.lyntin_command(varexpansion, 1, ses)
      return None
Пример #16
0
    def userfilter(self, args):
        """
    user_filter_hook for handling incoming user data.
    """
        ses = args["session"]
        internal = args["internal"]
        verbatim = args["verbatim"]
        text = args["dataadj"]

        if verbatim == 1:
            return text

        varexpansion = self.expand_command(ses, text)

        if varexpansion == text:
            return text
        else:
            exported.lyntin_command(varexpansion, 1, ses)
            return None
Пример #17
0
def recur(direc):
    global current,coords,no_go
    exported.write_message('going to move:'+direc)
    exported.lyntin_command(direc)
    if no_go:
        no_go = False
        with open('path_text.txt','a') as phile:
            phile.write(coords)
            coords.pop()
        return
    else:
        if direc == 'n':
            current = (coords[-1][0],coords[-1][1]+1)
        if direc == 'e':
            current = (coords[-1][0]+1,coords[-1][1])
        if direc == 'w':
            current = (coords[-1][0]-1,coords[-1][1])
        if direc == 's':
            current = (coords[-1][0],coords[-1][1]-1)
    for move in 'nesw':
        recur(move)
Пример #18
0
    def userfilter(self, args):
        """
    user_filter_hook function to check for speedwalking expansion.
    """
        ses = args["session"]
        internal = args["internal"]
        verbatim = args["verbatim"]
        text = args["dataadj"]

        if not self._hashes.has_key(ses) or exported.get_config(
                "speedwalk", ses) == 0 or verbatim == 1:
            return text

        sdata = self._hashes[ses]

        if not sdata._dirs or not sdata._regexp or text in sdata._excludes \
            or text in sdata._aliases or not sdata._regexp.match(text):
            return text

        swdirs = []
        dir = num = ""
        for char in text:
            if char.isdigit():
                num = num + char
            else:
                dir = dir + char
                if dir in sdata._dirs_available:
                    if num: count = int(num)
                    else: count = 1
                    for i in range(count):
                        swdirs.append(sdata._dirs[dir])
                    dir = num = ""

        output = ";".join(swdirs)
        if output == text:
            return text
        else:
            # anything that gets recursed on should be recursed internally
            exported.lyntin_command(output, 1, ses)
            return None
Пример #19
0
def handle_from_mud(args):
	global sessions
	
	if not args['session'] in sessions:
		return
	
	if not sessions[args['session']]['matched_room']:
		if "speaks from the" not in args['data']:
			# let's not waste time on this regex if we're not looking for room name
			m = re.match(r'((o|\*) HP:\w+ MV:\w+ > |)\033\[36m(.*)\033\[0m$', args['data'])
			
			if m:
				# matched room name
				sessions[args['session']]['matched_room'] = True
				exported.lyntin_command("#var {room_name} {%s} quiet=true" % m.group(3), internal=1, session=args['session'])
				sessions[args['session']]['room_name'] = m.group(3)
				sessions[args['session']]['room_desc'] = ""
				sessions[args['session']]['room_exit'] = ""
	else:
		# now we should be looking for exits, anything before that is room desc
		m = re.match('^\\[ obvious exits:(.*)\\]$', args['data'])
		if m:
			# got the exit line
			sessions[args['session']]['room_exit'] = m.group(1).strip()
			sessions[args['session']]['room_desc'] = sessions[args['session']]['room_desc'].rstrip('\n')
			exported.lyntin_command("#var {room_desc} {%s} quiet=true" % sessions[args['session']]['room_desc'], internal=1, session=args['session'])
			exported.lyntin_command("#var {room_exits} {%s} quiet=true" % m.group(1).strip(), internal=1, session=args['session'])
			sessions[args['session']]['matched_room'] = False
		else:
			# it's a desc line
			sessions[args['session']]['room_desc'] += args['data']
Пример #20
0
  def userfilter(self, args):
    """ 
    user_filter_hook.
    """
    # we check for aliases here--and if we find some, we
    # do the variable expansion and then recurse over the result
    ses = args["session"]
    internal = args["internal"]
    verbatim = args["verbatim"]
    text = args["dataadj"]
  
    if not self._aliasdata.has_key(ses) or verbatim == 1:
      return text

    aliasexpansion = self._aliasdata[ses].expand(text)

    if not aliasexpansion:
      return text
    else:
      aliasexpansion = utils.expand_placement_vars(text, aliasexpansion)
      exported.lyntin_command(aliasexpansion, 1, ses)
      return None
Пример #21
0
  def userfilter(self, args):
    """ 
    user_filter_hook.
    """
    # we check for aliases here--and if we find some, we
    # do the variable expansion and then recurse over the result
    ses = args["session"]
    internal = args["internal"]
    verbatim = args["verbatim"]
    text = args["dataadj"]
  
    if ses not in self._aliasdata or verbatim == 1:
      return text

    aliasexpansion = self._aliasdata[ses].expand(text)

    if not aliasexpansion:
      return text
    else:
      aliasexpansion = utils.expand_placement_vars(text, aliasexpansion)
      exported.lyntin_command(aliasexpansion, 1, ses)
      return None
Пример #22
0
  def userfilter(self, args):
    """
    user_filter_hook function to check for speedwalking expansion.
    """
    ses = args["session"]
    internal = args["internal"]
    verbatim = args["verbatim"]
    text = args["dataadj"]
    
    if not self._hashes.has_key(ses) or exported.get_config("speedwalk", ses) == 0 or verbatim == 1:
      return text

    sdata = self._hashes[ses]

    if not sdata._dirs or not sdata._regexp or text in sdata._excludes \
        or text in sdata._aliases or not sdata._regexp.match(text):
      return text
    
    swdirs = []
    dir = num = ""
    for char in text:
      if char.isdigit():
        num = num + char
      else:
        dir = dir + char
        if dir in sdata._dirs_available:
          if num: count = int(num)
          else: count = 1
          for i in range(count):
            swdirs.append(sdata._dirs[dir])
          dir = num = ""
    
    output = ";".join(swdirs)
    if output == text:
      return text
    else:
      # anything that gets recursed on should be recursed internally
      exported.lyntin_command(output, 1, ses)
      return None
def get_targs():
    global targets,conned
    if targets:
        exported.lyntin_command('kill '+ targets.pop())
    else:
        exported.lyntin_command(random.choice('eswn'))
        exported.lyntin_command('con all')
        conned = 1
Пример #24
0
def if_cmd(ses, args, input):
  """
  Allows you to do some boolean logic based on Lyntin variables
  or any Python expression.  If this expression returns a non-false
  value, then the action will be performed otherwise the elseaction
  (if there is one) will be peformed.

  examples:
    #if {$myhpvar < 100} {#showme PANIC!}
    #if {$myhpvar < 100 && $myspvar < 100} {#showme PANIC!}
    #if {'$name' == 'Joe'} {#showme That joe is a jerk.}

  When you're comparing variable values with other strings, make sure 
  to put them in quotes becuase variable expansion happens before
  the if command is evaluated.

  examples:
    WRONG: #if {$name == Joe} {#showme Joe is a jerk.}
    RIGHT: #if {'$name' == 'Joe'} {#showme Joe is a jerk.}

  category: commands
  """
  # original if_cmd code contributed by Sebastian John

  expr = args["expr"]
  action = args["action"]
  elseaction = args["elseaction"]

  try:
    if eval(expr):
      exported.lyntin_command(action, 1, ses)
    elif elseaction:
      exported.lyntin_command(elseaction, 1, ses)
  except SyntaxError:
    exported.write_error("if: invalid syntax / syntax error.", ses)
  except Exception, e:
    exported.write_error("if: exception: %s" % e, ses)
Пример #25
0
def if_cmd(ses, args, input):
    """
  Allows you to do some boolean logic based on Lyntin variables
  or any Python expression.  If this expression returns a non-false
  value, then the action will be performed otherwise the elseaction
  (if there is one) will be peformed.

  examples:
    #if {$myhpvar < 100} {#showme PANIC!}
    #if {$myhpvar < 100 and $myspvar < 100} {#showme PANIC!}
    #if {'$name' == 'Joe'} {#showme That joe is a jerk.}

  When you're comparing variable values with other strings, make sure 
  to put them in quotes becuase variable expansion happens before
  the if command is evaluated.

  examples:
    WRONG: #if {$name == Joe} {#showme Joe is a jerk.}
    RIGHT: #if {'$name' == 'Joe'} {#showme Joe is a jerk.}

  category: commands
  """
    # original if_cmd code contributed by Sebastian John

    expr = args["expr"]
    action = args["action"]
    elseaction = args["elseaction"]

    try:
        if eval(expr):
            exported.lyntin_command(action, 1, ses)
        elif elseaction:
            exported.lyntin_command(elseaction, 1, ses)
    except SyntaxError:
        exported.write_error("if: invalid syntax / syntax error.", ses)
    except Exception, e:
        exported.write_error("if: exception: %s" % e, ses)
Пример #26
0
    def do_command(self, e, cmd):
        if cmd == "disconnect":
            exported.lyntin_command("#zap")

        if cmd == "smile":
            exported.lyntin_command("улыбнуться", internal=1)

        if cmd == "connect":
            r = random.randint(0, 10)
            exported.lyntin_command("#session a{0} sowmud.ru 5555".format(r))
Пример #27
0
def get_targs():
    global immd_tars,taking_inputs,exits
    if immd_tars:
        exported.lyntin_command('kill '+ immd_tars.pop())
        exported.write_message('\nthese are current tars '+ str(immd_tars))
    else:
        if exits:
            exported.lyntin_command(random.choice(exits))
            taking_inputs = 'yes'
            exits = []
        else:
            exported.lyntin_command(random.choice('eswn'))
            taking_inputs = 'yes'
Пример #28
0
def display_ingr():
  global quest
  for k, v in quest.items():
    mobs = ", ".join(v)
    exported.lyntin_command("gtell |{:^25}: {mobs}".format(k, mobs=mobs))
  quest = {}
Пример #29
0
def main(defaultoptions={}):
  """
  This parses the command line arguments and makes sure they're all valid,
  instantiates a ui, does some setup, spins off an engine thread, and
  goes into the ui's mainloop.

  @param defaultoptions: the boot options to use.  we update the 
      config.options dict with these options--this is the easiest
      way to override the ui, moduledir, datadir, et al from a
      Lyntin run script.
  @type  defaultoptions: dict
  """
  try:
    import sys, os, traceback, ConfigParser
    from lyntin import config, event, utils, exported
    from lyntin.ui import base
    import locale

    locale.setlocale(locale.LC_ALL, '')

    config.options.update(defaultoptions)

    # read through options and arguments
    optlist = utils.parse_args(sys.argv[1:])

    for mem in optlist:
      if mem[0] == '--help':
        print constants.HELPTEXT
        sys.exit(0)

      elif mem[0] == '--version':
        print constants.VERSION
        sys.exit(0)

      elif mem[0] in ["--configuration", "-c"]:
        # ini files OVERRIDE the default options
        # they can provide multiple ini files, but each new
        # ini file will OVERRIDE the contents of the previous ini file
        # where the two files intersect.
        parser = ConfigParser.ConfigParser()
        parser.read([mem[1]])

        newoptions = {}
        for s in parser.sections():
          for o in parser.options(s):
            c = parser.get(s, o).split(",")
            if newoptions.has_key(o):
              newoptions[o] += c
            else:
              newoptions[o] = c
            
        config.options.update(newoptions)

      else:
        opt = mem[0]
        while opt.startswith("-"):
          opt = opt[1:]

        if len(opt) > 0:
          if config.options.has_key(opt):
            if type(config.options[opt]) is list:
              config.options[opt].append(mem[1])
            else:
              config.options[opt] = mem[1]
          else:
            config.options[opt] = [mem[1]]

    for mem in ["datadir", "ui", "commandchar"]:
      if config.options.has_key(mem) and type(config.options[mem]) is list:
        config.options[mem] = config.options[mem][0]

    # if they haven't set the datadir via the command line, then
    # we go see if they have a HOME in their environment variables....
    if not config.options["datadir"]:
      if os.environ.has_key("HOME"):
        config.options["datadir"] = os.environ["HOME"]
    config.options["datadir"] = utils.fixdir(config.options["datadir"])

    def on_shutdown():
      """
      This gets called by the Python interpreter atexit.  The reason
      we do shutdown stuff here is we're more likely to catch things
      here than we are to let everything cycle through the 
      ShutdownEvent.  This should probably get fixed up at some point
      in the future.
      """
      if not hasattr(sys, 'frozen'):
        sys.stderr.write("goodbye.\n")
      #exported.hook_spam("shutdown_hook", {})
    import atexit
    atexit.register(on_shutdown)

    # instantiate the engine
    Engine.instance = Engine()
    exported.myengine = Engine.instance
    Engine.instance._setupConfiguration()

    # instantiate the ui
    uiinstance = None
    try:
      uiname = str(config.options['ui'])
      modulename = uiname + "ui"
      uiinstance = base.get_ui(modulename)
      if not uiinstance:
        raise ValueError("No ui instance.")
    except Exception, e:
      print "Cannot start '%s': %s" % (uiname, e)
      traceback.print_exc()
      sys.exit(0)

    Engine.instance.setUI(uiinstance)

    # do some more silly initialization stuff
    # adds the .lyntinrc file to the readfile list if it exists.
    if config.options["datadir"]:
      lyntinrcfile = config.options["datadir"] + ".lyntinrc"
      if os.path.exists(lyntinrcfile):
        # we want the .lyntinrc file read in first, so then other
        # files can overwrite the contents therein
        config.options['readfile'].insert(0, lyntinrcfile)
  
    # import modules listed in modulesinit
    exported.write_message("Loading Lyntin modules.")
  
    try:
      import lyntin.modules
      lyntin.modules.load_modules()
    except:
      exported.write_traceback("Modules did not load correctly.")
      sys.exit(1)
  
    commandchar = Engine.instance._managers["config"].get("commandchar")

    # handle command files
    for mem in config.options['readfile']:
      exported.write_message("Reading in file " + mem)
      # we have to escape windows os separators because \ has a specific
      # meaning in the argparser
      mem = mem.replace("\\", "\\\\")
      exported.lyntin_command("%sread %s" % (commandchar, mem), internal=1)
  
    # spam the startup hook 
    exported.hook_spam("startup_hook", {})
  
    # we're done initialization!
    exported.write_message(constants.STARTUPTEXT)
    Engine.instance.writePrompt()

    engine_thread = Engine.instance.startthread("engine", Engine.instance.runengine)
    timer_thread = Engine.instance.startthread("timer", Engine.instance.runtimer)
    try:
      Engine.instance._ui.runui()
    finally:
      if not hasattr(sys, 'frozen'):
        sys.stderr.write("Shutting down...")
      event.ShutdownEvent().enqueue()
      engine_thread.join(10)
      timer_thread.join(10)
Пример #30
0
def main(defaultoptions={}):
    """
  This parses the command line arguments and makes sure they're all valid,
  instantiates a ui, does some setup, spins off an engine thread, and
  goes into the ui's mainloop.

  @param defaultoptions: the boot options to use.  we update the 
      config.options dict with these options--this is the easiest
      way to override the ui, moduledir, datadir, et al from a
      Lyntin run script.
  @type  defaultoptions: dict
  """
    try:
        import sys, os, traceback, ConfigParser
        from lyntin import config, event, utils, exported
        from lyntin.ui import base
        import locale

        locale.setlocale(locale.LC_ALL, '')

        config.options.update(defaultoptions)

        # read through options and arguments
        optlist = utils.parse_args(sys.argv[1:])

        for mem in optlist:
            if mem[0] == '--help':
                print constants.HELPTEXT
                sys.exit(0)

            elif mem[0] == '--version':
                print constants.VERSION
                sys.exit(0)

            elif mem[0] in ["--configuration", "-c"]:
                # ini files OVERRIDE the default options
                # they can provide multiple ini files, but each new
                # ini file will OVERRIDE the contents of the previous ini file
                # where the two files intersect.
                parser = ConfigParser.ConfigParser()
                parser.read([mem[1]])

                newoptions = {}
                for s in parser.sections():
                    for o in parser.options(s):
                        c = parser.get(s, o).split(",")
                        if newoptions.has_key(o):
                            newoptions[o] += c
                        else:
                            newoptions[o] = c

                config.options.update(newoptions)

            else:
                opt = mem[0]
                while opt.startswith("-"):
                    opt = opt[1:]

                if len(opt) > 0:
                    if config.options.has_key(opt):
                        if type(config.options[opt]) is list:
                            config.options[opt].append(mem[1])
                        else:
                            config.options[opt] = mem[1]
                    else:
                        config.options[opt] = [mem[1]]

        for mem in ["datadir", "ui", "commandchar"]:
            if config.options.has_key(mem) and type(
                    config.options[mem]) is list:
                config.options[mem] = config.options[mem][0]

        # if they haven't set the datadir via the command line, then
        # we go see if they have a HOME in their environment variables....
        if not config.options["datadir"]:
            if os.environ.has_key("HOME"):
                config.options["datadir"] = os.environ["HOME"]
        config.options["datadir"] = utils.fixdir(config.options["datadir"])

        def on_shutdown():
            """
      This gets called by the Python interpreter atexit.  The reason
      we do shutdown stuff here is we're more likely to catch things
      here than we are to let everything cycle through the 
      ShutdownEvent.  This should probably get fixed up at some point
      in the future.
      """
            sys.stderr.write("goodbye.\n")
            #exported.hook_spam("shutdown_hook", {})

        import atexit
        atexit.register(on_shutdown)

        # instantiate the engine
        Engine.instance = Engine()
        exported.myengine = Engine.instance
        Engine.instance._setupConfiguration()

        # instantiate the ui
        uiinstance = None
        try:
            uiname = str(config.options['ui'])
            modulename = uiname + "ui"
            uiinstance = base.get_ui(modulename)
            if not uiinstance:
                raise ValueError("No ui instance.")
        except Exception, e:
            print "Cannot start '%s': %s" % (uiname, e)
            traceback.print_exc()
            sys.exit(0)

        Engine.instance.setUI(uiinstance)

        # do some more silly initialization stuff
        # adds the .lyntinrc file to the readfile list if it exists.
        if config.options["datadir"]:
            lyntinrcfile = config.options["datadir"] + ".lyntinrc"
            if os.path.exists(lyntinrcfile):
                # we want the .lyntinrc file read in first, so then other
                # files can overwrite the contents therein
                config.options['readfile'].insert(0, lyntinrcfile)

        # import modules listed in modulesinit
        exported.write_message("Loading Lyntin modules.")

        try:
            import modules.__init__
            modules.__init__.load_modules()
        except:
            exported.write_traceback("Modules did not load correctly.")
            sys.exit(1)

        # spam the startup hook
        exported.hook_spam("startup_hook", {})

        commandchar = Engine.instance._managers["config"].get("commandchar")

        # handle command files
        for mem in config.options['readfile']:
            exported.write_message("Reading in file " + mem)
            # we have to escape windows os separators because \ has a specific
            # meaning in the argparser
            mem = mem.replace("\\", "\\\\")
            exported.lyntin_command("%sread %s" % (commandchar, mem),
                                    internal=1)

        # we're done initialization!
        exported.write_message(constants.STARTUPTEXT)
        Engine.instance.writePrompt()

        engine_thread = Engine.instance.startthread("engine",
                                                    Engine.instance.runengine)
        timer_thread = Engine.instance.startthread("timer",
                                                   Engine.instance.runtimer)
        try:
            Engine.instance._ui.runui()
        finally:
            sys.stderr.write("Shutting down...")
            event.ShutdownEvent().enqueue()
            engine_thread.join(10)
            timer_thread.join(10)
Пример #31
0
def remove(ses,args,input):
    global module
    exported.lyntin_command('-unload '+module)
Пример #32
0
 def handleinput(self, line, internal=0):
     self._append([(line + "\n", self.attr_user_)])
     if internal:
         exported.lyntin_command(line, internal=1)
     else:
         base.BaseUI.handleinput(self, line)
Пример #33
0
def join_cir(ses,args,input):
    name = args ['value']
    exported.lyntin_command('#session {} localhost 4000'.format(name))
Пример #34
0
def select_and_move():
    movement_choice = random.choice(movement_list)
    exported.write_message(movement_choice)
    exported.lyntin_command('exits')
#    start_wander = time.time()
    exported.lyntin_command(movement_choice)
Пример #35
0
def find_nmes(args):
    global exits_line,targets
    text= args['data']
    if "[ Exits:" in text:
        exits_line = 1
    if exits_line == 1:
        found = re.search('[A|An] (\w+) ',text)
        if found:
            exported.write_message(targets)
            targets.append(found.group(1))


    if '>' in text:
        exits_line = 0
        try:
            if health< 500:
                exported.lyntin_command('treat')
        except:
            pass
    health =re.search('(\d+/\d+)hp',text)
    if health:
        health = int(health.group(1).split('/')[0])

    if 'Fighting:' in text:
        if random.choice(range(7)) == 1:
            exported.lyntin_command('kick' if random.choice('kb')== 'k' else 'bash')
            exported.lyntin_command('dirt' if random.choice('es') == 'e' else 'stun')
        if random.choice(range(7)) == 1:
            exported.lyntin_command('intimidate')
        if health < 300 :
            exported.write_message('trying to flee \n')
            exported.lyntin_command('flee')
        if health < 100 :
            exported.lyntin_command('fle')
    return args['data']
Пример #36
0
def go_getem(ses,args,input):
    if presence == 'yes' and target != None:
        exported.lyntin_command('kill '+target)
Пример #37
0
            f.close()
    except Exception, e:
        exported.write_error(
            "read: file %s cannot be opened.\n%s" % (filename, e), ses)
        return

    contents = [m for m in contents if len(m.strip()) > 0]

    if len(contents) == 0:
        exported.write_message("read: %s had no data." % filename, ses)
        return

    c = exported.get_config("commandchar")
    if not contents[0].startswith(c):
        exported.lyntin_command("%sconfig commandchar %s" %
                                (c, contents[0][0]),
                                internal=1,
                                session=ses)

    command = ""
    continued = 0
    # FIXME - should this be a config setting?
    esc = "\\"

    for mem in contents:
        mem = mem.strip()
        if len(mem) > 0:
            # handle multi-line commands
            if mem.endswith(esc):
                mem = mem.rstrip(esc)
                continued = 1
            else:
Пример #38
0
 def handleinput(self, line, internal=0):
   self._append( [ (line+"\n", self.attr_user_) ] )
   if internal:
     exported.lyntin_command(line, internal=1)
   else:  
     base.BaseUI.handleinput(self, line)
Пример #39
0
def ifvar_cmd(session, args, input):
    if args['variable'] in session._vars.keys():
        exported.lyntin_command(args['action'], 1, session)
    elif args['elseaction']:
        exported.lyntin_command(args['elseaction'], 1, session)
Пример #40
0
 def reconnect(self, args):
   prev_ses = args['session'].getName()
   self.turn_off()
   exported.write_message("disconnected from SoW, {0}".format(prev_ses))
   exported.lyntin_command("#session a{0} sowmud.ru 5555".format(prev_ses))
Пример #41
0
def timerget(args):
    tick = args["tick"]
    if tick:
        if tick % random.choice(range(4, 10)) == 0:
            exported.lyntin_command(random.choice("eswn"))
    return tick
Пример #42
0
def commo_cmd(session, args, input):
	if args['action'] == "add":
		if not session in sessions:
			f = open(config.options['datadir'] + session.getName() + '-comms', 'w')
			sessions[session] = f
			exported.lyntin_command("#showme Session %s now monitored by comms logger" % session.getName(), True, session)
		else:
			exported.lyntin_command("#showme Session %s already monitored by comms logger" % session.getName(), True, session)
	elif args['action'] == "remove":
		if session in sessions:
			sessions[session].close()
			del sessions[session]
			exported.lyntin_command("#showme Session %s no longer monitored by comms logger" % session.getName(), True, session)
		else:
			exported.lyntin_command("#showme Session %s isn't monitored by comms logger" % session.getName(), True, session)
	elif args['action'] == "":
		if len(sessions):
			exported.lyntin_command("#showme Sessions monitored by comms logger:", True, session)
			for s in sessions:
				exported.lyntin_command("#showme %s" % s.getName(), True, session)
		else:
			exported.lyntin_command("#showme No sessions currently monitored by comms logger", True, session)
Пример #43
0
  def execute(self):
    """ Execute."""
    if not self._internal:
      exported.write_user_data(self._input)

    exported.lyntin_command(self._input, internal=self._internal, session=self._ses)
Пример #44
0
      f = open(filename, "r")
      contents = f.readlines()
      f.close()
  except Exception, e:
    exported.write_error("read: file %s cannot be opened.\n%s" % (filename, e), ses)
    return

  contents = [m for m in contents if len(m.strip()) > 0]

  if len(contents) == 0:
    exported.write_message("read: %s had no data." % filename, ses)
    return

  c = exported.get_config("commandchar")
  if not contents[0].startswith(c):
    exported.lyntin_command("%sconfig commandchar %s" % (c, contents[0][0]), internal=1, session=ses)

  command = ""
  continued = 0
  # FIXME - should this be a config setting?
  esc = "\\"

  for mem in contents:
    mem = mem.strip()
    if len(mem) > 0:
      # handle multi-line commands
      if mem.endswith(esc):
        mem = mem.rstrip(esc)
        continued = 1
      else:
        continued = 0
Пример #45
0
def test_load(ses,args,input):
    global module
    module = args['value']
    exported.lyntin_command('-load '+ module)
Пример #46
0
  def checkActions(self, text):
    """
    Checks to see if text triggered any actions.  Any resulting 
    actions will get added as an InputEvent to the queue.

    @param text: the data coming from the mud to check for triggers
    @type  text: string
    """
    # FIXME - make sure this works even when lines are broken up.

    actionlist = self._actionlist
    if not actionlist:
      actionlist = filter(lambda x: not self._disabled.has_key(x[6]),
                          self._actions.values())
      actionlist.sort(key=lambda i: i[3])
      self._actionlist = actionlist

    colorline = utils.filter_cm(text)
    nocolorline = ansi.filter_ansi(colorline)

    # go through all the lines in the data and see if we have
    # any matches
    for (action, actioncompiled, response, color, priority, onetime, tag) in actionlist:
      if color:
        match = actioncompiled.search(colorline)
        line = colorline
      else:
        match = actioncompiled.search(nocolorline)
        line = nocolorline

      if match:
        # for every match we figure out what the expanded response
        # is and add it as an InputEvent in the queue.  the reason
        # we do a series of separate events rather than one big
        # event with ; separators is due to possible issues with 
        # braces and such in malformed responses.

        # fill in values for all the variables in the match
        varvals = {}
        if match.lastindex is not None:
          if action.startswith('r['):
            for i in xrange(match.lastindex):
              varvals[str(i+1)] = match.group(i+1)
          else:
            # get variables from the action
            actionvars = get_ordered_vars(action)
            for i in xrange(len(actionvars)):
              varvals[actionvars[i]] = match.group(i+1)

        # add special variables
        varvals['a'] = line.replace(';', '_')
            
        # fill in response variables from those that
        # matched on the trigger
        response = utils.expand_vars(response, varvals)

        # event.InputEvent(response, internal=1, ses=self._ses).enqueue()
        try:
          exported.lyntin_command(response, internal=1, session=self._ses)
        except:
          exported.write_traceback()

        if onetime and self._actions.has_key(action):
          del self._actions[action]
          self._actionlist = None           # invalidate the list
Пример #47
0
def read_cmd(ses, args, input):
    """
  Reads in a file running each line as a Lyntin command.  This is the
  opposite of #write which allows you to save session settings and
  restore them using #read.

  You can also read in via the commandline when you start Lyntin:

    lyntin --read 3k

  And read can handle HTTP urls:

    lyntin --read http://lyntin.sourceforge.net/lyntinrc

    #read http://lyntin.sourceforge.net/lyntinrc

  Note: the first non-whitespace char is used to set the Lyntin
  command character.  If you use non Lyntin commands in your file,
  make sure the first one is a command char.  If not, use #nop .
  It will skip blank lines.

  If you don't specify a directory, Lyntin will look for the file
  in your datadir.

  category: commands
  """
    filename = args["filename"]

    import os
    if os.sep not in filename and not filename.startswith("http://"):
        filename = config.options["datadir"] + filename

    if filename.startswith("~"):
        filename = os.path.expanduser(filename)

    try:
        # http reading contributed by Sebastian John
        if filename.startswith("http://"):
            contents = utils.http_get(filename).split("\n")
        else:
            f = open(filename, "rb")
            contents = f.readlines()
            f.close()
    except Exception as e:
        exported.write_error(
            "read: file %s cannot be opened.\n%s" % (filename, e), ses)
        return

    contents = [x.decode("utf-8") for x in contents]
    contents = [m for m in contents if len(m.strip()) > 0]

    if len(contents) == 0:
        exported.write_message("read: %s had no data." % filename, ses)
        return

    c = exported.get_config("commandchar")
    if not contents[0].startswith(c):
        exported.lyntin_command("%sconfig commandchar %s" %
                                (c, contents[0][0]),
                                internal=1,
                                session=ses)

    command = ""
    continued = 0
    # FIXME - should this be a config setting?
    esc = "\\"

    for mem in contents:
        mem = mem.strip()
        if len(mem) > 0:
            # handle multi-line commands
            if mem.endswith(esc):
                mem = mem.rstrip(esc)
                continued = 1
            else:
                continued = 0

        command = command + mem
        if not continued:
            exported.lyntin_command(command, internal=1, session=ses)
            command = ""

    exported.write_message("read: file %s read." % filename, ses)
Пример #48
0
def treat():
    exported.lyntin_command('-4 treat')
Пример #49
0
def loop_cmd(ses, args, input):
    """
  Executes a given command replacing %0 in the command with
  the range of numbers specified in <from> and <to>.

  example:
    #loop {1,4} {reclaim %0.corpse}

  will execute:
    reclaim 1.corpse
    reclaim 2.corpse
    reclaim 3.corpse
    reclaim 4.corpse

  Additionally, it can iterate over a comma-separated string of items:

  example:
    #loop {joe,harry,fred,pete} {say hi, %0.} range=no

  will execute:

    say hi, joe.
    say hi, harry.
    say hi, fred.
    say hi, pete.

  A better way to execute a command a number of times without regard
  to an index, would be:

    #4 {reclaim corpse}

  which will send "reclaim corpse" to the mud 5 times.

  category: commands
  """
    loop = args["fromto"]
    command = args["comm"]
    r = args["range"]

    # split it into parts
    loopitems = loop.split(',')

    if r:
        if len(loopitems) != 2:
            exported.write_error("syntax: #loop <from,to> <command>", ses)
            return

        # remove trailing and leading whitespace and convert to ints
        # so we can use them in a range function
        ifrom = int(loopitems[0].strip())
        ito = int(loopitems[1].strip())

        # we need to handle backwards and forwards using the step
        # and need to adjust ito so the range is correctly bounded.
        if ifrom > ito:
            step = -1
        else:
            step = 1

        if ito > 0:
            ito = ito + step
        else:
            ito = ito - step

        loopitems = list(range(ifrom, ito, step))
        loopitems = [repr(m) for m in loopitems]
        # for i in range(ifrom, ito, step):
        #   loopcommand = command.replace("%0", repr(i))
        #   exported.lyntin_command(loopcommand, internal=1, session=ses)

    for mem in loopitems:
        mem = mem.strip()
        loopcommand = command.replace("%0", mem)
        exported.lyntin_command(loopcommand, internal=1, session=ses)