modulecore.py

Fri, 28 Nov 2014 22:45:55 -0500

author
Teemu Piippo <crimsondusk64@gmail.com>
date
Fri, 28 Nov 2014 22:45:55 -0500
changeset 94
2c93636202a5
parent 73
d67cc4fbc3f1
child 102
2bad379cd416
permissions
-rw-r--r--

- argrrgh

import os
import re
from configfile import Config

Modules = {}
Commands = {}

class CommandError (Exception):
	def __init__ (self, value):
		self.value = value
	def __str__ (self):
		return self.value

#
# init_data()
#
# Initializes command module data
#
def init_data():
	global Commands
	global Modules
	files = os.listdir ('.')

	for fn in files:
		if fn[0:4] != 'mod_' or fn[-3:] != '.py':
			continue

		fn = fn[0:-3]
		globals = {}
		module = __import__ (fn)
		Modules[fn] = module

		for cmd in module.ModuleData['commands']:
			if cmd['args'] == None:
				cmd['args'] = ''

			cmd['module'] = module
			cmd['regex'] = make_regex (cmd['args'])
			cmd['argnames'] = []
			Commands[cmd['name']] = cmd

			for argname in cmd['args'].split (' '):
				argname = argname[1:-1]

				if argname[-3:] == '...':
					argname = argname[0:-3]

				if argname == '':
					continue

				cmd['argnames'].append (argname)
			#done
		#done

		print "Loaded module %s" % fn
	#done

	print 'Loaded %d commands in %d modules' % (len (Commands), len (Modules))
#enddef

#
# command_error (message)
#
# Raises a command error
#
def command_error (message):
	raise CommandError (message)

#
# call_command (bot, message, cmdname, **kvargs)
#
# Calls a cobalt command
#
def call_command (bot, message, cmdname, **kvargs):
	try:
		cmd = Commands[cmdname]
	except KeyError:
		return False
	
	if cmd['level'] == 'admin' \
	and not "%s@%s" % (kvargs['ident'], kvargs['host']) in Config.get_value ('admins', default=[]):
		command_error ("you may not use %s" % cmdname)
	
	match = re.compile (cmd['regex']).match (message)
	
	if match == None:
		# didn't match
		print "regex: %s" % cmd['regex']
		command_error ('invalid arguments\nusage: %s %s' % (cmd['name'], cmd['args']))
	
	i = 1
	args = {}

	for argname in cmd['argnames']:
		args[argname] = match.group (i)
		i += 1
	
	getattr (cmd['module'], "cmd_%s" % cmdname) (bot=bot, cmdname=cmdname, args=args, **kvargs)
	return True

#
# make_regex
#
# Takes the argument list and returns a corresponding regular expression
#
def make_regex (arglist):
	if arglist == None:
		return '^.+$'

	gotoptional = False
	gotvariadic = False
	regex = ''

	for arg in arglist.split (' '):
		if gotvariadic:
			raise CommandError ('variadic argument is not last')

		if arg == '':
			continue
		
		gotliteral = False

		if arg[0] == '[' and arg[-1] == ']':
			arg = arg[1:-1]
			gotoptional = True
		elif arg[0] == '<' and arg[-1] == '>':
			if gotoptional:
				raise CommandError ('mandatory argument after optional one')

			arg = arg[1:-1]
		else:
			gotliteral = True

		if arg[-3:] == '...':
			gotvariadic = True
			arg = arg[0:-3]

		if gotoptional == False:
			regex += '\s+'
		else:
			regex += '\s*'

		if gotliteral:
			regex += arg
		elif gotoptional:
			if gotvariadic:
				regex += r'(.*)'
			else:
				regex += r'([^ ]*)'
		else:
			if gotvariadic:
				regex += r'(.+)'
			else:
				regex += r'([^ ]+)'
		#fi
	#done

	return '^[^ ]+%s$' % regex
#enddef

mercurial