Package rivescript ::
Module python
|
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26 from __future__ import print_function
27
28 __docformat__ = 'plaintext'
29
30
32 """A RiveScript object handler for Python code.
33
34 This class provides built-in support for your RiveScript documents to include
35 and execute object macros written in Python. For example:
36
37 > object base64 python
38 import base64 as b64
39 return b64.b64encode(" ".join(args))
40 < object
41
42 + encode * in base64
43 - OK: <call>base64 <star></call>
44
45 Python object macros receive these two parameters:
46
47 rs: The reference to the parent RiveScript instance
48 args: A list of argument words passed to your object macro
49
50 Python support is on by default. To turn it off, just unset the Python language
51 handler on your RiveScript object:
52
53 rs.set_handler("python", None)"""
54 _objects = {}
55
58
59 - def load(self, name, code):
60 """Prepare a Python code object given by the RiveScript interpreter."""
61
62 source = "def RSOBJ(rs, args):\n"
63 for line in code:
64 source = source + "\t" + line + "\n"
65
66 source += "self._objects[name] = RSOBJ\n"
67
68 try:
69 exec(source)
70
71 except Exception as e:
72 print("Failed to load code from object", name)
73 print("The error given was: ", e)
74
75 - def call(self, rs, name, user, fields):
76 """Invoke a previously loaded object."""
77
78 if not name in self._objects:
79 return '[ERR: Object Not Found]'
80 func = self._objects[name]
81 reply = ''
82 try:
83 reply = func(rs, fields)
84 if reply is None:
85 reply = ''
86 except Exception as e:
87 print("Error executing Python object:", e)
88 reply = '[ERR: Error when executing Python object]'
89 return str(reply)
90