1
2
3 """Python object macro support for RiveScript.
4
5 This class provides built-in support for your RiveScript documents to include
6 and execute object macros written in Python. For example:
7
8 > object base64 python
9 import base64 as b64
10 return b64.b64encode(" ".join(args))
11 < object
12
13 + encode * in base64
14 - OK: <call>base64 <star></call>
15
16 Python support is on by default. To turn it off, just unset the Python language
17 handler on your RiveScript object:
18
19 rs.set_handler("python", None)"""
20
21 __docformat__ = 'plaintext'
22
24 """A RiveScript object handler for Python code."""
25 _objects = {}
26
29
30 - def load(self, name, code):
31 """Prepare a Python code object given by the RiveScript interpreter."""
32
33 source = "def RSOBJ(rs, args):\n"
34 for line in code:
35 source = source + "\t" + line + "\n"
36
37 try:
38 exec source
39 self._objects[name] = RSOBJ
40 except:
41 print "Failed to load code from object " + name
42
43 - def call(self, rs, name, fields):
44 """Invoke a previously loaded object."""
45
46 func = self._objects[name]
47 reply = ''
48 try:
49 reply = func(rs, fields)
50 if reply == None:
51 reply = ''
52 except:
53 reply = '[ERR: Error when executing Python object]'
54 return reply
55