modulecore.py

Wed, 31 Dec 2014 15:49:11 -0500

author
Teemu Piippo <crimsondusk64@gmail.com>
date
Wed, 31 Dec 2014 15:49:11 -0500
changeset 114
0d1fd111cb22
parent 113
08e9b1c1b324
child 115
2bb5c4578ee1
permissions
-rw-r--r--

- .idgames now works with the page system

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)

		print "Loaded module %s" % fn

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

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

#
# is_available (cmd, ident, host)
#
# Is the given command available to the given user?
#
def is_available (cmd, ident, host):
	if cmd['level'] == 'admin' \
	and not "%s@%s" % (ident, host) in Config.get_value ('admins', default=[]):
		return False

	return True

#
# response_function
#
g_responsePages = [[]]
g_responsePageNum = 0

def response_function (message):
	global g_responsePages

	if len (g_responsePages[-1]) > 4:
		g_responsePages.append ([message])
	else:
		g_responsePages[-1].append (message)

def print_responses (bot, replyto):
	global g_responsePages
	global g_responsePageNum

	# Check bounds
	if g_responsePageNum >= len (g_responsePages):
		bot.privmsg (replyto, "No more messages.")
		return

	# Print this page
	for line in g_responsePages[g_responsePageNum]:
		bot.privmsg (replyto, line)

	# Advance page cursor
	g_responsePageNum += 1

	# If this was not the last page, tell the user there's more
	if g_responsePageNum != len (g_responsePages):
		num = (len (g_responsePages) - g_responsePageNum)
		bot.privmsg (replyto, "%d more page%s, use .more to continue output" \
			% (num, 's' if num != 1 else ''))

#
# call_command (bot, message, cmdname, **kvargs)
#
# Calls a cobalt command
#
def call_command (bot, message, cmdname, **kvargs):
	global g_responsePages
	global g_responsePageNum

	try:
		cmd = Commands[cmdname]
	except KeyError:
		return False
	
	if not is_available (cmd, kvargs['ident'], kvargs['host']):
		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']))

	# .more is special as it is an interface to the page system.
	# Anything else resets it.
	if cmdname != 'more':
		g_responsePages = [[]]
		g_responsePageNum = 0

	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, reply=response_function, **kvargs)

	# Print the first page of responses.
	if cmdname != 'more':
		print_responses (bot, kvargs['replyto'])

	return True

#
# get_available_commands
#
# Gets a list of commands available to the given user
#
def get_available_commands (ident, host):
	result=[]

	for cmdname,cmd in Commands.iteritems():
		if not is_available (cmd, ident, host):
			continue

		result.append (cmdname)

	return result

#
# get_command_by_name
#
# Gets a command by name
#
def get_command_by_name (name):
	try:
		return Commands[name]
	except:
		return None

#
# 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