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

Source Code for Module rivescript.rivescript

   1  #!/usr/bin/env python 
   2   
   3  # The MIT License (MIT) 
   4  # 
   5  # Copyright (c) 2016 Noah Petherbridge 
   6  # 
   7  # Permission is hereby granted, free of charge, to any person obtaining a copy 
   8  # of this software and associated documentation files (the "Software"), to deal 
   9  # in the Software without restriction, including without limitation the rights 
  10  # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
  11  # copies of the Software, and to permit persons to whom the Software is 
  12  # furnished to do so, subject to the following conditions: 
  13  # 
  14  # The above copyright notice and this permission notice shall be included in all 
  15  # copies or substantial portions of the Software. 
  16  # 
  17  # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
  18  # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
  19  # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
  20  # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
  21  # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
  22  # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 
  23  # SOFTWARE. 
  24   
  25  from __future__ import unicode_literals 
  26  from six import text_type 
  27  import sys 
  28  import os 
  29  import re 
  30  import string 
  31  import random 
  32  import pprint 
  33  import copy 
  34  import codecs 
  35   
  36  from . import __version__ 
  37  from . import python 
38 39 # Common regular expressions. 40 -class RE(object):
41 equals = re.compile('\s*=\s*') 42 ws = re.compile('\s+') 43 objend = re.compile('^\s*<\s*object') 44 weight = re.compile('\{weight=(\d+)\}') 45 inherit = re.compile('\{inherits=(\d+)\}') 46 wilds = re.compile('[\s\*\#\_]+') 47 nasties = re.compile('[^A-Za-z0-9 ]') 48 crlf = re.compile('<crlf>') 49 literal_w = re.compile(r'\\w') 50 array = re.compile(r'\@(.+?)\b') 51 def_syntax = re.compile(r'^.+(?:\s+.+|)\s*=\s*.+?$') 52 name_syntax = re.compile(r'[^a-z0-9_\-\s]') 53 utf8_trig = re.compile(r'[A-Z\\.]') 54 trig_syntax = re.compile(r'[^a-z0-9(\|)\[\]*_#@{}<>=\s]') 55 cond_syntax = re.compile(r'^.+?\s*(?:==|eq|!=|ne|<>|<|<=|>|>=)\s*.+?=>.+?$') 56 utf8_meta = re.compile(r'[\\<>]') 57 utf8_punct = re.compile(r'[.?,!;:@#$%^&*()]') 58 cond_split = re.compile(r'\s*=>\s*') 59 cond_parse = re.compile(r'^(.+?)\s+(==|eq|!=|ne|<>|<|<=|>|>=)\s+(.+?)$') 60 topic_tag = re.compile(r'\{topic=(.+?)\}') 61 set_tag = re.compile(r'<set (.+?)=(.+?)>') 62 bot_tag = re.compile(r'<bot (.+?)>') 63 get_tag = re.compile(r'<get (.+?)>') 64 star_tags = re.compile(r'<star(\d+)>') 65 botstars = re.compile(r'<botstar(\d+)>') 66 input_tags = re.compile(r'<input([1-9])>') 67 reply_tags = re.compile(r'<reply([1-9])>') 68 random_tags = re.compile(r'\{random\}(.+?)\{/random\}') 69 redir_tag = re.compile(r'\{@(.+?)\}') 70 tag_search = re.compile(r'<([^<]+?)>') 71 placeholder = re.compile(r'\x00(\d+)\x00') 72 zero_star = re.compile(r'^\*$') 73 optionals = re.compile(r'\[(.+?)\]')
74 75 # Version of RiveScript we support. 76 rs_version = 2.0 77 78 # Exportable constants. 79 RS_ERR_MATCH = "[ERR: No reply matched]" 80 RS_ERR_REPLY = "[ERR: No reply found]" 81 RS_ERR_DEEP_RECURSION = "[ERR: Deep recursion detected]" 82 RS_ERR_OBJECT = "[ERR: Error when executing Python object]" 83 RS_ERR_OBJECT_HANDLER = "[ERR: No Object Handler]" 84 RS_ERR_OBJECT_MISSING = "[ERR: Object Not Found]"
85 86 87 -class RiveScript(object):
88 """A RiveScript interpreter for Python 2 and 3.""" 89 90 # Concatenation mode characters. 91 _concat_modes = dict( 92 none="", 93 space=" ", 94 newline="\n", 95 ) 96 97 ############################################################################ 98 # Initialization and Utility Methods # 99 ############################################################################ 100
101 - def __init__(self, debug=False, strict=True, depth=50, log="", utf8=False):
102 """Initialize a new RiveScript interpreter. 103 104 bool debug: Specify a debug mode. 105 bool strict: Strict mode (RS syntax errors are fatal) 106 str log: Specify a log file for debug output to go to (instead of STDOUT). 107 int depth: Specify the recursion depth limit. 108 bool utf8: Enable UTF-8 support.""" 109 110 ### 111 # User configurable fields. 112 ### 113 114 # Debugging 115 self._debug = debug # Debug mode 116 self._log = log # Debug log file 117 118 # Unicode stuff 119 self._utf8 = utf8 # UTF-8 mode 120 self.unicode_punctuation = re.compile(r'[.,!?;:]') 121 122 # Misc. 123 self._strict = strict # Strict mode 124 self._depth = depth # Recursion depth limit 125 126 ### 127 # Internal fields. 128 ### 129 self._gvars = {} # 'global' variables 130 self._bvars = {} # 'bot' variables 131 self._subs = {} # 'sub' variables 132 self._person = {} # 'person' variables 133 self._arrays = {} # 'array' variables 134 self._users = {} # 'user' variables 135 self._freeze = {} # frozen 'user' variables 136 self._includes = {} # included topics 137 self._lineage = {} # inherited topics 138 self._handlers = {} # Object handlers 139 self._objlangs = {} # Languages of objects used 140 self._topics = {} # Main reply structure 141 self._thats = {} # %Previous reply structure 142 self._sorted = {} # Sorted buffers 143 self._syntax = {} # Syntax tracking (filenames & line no.'s) 144 self._regexc = { # Precomputed regexes for speed optimizations. 145 "trigger": {}, 146 "subs": {}, 147 "person": {}, 148 } 149 150 # "Current request" variables. 151 self._current_user = None # The current user ID. 152 153 # Define the default Python language handler. 154 self._handlers["python"] = python.PyRiveObjects() 155 156 self._say("Interpreter initialized.")
157 158 @classmethod
159 - def VERSION(self=None):
160 """Return the version number of the RiveScript library. 161 162 This may be called as either a class method or a method of a RiveScript object.""" 163 return __version__
164
165 - def _say(self, message):
166 if self._debug: 167 print("[RS] {}".format(message)) 168 if self._log: 169 # Log it to the file. 170 fh = open(self._log, 'a') 171 fh.write("[RS] " + message + "\n") 172 fh.close()
173
174 - def _warn(self, message, fname='', lineno=0):
175 header = "[RS]" 176 if self._debug: 177 header = "[RS::Warning]" 178 if len(fname) and lineno > 0: 179 print(header, message, "at", fname, "line", lineno) 180 else: 181 print(header, message)
182 183 ############################################################################ 184 # Loading and Parsing Methods # 185 ############################################################################ 186
187 - def load_directory(self, directory, ext=None):
188 """Load RiveScript documents from a directory. 189 190 Provide `ext` as a list of extensions to search for. The default list 191 is `.rive`, `.rs`""" 192 self._say("Loading from directory: " + directory) 193 194 if ext is None: 195 # Use the default extensions - .rive is preferable. 196 ext = ['.rive', '.rs'] 197 elif type(ext) == str: 198 # Backwards compatibility for ext being a string value. 199 ext = [ext] 200 201 if not os.path.isdir(directory): 202 self._warn("Error: " + directory + " is not a directory.") 203 return 204 205 for item in os.listdir(directory): 206 for extension in ext: 207 if item.lower().endswith(extension): 208 # Load this file. 209 self.load_file(os.path.join(directory, item)) 210 break
211
212 - def load_file(self, filename):
213 """Load and parse a RiveScript document.""" 214 self._say("Loading file: " + filename) 215 216 fh = codecs.open(filename, 'r', 'utf-8') 217 lines = fh.readlines() 218 fh.close() 219 220 self._say("Parsing " + str(len(lines)) + " lines of code from " + filename) 221 self._parse(filename, lines)
222
223 - def stream(self, code):
224 """Stream in RiveScript source code dynamically. 225 226 `code` can either be a string containing RiveScript code or an array 227 of lines of RiveScript code.""" 228 self._say("Streaming code.") 229 if type(code) in [str, text_type]: 230 code = code.split("\n") 231 self._parse("stream()", code)
232
233 - def _parse(self, fname, code):
234 """Parse RiveScript code into memory.""" 235 self._say("Parsing code") 236 237 # Track temporary variables. 238 topic = 'random' # Default topic=random 239 lineno = 0 # Line numbers for syntax tracking 240 comment = False # In a multi-line comment 241 inobj = False # In an object 242 objname = '' # The name of the object we're in 243 objlang = '' # The programming language of the object 244 objbuf = [] # Object contents buffer 245 ontrig = '' # The current trigger 246 repcnt = 0 # Reply counter 247 concnt = 0 # Condition counter 248 isThat = '' # Is a %Previous trigger 249 250 # Local (file scoped) parser options. 251 local_options = dict( 252 concat="none", # Concat mode for ^Continue command 253 ) 254 255 # Read each line. 256 for lp, line in enumerate(code): 257 lineno += 1 258 259 self._say("Line: " + line + " (topic: " + topic + ") incomment: " + str(inobj)) 260 if len(line.strip()) == 0: # Skip blank lines 261 continue 262 263 # In an object? 264 if inobj: 265 if re.match(RE.objend, line): 266 # End the object. 267 if len(objname): 268 # Call the object's handler. 269 if objlang in self._handlers: 270 self._objlangs[objname] = objlang 271 self._handlers[objlang].load(objname, objbuf) 272 else: 273 self._warn("Object creation failed: no handler for " + objlang, fname, lineno) 274 objname = '' 275 objlang = '' 276 objbuf = [] 277 inobj = False 278 else: 279 objbuf.append(line) 280 continue 281 282 line = line.strip() # Trim excess space. We do it down here so we 283 # don't mess up python objects! 284 285 # Look for comments. 286 if line[:2] == '//': # A single-line comment. 287 continue 288 elif line[0] == '#': 289 self._warn("Using the # symbol for comments is deprecated", fname, lineno) 290 elif line[:2] == '/*': # Start of a multi-line comment. 291 if '*/' not in line: # Cancel if the end is here too. 292 comment = True 293 continue 294 elif '*/' in line: 295 comment = False 296 continue 297 if comment: 298 continue 299 300 # Separate the command from the data. 301 if len(line) < 2: 302 self._warn("Weird single-character line '" + line + "' found.", fname, lineno) 303 continue 304 cmd = line[0] 305 line = line[1:].strip() 306 307 # Ignore inline comments if there's a space before and after 308 # the // symbols. 309 if " // " in line: 310 line = line.split(" // ")[0].strip() 311 312 # Run a syntax check on this line. 313 syntax_error = self.check_syntax(cmd, line) 314 if syntax_error: 315 # There was a syntax error! Are we enforcing strict mode? 316 syntax_error = "Syntax error in " + fname + " line " + str(lineno) + ": " \ 317 + syntax_error + " (near: " + cmd + " " + line + ")" 318 if self._strict: 319 raise Exception(syntax_error) 320 else: 321 self._warn(syntax_error) 322 return # Don't try to continue 323 324 # Reset the %Previous state if this is a new +Trigger. 325 if cmd == '+': 326 isThat = '' 327 328 # Do a lookahead for ^Continue and %Previous commands. 329 for i in range(lp + 1, len(code)): 330 lookahead = code[i].strip() 331 if len(lookahead) < 2: 332 continue 333 lookCmd = lookahead[0] 334 lookahead = lookahead[1:].strip() 335 336 # Only continue if the lookahead line has any data. 337 if len(lookahead) != 0: 338 # The lookahead command has to be either a % or a ^. 339 if lookCmd != '^' and lookCmd != '%': 340 break 341 342 # If the current command is a +, see if the following is 343 # a %. 344 if cmd == '+': 345 if lookCmd == '%': 346 isThat = lookahead 347 break 348 else: 349 isThat = '' 350 351 # If the current command is a ! and the next command(s) are 352 # ^, we'll tack each extension on as a line break (which is 353 # useful information for arrays). 354 if cmd == '!': 355 if lookCmd == '^': 356 line += "<crlf>" + lookahead 357 continue 358 359 # If the current command is not a ^ and the line after is 360 # not a %, but the line after IS a ^, then tack it on to the 361 # end of the current line. 362 if cmd != '^' and lookCmd != '%': 363 if lookCmd == '^': 364 line += self._concat_modes.get( 365 local_options["concat"], "" 366 ) + lookahead 367 else: 368 break 369 370 self._say("Command: " + cmd + "; line: " + line) 371 372 # Handle the types of RiveScript commands. 373 if cmd == '!': 374 # ! DEFINE 375 halves = re.split(RE.equals, line, 2) 376 left = re.split(RE.ws, halves[0].strip(), 2) 377 value, type, var = '', '', '' 378 if len(halves) == 2: 379 value = halves[1].strip() 380 if len(left) >= 1: 381 type = left[0].strip() 382 if len(left) >= 2: 383 var = ' '.join(left[1:]).strip() 384 385 # Remove 'fake' line breaks unless this is an array. 386 if type != 'array': 387 value = re.sub(RE.crlf, '', value) 388 389 # Handle version numbers. 390 if type == 'version': 391 # Verify we support it. 392 try: 393 if float(value) > rs_version: 394 self._warn("Unsupported RiveScript version. We only support " + rs_version, fname, lineno) 395 return 396 except: 397 self._warn("Error parsing RiveScript version number: not a number", fname, lineno) 398 continue 399 400 # All other types of defines require a variable and value name. 401 if len(var) == 0: 402 self._warn("Undefined variable name", fname, lineno) 403 continue 404 elif len(value) == 0: 405 self._warn("Undefined variable value", fname, lineno) 406 continue 407 408 # Handle the rest of the types. 409 if type == 'local': 410 # Local file-scoped parser options. 411 self._say("\tSet parser option " + var + " = " + value) 412 local_options[var] = value 413 elif type == 'global': 414 # 'Global' variables 415 self._say("\tSet global " + var + " = " + value) 416 417 if value == '<undef>': 418 try: 419 del(self._gvars[var]) 420 except: 421 self._warn("Failed to delete missing global variable", fname, lineno) 422 else: 423 self._gvars[var] = value 424 425 # Handle flipping debug and depth vars. 426 if var == 'debug': 427 if value.lower() == 'true': 428 value = True 429 else: 430 value = False 431 self._debug = value 432 elif var == 'depth': 433 try: 434 self._depth = int(value) 435 except: 436 self._warn("Failed to set 'depth' because the value isn't a number!", fname, lineno) 437 elif var == 'strict': 438 if value.lower() == 'true': 439 self._strict = True 440 else: 441 self._strict = False 442 elif type == 'var': 443 # Bot variables 444 self._say("\tSet bot variable " + var + " = " + value) 445 446 if value == '<undef>': 447 try: 448 del(self._bvars[var]) 449 except: 450 self._warn("Failed to delete missing bot variable", fname, lineno) 451 else: 452 self._bvars[var] = value 453 elif type == 'array': 454 # Arrays 455 self._say("\tArray " + var + " = " + value) 456 457 if value == '<undef>': 458 try: 459 del(self._arrays[var]) 460 except: 461 self._warn("Failed to delete missing array", fname, lineno) 462 continue 463 464 # Did this have multiple parts? 465 parts = value.split("<crlf>") 466 467 # Process each line of array data. 468 fields = [] 469 for val in parts: 470 if '|' in val: 471 fields.extend(val.split('|')) 472 else: 473 fields.extend(re.split(RE.ws, val)) 474 475 # Convert any remaining '\s' escape codes into spaces. 476 for f in fields: 477 f = f.replace('\s', ' ') 478 479 self._arrays[var] = fields 480 elif type == 'sub': 481 # Substitutions 482 self._say("\tSubstitution " + var + " => " + value) 483 484 if value == '<undef>': 485 try: 486 del(self._subs[var]) 487 except: 488 self._warn("Failed to delete missing substitution", fname, lineno) 489 else: 490 self._subs[var] = value 491 492 # Precompile the regexp. 493 self._precompile_substitution("subs", var) 494 elif type == 'person': 495 # Person Substitutions 496 self._say("\tPerson Substitution " + var + " => " + value) 497 498 if value == '<undef>': 499 try: 500 del(self._person[var]) 501 except: 502 self._warn("Failed to delete missing person substitution", fname, lineno) 503 else: 504 self._person[var] = value 505 506 # Precompile the regexp. 507 self._precompile_substitution("person", var) 508 else: 509 self._warn("Unknown definition type '" + type + "'", fname, lineno) 510 elif cmd == '>': 511 # > LABEL 512 temp = re.split(RE.ws, line) 513 type = temp[0] 514 name = '' 515 fields = [] 516 if len(temp) >= 2: 517 name = temp[1] 518 if len(temp) >= 3: 519 fields = temp[2:] 520 521 # Handle the label types. 522 if type == 'begin': 523 # The BEGIN block. 524 self._say("\tFound the BEGIN block.") 525 type = 'topic' 526 name = '__begin__' 527 if type == 'topic': 528 # Starting a new topic. 529 self._say("\tSet topic to " + name) 530 ontrig = '' 531 topic = name 532 533 # Does this topic include or inherit another one? 534 mode = '' # or 'inherits' or 'includes' 535 if len(fields) >= 2: 536 for field in fields: 537 if field == 'includes': 538 mode = 'includes' 539 elif field == 'inherits': 540 mode = 'inherits' 541 elif mode != '': 542 # This topic is either inherited or included. 543 if mode == 'includes': 544 if name not in self._includes: 545 self._includes[name] = {} 546 self._includes[name][field] = 1 547 else: 548 if name not in self._lineage: 549 self._lineage[name] = {} 550 self._lineage[name][field] = 1 551 elif type == 'object': 552 # If a field was provided, it should be the programming 553 # language. 554 lang = None 555 if len(fields) > 0: 556 lang = fields[0].lower() 557 558 # Only try to parse a language we support. 559 ontrig = '' 560 if lang is None: 561 self._warn("Trying to parse unknown programming language", fname, lineno) 562 lang = 'python' # Assume it's Python. 563 564 # See if we have a defined handler for this language. 565 if lang in self._handlers: 566 # We have a handler, so start loading the code. 567 objname = name 568 objlang = lang 569 objbuf = [] 570 inobj = True 571 else: 572 # We don't have a handler, just ignore it. 573 objname = '' 574 objlang = '' 575 objbuf = [] 576 inobj = True 577 else: 578 self._warn("Unknown label type '" + type + "'", fname, lineno) 579 elif cmd == '<': 580 # < LABEL 581 type = line 582 583 if type == 'begin' or type == 'topic': 584 self._say("\tEnd topic label.") 585 topic = 'random' 586 elif type == 'object': 587 self._say("\tEnd object label.") 588 inobj = False 589 elif cmd == '+': 590 # + TRIGGER 591 self._say("\tTrigger pattern: " + line) 592 if len(isThat): 593 self._initTT('thats', topic, isThat, line) 594 self._initTT('syntax', topic, line, 'thats') 595 self._syntax['thats'][topic][line]['trigger'] = (fname, lineno) 596 else: 597 self._initTT('topics', topic, line) 598 self._initTT('syntax', topic, line, 'topic') 599 self._syntax['topic'][topic][line]['trigger'] = (fname, lineno) 600 ontrig = line 601 repcnt = 0 602 concnt = 0 603 604 # Pre-compile the trigger's regexp if possible. 605 self._precompile_regexp(ontrig) 606 elif cmd == '-': 607 # - REPLY 608 if ontrig == '': 609 self._warn("Response found before trigger", fname, lineno) 610 continue 611 self._say("\tResponse: " + line) 612 if len(isThat): 613 self._thats[topic][isThat][ontrig]['reply'][repcnt] = line 614 self._syntax['thats'][topic][ontrig]['reply'][repcnt] = (fname, lineno) 615 else: 616 self._topics[topic][ontrig]['reply'][repcnt] = line 617 self._syntax['topic'][topic][ontrig]['reply'][repcnt] = (fname, lineno) 618 repcnt += 1 619 elif cmd == '%': 620 # % PREVIOUS 621 pass # This was handled above. 622 elif cmd == '^': 623 # ^ CONTINUE 624 pass # This was handled above. 625 elif cmd == '@': 626 # @ REDIRECT 627 self._say("\tRedirect response to " + line) 628 if len(isThat): 629 self._thats[topic][isThat][ontrig]['redirect'] = line 630 self._syntax['thats'][topic][ontrig]['redirect'] = (fname, lineno) 631 else: 632 self._topics[topic][ontrig]['redirect'] = line 633 self._syntax['topic'][topic][ontrig]['redirect'] = (fname, lineno) 634 elif cmd == '*': 635 # * CONDITION 636 self._say("\tAdding condition: " + line) 637 if len(isThat): 638 self._thats[topic][isThat][ontrig]['condition'][concnt] = line 639 self._syntax['thats'][topic][ontrig]['condition'][concnt] = (fname, lineno) 640 else: 641 self._topics[topic][ontrig]['condition'][concnt] = line 642 self._syntax['topic'][topic][ontrig]['condition'][concnt] = (fname, lineno) 643 concnt += 1 644 else: 645 self._warn("Unrecognized command \"" + cmd + "\"", fname, lineno) 646 continue
647
648 - def check_syntax(self, cmd, line):
649 """Syntax check a RiveScript command and line. 650 651 Returns a syntax error string on error; None otherwise.""" 652 653 # Run syntax checks based on the type of command. 654 if cmd == '!': 655 # ! Definition 656 # - Must be formatted like this: 657 # ! type name = value 658 # OR 659 # ! type = value 660 match = re.match(RE.def_syntax, line) 661 if not match: 662 return "Invalid format for !Definition line: must be '! type name = value' OR '! type = value'" 663 elif cmd == '>': 664 # > Label 665 # - The "begin" label must have only one argument ("begin") 666 # - "topic" labels must be lowercased but can inherit other topics (a-z0-9_\s) 667 # - "object" labels must follow the same rules as "topic", but don't need to be lowercase 668 parts = re.split(" ", line, 2) 669 if parts[0] == "begin" and len(parts) > 1: 670 return "The 'begin' label takes no additional arguments, should be verbatim '> begin'" 671 elif parts[0] == "topic": 672 match = re.match(RE.name_syntax, line) 673 if match: 674 return "Topics should be lowercased and contain only numbers and letters" 675 elif parts[0] == "object": 676 match = re.match(RE.name_syntax, line) 677 if match: 678 return "Objects can only contain numbers and letters" 679 elif cmd == '+' or cmd == '%' or cmd == '@': 680 # + Trigger, % Previous, @ Redirect 681 # This one is strict. The triggers are to be run through the regexp engine, 682 # therefore it should be acceptable for the regexp engine. 683 # - Entirely lowercase 684 # - No symbols except: ( | ) [ ] * _ # @ { } < > = 685 # - All brackets should be matched 686 parens = 0 # Open parenthesis 687 square = 0 # Open square brackets 688 curly = 0 # Open curly brackets 689 angle = 0 # Open angled brackets 690 691 # Count brackets. 692 for char in line: 693 if char == '(': 694 parens += 1 695 elif char == ')': 696 parens -= 1 697 elif char == '[': 698 square += 1 699 elif char == ']': 700 square -= 1 701 elif char == '{': 702 curly += 1 703 elif char == '}': 704 curly -= 1 705 elif char == '<': 706 angle += 1 707 elif char == '>': 708 angle -= 1 709 710 # Any mismatches? 711 if parens != 0: 712 return "Unmatched parenthesis brackets" 713 elif square != 0: 714 return "Unmatched square brackets" 715 elif curly != 0: 716 return "Unmatched curly brackets" 717 elif angle != 0: 718 return "Unmatched angle brackets" 719 720 # In UTF-8 mode, most symbols are allowed. 721 if self._utf8: 722 match = re.match(RE.utf8_trig, line) 723 if match: 724 return "Triggers can't contain uppercase letters, backslashes or dots in UTF-8 mode." 725 else: 726 match = re.match(RE.trig_syntax, line) 727 if match: 728 return "Triggers may only contain lowercase letters, numbers, and these symbols: ( | ) [ ] * _ # @ { } < > =" 729 elif cmd == '-' or cmd == '^' or cmd == '/': 730 # - Trigger, ^ Continue, / Comment 731 # These commands take verbatim arguments, so their syntax is loose. 732 pass 733 elif cmd == '*': 734 # * Condition 735 # Syntax for a conditional is as follows: 736 # * value symbol value => response 737 match = re.match(RE.cond_syntax, line) 738 if not match: 739 return "Invalid format for !Condition: should be like '* value symbol value => response'" 740 741 return None
742
743 - def deparse(self):
744 """Return the in-memory RiveScript document as a Python data structure. 745 746 This would be useful for developing a user interface for editing 747 RiveScript replies without having to edit the RiveScript code 748 manually.""" 749 750 # Data to return. 751 result = { 752 "begin": { 753 "global": {}, 754 "var": {}, 755 "sub": {}, 756 "person": {}, 757 "array": {}, 758 "triggers": {}, 759 "that": {}, 760 }, 761 "topic": {}, 762 "that": {}, 763 "inherit": {}, 764 "include": {}, 765 } 766 767 # Populate the config fields. 768 if self._debug: 769 result["begin"]["global"]["debug"] = self._debug 770 if self._depth != 50: 771 result["begin"]["global"]["depth"] = 50 772 773 # Definitions 774 result["begin"]["var"] = self._bvars.copy() 775 result["begin"]["sub"] = self._subs.copy() 776 result["begin"]["person"] = self._person.copy() 777 result["begin"]["array"] = self._arrays.copy() 778 result["begin"]["global"].update(self._gvars.copy()) 779 780 # Topic Triggers. 781 for topic in self._topics: 782 dest = {} # Where to place the topic info 783 784 if topic == "__begin__": 785 # Begin block. 786 dest = result["begin"]["triggers"] 787 else: 788 # Normal topic. 789 if topic not in result["topic"]: 790 result["topic"][topic] = {} 791 dest = result["topic"][topic] 792 793 # Copy the triggers. 794 for trig, data in self._topics[topic].iteritems(): 795 dest[trig] = self._copy_trigger(trig, data) 796 797 # %Previous's. 798 for topic in self._thats: 799 dest = {} # Where to place the topic info 800 801 if topic == "__begin__": 802 # Begin block. 803 dest = result["begin"]["that"] 804 else: 805 # Normal topic. 806 if topic not in result["that"]: 807 result["that"][topic] = {} 808 dest = result["that"][topic] 809 810 # The "that" structure is backwards: bot reply, then trigger, then info. 811 for previous, pdata in self._thats[topic].iteritems(): 812 for trig, data in pdata.iteritems(): 813 dest[trig] = self._copy_trigger(trig, data, previous) 814 815 # Inherits/Includes. 816 for topic, data in self._lineage.iteritems(): 817 result["inherit"][topic] = [] 818 for inherit in data: 819 result["inherit"][topic].append(inherit) 820 for topic, data in self._includes.iteritems(): 821 result["include"][topic] = [] 822 for include in data: 823 result["include"][topic].append(include) 824 825 return result
826
827 - def write(self, fh, deparsed=None):
828 """Write the currently parsed RiveScript data into a file. 829 830 Pass either a file name (string) or a file handle object. 831 832 This uses `deparse()` to dump a representation of the loaded data and 833 writes it to the destination file. If you provide your own data as the 834 `deparsed` argument, it will use that data instead of calling 835 `deparse()` itself. This way you can use `deparse()`, edit the data, 836 and use that to write the RiveScript document (for example, to be used 837 by a user interface for editing RiveScript without writing the code 838 directly).""" 839 840 # Passed a string instead of a file handle? 841 if type(fh) is str: 842 fh = codecs.open(fh, "w", "utf-8") 843 844 # Deparse the loaded data. 845 if deparsed is None: 846 deparsed = self.deparse() 847 848 # Start at the beginning. 849 fh.write("// Written by rivescript.deparse()\n") 850 fh.write("! version = 2.0\n\n") 851 852 # Variables of all sorts! 853 for kind in ["global", "var", "sub", "person", "array"]: 854 if len(deparsed["begin"][kind].keys()) == 0: 855 continue 856 857 for var in sorted(deparsed["begin"][kind].keys()): 858 # Array types need to be separated by either spaces or pipes. 859 data = deparsed["begin"][kind][var] 860 if type(data) not in [str, text_type]: 861 needs_pipes = False 862 for test in data: 863 if " " in test: 864 needs_pipes = True 865 break 866 867 # Word-wrap the result, target width is 78 chars minus the 868 # kind, var, and spaces and equals sign. 869 width = 78 - len(kind) - len(var) - 4 870 871 if needs_pipes: 872 data = self._write_wrapped("|".join(data), sep="|") 873 else: 874 data = " ".join(data) 875 876 fh.write("! {kind} {var} = {data}\n".format( 877 kind=kind, 878 var=var, 879 data=data, 880 )) 881 fh.write("\n") 882 883 # Begin block. 884 if len(deparsed["begin"]["triggers"].keys()): 885 fh.write("> begin\n\n") 886 self._write_triggers(fh, deparsed["begin"]["triggers"], indent="\t") 887 fh.write("< begin\n\n") 888 889 # The topics. Random first! 890 topics = ["random"] 891 topics.extend(sorted(deparsed["topic"].keys())) 892 done_random = False 893 for topic in topics: 894 if topic not in deparsed["topic"]: continue 895 if topic == "random" and done_random: continue 896 if topic == "random": done_random = True 897 898 tagged = False # Used > topic tag 899 900 if topic != "random" or topic in deparsed["include"] or topic in deparsed["inherit"]: 901 tagged = True 902 fh.write("> topic " + topic) 903 904 if topic in deparsed["inherit"]: 905 fh.write(" inherits " + " ".join(deparsed["inherit"][topic])) 906 if topic in deparsed["include"]: 907 fh.write(" includes " + " ".join(deparsed["include"][topic])) 908 909 fh.write("\n\n") 910 911 indent = "\t" if tagged else "" 912 self._write_triggers(fh, deparsed["topic"][topic], indent=indent) 913 914 # Any %Previous's? 915 if topic in deparsed["that"]: 916 self._write_triggers(fh, deparsed["that"][topic], indent=indent) 917 918 if tagged: 919 fh.write("< topic\n\n") 920 921 return True
922
923 - def _copy_trigger(self, trig, data, previous=None):
924 """Make copies of all data below a trigger.""" 925 # Copied data. 926 dest = {} 927 928 if previous: 929 dest["previous"] = previous 930 931 if "redirect" in data and data["redirect"]: 932 # @Redirect 933 dest["redirect"] = data["redirect"] 934 935 if "condition" in data and len(data["condition"].keys()): 936 # *Condition 937 dest["condition"] = [] 938 for i in sorted(data["condition"].keys()): 939 dest["condition"].append(data["condition"][i]) 940 941 if "reply" in data and len(data["reply"].keys()): 942 # -Reply 943 dest["reply"] = [] 944 for i in sorted(data["reply"].keys()): 945 dest["reply"].append(data["reply"][i]) 946 947 return dest
948
949 - def _write_triggers(self, fh, triggers, indent=""):
950 """Write triggers to a file handle.""" 951 952 for trig in sorted(triggers.keys()): 953 fh.write(indent + "+ " + self._write_wrapped(trig, indent=indent) + "\n") 954 d = triggers[trig] 955 956 if "previous" in d: 957 fh.write(indent + "% " + self._write_wrapped(d["previous"], indent=indent) + "\n") 958 959 if "condition" in d: 960 for cond in d["condition"]: 961 fh.write(indent + "* " + self._write_wrapped(cond, indent=indent) + "\n") 962 963 if "redirect" in d: 964 fh.write(indent + "@ " + self._write_wrapped(d["redirect"], indent=indent) + "\n") 965 966 if "reply" in d: 967 for reply in d["reply"]: 968 fh.write(indent + "- " + self._write_wrapped(reply, indent=indent) + "\n") 969 970 fh.write("\n")
971
972 - def _write_wrapped(self, line, sep=" ", indent="", width=78):
973 """Word-wrap a line of RiveScript code for being written to a file.""" 974 975 words = line.split(sep) 976 lines = [] 977 line = "" 978 buf = [] 979 980 while len(words): 981 buf.append(words.pop(0)) 982 line = sep.join(buf) 983 if len(line) > width: 984 # Need to word wrap! 985 words.insert(0, buf.pop()) # Undo 986 lines.append(sep.join(buf)) 987 buf = [] 988 line = "" 989 990 # Straggler? 991 if line: 992 lines.append(line) 993 994 # Returned output 995 result = lines.pop(0) 996 if len(lines): 997 eol = "" 998 if sep == " ": 999 eol = "\s" 1000 for item in lines: 1001 result += eol + "\n" + indent + "^ " + item 1002 1003 return result
1004
1005 - def _initTT(self, toplevel, topic, trigger, what=''):
1006 """Initialize a Topic Tree data structure.""" 1007 if toplevel == 'topics': 1008 if topic not in self._topics: 1009 self._topics[topic] = {} 1010 if trigger not in self._topics[topic]: 1011 self._topics[topic][trigger] = {} 1012 self._topics[topic][trigger]['reply'] = {} 1013 self._topics[topic][trigger]['condition'] = {} 1014 self._topics[topic][trigger]['redirect'] = None 1015 elif toplevel == 'thats': 1016 if topic not in self._thats: 1017 self._thats[topic] = {} 1018 if trigger not in self._thats[topic]: 1019 self._thats[topic][trigger] = {} 1020 if what not in self._thats[topic][trigger]: 1021 self._thats[topic][trigger][what] = {} 1022 self._thats[topic][trigger][what]['reply'] = {} 1023 self._thats[topic][trigger][what]['condition'] = {} 1024 self._thats[topic][trigger][what]['redirect'] = {} 1025 elif toplevel == 'syntax': 1026 if what not in self._syntax: 1027 self._syntax[what] = {} 1028 if topic not in self._syntax[what]: 1029 self._syntax[what][topic] = {} 1030 if trigger not in self._syntax[what][topic]: 1031 self._syntax[what][topic][trigger] = {} 1032 self._syntax[what][topic][trigger]['reply'] = {} 1033 self._syntax[what][topic][trigger]['condition'] = {} 1034 self._syntax[what][topic][trigger]['redirect'] = {}
1035 1036 ############################################################################ 1037 # Sorting Methods # 1038 ############################################################################ 1039
1040 - def sort_replies(self, thats=False):
1041 """Sort the loaded triggers.""" 1042 # This method can sort both triggers and that's. 1043 triglvl = None 1044 sortlvl = None 1045 if thats: 1046 triglvl = self._thats 1047 sortlvl = 'thats' 1048 else: 1049 triglvl = self._topics 1050 sortlvl = 'topics' 1051 1052 # (Re)Initialize the sort cache. 1053 self._sorted[sortlvl] = {} 1054 1055 self._say("Sorting triggers...") 1056 1057 # Loop through all the topics. 1058 for topic in triglvl: 1059 self._say("Analyzing topic " + topic) 1060 1061 # Collect a list of all the triggers we're going to need to worry 1062 # about. If this topic inherits another topic, we need to 1063 # recursively add those to the list. 1064 alltrig = self._topic_triggers(topic, triglvl) 1065 1066 # Keep in mind here that there is a difference between 'includes' 1067 # and 'inherits' -- topics that inherit other topics are able to 1068 # OVERRIDE triggers that appear in the inherited topic. This means 1069 # that if the top topic has a trigger of simply '*', then *NO* 1070 # triggers are capable of matching in ANY inherited topic, because 1071 # even though * has the lowest sorting priority, it has an automatic 1072 # priority over all inherited topics. 1073 # 1074 # The _topic_triggers method takes this into account. All topics 1075 # that inherit other topics will have their triggers prefixed with 1076 # a fictional {inherits} tag, which would start at {inherits=0} and 1077 # increment if the topic tree has other inheriting topics. So we can 1078 # use this tag to make sure topics that inherit things will have 1079 # their triggers always be on top of the stack, from inherits=0 to 1080 # inherits=n. 1081 1082 # Sort these triggers. 1083 running = self._sort_trigger_set(alltrig) 1084 1085 # Save this topic's sorted list. 1086 if sortlvl not in self._sorted: 1087 self._sorted[sortlvl] = {} 1088 self._sorted[sortlvl][topic] = running 1089 1090 # And do it all again for %Previous! 1091 if not thats: 1092 # This will sort the %Previous lines to best match the bot's last reply. 1093 self.sort_replies(True) 1094 1095 # If any of those %Previous's had more than one +trigger for them, 1096 # this will sort all those +triggers to pair back the best human 1097 # interaction. 1098 self._sort_that_triggers() 1099 1100 # Also sort both kinds of substitutions. 1101 self._sort_list('subs', self._subs) 1102 self._sort_list('person', self._person)
1103
1104 - def _sort_that_triggers(self):
1105 """Make a sorted list of triggers that correspond to %Previous groups.""" 1106 self._say("Sorting reverse triggers for %Previous groups...") 1107 1108 if "that_trig" not in self._sorted: 1109 self._sorted["that_trig"] = {} 1110 1111 for topic in self._thats: 1112 if topic not in self._sorted["that_trig"]: 1113 self._sorted["that_trig"][topic] = {} 1114 1115 for bottrig in self._thats[topic]: 1116 if bottrig not in self._sorted["that_trig"][topic]: 1117 self._sorted["that_trig"][topic][bottrig] = [] 1118 triggers = self._sort_trigger_set(self._thats[topic][bottrig].keys()) 1119 self._sorted["that_trig"][topic][bottrig] = triggers
1120
1121 - def _sort_trigger_set(self, triggers):
1122 """Sort a group of triggers in optimal sorting order.""" 1123 1124 # Create a priority map. 1125 prior = { 1126 0: [] # Default priority=0 1127 } 1128 1129 for trig in triggers: 1130 match, weight = re.search(RE.weight, trig), 0 1131 if match: 1132 weight = int(match.group(1)) 1133 if weight not in prior: 1134 prior[weight] = [] 1135 1136 prior[weight].append(trig) 1137 1138 # Keep a running list of sorted triggers for this topic. 1139 running = [] 1140 1141 # Sort them by priority. 1142 for p in sorted(prior.keys(), reverse=True): 1143 self._say("\tSorting triggers with priority " + str(p)) 1144 1145 # So, some of these triggers may include {inherits} tags, if they 1146 # came form a topic which inherits another topic. Lower inherits 1147 # values mean higher priority on the stack. 1148 inherits = -1 # -1 means no {inherits} tag 1149 highest_inherits = -1 # highest inheritance number seen 1150 1151 # Loop through and categorize these triggers. 1152 track = { 1153 inherits: self._init_sort_track() 1154 } 1155 1156 for trig in prior[p]: 1157 self._say("\t\tLooking at trigger: " + trig) 1158 1159 # See if it has an inherits tag. 1160 match = re.search(RE.inherit, trig) 1161 if match: 1162 inherits = int(match.group(1)) 1163 if inherits > highest_inherits: 1164 highest_inherits = inherits 1165 self._say("\t\t\tTrigger belongs to a topic which inherits other topics: level=" + str(inherits)) 1166 trig = re.sub(RE.inherit, "", trig) 1167 else: 1168 inherits = -1 1169 1170 # If this is the first time we've seen this inheritance level, 1171 # initialize its track structure. 1172 if inherits not in track: 1173 track[inherits] = self._init_sort_track() 1174 1175 # Start inspecting the trigger's contents. 1176 if '_' in trig: 1177 # Alphabetic wildcard included. 1178 cnt = self._word_count(trig) 1179 self._say("\t\t\tHas a _ wildcard with " + str(cnt) + " words.") 1180 if cnt > 1: 1181 if cnt not in track[inherits]['alpha']: 1182 track[inherits]['alpha'][cnt] = [] 1183 track[inherits]['alpha'][cnt].append(trig) 1184 else: 1185 track[inherits]['under'].append(trig) 1186 elif '#' in trig: 1187 # Numeric wildcard included. 1188 cnt = self._word_count(trig) 1189 self._say("\t\t\tHas a # wildcard with " + str(cnt) + " words.") 1190 if cnt > 1: 1191 if cnt not in track[inherits]['number']: 1192 track[inherits]['number'][cnt] = [] 1193 track[inherits]['number'][cnt].append(trig) 1194 else: 1195 track[inherits]['pound'].append(trig) 1196 elif '*' in trig: 1197 # Wildcard included. 1198 cnt = self._word_count(trig) 1199 self._say("\t\t\tHas a * wildcard with " + str(cnt) + " words.") 1200 if cnt > 1: 1201 if cnt not in track[inherits]['wild']: 1202 track[inherits]['wild'][cnt] = [] 1203 track[inherits]['wild'][cnt].append(trig) 1204 else: 1205 track[inherits]['star'].append(trig) 1206 elif '[' in trig: 1207 # Optionals included. 1208 cnt = self._word_count(trig) 1209 self._say("\t\t\tHas optionals and " + str(cnt) + " words.") 1210 if cnt not in track[inherits]['option']: 1211 track[inherits]['option'][cnt] = [] 1212 track[inherits]['option'][cnt].append(trig) 1213 else: 1214 # Totally atomic. 1215 cnt = self._word_count(trig) 1216 self._say("\t\t\tTotally atomic and " + str(cnt) + " words.") 1217 if cnt not in track[inherits]['atomic']: 1218 track[inherits]['atomic'][cnt] = [] 1219 track[inherits]['atomic'][cnt].append(trig) 1220 1221 # Move the no-{inherits} triggers to the bottom of the stack. 1222 track[highest_inherits + 1] = track[-1] 1223 del(track[-1]) 1224 1225 # Add this group to the sort list. 1226 for ip in sorted(track.keys()): 1227 self._say("ip=" + str(ip)) 1228 for kind in ['atomic', 'option', 'alpha', 'number', 'wild']: 1229 for wordcnt in sorted(track[ip][kind], reverse=True): 1230 # Triggers with a matching word count should be sorted 1231 # by length, descending. 1232 running.extend(sorted(track[ip][kind][wordcnt], key=len, reverse=True)) 1233 running.extend(sorted(track[ip]['under'], key=len, reverse=True)) 1234 running.extend(sorted(track[ip]['pound'], key=len, reverse=True)) 1235 running.extend(sorted(track[ip]['star'], key=len, reverse=True)) 1236 return running
1237
1238 - def _sort_list(self, name, items):
1239 """Sort a simple list by number of words and length.""" 1240 1241 def by_length(word1, word2): 1242 return len(word2) - len(word1)
1243 1244 # Initialize the list sort buffer. 1245 if "lists" not in self._sorted: 1246 self._sorted["lists"] = {} 1247 self._sorted["lists"][name] = [] 1248 1249 # Track by number of words. 1250 track = {} 1251 1252 # Loop through each item. 1253 for item in items: 1254 # Count the words. 1255 cword = self._word_count(item, all=True) 1256 if cword not in track: 1257 track[cword] = [] 1258 track[cword].append(item) 1259 1260 # Sort them. 1261 output = [] 1262 for count in sorted(track.keys(), reverse=True): 1263 sort = sorted(track[count], key=len, reverse=True) 1264 output.extend(sort) 1265 1266 self._sorted["lists"][name] = output
1267
1268 - def _init_sort_track(self):
1269 """Returns a new dict for keeping track of triggers for sorting.""" 1270 return { 1271 'atomic': {}, # Sort by number of whole words 1272 'option': {}, # Sort optionals by number of words 1273 'alpha': {}, # Sort alpha wildcards by no. of words 1274 'number': {}, # Sort number wildcards by no. of words 1275 'wild': {}, # Sort wildcards by no. of words 1276 'pound': [], # Triggers of just # 1277 'under': [], # Triggers of just _ 1278 'star': [] # Triggers of just * 1279 }
1280 1281 1282 ############################################################################ 1283 # Public Configuration Methods # 1284 ############################################################################ 1285
1286 - def set_handler(self, language, obj):
1287 """Define a custom language handler for RiveScript objects. 1288 1289 language: The lowercased name of the programming language, 1290 e.g. python, javascript, perl 1291 obj: An instance of a class object that provides the following interface: 1292 1293 class MyObjectHandler: 1294 def __init__(self): 1295 pass 1296 def load(self, name, code): 1297 # name = the name of the object from the RiveScript code 1298 # code = the source code of the object 1299 def call(self, rs, name, fields): 1300 # rs = the current RiveScript interpreter object 1301 # name = the name of the object being called 1302 # fields = array of arguments passed to the object 1303 return reply 1304 1305 Pass in a None value for the object to delete an existing handler (for example, 1306 to prevent Python code from being able to be run by default). 1307 1308 Look in the `eg` folder of the rivescript-python distribution for an example 1309 script that sets up a JavaScript language handler.""" 1310 1311 # Allow them to delete a handler too. 1312 if obj is None: 1313 if language in self._handlers: 1314 del self._handlers[language] 1315 else: 1316 self._handlers[language] = obj
1317
1318 - def set_subroutine(self, name, code):
1319 """Define a Python object from your program. 1320 1321 This is equivalent to having an object defined in the RiveScript code, except 1322 your Python code is defining it instead. `name` is the name of the object, and 1323 `code` is a Python function (a `def`) that accepts rs,args as its parameters. 1324 1325 This method is only available if there is a Python handler set up (which there 1326 is by default, unless you've called set_handler("python", None)).""" 1327 1328 # Do we have a Python handler? 1329 if 'python' in self._handlers: 1330 self._handlers['python']._objects[name] = code 1331 else: 1332 self._warn("Can't set_subroutine: no Python object handler!")
1333
1334 - def set_global(self, name, value):
1335 """Set a global variable. 1336 1337 Equivalent to `! global` in RiveScript code. Set to None to delete.""" 1338 if value is None: 1339 # Unset the variable. 1340 if name in self._gvars: 1341 del self._gvars[name] 1342 self._gvars[name] = value
1343
1344 - def set_variable(self, name, value):
1345 """Set a bot variable. 1346 1347 Equivalent to `! var` in RiveScript code. Set to None to delete.""" 1348 if value is None: 1349 # Unset the variable. 1350 if name in self._bvars: 1351 del self._bvars[name] 1352 self._bvars[name] = value
1353
1354 - def set_substitution(self, what, rep):
1355 """Set a substitution. 1356 1357 Equivalent to `! sub` in RiveScript code. Set to None to delete.""" 1358 if rep is None: 1359 # Unset the variable. 1360 if what in self._subs: 1361 del self._subs[what] 1362 self._subs[what] = rep
1363
1364 - def set_person(self, what, rep):
1365 """Set a person substitution. 1366 1367 Equivalent to `! person` in RiveScript code. Set to None to delete.""" 1368 if rep is None: 1369 # Unset the variable. 1370 if what in self._person: 1371 del self._person[what] 1372 self._person[what] = rep
1373
1374 - def set_uservar(self, user, name, value):
1375 """Set a variable for a user.""" 1376 1377 if user not in self._users: 1378 self._users[user] = {"topic": "random"} 1379 1380 self._users[user][name] = value
1381
1382 - def get_uservar(self, user, name):
1383 """Get a variable about a user. 1384 1385 If the user has no data at all, returns None. If the user doesn't have a value 1386 set for the variable you want, returns the string 'undefined'.""" 1387 1388 if user in self._users: 1389 if name in self._users[user]: 1390 return self._users[user][name] 1391 else: 1392 return "undefined" 1393 else: 1394 return None
1395
1396 - def get_uservars(self, user=None):
1397 """Get all variables about a user (or all users). 1398 1399 If no username is passed, returns the entire user database structure. Otherwise, 1400 only returns the variables for the given user, or None if none exist.""" 1401 1402 if user is None: 1403 # All the users! 1404 return self._users 1405 elif user in self._users: 1406 # Just this one! 1407 return self._users[user] 1408 else: 1409 # No info. 1410 return None
1411
1412 - def clear_uservars(self, user=None):
1413 """Delete all variables about a user (or all users). 1414 1415 If no username is passed, deletes all variables about all users. Otherwise, only 1416 deletes all variables for the given user.""" 1417 1418 if user is None: 1419 # All the users! 1420 self._users = {} 1421 elif user in self._users: 1422 # Just this one. 1423 self._users[user] = {}
1424
1425 - def freeze_uservars(self, user):
1426 """Freeze the variable state for a user. 1427 1428 This will clone and preserve a user's entire variable state, so that it can be 1429 restored later with `thaw_uservars`.""" 1430 1431 if user in self._users: 1432 # Clone the user's data. 1433 self._freeze[user] = copy.deepcopy(self._users[user]) 1434 else: 1435 self._warn("Can't freeze vars for user " + user + ": not found!")
1436
1437 - def thaw_uservars(self, user, action="thaw"):
1438 """Thaw a user's frozen variables. 1439 1440 The `action` can be one of the following options: 1441 1442 discard: Don't restore the user's variables, just delete the frozen copy. 1443 keep: Keep the frozen copy after restoring the variables. 1444 thaw: Restore the variables, then delete the frozen copy (default).""" 1445 1446 if user in self._freeze: 1447 # What are we doing? 1448 if action == "thaw": 1449 # Thawing them out. 1450 self.clear_uservars(user) 1451 self._users[user] = copy.deepcopy(self._freeze[user]) 1452 del self._freeze[user] 1453 elif action == "discard": 1454 # Just discard the frozen copy. 1455 del self._freeze[user] 1456 elif action == "keep": 1457 # Keep the frozen copy afterward. 1458 self.clear_uservars(user) 1459 self._users[user] = copy.deepcopy(self._freeze[user]) 1460 else: 1461 self._warn("Unsupported thaw action") 1462 else: 1463 self._warn("Can't thaw vars for user " + user + ": not found!")
1464
1465 - def last_match(self, user):
1466 """Get the last trigger matched for the user. 1467 1468 This will return the raw trigger text that the user's last message matched. If 1469 there was no match, this will return None.""" 1470 return self.get_uservar(user, "__lastmatch__")
1471
1472 - def trigger_info(self, trigger=None, dump=False):
1473 """Get information about a trigger. 1474 1475 Pass in a raw trigger to find out what file name and line number it appeared at. 1476 This is useful for e.g. tracking down the location of the trigger last matched 1477 by the user via last_match(). Returns a list of matching triggers, containing 1478 their topics, filenames and line numbers. Returns None if there weren't 1479 any matches found. 1480 1481 The keys in the trigger info is as follows: 1482 1483 * category: Either 'topic' (for normal) or 'thats' (for %Previous triggers) 1484 * topic: The topic name 1485 * trigger: The raw trigger text 1486 * filename: The filename the trigger was found in. 1487 * lineno: The line number the trigger was found on. 1488 1489 Pass in a true value for `dump`, and the entire syntax tracking 1490 tree is returned.""" 1491 if dump: 1492 return self._syntax 1493 1494 response = None 1495 1496 # Search the syntax tree for the trigger. 1497 for category in self._syntax: 1498 for topic in self._syntax[category]: 1499 if trigger in self._syntax[category][topic]: 1500 # We got a match! 1501 if response is None: 1502 response = list() 1503 fname, lineno = self._syntax[category][topic][trigger]['trigger'] 1504 response.append(dict( 1505 category=category, 1506 topic=topic, 1507 trigger=trigger, 1508 filename=fname, 1509 line=lineno, 1510 )) 1511 1512 return response
1513
1514 - def current_user(self):
1515 """Retrieve the user ID of the current user talking to your bot. 1516 1517 This is mostly useful inside of a Python object macro to get the user ID of the 1518 person who caused the object macro to be invoked (i.e. to set a variable for 1519 that user from within the object). 1520 1521 This will return None if used outside of the context of getting a reply (i.e. 1522 the value is unset at the end of the `reply()` method).""" 1523 if self._current_user is None: 1524 # They're doing it wrong. 1525 self._warn("current_user() is meant to be used from within a Python object macro!") 1526 return self._current_user
1527 1528 ############################################################################ 1529 # Reply Fetching Methods # 1530 ############################################################################ 1531
1532 - def reply(self, user, msg, errors_as_replies=True):
1533 """Fetch a reply from the RiveScript brain.""" 1534 self._say("Get reply to [" + user + "] " + msg) 1535 1536 # Store the current user in case an object macro needs it. 1537 self._current_user = user 1538 1539 # Format their message. 1540 msg = self._format_message(msg) 1541 1542 reply = '' 1543 1544 # If the BEGIN block exists, consult it first. 1545 if "__begin__" in self._topics: 1546 begin = self._getreply(user, 'request', context='begin', ignore_object_errors=errors_as_replies) 1547 1548 # Okay to continue? 1549 if '{ok}' in begin: 1550 try: 1551 reply = self._getreply(user, msg, ignore_object_errors=errors_as_replies) 1552 except RiveScriptError as e: 1553 if not errors_as_replies: 1554 raise 1555 reply = e.error_message 1556 begin = begin.replace('{ok}', reply) 1557 1558 reply = begin 1559 1560 # Run more tag substitutions. 1561 reply = self._process_tags(user, msg, reply, ignore_object_errors=errors_as_replies) 1562 else: 1563 # Just continue then. 1564 try: 1565 reply = self._getreply(user, msg, ignore_object_errors=errors_as_replies) 1566 except RiveScriptError as e: 1567 if not errors_as_replies: 1568 raise 1569 reply = e.error_message 1570 1571 # Save their reply history. 1572 oldInput = self._users[user]['__history__']['input'][:8] 1573 self._users[user]['__history__']['input'] = [msg] 1574 self._users[user]['__history__']['input'].extend(oldInput) 1575 oldReply = self._users[user]['__history__']['reply'][:8] 1576 self._users[user]['__history__']['reply'] = [reply] 1577 self._users[user]['__history__']['reply'].extend(oldReply) 1578 1579 # Unset the current user. 1580 self._current_user = None 1581 1582 return reply
1583
1584 - def _format_message(self, msg, botreply=False):
1585 """Format a user's message for safe processing.""" 1586 1587 # Make sure the string is Unicode for Python 2. 1588 if sys.version_info[0] < 3 and isinstance(msg, str): 1589 msg = msg.decode('utf8') 1590 1591 # Lowercase it. 1592 msg = msg.lower() 1593 1594 # Run substitutions on it. 1595 msg = self._substitute(msg, "subs") 1596 1597 # In UTF-8 mode, only strip metacharacters and HTML brackets 1598 # (to protect from obvious XSS attacks). 1599 if self._utf8: 1600 msg = re.sub(RE.utf8_meta, '', msg) 1601 msg = re.sub(self.unicode_punctuation, '', msg) 1602 1603 # For the bot's reply, also strip common punctuation. 1604 if botreply: 1605 msg = re.sub(RE.utf8_punct, '', msg) 1606 else: 1607 # For everything else, strip all non-alphanumerics. 1608 msg = self._strip_nasties(msg) 1609 1610 return msg
1611
1612 - def _getreply(self, user, msg, context='normal', step=0, ignore_object_errors=True):
1613 # Needed to sort replies? 1614 if 'topics' not in self._sorted: 1615 raise RepliesNotSortedError("You must call sort_replies() once you are done loading RiveScript documents") 1616 1617 # Initialize the user's profile? 1618 if user not in self._users: 1619 self._users[user] = {'topic': 'random'} 1620 1621 # Collect data on the user. 1622 topic = self._users[user]['topic'] 1623 stars = [] 1624 thatstars = [] # For %Previous's. 1625 reply = '' 1626 1627 # Avoid letting them fall into a missing topic. 1628 if topic not in self._topics: 1629 self._warn("User " + user + " was in an empty topic named '" + topic + "'") 1630 topic = self._users[user]['topic'] = 'random' 1631 1632 # Avoid deep recursion. 1633 if step > self._depth: 1634 raise DeepRecursionError 1635 1636 # Are we in the BEGIN statement? 1637 if context == 'begin': 1638 topic = '__begin__' 1639 1640 # Initialize this user's history. 1641 if '__history__' not in self._users[user]: 1642 self._users[user]['__history__'] = { 1643 'input': [ 1644 'undefined', 'undefined', 'undefined', 'undefined', 1645 'undefined', 'undefined', 'undefined', 'undefined', 1646 'undefined' 1647 ], 1648 'reply': [ 1649 'undefined', 'undefined', 'undefined', 'undefined', 1650 'undefined', 'undefined', 'undefined', 'undefined', 1651 'undefined' 1652 ] 1653 } 1654 1655 # More topic sanity checking. 1656 if topic not in self._topics: 1657 # This was handled before, which would mean topic=random and 1658 # it doesn't exist. Serious issue! 1659 raise NoDefaultRandomTopicError("no default topic 'random' was found") 1660 1661 # Create a pointer for the matched data when we find it. 1662 matched = None 1663 matchedTrigger = None 1664 foundMatch = False 1665 1666 # See if there were any %Previous's in this topic, or any topic related 1667 # to it. This should only be done the first time -- not during a 1668 # recursive redirection. This is because in a redirection, "lastreply" 1669 # is still gonna be the same as it was the first time, causing an 1670 # infinite loop! 1671 if step == 0: 1672 allTopics = [topic] 1673 if topic in self._includes or topic in self._lineage: 1674 # Get all the topics! 1675 allTopics = self._get_topic_tree(topic) 1676 1677 # Scan them all! 1678 for top in allTopics: 1679 self._say("Checking topic " + top + " for any %Previous's.") 1680 if top in self._sorted["thats"]: 1681 self._say("There is a %Previous in this topic!") 1682 1683 # Do we have history yet? 1684 lastReply = self._users[user]["__history__"]["reply"][0] 1685 1686 # Format the bot's last reply the same way as the human's. 1687 lastReply = self._format_message(lastReply, botreply=True) 1688 1689 self._say("lastReply: " + lastReply) 1690 1691 # See if it's a match. 1692 for trig in self._sorted["thats"][top]: 1693 botside = self._reply_regexp(user, trig) 1694 self._say("Try to match lastReply (" + lastReply + ") to " + trig) 1695 1696 # Match?? 1697 match = re.match(botside, lastReply) 1698 if match: 1699 # Huzzah! See if OUR message is right too. 1700 self._say("Bot side matched!") 1701 thatstars = match.groups() 1702 for subtrig in self._sorted["that_trig"][top][trig]: 1703 humanside = self._reply_regexp(user, subtrig) 1704 self._say("Now try to match " + msg + " to " + subtrig) 1705 1706 match = re.match(humanside, msg) 1707 if match: 1708 self._say("Found a match!") 1709 matched = self._thats[top][trig][subtrig] 1710 matchedTrigger = subtrig 1711 foundMatch = True 1712 1713 # Get the stars! 1714 stars = match.groups() 1715 break 1716 1717 # Break if we found a match. 1718 if foundMatch: 1719 break 1720 # Break if we found a match. 1721 if foundMatch: 1722 break 1723 1724 # Search their topic for a match to their trigger. 1725 if not foundMatch: 1726 for trig in self._sorted["topics"][topic]: 1727 # Process the triggers. 1728 regexp = self._reply_regexp(user, trig) 1729 self._say("Try to match %r against %r (%r)" % (msg, trig, regexp)) 1730 1731 # Python's regular expression engine is slow. Try a verbatim 1732 # match if this is an atomic trigger. 1733 isAtomic = self._is_atomic(trig) 1734 isMatch = False 1735 if isAtomic: 1736 # Only look for exact matches, no sense running atomic triggers 1737 # through the regexp engine. 1738 if msg == trig: 1739 isMatch = True 1740 else: 1741 # Non-atomic triggers always need the regexp. 1742 match = re.match(regexp, msg) 1743 if match: 1744 # The regexp matched! 1745 isMatch = True 1746 1747 # Collect the stars. 1748 stars = match.groups() 1749 1750 if isMatch: 1751 self._say("Found a match!") 1752 1753 # We found a match, but what if the trigger we've matched 1754 # doesn't belong to our topic? Find it! 1755 if trig not in self._topics[topic]: 1756 # We have to find it. 1757 matched = self._find_trigger_by_inheritance(topic, trig) 1758 else: 1759 # We do have it! 1760 matched = self._topics[topic][trig] 1761 1762 foundMatch = True 1763 matchedTrigger = trig 1764 break 1765 1766 # Store what trigger they matched on. If their matched trigger is None, 1767 # this will be too, which is great. 1768 self._users[user]["__lastmatch__"] = matchedTrigger 1769 1770 if matched: 1771 for nil in [1]: 1772 # See if there are any hard redirects. 1773 if matched["redirect"]: 1774 self._say("Redirecting us to " + matched["redirect"]) 1775 redirect = self._process_tags(user, msg, matched["redirect"], stars, thatstars, step, 1776 ignore_object_errors) 1777 self._say("Pretend user said: " + redirect) 1778 reply = self._getreply(user, redirect, step=(step + 1), ignore_object_errors=ignore_object_errors) 1779 break 1780 1781 # Check the conditionals. 1782 for con in sorted(matched["condition"]): 1783 halves = re.split(RE.cond_split, matched["condition"][con]) 1784 if halves and len(halves) == 2: 1785 condition = re.match(RE.cond_parse, halves[0]) 1786 if condition: 1787 left = condition.group(1) 1788 eq = condition.group(2) 1789 right = condition.group(3) 1790 potreply = halves[1] 1791 self._say("Left: " + left + "; eq: " + eq + "; right: " + right + " => " + potreply) 1792 1793 # Process tags all around. 1794 left = self._process_tags(user, msg, left, stars, thatstars, step, ignore_object_errors) 1795 right = self._process_tags(user, msg, right, stars, thatstars, step, ignore_object_errors) 1796 1797 # Defaults? 1798 if len(left) == 0: 1799 left = 'undefined' 1800 if len(right) == 0: 1801 right = 'undefined' 1802 1803 self._say("Check if " + left + " " + eq + " " + right) 1804 1805 # Validate it. 1806 passed = False 1807 if eq == 'eq' or eq == '==': 1808 if left == right: 1809 passed = True 1810 elif eq == 'ne' or eq == '!=' or eq == '<>': 1811 if left != right: 1812 passed = True 1813 else: 1814 # Gasp, dealing with numbers here... 1815 try: 1816 left, right = int(left), int(right) 1817 if eq == '<': 1818 if left < right: 1819 passed = True 1820 elif eq == '<=': 1821 if left <= right: 1822 passed = True 1823 elif eq == '>': 1824 if left > right: 1825 passed = True 1826 elif eq == '>=': 1827 if left >= right: 1828 passed = True 1829 except: 1830 self._warn("Failed to evaluate numeric condition!") 1831 1832 # How truthful? 1833 if passed: 1834 reply = potreply 1835 break 1836 1837 # Have our reply yet? 1838 if len(reply) > 0: 1839 break 1840 1841 # Process weights in the replies. 1842 bucket = [] 1843 for rep in sorted(matched["reply"]): 1844 text = matched["reply"][rep] 1845 weight = 1 1846 match = re.match(RE.weight, text) 1847 if match: 1848 weight = int(match.group(1)) 1849 if weight <= 0: 1850 self._warn("Can't have a weight <= 0!") 1851 weight = 1 1852 for i in range(0, weight): 1853 bucket.append(text) 1854 1855 # Get a random reply. 1856 reply = random.choice(bucket) 1857 break 1858 1859 # Still no reply? 1860 if not foundMatch: 1861 raise NoMatchError 1862 elif len(reply) == 0: 1863 raise NoReplyError 1864 1865 self._say("Reply: " + reply) 1866 1867 # Process tags for the BEGIN block. 1868 if context == "begin": 1869 # BEGIN blocks can only set topics and uservars. The rest happen 1870 # later! 1871 reTopic = re.findall(RE.topic_tag, reply) 1872 for match in reTopic: 1873 self._say("Setting user's topic to " + match) 1874 self._users[user]["topic"] = match 1875 reply = reply.replace('{{topic={match}}}'.format(match=match), '') 1876 1877 reSet = re.findall(RE.set_tag, reply) 1878 for match in reSet: 1879 self._say("Set uservar " + str(match[0]) + "=" + str(match[1])) 1880 self._users[user][match[0]] = match[1] 1881 reply = reply.replace('<set {key}={value}>'.format(key=match[0], value=match[1]), '') 1882 else: 1883 # Process more tags if not in BEGIN. 1884 reply = self._process_tags(user, msg, reply, stars, thatstars, step, ignore_object_errors) 1885 1886 return reply
1887
1888 - def _substitute(self, msg, kind):
1889 """Run a kind of substitution on a message.""" 1890 1891 # Safety checking. 1892 if 'lists' not in self._sorted: 1893 raise RepliesNotSortedError("You must call sort_replies() once you are done loading RiveScript documents") 1894 if kind not in self._sorted["lists"]: 1895 raise RepliesNotSortedError("You must call sort_replies() once you are done loading RiveScript documents") 1896 1897 # Get the substitution map. 1898 subs = None 1899 if kind == 'subs': 1900 subs = self._subs 1901 else: 1902 subs = self._person 1903 1904 # Make placeholders each time we substitute something. 1905 ph = [] 1906 i = 0 1907 1908 for pattern in self._sorted["lists"][kind]: 1909 result = subs[pattern] 1910 1911 # Make a placeholder. 1912 ph.append(result) 1913 placeholder = "\x00%d\x00" % i 1914 i += 1 1915 1916 cache = self._regexc[kind][pattern] 1917 msg = re.sub(cache["sub1"], placeholder, msg) 1918 msg = re.sub(cache["sub2"], placeholder + r'\1', msg) 1919 msg = re.sub(cache["sub3"], r'\1' + placeholder + r'\2', msg) 1920 msg = re.sub(cache["sub4"], r'\1' + placeholder, msg) 1921 1922 placeholders = re.findall(RE.placeholder, msg) 1923 for match in placeholders: 1924 i = int(match) 1925 result = ph[i] 1926 msg = msg.replace('\x00' + match + '\x00', result) 1927 1928 # Strip & return. 1929 return msg.strip()
1930
1931 - def _precompile_substitution(self, kind, pattern):
1932 """Pre-compile the regexp for a substitution pattern. 1933 1934 This will speed up the substitutions that happen at the beginning of 1935 the reply fetching process. With the default brain, this took the 1936 time for _substitute down from 0.08s to 0.02s""" 1937 if pattern not in self._regexc[kind]: 1938 qm = re.escape(pattern) 1939 self._regexc[kind][pattern] = { 1940 "qm": qm, 1941 "sub1": re.compile(r'^' + qm + r'$'), 1942 "sub2": re.compile(r'^' + qm + r'(\W+)'), 1943 "sub3": re.compile(r'(\W+)' + qm + r'(\W+)'), 1944 "sub4": re.compile(r'(\W+)' + qm + r'$'), 1945 }
1946
1947 - def _reply_regexp(self, user, regexp):
1948 """Prepares a trigger for the regular expression engine.""" 1949 1950 if regexp in self._regexc["trigger"]: 1951 # Already compiled this one! 1952 return self._regexc["trigger"][regexp] 1953 1954 # If the trigger is simply '*' then the * there needs to become (.*?) 1955 # to match the blank string too. 1956 regexp = re.sub(RE.zero_star, r'<zerowidthstar>', regexp) 1957 1958 # Simple replacements. 1959 regexp = regexp.replace('*', '(.+?)') # Convert * into (.+?) 1960 regexp = regexp.replace('#', '(\d+?)') # Convert # into (\d+?) 1961 regexp = regexp.replace('_', '(\w+?)') # Convert _ into (\w+?) 1962 regexp = re.sub(r'\{weight=\d+\}', '', regexp) # Remove {weight} tags 1963 regexp = regexp.replace('<zerowidthstar>', r'(.*?)') 1964 1965 # Optionals. 1966 optionals = re.findall(RE.optionals, regexp) 1967 for match in optionals: 1968 parts = match.split("|") 1969 new = [] 1970 for p in parts: 1971 p = r'(?:\\s|\\b)+{}(?:\\s|\\b)+'.format(p) 1972 new.append(p) 1973 1974 # If this optional had a star or anything in it, make it 1975 # non-matching. 1976 pipes = '|'.join(new) 1977 pipes = re.sub(re.escape('(.+?)'), '(?:.+?)', pipes) 1978 pipes = re.sub(re.escape('(\d+?)'), '(?:\d+?)', pipes) 1979 pipes = re.sub(re.escape('([A-Za-z]+?)'), '(?:[A-Za-z]+?)', pipes) 1980 1981 regexp = re.sub(r'\s*\[' + re.escape(match) + '\]\s*', 1982 '(?:' + pipes + r'|(?:\\s|\\b))', regexp) 1983 1984 # _ wildcards can't match numbers! 1985 regexp = re.sub(RE.literal_w, r'[A-Za-z]', regexp) 1986 1987 # Filter in arrays. 1988 arrays = re.findall(RE.array, regexp) 1989 for array in arrays: 1990 rep = '' 1991 if array in self._arrays: 1992 rep = r'(?:' + '|'.join(self._arrays[array]) + ')' 1993 regexp = re.sub(r'\@' + re.escape(array) + r'\b', rep, regexp) 1994 1995 # Filter in bot variables. 1996 bvars = re.findall(RE.bot_tag, regexp) 1997 for var in bvars: 1998 rep = '' 1999 if var in self._bvars: 2000 rep = self._strip_nasties(self._bvars[var]) 2001 regexp = regexp.replace('<bot {var}>'.format(var=var), rep) 2002 2003 # Filter in user variables. 2004 uvars = re.findall(RE.get_tag, regexp) 2005 for var in uvars: 2006 rep = '' 2007 if var in self._users[user]: 2008 rep = self._strip_nasties(self._users[user][var]) 2009 regexp = regexp.replace('<get {var}>'.format(var=var), rep) 2010 2011 # Filter in <input> and <reply> tags. This is a slow process, so only 2012 # do it if we have to! 2013 if '<input' in regexp or '<reply' in regexp: 2014 for type in ['input', 'reply']: 2015 tags = re.findall(r'<' + type + r'([0-9])>', regexp) 2016 for index in tags: 2017 rep = self._format_message(self._users[user]['__history__'][type][int(index) - 1]) 2018 regexp = regexp.replace('<{type}{index}>'.format(type=type, index=index), rep) 2019 regexp = regexp.replace('<{type}>'.format(type=type), 2020 self._format_message(self._users[user]['__history__'][type][0])) 2021 # TODO: the Perl version doesn't do just <input>/<reply> in trigs! 2022 2023 return re.compile(r'^' + regexp + r'$')
2024
2025 - def _precompile_regexp(self, trigger):
2026 """Precompile the regex for most triggers. 2027 2028 If the trigger is non-atomic, and doesn't include dynamic tags like 2029 `<bot>`, `<get>`, `<input>/<reply>` or arrays, it can be precompiled 2030 and save time when matching.""" 2031 if self._is_atomic(trigger): 2032 return # Don't need a regexp for atomic triggers. 2033 2034 # Check for dynamic tags. 2035 for tag in ["@", "<bot", "<get", "<input", "<reply"]: 2036 if tag in trigger: 2037 return # Can't precompile this trigger. 2038 2039 self._regexc["trigger"][trigger] = self._reply_regexp(None, trigger)
2040
2041 - def _process_tags(self, user, msg, reply, st=[], bst=[], depth=0, ignore_object_errors=True):
2042 """Post process tags in a message.""" 2043 stars = [''] 2044 stars.extend(st) 2045 botstars = [''] 2046 botstars.extend(bst) 2047 if len(stars) == 1: 2048 stars.append("undefined") 2049 if len(botstars) == 1: 2050 botstars.append("undefined") 2051 2052 # Tag shortcuts. 2053 reply = reply.replace('<person>', '{person}<star>{/person}') 2054 reply = reply.replace('<@>', '{@<star>}') 2055 reply = reply.replace('<formal>', '{formal}<star>{/formal}') 2056 reply = reply.replace('<sentence>', '{sentence}<star>{/sentence}') 2057 reply = reply.replace('<uppercase>', '{uppercase}<star>{/uppercase}') 2058 reply = reply.replace('<lowercase>', '{lowercase}<star>{/lowercase}') 2059 2060 # Weight and <star> tags. 2061 reply = re.sub(RE.weight, '', reply) # Leftover {weight}s 2062 if len(stars) > 0: 2063 reply = reply.replace('<star>', stars[1]) 2064 reStars = re.findall(RE.star_tags, reply) 2065 for match in reStars: 2066 if int(match) < len(stars): 2067 reply = reply.replace('<star{match}>'.format(match=match), stars[int(match)]) 2068 if len(botstars) > 0: 2069 reply = reply.replace('<botstar>', botstars[1]) 2070 reStars = re.findall(RE.botstars, reply) 2071 for match in reStars: 2072 if int(match) < len(botstars): 2073 reply = reply.replace('<botstar{match}>'.format(match=match), botstars[int(match)]) 2074 2075 # <input> and <reply> 2076 reply = reply.replace('<input>', self._users[user]['__history__']['input'][0]) 2077 reply = reply.replace('<reply>', self._users[user]['__history__']['reply'][0]) 2078 reInput = re.findall(RE.input_tags, reply) 2079 for match in reInput: 2080 reply = reply.replace('<input{match}>'.format(match=match), 2081 self._users[user]['__history__']['input'][int(match) - 1]) 2082 reReply = re.findall(RE.reply_tags, reply) 2083 for match in reReply: 2084 reply = reply.replace('<reply{match}>'.format(match=match), 2085 self._users[user]['__history__']['reply'][int(match) - 1]) 2086 2087 # <id> and escape codes. 2088 reply = reply.replace('<id>', user) 2089 reply = reply.replace('\\s', ' ') 2090 reply = reply.replace('\\n', "\n") 2091 reply = reply.replace('\\#', '#') 2092 2093 # Random bits. 2094 reRandom = re.findall(RE.random_tags, reply) 2095 for match in reRandom: 2096 output = '' 2097 if '|' in match: 2098 output = random.choice(match.split('|')) 2099 else: 2100 output = random.choice(match.split(' ')) 2101 reply = reply.replace('{{random}}{match}{{/random}}'.format(match=match), output) 2102 2103 # Person Substitutions and String Formatting. 2104 for item in ['person', 'formal', 'sentence', 'uppercase', 'lowercase']: 2105 matcher = re.findall(r'\{' + item + r'\}(.+?)\{/' + item + r'\}', reply) 2106 for match in matcher: 2107 output = None 2108 if item == 'person': 2109 # Person substitutions. 2110 output = self._substitute(match, "person") 2111 else: 2112 output = self._string_format(match, item) 2113 reply = reply.replace('{{{item}}}{match}{{/{item}}}'.format(item=item, match=match), output) 2114 2115 # Handle all variable-related tags with an iterative regex approach, 2116 # to allow for nesting of tags in arbitrary ways (think <set a=<get b>>) 2117 # Dummy out the <call> tags first, because we don't handle them right 2118 # here. 2119 reply = reply.replace("<call>", "{__call__}") 2120 reply = reply.replace("</call>", "{/__call__}") 2121 while True: 2122 # This regex will match a <tag> which contains no other tag inside 2123 # it, i.e. in the case of <set a=<get b>> it will match <get b> but 2124 # not the <set> tag, on the first pass. The second pass will get the 2125 # <set> tag, and so on. 2126 match = re.search(RE.tag_search, reply) 2127 if not match: break # No remaining tags! 2128 2129 match = match.group(1) 2130 parts = match.split(" ", 1) 2131 tag = parts[0].lower() 2132 data = parts[1] if len(parts) > 1 else "" 2133 insert = "" # Result of the tag evaluation 2134 2135 # Handle the tags. 2136 if tag == "bot" or tag == "env": 2137 # <bot> and <env> tags are similar. 2138 target = self._bvars if tag == "bot" else self._gvars 2139 if "=" in data: 2140 # Setting a bot/env variable. 2141 parts = data.split("=") 2142 self._say("Set " + tag + " variable " + text_type(parts[0]) + "=" + text_type(parts[1])) 2143 target[parts[0]] = parts[1] 2144 else: 2145 # Getting a bot/env variable. 2146 insert = target.get(data, "undefined") 2147 elif tag == "set": 2148 # <set> user vars. 2149 parts = data.split("=") 2150 self._say("Set uservar " + text_type(parts[0]) + "=" + text_type(parts[1])) 2151 self._users[user][parts[0]] = parts[1] 2152 elif tag in ["add", "sub", "mult", "div"]: 2153 # Math operator tags. 2154 parts = data.split("=") 2155 var = parts[0] 2156 value = parts[1] 2157 2158 # Sanity check the value. 2159 try: 2160 value = int(value) 2161 if var not in self._users[user]: 2162 # Initialize it. 2163 self._users[user][var] = 0 2164 except: 2165 insert = "[ERR: Math can't '{}' non-numeric value '{}']".format(tag, value) 2166 2167 # Attempt the operation. 2168 try: 2169 orig = int(self._users[user][var]) 2170 new = 0 2171 if tag == "add": 2172 new = orig + value 2173 elif tag == "sub": 2174 new = orig - value 2175 elif tag == "mult": 2176 new = orig * value 2177 elif tag == "div": 2178 new = orig / value 2179 self._users[user][var] = new 2180 except: 2181 insert = "[ERR: Math couldn't '{}' to value '{}']".format(tag, self._users[user][var]) 2182 elif tag == "get": 2183 insert = self._users[user].get(data, "undefined") 2184 else: 2185 # Unrecognized tag. 2186 insert = "\x00{}\x01".format(match) 2187 2188 reply = reply.replace("<{}>".format(match), insert) 2189 2190 # Restore unrecognized tags. 2191 reply = reply.replace("\x00", "<").replace("\x01", ">") 2192 2193 # Streaming code. DEPRECATED! 2194 if '{!' in reply: 2195 self._warn("Use of the {!...} tag is deprecated and not supported here.") 2196 2197 # Topic setter. 2198 reTopic = re.findall(RE.topic_tag, reply) 2199 for match in reTopic: 2200 self._say("Setting user's topic to " + match) 2201 self._users[user]["topic"] = match 2202 reply = reply.replace('{{topic={match}}}'.format(match=match), '') 2203 2204 # Inline redirecter. 2205 reRedir = re.findall(RE.redir_tag, reply) 2206 for match in reRedir: 2207 self._say("Redirect to " + match) 2208 at = match.strip() 2209 subreply = self._getreply(user, at, step=(depth + 1)) 2210 reply = reply.replace('{{@{match}}}'.format(match=match), subreply) 2211 2212 # Object caller. 2213 reply = reply.replace("{__call__}", "<call>") 2214 reply = reply.replace("{/__call__}", "</call>") 2215 reCall = re.findall(r'<call>(.+?)</call>', reply) 2216 for match in reCall: 2217 parts = re.split(RE.ws, match) 2218 output = '' 2219 obj = parts[0] 2220 args = [] 2221 if len(parts) > 1: 2222 args = parts[1:] 2223 2224 # Do we know this object? 2225 if obj in self._objlangs: 2226 # We do, but do we have a handler for that language? 2227 lang = self._objlangs[obj] 2228 if lang in self._handlers: 2229 # We do. 2230 try: 2231 output = self._handlers[lang].call(self, obj, user, args) 2232 except python.PythonObjectError as e: 2233 self._warn(str(e)) 2234 if not ignore_object_errors: 2235 raise ObjectError(str(e)) 2236 output = RS_ERR_OBJECT 2237 else: 2238 if not ignore_object_errors: 2239 raise ObjectError(RS_ERR_OBJECT_HANDLER) 2240 output = RS_ERR_OBJECT_HANDLER 2241 else: 2242 if not ignore_object_errors: 2243 raise ObjectError(RS_ERR_OBJECT_MISSING) 2244 output = RS_ERR_OBJECT_MISSING 2245 2246 reply = reply.replace('<call>{match}</call>'.format(match=match), output) 2247 2248 return reply
2249
2250 - def _string_format(self, msg, method):
2251 """Format a string (upper, lower, formal, sentence).""" 2252 if method == "uppercase": 2253 return msg.upper() 2254 elif method == "lowercase": 2255 return msg.lower() 2256 elif method == "sentence": 2257 return msg.capitalize() 2258 elif method == "formal": 2259 return string.capwords(msg)
2260 2261 ############################################################################ 2262 # Topic inheritance Utility Methods # 2263 ############################################################################ 2264
2265 - def _topic_triggers(self, topic, triglvl, depth=0, inheritance=0, inherited=False):
2266 """Recursively scan a topic and return a list of all triggers.""" 2267 2268 # Break if we're in too deep. 2269 if depth > self._depth: 2270 self._warn("Deep recursion while scanning topic inheritance") 2271 2272 # Important info about the depth vs inheritance params to this function: 2273 # depth increments by 1 each time this function recursively calls itself. 2274 # inheritance increments by 1 only when this topic inherits another 2275 # topic. 2276 # 2277 # This way, '> topic alpha includes beta inherits gamma' will have this 2278 # effect: 2279 # alpha and beta's triggers are combined together into one matching 2280 # pool, and then those triggers have higher matching priority than 2281 # gamma's. 2282 # 2283 # The inherited option is True if this is a recursive call, from a topic 2284 # that inherits other topics. This forces the {inherits} tag to be added 2285 # to the triggers. This only applies when the top topic 'includes' 2286 # another topic. 2287 self._say("\tCollecting trigger list for topic " + topic + "(depth=" 2288 + str(depth) + "; inheritance=" + str(inheritance) + "; " 2289 + "inherited=" + str(inherited) + ")") 2290 2291 # topic: the name of the topic 2292 # triglvl: reference to self._topics or self._thats 2293 # depth: starts at 0 and ++'s with each recursion 2294 2295 # Collect an array of triggers to return. 2296 triggers = [] 2297 2298 # Get those that exist in this topic directly. 2299 inThisTopic = [] 2300 if topic in triglvl: 2301 for trigger in triglvl[topic]: 2302 inThisTopic.append(trigger) 2303 2304 # Does this topic include others? 2305 if topic in self._includes: 2306 # Check every included topic. 2307 for includes in self._includes[topic]: 2308 self._say("\t\tTopic " + topic + " includes " + includes) 2309 triggers.extend(self._topic_triggers(includes, triglvl, (depth + 1), inheritance, True)) 2310 2311 # Does this topic inherit others? 2312 if topic in self._lineage: 2313 # Check every inherited topic. 2314 for inherits in self._lineage[topic]: 2315 self._say("\t\tTopic " + topic + " inherits " + inherits) 2316 triggers.extend(self._topic_triggers(inherits, triglvl, (depth + 1), (inheritance + 1), False)) 2317 2318 # Collect the triggers for *this* topic. If this topic inherits any 2319 # other topics, it means that this topic's triggers have higher 2320 # priority than those in any inherited topics. Enforce this with an 2321 # {inherits} tag. 2322 if topic in self._lineage or inherited: 2323 for trigger in inThisTopic: 2324 self._say("\t\tPrefixing trigger with {inherits=" + str(inheritance) + "}" + trigger) 2325 triggers.append("{inherits=" + str(inheritance) + "}" + trigger) 2326 else: 2327 triggers.extend(inThisTopic) 2328 2329 return triggers
2330
2331 - def _find_trigger_by_inheritance(self, topic, trig, depth=0):
2332 """Locate the replies for a trigger in an inherited/included topic.""" 2333 2334 # This sub was called because the user matched a trigger from the sorted 2335 # array, but the trigger doesn't belong to their topic, and is instead 2336 # in an inherited or included topic. This is to search for it. 2337 2338 # Prevent recursion. 2339 if depth > self._depth: 2340 self._warn("Deep recursion detected while following an inheritance trail!") 2341 return None 2342 2343 # inheritance is more important than inclusion: triggers in one topic can 2344 # override those in an inherited topic. 2345 if topic in self._lineage: 2346 for inherits in sorted(self._lineage[topic]): 2347 # See if this inherited topic has our trigger. 2348 if trig in self._topics[inherits]: 2349 # Great! 2350 return self._topics[inherits][trig] 2351 else: 2352 # Check what THAT topic inherits from. 2353 match = self._find_trigger_by_inheritance( 2354 inherits, trig, (depth + 1) 2355 ) 2356 if match: 2357 # Found it! 2358 return match 2359 2360 # See if this topic has an "includes" 2361 if topic in self._includes: 2362 for includes in sorted(self._includes[topic]): 2363 # See if this included topic has our trigger. 2364 if trig in self._topics[includes]: 2365 # Great! 2366 return self._topics[includes][trig] 2367 else: 2368 # Check what THAT topic inherits from. 2369 match = self._find_trigger_by_inheritance( 2370 includes, trig, (depth + 1) 2371 ) 2372 if match: 2373 # Found it! 2374 return match 2375 2376 # Don't know what else to do! 2377 return None
2378
2379 - def _get_topic_tree(self, topic, depth=0):
2380 """Given one topic, get the list of all included/inherited topics.""" 2381 2382 # Break if we're in too deep. 2383 if depth > self._depth: 2384 self._warn("Deep recursion while scanning topic trees!") 2385 return [] 2386 2387 # Collect an array of all topics. 2388 topics = [topic] 2389 2390 # Does this topic include others? 2391 if topic in self._includes: 2392 # Try each of these. 2393 for includes in sorted(self._includes[topic]): 2394 topics.extend(self._get_topic_tree(includes, depth + 1)) 2395 2396 # Does this topic inherit others? 2397 if topic in self._lineage: 2398 # Try each of these. 2399 for inherits in sorted(self._lineage[topic]): 2400 topics.extend(self._get_topic_tree(inherits, depth + 1)) 2401 2402 return topics
2403 2404 ############################################################################ 2405 # Miscellaneous Private Methods # 2406 ############################################################################ 2407
2408 - def _is_atomic(self, trigger):
2409 """Determine if a trigger is atomic or not.""" 2410 2411 # Atomic triggers don't contain any wildcards or parenthesis or anything 2412 # of the sort. We don't need to test the full character set, just left 2413 # brackets will do. 2414 special = ['*', '#', '_', '(', '[', '<', '@'] 2415 for char in special: 2416 if char in trigger: 2417 return False 2418 2419 return True
2420
2421 - def _word_count(self, trigger, all=False):
2422 """Count the words that aren't wildcards in a trigger.""" 2423 words = [] 2424 if all: 2425 words = re.split(RE.ws, trigger) 2426 else: 2427 words = re.split(RE.wilds, trigger) 2428 2429 wc = 0 # Word count 2430 for word in words: 2431 if len(word) > 0: 2432 wc += 1 2433 2434 return wc
2435
2436 - def _strip_nasties(self, s):
2437 """Formats a string for ASCII regex matching.""" 2438 s = re.sub(RE.nasties, '', s) 2439 return s
2440
2441 - def _dump(self):
2442 """For debugging, dump the entire data structure.""" 2443 pp = pprint.PrettyPrinter(indent=4) 2444 2445 print("=== Variables ===") 2446 print("-- Globals --") 2447 pp.pprint(self._gvars) 2448 print("-- Bot vars --") 2449 pp.pprint(self._bvars) 2450 print("-- Substitutions --") 2451 pp.pprint(self._subs) 2452 print("-- Person Substitutions --") 2453 pp.pprint(self._person) 2454 print("-- Arrays --") 2455 pp.pprint(self._arrays) 2456 2457 print("=== Topic Structure ===") 2458 pp.pprint(self._topics) 2459 print("=== %Previous Structure ===") 2460 pp.pprint(self._thats) 2461 2462 print("=== Includes ===") 2463 pp.pprint(self._includes) 2464 2465 print("=== Inherits ===") 2466 pp.pprint(self._lineage) 2467 2468 print("=== Sort Buffer ===") 2469 pp.pprint(self._sorted) 2470 2471 print("=== Syntax Tree ===") 2472 pp.pprint(self._syntax)
2473
2474 2475 ################################################################################ 2476 # Exception Classes # 2477 ################################################################################ 2478 2479 -class RiveScriptError(Exception):
2480 """RiveScript base exception class"""
2481 - def __init__(self, error_message=None):
2482 super(RiveScriptError, self).__init__(error_message) 2483 self.error_message = error_message
2484
2485 2486 -class NoMatchError(RiveScriptError):
2487 """No reply could be matched"""
2488 - def __init__(self):
2489 super(NoMatchError, self).__init__(RS_ERR_MATCH)
2490
2491 2492 -class NoReplyError(RiveScriptError):
2493 """No reply could be found"""
2494 - def __init__(self):
2495 super(NoReplyError, self).__init__(RS_ERR_REPLY)
2496
2497 2498 -class ObjectError(RiveScriptError):
2499 """An error occurred when executing a Python object"""
2500 - def __init__(self, error_message=RS_ERR_OBJECT):
2501 super(ObjectError, self).__init__(error_message)
2502
2503 2504 -class DeepRecursionError(RiveScriptError):
2505 """Prevented an infinite loop / deep recursion, unable to retrieve a reply for this message"""
2506 - def __init__(self):
2508
2509 2510 -class NoDefaultRandomTopicError(Exception):
2511 """No default topic 'random' could be found, critical error""" 2512 pass
2513
2514 2515 -class RepliesNotSortedError(Exception):
2516 """sort_replies() was not called after the RiveScript documents were loaded, critical error""" 2517 pass
2518 2519 2520 ################################################################################ 2521 # Interactive Mode # 2522 ################################################################################ 2523 2524 if __name__ == "__main__": 2525 from interactive import interactive_mode 2526 interactive_mode() 2527 2528 # vim:expandtab 2529