Download:
child 11:1be0d90ed46b
parent 9:88927ae72d71
10:9fa8b4b32368
Anton Shestakov <av6@dwimlabs.net>, Sat, 14 May 2016 14:05:49 +0800
rollbot: help command that can list available commands and explain their usage

1 файлов изменено, 43 вставок(+), 5 удалений(-) [+]
rollbot.py file | annotate | diff | comparison | revisions
--- a/rollbot.py Wed May 11 14:43:23 2016 +0800
+++ b/rollbot.py Sat May 14 14:05:49 2016 +0800
@@ -14,13 +14,46 @@
raw_input = input
+class Command(object):
+ name = 'command'
+
+ def __init__(self, rollbot):
+ self.rollbot = rollbot
+
+ def usage(self):
+ return '(no help available, try experimenting)'
+
+
+class Help(Command):
+ name = 'help'
+
+ def usage(self):
+ return '%s or %s <command>' % (self.name, self.name)
+
+ def respond(self, words, message):
+ if len(words) == 2:
+ cmdname = words[1]
+ if cmdname in self.rollbot.commands:
+ command = self.rollbot.commands[cmdname]
+ return '%s usage: %s' % (command.name, command.usage())
+ else:
+ return 'no such command: %s' % cmdname
+ elif len(words) == 1:
+ cmds = ' '.join(sorted(self.rollbot.commands.keys()))
+ return 'available commands: %s' % cmds
+ else:
+ return '%s usage: %s' % (self.name, self.usage())
+
+
class RollBot(sleekxmpp.ClientXMPP):
def __init__(self, jid, password, nick, prefix):
sleekxmpp.ClientXMPP.__init__(self, jid, password)
self.nick = nick
self.prefix = prefix
- self.commands = []
+
+ self.commands = {}
+ self.add_command(Help)
self.add_event_handler('session_start', self.start)
self.add_event_handler('message', self.message)
@@ -28,6 +61,9 @@
self.add_event_handler('groupchat_invite', self.muc_invite)
self.add_event_handler('groupchat_direct_invite', self.muc_direct_invite)
+ def add_command(self, commandcls):
+ self.commands[commandcls.name] = commandcls(self)
+
def start(self, event):
self.get_roster()
self.send_presence()
@@ -77,10 +113,12 @@
def respond(self, message, prefix=None):
response = ''
- for command in self.commands:
- response = command.parse(message)
- if response:
- break
+ words = message.split()
+ if words:
+ cmdname = words[0].lower()
+ if cmdname in self.commands:
+ command = self.commands[cmdname]
+ response = command.respond(words, message)
return response