forked from aichaos/rivescript-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinteractive.py
More file actions
258 lines (215 loc) · 7.35 KB
/
Copy pathinteractive.py
File metadata and controls
258 lines (215 loc) · 7.35 KB
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
#!/usr/bin/env python
# The MIT License (MIT)
#
# Copyright (c) 2015 Noah Petherbridge
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import print_function, unicode_literals
"""interactive.py: RiveScript's built-in interactive mode.
To run this, run: python rivescript
or: python __init__.py
or: python __main__.py
The preferred method is the former."""
__docformat__ = 'plaintext'
import re
import sys
import getopt
import json
from rivescript import RiveScript
# Compatible wrapper for inputs.
def _input(prompt=None):
if sys.version_info[0] < 3:
return raw_input(prompt)
else:
return input(prompt)
def json_in(bot, buffer, stateful):
# Prepare the response.
resp = {
'status': 'ok',
'reply': '',
'vars': {}
}
# Decode the incoming JSON.
try:
incoming = json.loads(buffer)
except:
resp['status'] = 'error'
resp['reply'] = 'Failed to decode incoming JSON data.'
print(json.dumps(resp))
if stateful:
print("__END__")
return
# Username?
username = "json"
if 'username' in incoming:
username = incoming["username"]
# Decode their variables.
if "vars" in incoming:
for var in incoming["vars"]:
bot.set_uservar(username, var, incoming["vars"][var])
# Get a response.
if 'message' in incoming:
resp['reply'] = bot.reply(username, incoming["message"])
else:
resp['reply'] = "[ERR: No message provided]"
# Retrieve vars.
resp['vars'] = bot.get_uservars(username)
print(json.dumps(resp))
if stateful:
print("__END__")
def interactive_mode():
# Get command line options.
options, remainder = [], []
try:
options, remainder = getopt.getopt(sys.argv[1:], 'dju', ['debug',
'json',
'utf8',
'log=',
'strict',
'nostrict',
'depth=',
'help'])
except:
print("Unrecognized options given, try " + sys.argv[0] + " --help")
exit()
# Handle the options.
debug, depth, strict = False, 50, True
with_json, help, log = False, False, None
utf8 = False
for opt in options:
if opt[0] == '--debug' or opt[0] == '-d':
debug = True
elif opt[0] == '--strict':
strict = True
elif opt[0] == '--nostrict':
strict = False
elif opt[0] == '--json':
with_json = True
elif opt[0] == '--utf8' or opt[0] == '-u':
utf8 = True
elif opt[0] == '--help' or opt[0] == '-h':
help = True
elif opt[0] == '--depth':
depth = int(opt[1])
elif opt[0] == '--log':
log = opt[1]
# Help?
if help:
print("""Usage: rivescript [options] <directory>
Options:
--debug, -d
Enable debug mode.
--log FILE
Log debug output to a file (instead of the console). Use this instead
of --debug.
--json, -j
Communicate using JSON. Useful for third party programs.
--strict, --nostrict
Enable or disable strict mode (enabled by default).
--depth=50
Set the recursion depth limit (default is 50).
--help
Display this help.
JSON Mode:
In JSON mode, input and output is done using JSON data structures. The
format for incoming JSON data is as follows:
{
'username': 'localuser',
'message': 'Hello bot!',
'vars': {
'name': 'Aiden'
}
}
The format that would be expected from this script is:
{
'status': 'ok',
'reply': 'Hello, human!',
'vars': {
'name': 'Aiden'
}
}
If the calling program sends an EOF signal at the end of their JSON data,
this script will print its response and exit. To keep a session going,
send the string '__END__' on a line by itself at the end of your message.
The script will do the same after its response. The pipe can then be used
again for further interactions.""")
quit()
# Given a directory?
if len(remainder) == 0:
print("Usage: rivescript [options] <directory>")
print("Try rivescript --help")
quit()
root = remainder[0]
# Make the bot.
bot = RiveScript(
debug=debug,
strict=strict,
depth=depth,
utf8=utf8,
log=log
)
bot.load_directory(root)
bot.sort_replies()
# Interactive mode?
if with_json:
# Read from standard input.
buffer = ""
stateful = False
while True:
line = ""
try:
line = _input()
except EOFError:
break
# Look for the __END__ line.
end = re.match(r'^__END__$', line)
if end:
# Process it.
stateful = True # This is a stateful session
json_in(bot, buffer, stateful)
buffer = ""
continue
else:
buffer += line + "\n"
# We got the EOF. If the session was stateful, just exit,
# otherwise process what we just read.
if stateful:
quit()
json_in(bot, buffer, stateful)
quit()
print("""RiveScript Interpreter (Python) -- Interactive Mode"
---------------------------------------------------"
rivescript version: %s
Reply Root: %s
You are now chatting with the RiveScript bot. Type a message and press Return"
to send it. When finished, type '/quit' to exit the program."
Type '/help' for other options."
""" % (str(bot.VERSION()), root))
while True:
msg = _input("You> ")
# Commands
if msg == '/help':
print("> Supported Commands:")
print("> /help - Displays this message.")
print("> /quit - Exit the program.")
elif msg == '/quit':
exit()
else:
reply = bot.reply("localuser", msg)
print("Bot>", reply)