Package rivescript :: Module interactive
[hide private]
[frames] | no frames]

Source Code for Module rivescript.interactive

  1  #!/usr/bin/env python 
  2   
  3  """interactive.py: RiveScript's built-in interactive mode. 
  4   
  5  To run this, run: python rivescript 
  6                or: python __init__.py 
  7                or: python __main__.py 
  8  The preferred method is the former.""" 
  9   
 10  __docformat__ = 'plaintext' 
 11   
 12  import sys 
 13  import getopt 
 14  import json 
 15   
 16  from __init__ import RiveScript 
 17   
18 -def json_in(bot, buffer, stateful):
19 # Prepare the response. 20 resp = { 21 'status': 'ok', 22 'reply': '', 23 'vars': {} 24 } 25 26 # Decode the incoming JSON. 27 try: 28 incoming = json.loads(buffer) 29 except: 30 resp['status'] = 'error' 31 resp['reply'] = 'Failed to decode incoming JSON data.' 32 print json.dumps(resp) 33 if stateful: 34 print "__END__" 35 return 36 37 # Username? 38 username = "json" 39 if 'username' in incoming: 40 username = incoming["username"] 41 42 # Decode their variables. 43 if "vars" in incoming: 44 for var in incoming["vars"]: 45 bot.set_uservar(username, var, incoming["vars"][var]) 46 47 # Get a response. 48 if 'message' in incoming: 49 resp['reply'] = bot.reply(username, incoming["message"]) 50 else: 51 resp['reply'] = "[ERR: No message provided]" 52 53 # Retrieve vars. 54 resp['vars'] = bot.get_uservars(username) 55 56 print json.dumps(resp) 57 if stateful: 58 print "__END__"
59
60 -def interactive_mode():
61 # Get command line options. 62 options, remainder = [], [] 63 try: 64 options, remainder = getopt.getopt(sys.argv[1:], 'dj', ['debug', 65 'json', 66 'log=', 67 'strict', 68 'nostrict', 69 'depth=', 70 'help']) 71 except: 72 print "Unrecognized options given, try " + sys.argv[0] + " --help" 73 exit() 74 75 # Handle the options. 76 debug, depth, strict, with_json, help, log = False, 50, True, False, False, None 77 for opt in options: 78 if opt[0] == '--debug' or opt[0] == '-d': 79 debug = True 80 elif opt[0] == '--strict': 81 strict = True 82 elif opt[0] == '--nostrict': 83 strict = False 84 elif opt[0] == '--json': 85 with_json = True 86 elif opt[0] == '--help' or opt[0] == '-h': 87 help = True 88 elif opt[0] == '--depth': 89 depth = int(opt[1]) 90 elif opt[0] == '--log': 91 log = opt[1] 92 93 # Help? 94 if help: 95 print """Usage: rivescript [options] <directory> 96 97 Options: 98 99 --debug, -d 100 Enable debug mode. 101 102 --log FILE 103 Log debug output to a file (instead of the console). Use this instead 104 of --debug. 105 106 --json, -j 107 Communicate using JSON. Useful for third party programs. 108 109 --strict, --nostrict 110 Enable or disable strict mode (enabled by default). 111 112 --depth=50 113 Set the recursion depth limit (default is 50). 114 115 --help 116 Display this help. 117 118 JSON Mode: 119 120 In JSON mode, input and output is done using JSON data structures. The 121 format for incoming JSON data is as follows: 122 123 { 124 'username': 'localuser', 125 'message': 'Hello bot!', 126 'vars': { 127 'name': 'Aiden' 128 } 129 } 130 131 The format that would be expected from this script is: 132 133 { 134 'status': 'ok', 135 'reply': 'Hello, human!', 136 'vars': { 137 'name': 'Aiden' 138 } 139 } 140 141 If the calling program sends an EOF signal at the end of their JSON data, 142 this script will print its response and exit. To keep a session going, 143 send the string '__END__' on a line by itself at the end of your message. 144 The script will do the same after its response. The pipe can then be used 145 again for further interactions.""" 146 quit() 147 148 # Given a directory? 149 if len(remainder) == 0: 150 print "Usage: rivescript [options] <directory>" 151 print "Try rivescript --help" 152 quit() 153 root = remainder[0] 154 155 # Make the bot. 156 bot = RiveScript( 157 debug=debug, 158 strict=strict, 159 depth=depth, 160 log=log 161 ) 162 bot.load_directory(root) 163 bot.sort_replies() 164 165 # Interactive mode? 166 if with_json: 167 # Read from standard input. 168 buffer = "" 169 stateful = False 170 while True: 171 line = "" 172 try: 173 line = raw_input() 174 except EOFError: 175 break 176 177 # Look for the __END__ line. 178 end = re.match(r'^__END__$', line) 179 if end: 180 # Process it. 181 stateful = True # This is a stateful session 182 json_in(bot, buffer, stateful) 183 buffer = "" 184 continue 185 else: 186 buffer += line + "\n" 187 188 # We got the EOF. If the session was stateful, just exit, 189 # otherwise process what we just read. 190 if stateful: 191 quit() 192 json_in(bot, buffer, stateful) 193 quit() 194 195 print "RiveScript Interpreter (Python) -- Interactive Mode" 196 print "---------------------------------------------------" 197 print "rivescript version: " + str(bot.VERSION()) 198 print " Reply Root: " + root 199 print "" 200 print "You are now chatting with the RiveScript bot. Type a message and press Return" 201 print "to send it. When finished, type '/quit' to exit the program." 202 print "Type '/help' for other options." 203 print "" 204 205 while True: 206 msg = raw_input("You> ") 207 208 # Commands 209 if msg == '/help': 210 print "> Supported Commands:" 211 print "> /help - Displays this message." 212 print "> /quit - Exit the program." 213 elif msg == '/quit': 214 exit() 215 else: 216 reply = bot.reply("localuser", msg) 217 print "Bot>", reply
218