|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +# Example for how to set a Perl object handler. |
| 4 | + |
| 5 | +import rivescript |
| 6 | +from json import dumps, loads |
| 7 | +from subprocess import Popen, PIPE |
| 8 | + |
| 9 | +class PerlObject: |
| 10 | + """A Perl object handler for RiveScript.""" |
| 11 | + _objects = {} # The cache of objects loaded |
| 12 | + |
| 13 | + def load(self, name, code): |
| 14 | + """Prepare a Perl code object given by the RS interpreter.""" |
| 15 | + |
| 16 | + source = "\n".join(code) |
| 17 | + self._objects[name] = source |
| 18 | + |
| 19 | + def call(self, rs, name, user, fields): |
| 20 | + if not name in self._objects: |
| 21 | + return "[ERR: Object Not Found]" |
| 22 | + |
| 23 | + # JSON data to send to Perl. |
| 24 | + outgoing = dict( |
| 25 | + id=user, |
| 26 | + message=" ".join(fields), |
| 27 | + code=self._objects[name], |
| 28 | + vars={}, |
| 29 | + ) |
| 30 | + |
| 31 | + # Copy their current user vars over. |
| 32 | + vars = rs.get_uservars(user) |
| 33 | + for key, value in vars.iteritems(): |
| 34 | + if type(value) != str: |
| 35 | + continue |
| 36 | + outgoing['vars'][key] = value |
| 37 | + |
| 38 | + # Fire up Perl and give it all this data. |
| 39 | + proc = Popen(["perl", "accomplice.pl"], stdin=PIPE, stdout=PIPE) |
| 40 | + proc.stdin.write(dumps(outgoing)) |
| 41 | + proc.stdin.close() |
| 42 | + result = proc.stdout.read() |
| 43 | + |
| 44 | + # Hopefully that was JSON data we got! |
| 45 | + try: |
| 46 | + result = loads(result) |
| 47 | + except: |
| 48 | + return "[ERR: Got an unexpected result from Perl!]" |
| 49 | + |
| 50 | + # OK? |
| 51 | + if result['status'] == 'error': |
| 52 | + return "[ERR: %s]" % result['message'] |
| 53 | + |
| 54 | + # Restore user variables from Perl, in case it changed anything. |
| 55 | + for key, value in result['vars'].iteritems(): |
| 56 | + if type(value) != str: |
| 57 | + continue |
| 58 | + rs.set_uservar(user, key, value) |
| 59 | + |
| 60 | + return result['reply'] |
| 61 | + |
| 62 | +bot = rivescript.RiveScript() |
| 63 | +bot.set_handler("perl", PerlObject()) |
| 64 | +bot.load_file("perl.rs") |
| 65 | +bot.sort_replies() |
| 66 | +while True: |
| 67 | + msg = raw_input("You> ") |
| 68 | + reply = bot.reply("localuser", msg) |
| 69 | + print "Bot>", reply |
| 70 | + |
| 71 | +# vim:expandtab |
0 commit comments