/usr/share/perl5/RiveScript.pm is in librivescript-perl 1.26-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 | package RiveScript;
use strict;
use warnings;
our $VERSION = '1.26'; # Version of the Perl RiveScript interpreter.
our $SUPPORT = '2.0'; # Which RS standard we support.
our $basedir = (__FILE__ =~ /^(.+?)\.pm$/i ? $1 : '.');
=head1 NAME
RiveScript - Rendering Intelligence Very Easily
=head1 SYNOPSIS
use RiveScript;
# Create a new RiveScript interpreter.
my $rs = new RiveScript;
# Load a directory of replies.
$rs->loadDirectory ("./replies");
# Load another file.
$rs->loadFile ("./more_replies.rs");
# Stream in some RiveScript code.
$rs->stream (q~
+ hello bot
- Hello, human.
~);
# Sort all the loaded replies.
$rs->sortReplies;
# Chat with the bot.
while (1) {
print "You> ";
chomp (my $msg = <STDIN>);
my $reply = $rs->reply ('localuser',$msg);
print "Bot> $reply\n";
}
=head1 DESCRIPTION
RiveScript is a simple trigger/response language primarily used for the creation
of chatting robots. It's designed to have an easy-to-learn syntax but provide a
lot of power and flexibility. For more information, visit
http://www.rivescript.com/
=head1 METHODS
=head2 GENERAL
=over 4
=cut
################################################################################
## Constructor and Debug Methods ##
################################################################################
=item RiveScript new (hash %ARGS)
Create a new instance of a RiveScript interpreter. The instance will become its
own "chatterbot," with its own set of responses and user variables. You can pass
in any global variables here. The two standard variables are:
debug - Turns on debug mode (a LOT of information will be printed to the
terminal!). Default is 0 (disabled).
verbose - When debug mode is on, all debug output will be printed to the
terminal if 'verbose' is also true. The default value is 1.
debugfile - Optional: paired with debug mode, all debug output is also written
to this file name. Since debug mode prints such a large amount of
data, it is often more practical to have the output go to an
external file for later review. Default is '' (no file).
depth - Determines the recursion depth limit when following a trail of replies
that point to other replies. Default is 50.
strict - If this has a true value, any syntax errors detected while parsing
a RiveScript document will result in a fatal error. Set it to a
false value and only a warning will result. Default is 1.
It's recommended that if you set any other global variables that you do so by
calling C<setGlobal> or defining it within the RiveScript code. This will avoid
the possibility of overriding reserved globals. Currently, these variable names
are reserved:
topics sorted sortsthat sortedthat thats
arrays subs person client bot
objects syntax sortlist reserved debugopts
frozen globals handlers objlangs
Note: the options "verbose" and "debugfile", when provided, are noted and then
deleted from the root object space, so that if your RiveScript code uses variables
by the same values it won't conflict with the values that you passed here.
=back
=cut
sub new {
my $proto = shift;
my $class = ref($proto) || $proto || 'RiveScript';
my $self = {
debug => 0,
debugopts => {
verbose => 1, # Print to the terminal
file => '', # Print to a filename
},
depth => 50, # Recursion depth allowed.
strict => 1, # Strict syntax checking (causes a die)
topics => {}, # Loaded replies under topics
lineage => {}, # Keep track of topics that inherit other topics
includes => {}, # Keep track of topics that include other topics
sorted => {}, # Sorted triggers
sortsthat => {}, # Sorted %previous's.
sortedthat => {}, # Sorted triggers that go with %previous's
thats => {}, # Reverse mapping for %previous, under topics
arrays => {}, # Arrays
subs => {}, # Substitutions
person => {}, # Person substitutions
client => {}, # User variables
frozen => {}, # Frozen (backed-up) user variables
bot => {}, # Bot variables
objects => {}, # Subroutines
syntax => {}, # Syntax tracking
sortlist => {}, # Sorted lists (i.e. person subs)
handlers => {}, # Object handlers
globals => {}, # Globals that conflict with reserved names go here
objlangs => {}, # Map object names to their programming languages
reserved => [ # Reserved global variable names.
qw(topics sorted sortsthat sortedthat thats arrays subs person
client bot objects syntax sortlist reserved debugopts frozen
handlers globals objlangs)
],
@_,
};
bless ($self,$class);
# Set the default object handler for Perl objects.
$self->setHandler (perl => sub {
my ($rs,$action,$name,$data) = @_;
# $action will be "load" during the parsing phase, or "call"
# when called via <call>.
# Loading
if ($action eq "load") {
# Create a dynamic Perl subroutine.
my $code = "sub RSOBJ_$name {\n"
. $data
. "}";
# Evaluate it.
eval ($code);
if ($@) {
$rs->issue("Perl object $name creation failed: $@");
}
else {
# Load it.
$rs->setSubroutine($name => \&{"RSOBJ_$name"});
}
}
# Calling
elsif ($action eq "call") {
# Make sure the object exists.
if (exists $rs->{objects}->{$name}) {
# Call it.
my @args = @{$data};
my $return = &{ $rs->{objects}->{$name} } ($rs,@args);
return $return;
}
else {
return "[ERR: Object Not Found]";
}
}
});
# See if any additional debug options were provided.
if (exists $self->{verbose}) {
$self->{debugopts}->{verbose} = delete $self->{verbose};
}
if (exists $self->{debugfile}) {
$self->{debugopts}->{file} = delete $self->{debugfile};
}
$self->debug ("RiveScript $VERSION Initialized");
return $self;
}
sub debug {
my ($self,$msg) = @_;
if ($self->{debug}) {
# Verbose debugging?
if ($self->{debugopts}->{verbose}) {
print "RiveScript: $msg\n";
}
# Debugging to a file?
if (length $self->{debugopts}->{file}) {
# Get a real quick timestamp.
my @time = localtime(time());
my $stamp = join(":",$time[2],$time[1],$time[0]);
open (WRITE, ">>$self->{debugopts}->{file}");
print WRITE "[$stamp] RiveScript: $msg\n";
close (WRITE);
}
}
}
sub issue {
my ($self,$msg) = @_;
if ($self->{debug}) {
print "# RiveScript::Warning: $msg\n";
}
else {
warn "RiveScript::Warning: $msg\n";
}
}
################################################################################
## Parsing Methods ##
################################################################################
=head2 LOADING AND PARSING
=over 4
=item bool loadDirectory (string $PATH[, string @EXTS])
Load a directory full of RiveScript documents. C<$PATH> must be a path to a
directory. C<@EXTS> is optionally an array containing file extensions, including
the dot. By default C<@EXTS> is C<('.rs')>.
Returns true on success, false on failure.
=cut
sub loadDirectory {
my $self = shift;
my $dir = shift || '.';
my (@exts) = @_ || ('.rs');
if (!-d $dir) {
$self->issue ("loadDirectory failed: $dir is not a directory!");
return 0;
}
$self->debug ("loadDirectory: Open $dir");
# If a begin.rs file exists, load it first.
if (-f "$dir/begin.rs") {
$self->debug ("loadDirectory: Read begin.rs");
$self->loadFile ("$dir/begin.rs");
}
opendir (DIR, $dir);
foreach my $file (sort { $a cmp $b } readdir(DIR)) {
next if $file eq '.';
next if $file eq '..';
next if $file =~ /\~$/i; # Skip backup files
next if $file eq 'begin.rs';
my $badExt = 0;
foreach (@exts) {
my $re = quotemeta($_);
$badExt = 1 unless $file =~ /$re$/;
}
next if $badExt;
$self->debug ("loadDirectory: Read $file");
$self->loadFile ("$dir/$file");
}
closedir (DIR);
return 1;
}
=item bool loadFile (string $PATH)
Load a single RiveScript document. C<$PATH> should be the path to a valid
RiveScript file. Returns true on success; false otherwise.
=cut
sub loadFile {
my ($self,$file) = @_;
if (not defined $file) {
$self->issue ("loadFile requires a file path.");
return 0;
}
if (!-f $file) {
$self->issue ("loadFile failed: $file is not a file!");
return 0;
}
open (READ, $file);
my @code = <READ>;
close (READ);
chomp @code;
# Parse the file.
$self->debug ("loadFile: Parsing " . (scalar @code) . " lines from $file.");
$self->parse ($file,join("\n",@code));
return 1;
}
=item bool stream (arrayref $CODE)
Stream RiveScript code directly into the module. This is for providing RS code
from within the Perl script instead of from an external file. Returns true on
success.
=cut
sub stream {
my ($self,$code) = @_;
if (not defined $code) {
$self->issue ("stream requires RiveScript code.");
return 0;
}
# Stream the code.
$self->debug ("stream: Streaming code.");
$self->parse ("stream()",$code);
return 1;
}
sub parse {
my ($self,$fname,$code) = @_;
# Track temporary variables.
my $topic = 'random'; # Default topic=random
my $lineno = 0; # Keep track of line numbers
my $comment = 0; # In a multi-line comment.
my $inobj = 0; # Trying to parse an object.
my $objname = ''; # Object name.
my $objlang = ''; # Object programming language.
my $objbuf = ''; # Object contents buffer.
my $ontrig = ''; # Current trigger.
my $repcnt = 0; # Reply counter.
my $concnt = 0; # Condition counter.
my $lastcmd = ''; # Last command code.
my $isThat = ''; # Is a %Previous trigger.
# Split the RS code into lines.
$code =~ s/([\x0d\x0a])+/\x0a/ig;
my @lines = split(/\x0a/, $code);
# Read each line.
$self->debug ("Parsing file data from $fname");
my $lp = 0; # line number index
for ($lp = 0; $lp < scalar(@lines); $lp++) {
$lineno++;
my $line = $lines[$lp];
# Chomp the line further.
chomp $line;
$line =~ s/^(\t|\x0a|\x0d|\s)+//ig;
$line =~ s/(\t|\x0a|\x0d|\s)+$//ig;
$self->debug ("Line: $line (topic: $topic)");
# In an object?
if ($inobj) {
if ($line =~ /^<\s*object/i) {
# End the object.
if (length $objname) {
# Call this object's handler.
if (exists $self->{handlers}->{$objlang}) {
$self->{objlangs}->{$objname} = $objlang;
&{ $self->{handlers}->{$objlang} } ($self,"load",$objname,$objbuf);
}
else {
$self->issue ("Object creation failed: no handler for $objlang!");
}
}
$objname = '';
$objlang = '';
$objbuf = '';
}
else {
$objbuf .= "$line\n";
next;
}
}
# Look for comments.
if ($line =~ /^(\/\/|#)/i) {
# The "#" format for comments is deprecated.
if ($line =~ /^#/) {
$self->issue ("Using the # symbol for comments is deprecated at $fname line $lineno (near $line)");
}
next;
}
elsif ($line =~ /^\/\*/) {
if ($line =~ /\*\//) {
# Well this was a short comment.
next;
}
# Start of a multi-line comment.
$comment = 1;
next;
}
elsif ($line =~ /\*\//) {
$comment = 0;
next;
}
if ($comment) {
next;
}
# Skip blank lines.
next if length $line == 0;
# Separate the command from the data.
my ($cmd) = $line =~ /^(.)/i;
$line =~ s/^.//i;
$line =~ s/^\s+?//ig;
# Ignore inline comments if there's a space before and after
# the // or # symbols.
my $inline_comment_regexp = "(\\s+\\#\\s+|\\/\\/)";
$line =~ s/\\\/\//\\\/\\\//g; # Turn \// into \/\/
if ($cmd eq '+') {
$inline_comment_regexp = "(\\s\\s\\#|\\/\\/)";
if ($line =~ /\s\s#\s/) {
# Deprecated.
$self->issue ("Using the # symbol for comments is deprecated at $fname line $lineno (near: $line).");
}
}
else {
if ($line =~ /\s#\s/) {
# Deprecated.
$self->issue ("Using the # symbol for comments is deprecated at $fname line $lineno (near: $line).");
}
}
if ($line =~ /$inline_comment_regexp/) {
my ($left,$comment) = split(/$inline_comment_regexp/, $line, 2);
$left =~ s/\s+$//g;
$line = $left;
}
$self->debug ("\tCmd: $cmd");
# Run a syntax check on this line. We put this into a separate function so that
# we can have all the syntax logic all in one place.
my $syntax_error = $self->checkSyntax($cmd,$line);
if ($syntax_error) {
# There was a syntax error! Are we enforcing "strict"?
$syntax_error = "Syntax error in $fname line $lineno: $syntax_error (near: $cmd $line)";
if ($self->{strict}) {
# This is fatal then!
die $syntax_error;
}
else {
# This is a warning; warn it, and then abort processing this file!
warn $syntax_error;
return;
}
}
# Reset the %previous state if this is a new +Trigger.
if ($cmd eq '+') {
$isThat = '';
}
# Do a lookahead for ^Continue and %Previous commands.
for (my $i = ($lp + 1); $i < scalar(@lines); $i++) {
my $lookahead = $lines[$i];
$lookahead =~ s/^(\t|\x0a|\x0d|\s)+//g;
my ($lookCmd) = $lookahead =~ /^(.)/i;
$lookahead =~ s/^([^\s]+)\s+//i;
# Only continue if the lookahead line has any data.
if (defined $lookahead && length $lookahead > 0) {
# The lookahead command has to be either a % or a ^.
if ($lookCmd ne '^' && $lookCmd ne '%') {
#$isThat = '';
last;
}
# If the current command is a +, see if the following command
# is a % (previous)
if ($cmd eq '+') {
# Look for %Previous.
if ($lookCmd eq '%') {
$self->debug ("\tIs a %previous ($lookahead)");
$isThat = $lookahead;
last;
}
else {
$isThat = '';
}
}
# If the current command is a ! and the next command(s) are
# ^, we'll tack each extension on as a line break (which is
# useful information for arrays; everything else is gonna ditch
# this info).
if ($cmd eq '!') {
if ($lookCmd eq '^') {
$self->debug ("\t^ [$lp;$i] $lookahead");
$line .= "<crlf>$lookahead";
$self->debug ("\tLine: $line");
}
next;
}
# If the current command is not a ^ and the line after is
# not a %, but the line after IS a ^, then tack it onto the
# end of the current line (this is fine for every other type
# of command that doesn't require special treatment).
if ($cmd ne '^' && $lookCmd ne '%') {
if ($lookCmd eq '^') {
$self->debug ("\t^ [$lp;$i] $lookahead");
$line .= $lookahead;
}
else {
last;
}
}
}
}
if ($cmd eq '!') {
# ! DEFINE
my ($left,$value) = split(/\s*=\s*/, $line, 2);
my ($type,$var) = split(/\s+/, $left, 2);
$ontrig = '';
$self->debug ("\t! DEFINE");
# Remove line breaks unless this is an array.
if ($type ne 'array') {
$value =~ s/<crlf>//ig;
}
if ($type eq 'version') {
$self->debug ("\tUsing RiveScript version $value");
if ($value > $SUPPORT) {
$self->issue ("Unsupported RiveScript Version. Skipping file $fname.");
return;
}
}
elsif ($type eq 'global') {
if (not defined $var) {
$self->issue ("Undefined global variable at $fname line $lineno.");
next;
}
if (not defined $value) {
$self->issue ("Undefined global value at $fname line $lineno.");
next;
}
$self->debug ("\tSet global $var = $value");
# Don't allow the overriding of a reserved global.
my $ok = 1;
foreach my $res (@{$self->{reserved}}) {
if ($var eq $res) {
$ok = 0;
last;
}
}
if ($ok) {
# Allow in the global name space.
if ($value eq '<undef>') {
delete $self->{$var};
}
else {
$self->{$var} = $value;
}
}
else {
# Allow in the protected name space.
if ($value eq '<undef>') {
delete $self->{globals}->{$var};
}
else {
$self->{globals}->{$var} = $value;
}
}
}
elsif ($type eq 'var') {
$self->debug ("\tSet bot variable $var = $value");
if (not defined $var) {
$self->issue ("Undefined bot variable at $fname line $lineno.");
next;
}
if (not defined $value) {
$self->issue ("Undefined bot value at $fname line $lineno.");
next;
}
if ($value eq '<undef>') {
delete $self->{bot}->{$var};
}
else {
$self->{bot}->{$var} = $value;
}
}
elsif ($type eq 'array') {
$self->debug ("\tSet array $var");
if (not defined $var) {
$self->issue ("Undefined array variable at $fname line $lineno.");
next;
}
if (not defined $value) {
$self->issue ("Undefined array value at $fname line $lineno.");
next;
}
if ($value eq '<undef>') {
delete $self->{arrays}->{$var};
next;
}
# Did this have multiple lines?
my @parts = split(/<crlf>/i, $value);
$self->debug("Array lines: " . join(";",@parts));
# Process each line of array data.
my @fields = ();
foreach my $val (@parts) {
# Split at pipes or spaces?
if ($val =~ /\|/) {
push (@fields,split(/\|/, $val));
}
else {
push (@fields,split(/\s+/, $val));
}
}
# Convert any remaining \s escape codes into spaces.
foreach my $f (@fields) {
$f =~ s/\\s/ /ig;
}
$self->{arrays}->{$var} = [ @fields ];
}
elsif ($type eq 'sub') {
$self->debug ("\tSubstitution $var => $value");
if (not defined $var) {
$self->issue ("Undefined sub pattern at $fname line $lineno.");
next;
}
if (not defined $value) {
$self->issue ("Undefined sub replacement at $fname line $lineno.");
next;
}
if ($value eq '<undef>') {
delete $self->{subs}->{$var};
next;
}
$self->{subs}->{$var} = $value;
}
elsif ($type eq 'person') {
$self->debug ("\tPerson substitution $var => $value");
if (not defined $var) {
$self->issue ("Undefined person sub pattern at $fname line $lineno.");
next;
}
if (not defined $value) {
$self->issue ("Undefined person sub replacement at $fname line $lineno.");
next;
}
if ($value eq '<undef>') {
delete $self->{person}->{$var};
next;
}
$self->{person}->{$var} = $value;
}
else {
$self->issue ("Unknown definition type \"$type\" at $fname line $lineno.");
next;
}
}
elsif ($cmd eq '>') {
# > LABEL
my ($type,$name,@fields) = split(/\s+/, $line);
$type = lc($type);
# Handle the label types.
if ($type eq 'begin') {
# The BEGIN statement.
$self->debug ("Found the BEGIN Statement.");
$type = 'topic';
$name = '__begin__';
}
if ($type eq 'topic') {
# Starting a new topic.
$self->debug ("Set topic to $name.");
$ontrig = '';
$topic = $name;
# Does this topic include or inherit another one?
my $mode = ''; # or 'inherits' || 'includes'
if (scalar(@fields) >= 2) {
foreach my $field (@fields) {
if ($field eq 'includes') {
$mode = 'includes';
}
elsif ($field eq 'inherits') {
$mode = 'inherits';
}
elsif ($mode ne '') {
# This topic is either inherited or included.
if ($mode eq 'includes') {
$self->{includes}->{$name}->{$field} = 1;
}
else {
$self->{lineage}->{$name}->{$field} = 1;
}
}
}
}
}
if ($type eq 'object') {
# If a field was provided, it should be the programming language.
my $lang = (scalar(@fields) ? $fields[0] : undef);
$lang = lc($lang); $lang =~ s/\s+//g;
# Only try to parse a language we support.
$ontrig = '';
if (not defined $lang) {
$self->issue ("Trying to parse unknown programming language at $fname line $lineno.");
$lang = "perl"; # Assume it's Perl.
}
# See if we have a defined handler for this language.
if (exists $self->{handlers}->{$lang}) {
# We have a handler, so load this object's code.
$objname = $name;
$objlang = $lang;
$objbuf = '';
$inobj = 1;
}
else {
# We don't have a handler, just ignore this code.
$objname = '';
$objlang = '';
$objbuf = '';
$inobj = 1;
}
}
}
elsif ($cmd eq '<') {
# < LABEL
my $type = $line;
if ($type eq 'begin' || $type eq 'topic') {
$self->debug ("End topic label.");
$topic = 'random';
}
elsif ($type eq 'object') {
$self->debug ("End object label.");
$inobj = 0;
}
}
elsif ($cmd eq '+') {
# + TRIGGER
$self->debug ("\tTrigger pattern: $line");
if (length $isThat) {
$self->debug ("\t\tInitializing the \%previous structure.");
$self->{thats}->{$topic}->{$isThat}->{$line} = {};
}
else {
$self->{topics}->{$topic}->{$line} = {};
$self->{syntax}->{$topic}->{$line}->{ref} = "$fname line $lineno";
$self->debug ("\t\tSaved to \$self->{topics}->{$topic}->{$line}: "
. "$self->{topics}->{$topic}->{$line}");
}
$ontrig = $line;
$repcnt = 0;
$concnt = 0;
}
elsif ($cmd eq '-') {
# - REPLY
if ($ontrig eq '') {
$self->issue ("Response found before trigger at $fname line $lineno.");
next;
}
$self->debug ("\tResponse: $line");
if (length $isThat) {
$self->{thats}->{$topic}->{$isThat}->{$ontrig}->{reply}->{$repcnt} = $line;
}
else {
$self->{topics}->{$topic}->{$ontrig}->{reply}->{$repcnt} = $line;
$self->{syntax}->{$topic}->{$ontrig}->{reply}->{$repcnt}->{ref} = "$fname line $lineno";
$self->debug ("\t\tSaved to \$self->{topics}->{$topic}->{$ontrig}->{reply}->{$repcnt}: "
. "$self->{topics}->{$topic}->{$ontrig}->{reply}->{$repcnt}");
}
$repcnt++;
}
elsif ($cmd eq '%') {
# % PREVIOUS
$self->debug ("\t% Previous pattern: $line");
# This was handled above.
}
elsif ($cmd eq '^') {
# ^ CONTINUE
# This should've been handled above...
}
elsif ($cmd eq '@') {
# @ REDIRECT
$self->debug ("\tRedirect the response to $line");
if (length $isThat) {
$self->{thats}->{$topic}->{$isThat}->{$ontrig}->{redirect} = $line;
}
else {
$self->{topics}->{$topic}->{$ontrig}->{redirect} = $line;
}
}
elsif ($cmd eq '*') {
# * CONDITION
$self->debug ("\tAdding condition.");
if (length $isThat) {
$self->{thats}->{$topic}->{$isThat}->{$ontrig}->{condition}->{$concnt} = $line;
}
else {
$self->{topics}->{$topic}->{$ontrig}->{condition}->{$concnt} = $line;
}
$concnt++;
}
else {
$self->issue ("Unrecognized command \"$cmd\" at $fname line $lineno.");
next;
}
}
}
=item string checkSyntax (char $COMMAND, string $LINE)
Check the syntax of a line of RiveScript code. This is called automatically
for each line parsed by the module. C<$COMMAND> is the command part of the
line, and C<$LINE> is the rest of the line following the command (and
excluding inline comments).
If there is no problem with the line, this method returns C<undef>. Otherwise
it returns the text of the syntax error.
If C<strict> mode is enabled in the constructor (which is on by default), a
syntax error will result in a fatal error. If it's not enabled, the error is
only sent via C<warn> and the file currently being processed is aborted.
=cut
sub checkSyntax {
my ($self,$cmd,$line) = @_;
# This function returns undef when no syntax errors are present, otherwise
# returns the text of the syntax error.
# Run syntax checks based on the type of command.
if ($cmd eq '!') {
# ! Definition
# - Must be formatted like this:
# ! type name = value
# OR
# ! type = value
# - Type options are NOT enforceable, for future compatibility; if RiveScript
# encounters a new type that it can't handle, it can safely warn and skip it.
if ($line !~ /^.+(?:\s+.+|)\s*=\s*.+?$/) {
return "Invalid format for !Definition line: must be '! type name = value' OR '! type = value'";
}
}
elsif ($cmd eq '>') {
# > Label
# - The "begin" label must have only one argument ("begin")
# - "topic" labels must be lowercase but can inherit other topics ([A-Za-z0-9_\s])
# - "object" labels follow the same rules as "topic" labels, but don't need be lowercase
if ($line =~ /^begin/ && $line =~ /\s+/) {
return "The 'begin' label takes no additional arguments, should be verbatim '> begin'";
}
elsif ($line =~ /^topic/i && $line =~ /[^a-z0-9_\-\s]/) {
return "Topics should be lowercased and contain only numbers and letters!";
}
elsif ($line =~ /[^A-Za-z0-9_\-\s]/) {
return "Objects can only contain numbers and letters!";
}
}
elsif ($cmd eq '+' || $cmd eq '%' || $cmd eq '@') {
# + Trigger, % Previous, @ Redirect
# This one is strict. The triggers are to be run through Perl's regular expression
# engine. Therefore it should be acceptable by the regexp engine.
# - Entirely lowercase
# - No symbols except: ( | ) [ ] * _ # @ { } < > =
# - All brackets should be matched
my $parens = 0; # Open parenthesis
my $square = 0; # Open square brackets
my $curly = 0; # Open curly brackets
my $chevron = 0; # Open angled brackets
# Look for obvious errors.
if ($line =~ /[^a-z0-9(\|)\[\]*_#\@{}<>=\s]/) {
return "Triggers may only contain lowercase letters, numbers, and these symbols: ( | ) [ ] * _ # @ { } < > =";
}
# Count brackets.
my @chr = split(//, $line);
for (my $i = 0; $i < scalar(@chr); $i++) {
my $char = $chr[$i];
# Count brackets.
$parens++ if $char eq '('; $parens-- if $char eq ')';
$square++ if $char eq '['; $square-- if $char eq ']';
$curly++ if $char eq '{'; $curly-- if $char eq '}';
$chevron++ if $char eq '<'; $chevron-- if $char eq '>';
}
# Any mismatches?
if ($parens) {
return "Unmatched " . ($parens > 0 ? "left" : "right") . " parenthesis bracket ()";
}
if ($square) {
return "Unmatched " . ($square > 0 ? "left" : "right") . " square bracket []";
}
if ($curly) {
return "Unmatched " . ($curly > 0 ? "left" : "right") . " curly bracket {}";
}
if ($chevron) {
return "Unmatched " . ($chevron > 0 ? "left" : "right" ) . " angled bracket <>";
}
}
elsif ($cmd eq '-' || $cmd eq '^' || $cmd eq '/') {
# - Trigger, ^ Continue, / Comment
# These commands take verbatim arguments, so their syntax is loose.
}
elsif ($cmd eq '*') {
# * Condition
# Syntax for a conditional is as follows:
# * value symbol value => response
if ($line !~ /^.+?\s*(==|eq|!=|ne|<>|<|<=|>|>=)\s*.+?=>.+?$/) {
return "Invalid format for !Condition: should be like `* value symbol value => response`";
}
}
# All good? Return undef.
return undef;
}
=item void sortReplies ()
Call this method after loading replies to create an internal sort buffer. This
is necessary for trigger matching purposes. If you fail to call this method
yourself, RiveScript will call it once when you request a reply. However, it
will complain loudly about it.
=cut
sub sortReplies {
my $self = shift;
my $thats = shift || 'no';
# Make this method dynamic: allow it to sort both triggers and %previous.
# To that end we need to make some more references.
my $triglvl = {};
my $sortlvl = 'sorted';
if ($thats eq 'thats') {
$triglvl = $self->{thats};
$sortlvl = 'sortsthat';
}
else {
$triglvl = $self->{topics};
}
$self->debug ("Sorting triggers...");
# Loop through all the topics.
foreach my $topic (keys %{$triglvl}) {
$self->debug ("Analyzing topic $topic");
# Create a priority map.
my $prior = {
0 => [], # Default
};
# Collect a list of all the triggers we're going to need to
# worry about. If this topic inherits another topic, we need to
# recursively add those to the list.
my @alltrig = $self->_topicTriggers($topic,$triglvl,0,0,0);
#foreach my $trig (keys %{$triglvl->{$topic}}) {
foreach my $trig (@alltrig) {
if ($trig =~ /\{weight=(\d+)\}/i) {
my $weight = $1;
if (!exists $prior->{$weight}) {
$prior->{$weight} = [];
}
push (@{$prior->{$weight}}, $trig);
}
else {
push (@{$prior->{0}}, $trig);
}
}
# Keep in mind here that there is a difference between 'includes'
# and 'inherits' -- topics that inherit other topics are able to
# OVERRIDE triggers that appear in the inherited topic. This means
# that if the top topic has a trigger of simply '*', then *NO* triggers
# are capable of matching in ANY inherited topic, because even though
# * has the lowest sorting priority, it has an automatic priority over
# all inherited topics.
#
# The _topicTriggers method takes this into account. All topics that
# inherit other topics will have their triggers prefixed with a fictional
# {inherits} tag, which would start at {inherits=0} and increment if the
# topic tree has other inheriting topics. So we can use this tag to
# make sure topics that inherit things will have their triggers always
# be on the top of the stack, from inherits=0 to inherits=n.
# Keep a running list of sorted triggers for this topic.
my @running = ();
# Sort them by priority.
foreach my $p (sort { $b <=> $a } keys %{$prior}) {
$self->debug ("\tSorting triggers with priority $p.");
# So, some of these triggers may include {inherits} tags, if they
# came from a topic which inherits another topic. Lower inherits
# values mean higher priority on the stack. Keep this in mind when
# keeping track of how to sort these things.
my $inherits = -1; # -1 means no {inherits} tag, for flexibility
my $highest_inherits = -1; # highest inheritence # we've seen
# Loop through and categorize these triggers.
my $track = {
$inherits => {
atomic => {}, # Sort by # of whole words
option => {}, # Sort optionals by # of words
alpha => {}, # Sort alpha wildcards by # of words
number => {}, # Sort numeric wildcards by # of words
wild => {}, # Sort wildcards by # of words
pound => [], # Triggers of just #
under => [], # Triggers of just _
star => [], # Triggers of just *
},
};
foreach my $trig (@{$prior->{$p}}) {
$self->debug("\t\tLooking at trigger: $trig");
# See if this trigger has an inherits number.
if ($trig =~ /{inherits=(\d+)}/) {
$inherits = $1;
if ($inherits > $highest_inherits) {
$highest_inherits = $inherits;
}
$self->debug("\t\t\tTrigger belongs to a topic which inherits other topics: level=$inherits");
$trig =~ s/{inherits=\d+}//g;
}
else {
$inherits = -1;
}
# If this is the first time we've seen this inheritence priority
# level, initialize its structure.
if (!exists $track->{$inherits}) {
$track->{$inherits} = {
atomic => {},
option => {},
alpha => {},
number => {},
wild => {},
pound => [],
under => [],
star => [],
};
}
if ($trig =~ /\_/) {
# Alphabetic wildcard included.
my @words = split(/[\s\*\#\_]+/, $trig);
my $cnt = scalar(@words);
$self->debug("\t\tHas a _ wildcard with $cnt words.");
if ($cnt > 1) {
if (!exists $track->{$inherits}->{alpha}->{$cnt}) {
$track->{$inherits}->{alpha}->{$cnt} = [];
}
push (@{$track->{$inherits}->{alpha}->{$cnt}}, $trig);
}
else {
push (@{$track->{$inherits}->{under}}, $trig);
}
}
elsif ($trig =~ /\#/) {
# Numeric wildcard included.
my @words = split(/[\s\*\#\_]+/, $trig);
my $cnt = scalar(@words);
$self->debug("\t\tHas a # wildcard with $cnt words.");
if ($cnt > 1) {
if (!exists $track->{$inherits}->{number}->{$cnt}) {
$track->{$inherits}->{number}->{$cnt} = [];
}
push (@{$track->{$inherits}->{number}->{$cnt}}, $trig);
}
else {
push (@{$track->{$inherits}->{pound}}, $trig);
}
}
elsif ($trig =~ /\*/) {
# Wildcards included.
my @words = split(/[\s\*\#\_]+/, $trig);
my $cnt = scalar(@words);
$self->debug("Has a * wildcard with $cnt words.");
if ($cnt > 1) {
if (!exists $track->{$inherits}->{wild}->{$cnt}) {
$track->{$inherits}->{wild}->{$cnt} = [];
}
push (@{$track->{$inherits}->{wild}->{$cnt}}, $trig);
}
else {
push (@{$track->{$inherits}->{star}}, $trig);
}
}
elsif ($trig =~ /\[(.+?)\]/) {
# Optionals included.
my @words = split(/[\s\*\#\_]+/, $trig);
my $cnt = scalar(@words);
$self->debug("Has optionals and $cnt words.");
if (!exists $track->{$inherits}->{option}->{$cnt}) {
$track->{$inherits}->{option}->{$cnt} = [];
}
push (@{$track->{$inherits}->{option}->{$cnt}}, $trig);
}
else {
# Totally atomic.
my @words = split(/[\s\*\#\_]+/, $trig);
my $cnt = scalar(@words);
$self->debug("Totally atomic and $cnt words.");
if (!exists $track->{$inherits}->{atomic}->{$cnt}) {
$track->{$inherits}->{atomic}->{$cnt} = [];
}
push (@{$track->{$inherits}->{atomic}->{$cnt}}, $trig);
}
}
# Add this group to the sort list.
$track->{ ($highest_inherits + 1) } = delete $track->{'-1'}; # Move the no-{inherits} group away for a sec
foreach my $ip (sort { $a <=> $b } keys %{$track}) {
$self->debug("ip=$ip");
foreach my $i (sort { $b <=> $a } keys %{$track->{$ip}->{atomic}}) {
push (@running,@{$track->{$ip}->{atomic}->{$i}});
}
foreach my $i (sort { $b <=> $a } keys %{$track->{$ip}->{option}}) {
push (@running,@{$track->{$ip}->{option}->{$i}});
}
foreach my $i (sort { $b <=> $a } keys %{$track->{$ip}->{alpha}}) {
push (@running,@{$track->{$ip}->{alpha}->{$i}});
}
foreach my $i (sort { $b <=> $a } keys %{$track->{$ip}->{number}}) {
push (@running,@{$track->{$ip}->{number}->{$i}});
}
foreach my $i (sort { $b <=> $a } keys %{$track->{$ip}->{wild}}) {
push (@running,@{$track->{$ip}->{wild}->{$i}});
}
push (@running, sort { length($b) <=> length($a) } @{$track->{$ip}->{under}});
push (@running, sort { length($b) <=> length($a) } @{$track->{$ip}->{pound}});
push (@running, sort { length($b) <=> length($a) } @{$track->{$ip}->{star}});
}
}
# Save this topic's sorted list.
$self->{$sortlvl}->{$topic} = [ @running ];
}
# Also sort that's.
if ($thats ne 'thats') {
# This will sort the %previous lines to best match the bot's last reply.
$self->sortReplies ('thats');
# If any of those %previous's had more than one +trigger for them, this
# will sort all those +trigger's to pair back the best human interaction.
$self->sortThatTriggers;
# Also sort both kinds of substitutions.
$self->sortList ('subs', keys %{$self->{subs}});
$self->sortList ('person', keys %{$self->{person}});
}
}
sub sortThatTriggers {
my ($self) = @_;
# Usage case: if you have more than one +trigger with the same %previous,
# this will create a sort buffer for all those +trigger's.
# Ex:
#
# + how [are] you [doing]
# - I'm doing great, how are you?
# - Good -- how are you?
# - Fine, how are you?
#
# + [*] @good [*]
# % * how are you
# - That's good. :-)
#
# # // TODO: why isn't this ever called?
# + [*] @bad [*]
# % * how are you
# - Aww. :-( What's the matter?
#
# + *
# % * how are you
# - I see...
# The sort buffer for this.
$self->{sortedthat} = {};
# Eventual structure:
# $self->{sortedthat} = {
# random => {
# '* how are you' => [
# '[*] @good [*]',
# '[*] @bad [*]',
# '*',
# ],
# },
# };
$self->debug ("Sorting reverse triggers for %previous groups...");
foreach my $topic (keys %{$self->{thats}}) {
# Create a running list of the sort buffer for this topic.
my @running = ();
$self->debug ("Sorting the 'that' triggers for topic $topic");
foreach my $that (keys %{$self->{thats}->{$topic}}) {
$self->debug ("Sorting triggers that go with the 'that' of \"$that\"");
# Loop through and categorize these triggers.
my $track = {
atomic => {}, # Sort by # of whole words
option => {}, # Sort optionals by # of words
alpha => {}, # Sort letters by # of words
number => {}, # Sort numbers by # of words
wild => {}, # Sort wildcards by # of words
pound => [], # Triggers of just #
under => [], # Triggers of just _
star => [], # Triggers of just *
};
# Loop through all the triggers for this %previous.
foreach my $trig (keys %{$self->{thats}->{$topic}->{$that}}) {
if ($trig =~ /\_/) {
# Alphabetic wildcard included.
my @words = split(/[\s\*\#\_]+/, $trig);
my $cnt = scalar(@words);
if ($cnt > 1) {
if (!exists $track->{alpha}->{$cnt}) {
$track->{alpha}->{$cnt} = [];
}
push (@{$track->{alpha}->{$cnt}}, $trig);
}
else {
push (@{$track->{under}}, $trig);
}
}
elsif ($trig =~ /\#/) {
# Numeric wildcard included.
my @words = split(/[\s\*\#\_]+/, $trig);
my $cnt = scalar(@words);
if ($cnt > 1) {
if (!exists $track->{number}->{$cnt}) {
$track->{number}->{$cnt} = [];
}
push (@{$track->{number}->{$cnt}}, $trig);
}
else {
push (@{$track->{pound}}, $trig);
}
}
elsif ($trig =~ /\*/) {
# Wildcards included.
my @words = split(/[\s\*\#\_]+/, $trig);
my $cnt = scalar(@words);
if ($cnt > 1) {
if (!exists $track->{wild}->{$cnt}) {
$track->{wild}->{$cnt} = [];
}
push (@{$track->{wild}->{$cnt}}, $trig);
}
else {
push (@{$track->{star}}, $trig);
}
}
elsif ($trig =~ /\[(.+?)\]/) {
# Optionals included.
my @words = split(/[\s\*\#\_]+/, $trig);
my $cnt = scalar(@words);
if (!exists $track->{option}->{$cnt}) {
$track->{option}->{$cnt} = [];
}
push (@{$track->{option}->{$cnt}}, $trig);
}
else {
# Totally atomic.
my @words = split(/[\s\*\#\_]+/, $trig);
my $cnt = scalar(@words);
if (!exists $track->{atomic}->{$cnt}) {
$track->{atomic}->{$cnt} = [];
}
push (@{$track->{atomic}->{$cnt}}, $trig);
}
}
# Add this group to the sort list.
my @running = ();
foreach my $i (sort { $b <=> $a } keys %{$track->{atomic}}) {
push (@running,@{$track->{atomic}->{$i}});
}
foreach my $i (sort { $b <=> $a } keys %{$track->{option}}) {
push (@running,@{$track->{option}->{$i}});
}
foreach my $i (sort { $b <=> $a } keys %{$track->{alpha}}) {
push (@running,@{$track->{alpha}->{$i}});
}
foreach my $i (sort { $b <=> $a } keys %{$track->{number}}) {
push (@running,@{$track->{number}->{$i}});
}
foreach my $i (sort { $b <=> $a } keys %{$track->{wild}}) {
push (@running,@{$track->{wild}->{$i}});
}
push (@running, sort { length($b) <=> length($a) } @{$track->{under}});
push (@running, sort { length($b) <=> length($a) } @{$track->{pound}});
push (@running, sort { length($b) <=> length($a) } @{$track->{star}});
# Keep this buffer.
$self->{sortedthat}->{$topic}->{$that} = [ @running ];
}
}
}
sub sortList {
my ($self,$name,@list) = @_;
# If a sorted list by this name already exists, delete it.
if (exists $self->{sortlist}->{$name}) {
delete $self->{sortlist}->{$name};
}
# Initialize the sorted list.
$self->{sortlist}->{$name} = [];
# Track by number of words.
my $track = {};
# Loop through each item in the list.
foreach my $item (@list) {
# Count the words.
my @words = split(/\s+/, $item);
my $cword = scalar(@words);
# Store this by group of word counts.
if (!exists $track->{$cword}) {
$track->{$cword} = [];
}
push (@{$track->{$cword}}, $item);
}
# Sort them.
my @sorted = ();
foreach my $count (sort { $b <=> $a } keys %{$track}) {
my @items = sort { length $b <=> length $a } @{$track->{$count}};
push (@sorted,@items);
}
# Store this list.
$self->{sortlist}->{$name} = [ @sorted ];
return 1;
}
# Given one topic, walk the inheritence tree and return an array of all topics.
sub _getTopicTree {
my ($self,$topic,$depth) = @_;
# Break if we're in too deep.
if ($depth > $self->{depth}) {
$self->issue ("Deep recursion while scanning topic inheritance (topic $topic was involved)");
return ();
}
# Collect an array of topics.
my @topics = ($topic);
$self->debug ("_getTopicTree depth $depth; topics: @topics");
# Does this topic include others?
if (exists $self->{includes}->{$topic}) {
# Try each of these.
foreach my $includes (sort { $a cmp $b } keys %{$self->{includes}->{$topic}}) {
$self->debug ("Topic $topic includes $includes");
push (@topics, $self->_getTopicTree($includes,($depth + 1)));
}
$self->debug ("_getTopicTree depth $depth (b); topics: @topics");
}
# Does the topic inherit others?
if (exists $self->{lineage}->{$topic}) {
# Try each of these.
foreach my $inherits (sort { $a cmp $b } keys %{$self->{lineage}->{$topic}}) {
$self->debug ("Topic $topic inherits $inherits");
push (@topics, $self->_getTopicTree($inherits,($depth + 1)));
}
$self->debug ("_getTopicTree depth $depth (b); topics: @topics");
}
# Return them.
return (@topics);
}
# Gather an array of all triggers in a topic. If the topic inherits other
# topics, recursively collect those triggers too. Take care about recursion.
sub _topicTriggers {
my ($self,$topic,$triglvl,$depth,$inheritence,$inherited) = @_;
# Break if we're in too deep.
if ($depth > $self->{depth}) {
$self->issue ("Deep recursion while scanning topic inheritance (topic $topic was involved)");
return ();
}
# Important info about the depth vs inheritence params to this function:
# depth increments by 1 every time this function recursively calls itself.
# inheritence increments by 1 only when this topic inherits another topic.
#
# This way, `> topic alpha includes beta inherits gamma` will have this effect:
# alpha and beta's triggers are combined together into one matching pool, and then
# these triggers have higher matching priority than gamma's.
#
# The $inherited option is 1 if this is a recursive call, from a topic that
# inherits other topics. This forces the {inherits} tag to be added to the
# triggers. This only applies when the top topic "includes" another topic.
$self->debug ("\tCollecting trigger list for topic $topic (depth=$depth; inheritence=$inheritence; inherited=$inherited)");
# topic: the name of the topic
# triglvl: either $self->{topics} or $self->{thats}
# depth: starts at 0 and ++'s with each recursion
# Collect an array of triggers to return.
my @triggers = ();
# Does this topic include others?
if (exists $self->{includes}->{$topic}) {
# Check every included topic.
foreach my $includes (sort { $a cmp $b } keys %{$self->{includes}->{$topic}}) {
$self->debug ("\t\tTopic $topic includes $includes");
push (@triggers, $self->_topicTriggers($includes,$triglvl,($depth + 1), $inheritence, 1));
}
}
# Does this topic inherit others?
if (exists $self->{lineage}->{$topic}) {
# Check every inherited topic.
foreach my $inherits (sort { $a cmp $b } keys %{$self->{lineage}->{$topic}}) {
$self->debug ("\t\tTopic $topic inherits $inherits");
push (@triggers, $self->_topicTriggers($inherits,$triglvl,($depth + 1), ($inheritence + 1), 0));
}
}
# Collect the triggers for *this* topic. If this topic inherits any other
# topics, it means that this topic's triggers have higher priority than those
# in any inherited topics. Enforce this with an {inherits} tag.
if (exists $self->{lineage}->{$topic} || $inherited) {
my @inThisTopic = keys %{$triglvl->{$topic}};
foreach my $trigger (@inThisTopic) {
$self->debug ("\t\tPrefixing trigger with {inherits=$inheritence}$trigger");
push (@triggers, "{inherits=$inheritence}$trigger");
}
}
else {
push (@triggers, keys %{$triglvl->{$topic}});
}
# Return them.
return (@triggers);
}
=item data deparse ()
Translate the in-memory representation of the loaded RiveScript documents into
a Perl data structure. This would be useful for developing a user interface to
facilitate editing of RiveScript replies without having to edit the RiveScript
code manually.
The data structure returned from this will follow this format:
{
"begin" => { # Contains begin block and config settings
"global" => { # ! global (global variables)
"depth" => 50,
...
},
"var" => { # ! var (bot variables)
"name" => "Aiden",
...
},
"sub" => { # ! sub (substitutions)
"what's" => "what is",
...
},
"person" => { # ! person (person substitutions)
"you" => "I",
...
},
"array" => { # ! array (arrays)
"colors" => [ "red", "green", "light green", "blue" ],
...
},
"triggers" => { # triggers in your > begin block
"request" => { # trigger "+ request"
"reply" => [ "{ok}" ],
},
},
},
"topic" => { # all topics under here
"random" => { # topic names (default is random)
"hello bot" => { # trigger labels
"reply" => [ "Hello human!" ], # Array of -Replies
"redirect" => "hello", # Only if @Redirect exists
"previous" => "hello human", # Only if %Previous exists
"condition" => [ # Only if *Conditions exist
"<get name> != undefined => Hello <get name>!",
...
],
},
},
},
"include" => { # topic inclusion
"alpha" => [ "beta", "gamma" ], # > topic alpha includes beta gamma
},
"inherit" => { # topic inheritence
"alpha" => [ "delta" ], # > topic alpha inherits delta
}
}
Note that inline object macros can't be deparsed this way. This is probably for
the best (for security, etc). The global variables "debug" and "depth" are only
provided if the values differ from the defaults (true and 50, respectively).
=cut
sub deparse {
my ($self) = @_;
# Can we clone?
eval {
require Clone;
$self->{_can_clone} = 1;
};
if ($@) {
warn "You don't have the Clone module installed. Output from "
. "RiveScript->deparse will remain referenced to internal data "
. "structures. Be careful!";
$self->{_can_clone} = 0;
}
# Data to return.
my $deparse = {
begin => {
global => {},
var => {},
sub => {},
person => {},
array => {},
triggers => {},
},
topic => {},
inherit => {},
include => {},
};
# Populate the config fields.
if ($self->{debug}) {
$deparse->{begin}->{global}->{debug} = $self->{debug};
}
if ($self->{depth} != 50) {
$deparse->{begin}->{global}->{depth} = $self->{depth};
}
$deparse->{begin}->{var} = $self->_clone($self->{bot});
$deparse->{begin}->{sub} = $self->_clone($self->{subs});
$deparse->{begin}->{person} = $self->_clone($self->{person});
$deparse->{begin}->{array} = $self->_clone($self->{arrays});
foreach my $global (keys %{$self->{globals}}) {
$deparse->{begin}->{global}->{$global} = $self->{globals}->{$global};
}
# Triggers.
foreach my $topic (keys %{$self->{topics}}) {
my $dest; # Where to place the topic info.
if ($topic eq "__begin__") {
# Begin block.
$dest = $deparse->{begin}->{triggers};
}
else {
# Normal topic.
if (!exists $deparse->{topic}->{$topic}) {
$deparse->{topic}->{$topic} = {};
}
$dest = $deparse->{topic}->{$topic};
}
foreach my $trig (keys %{$self->{topics}->{$topic}}) {
my $src = $self->{topics}->{$topic}->{$trig};
$dest->{$trig} = {};
$self->_copy_trigger($trig, $src, $dest);
}
}
# %Previous's.
foreach my $topic (keys %{$self->{thats}}) {
my $dest; # Where to place the topic info.
if ($topic eq "__begin__") {
# Begin block.
$dest = $deparse->{begin}->{triggers};
}
else {
# Normal topic.
if (!exists $deparse->{topic}->{$topic}) {
$deparse->{topic}->{$topic} = {};
}
$dest = $deparse->{topic}->{$topic};
}
# The "that" structure is backwards: bot reply, then trigger, then info.
foreach my $previous (keys %{$self->{thats}->{$topic}}) {
foreach my $trig (keys %{$self->{thats}->{$topic}->{$previous}}) {
my $src = $self->{thats}->{$topic}->{$previous}->{$trig};
$dest->{$trig}->{previous} = $previous;
$self->_copy_trigger($trig, $src, $dest);
}
}
}
# Inherits/Includes.
foreach my $topic (keys %{$self->{lineage}}) {
$deparse->{inherit}->{$topic} = [];
foreach my $inherit (keys %{$self->{lineage}->{$topic}}) {
push @{$deparse->{inherit}->{$topic}}, $inherit;
}
}
foreach my $topic (keys %{$self->{includes}}) {
$deparse->{include}->{$topic} = [];
foreach my $include (keys %{$self->{includes}->{$topic}}) {
push @{$deparse->{include}->{$topic}}, $include;
}
}
return $deparse;
}
sub _copy_trigger {
my ($self, $trig, $src, $dest) = @_;
if (exists $src->{redirect}) { # @Redirect
$dest->{$trig}->{redirect} = $src->{redirect};
}
if (exists $src->{condition}) { # *Condition
$dest->{$trig}->{condition} = [];
foreach my $i (sort { $a <=> $b } keys %{$src->{condition}}) {
push @{$dest->{$trig}->{condition}}, $src->{condition}->{$i};
}
}
if (exists $src->{reply}) { # -Reply
$dest->{$trig}->{reply} = [];
foreach my $i (sort { $a <=> $b } keys %{$src->{reply}}) {
push @{$dest->{$trig}->{reply}}, $src->{reply}->{$i};
}
}
}
sub _clone {
my ($self,$data) = @_;
# Can clone?
if ($self->{_can_clone}) {
return Clone::clone($data);
}
return $data;
}
=item void write (glob $fh || string $file[, data $deparsed])
Write the currently parsed RiveScript data into a RiveScript file. This uses
C<deparse()> to dump a representation of the loaded data and writes it to the
destination file. Pass either a filehandle or a file name.
If you provide C<$deparsed>, it should be a data structure matching the format
of C<deparse()>. This way you can deparse your RiveScript brain, add/edit
replies and then pass in the new version to this method to save the changes
back to disk. Otherwise, C<deparse()> will be called to get the current
snapshot of the brain.
=back
=cut
sub write {
my ($self, $file, $deparsed) = @_;
my $fh;
if (ref($file) eq "GLOB") {
$fh = $file;
}
elsif (ref($file)) {
die "Must pass either a filehandle or file name to write()";
}
else {
open ($fh, ">", $file) or die "Can't write to $file: $!";
}
my $deparse = ref($deparsed) ? $deparsed : $self->deparse();
# Start at the beginning.
print {$fh} "// Written by RiveScript::deparse()\n";
print {$fh} "! version = 2.0\n\n";
# Variables of all sorts!
foreach my $sort (qw/global var sub person array/) {
next unless scalar keys %{$deparse->{begin}->{$sort}} > 0;
foreach my $var (sort keys %{$deparse->{begin}->{$sort}}) {
my $value = ref($deparse->{begin}->{$sort}->{$var}) ?
join("|", @{$deparse->{begin}->{$sort}->{$var}}) :
$deparse->{begin}->{$sort}->{$var};
print {$fh} "! $sort $var = " . $self->_write_wrapped($value,
$sort eq "array" ? "|" : " ") . "\n";
}
print {$fh} "\n";
}
if (scalar keys %{$deparse->{begin}->{triggers}}) {
print {$fh} "> begin\n\n";
$self->_write_triggers($fh, $deparse->{begin}->{triggers}, "indent");
print {$fh} "< begin\n\n";
}
# The topics. Random first!
my $doneRandom = 0;
foreach my $topic ("random", sort keys %{$deparse->{topic}}) {
next unless exists $deparse->{topic}->{$topic};
next if $topic eq "random" && $doneRandom;
$doneRandom = 1 if $topic eq "random";
my $tagged = 0; # Used > topic tag
if ($topic ne "random" || exists $deparse->{include}->{$topic} || exists $deparse->{inherit}->{$topic}) {
$tagged = 1;
print {$fh} "> topic $topic";
if (exists $deparse->{inherit}->{$topic}) {
print {$fh} " inherits " . join(" ", @{$deparse->{inherit}->{$topic}});
}
if (exists $deparse->{include}->{$topic}) {
print {$fh} " includes " . join(" ", @{$deparse->{include}->{$topic}});
}
print {$fh} "\n\n";
}
$self->_write_triggers($fh, $deparse->{topic}->{$topic}, $tagged ? "indent" : 0);
if ($tagged) {
print {$fh} "< topic\n\n";
}
}
return 1;
}
sub _write_triggers {
my ($self, $fh, $trigs, $id) = @_;
$id = $id ? "\t" : "";
foreach my $trig (sort keys %{$trigs}) {
print {$fh} $id . "+ " . $self->_write_wrapped($trig," ",$id) . "\n";
my $d = $trigs->{$trig};
if (exists $d->{previous}) {
print {$fh} $id . "% " . $self->_write_wrapped($d->{previous}," ",$id) . "\n";
}
if (exists $d->{condition}) {
foreach my $cond (@{$d->{condition}}) {
print {$fh} $id . "* " . $self->_write_wrapped($cond," ",$id) . "\n";
}
}
if (exists $d->{redirect}) {
print {$fh} $id . "@ " . $self->_write_wrapped($d->{redirect}," ",$id) . "\n";
}
if (exists $d->{reply}) {
foreach my $reply (@{$d->{reply}}) {
print {$fh} $id . "- " . $self->_write_wrapped($reply," ",$id) . "\n";
}
}
print {$fh} "\n";
}
}
sub _write_wrapped {
my ($self, $line, $sep, $indent) = @_;
my $id = $indent ? "\t" : "";
my @words;
if ($sep eq " ") {
@words = split(/\s+/, $line);
}
elsif ($sep eq "|") {
@words = split(/\|/, $line);
}
my @lines = ();
$line = "";
my @buf = ();
while (scalar(@words)) {
push (@buf, shift(@words));
$line = join($sep, @buf);
if (length $line > 78) {
# Need to word wrap.
unshift(@words, pop(@buf)); # Undo
push (@lines, join($sep,@buf));
@buf = ();
$line = "";
}
}
# Straggler?
if ($line) {
push @lines, $line;
}
my $return = shift(@lines);
if (scalar(@lines)) {
my $eol = ($sep eq " " ? '\s' : "");
foreach my $ln (@lines) {
$return .= "$eol\n$id^ $ln";
}
}
return $return;
}
################################################################################
## Configuration Methods ##
################################################################################
=head2 CONFIGURATION
=over 4
=item bool setHandler (string $LANGUAGE => code $CODEREF, ...)
Define some code to handle objects of a particular programming language. If the
coderef is C<undef>, it will delete the handler.
The code receives the variables C<$rs, $action, $name,> and C<$data>. These
variables are described here:
$rs = Reference to Perl RiveScript object.
$action = "load" during the parsing phase when an >object is found.
"call" when provoked via a <call> tag for a reply
$name = The name of the object.
$data = The source of the object during the parsing phase, or an array
reference of arguments when provoked via a <call> tag.
There is a default handler set up that handles Perl objects.
If you want to block Perl objects from being loaded, you can just set it to be
undef, and its handler will be deleted and Perl objects will be skipped over:
$rs->setHandler (perl => undef);
The rationale behind this "pluggable" object interface is that it makes
RiveScript more flexible given certain environments. For instance, if you use
RiveScript on the web where the user chats with your bot using CGI, you might
define a handler so that JavaScript objects can be loaded and called. Perl
itself can't execute JavaScript, but the user's web browser can.
See the JavaScript example in the C<docs> directory in this distribution.
=cut
sub setHandler {
my ($self,%info) = @_;
foreach my $lang (keys %info) {
my $code = $info{$lang};
$lang = lc($lang);
$lang =~ s/\s+//g;
# If the coderef is undef, delete the handler.
if (!defined $code) {
delete $self->{handlers}->{$lang};
}
else {
# Otherwise it must be a coderef.
if (ref($code) eq "CODE") {
$self->{handlers}->{$lang} = $code;
}
else {
$self->issue("Handler for language $lang must be a code reference!");
}
}
}
return 1;
}
=item bool setSubroutine (string $NAME, code $CODEREF)
Manually create a RiveScript object (a dynamic bit of Perl code that can be
provoked in a RiveScript response). C<$NAME> should be a single-word,
alphanumeric string. C<$CODEREF> should be a pointer to a subroutine or an
anonymous sub.
=cut
sub setSubroutine {
my ($self,$name,$sub) = @_;
$self->{objects}->{$name} = $sub;
return 1;
}
=item bool setGlobal (hash %DATA)
Set one or more global variables, in hash form, where the keys are the variable
names and the values are their value. This subroutine will make sure that you
don't override any reserved global variables, and warn if that happens.
This is equivalent to C<! global> in RiveScript code.
To delete a global, set its value to C<undef> or "C<E<lt>undefE<gt>>". This
is true for variables, substitutions, person, and uservars.
=cut
sub setGlobal {
my ($self,%data) = @_;
foreach my $key (keys %data) {
if (!defined $data{$key}) {
$data{$key} = "<undef>";
}
my $reserved = 0;
foreach my $res (@{$self->{reserved}}) {
if ($res eq $key) {
$reserved = 1;
last;
}
}
if ($reserved) {
if ($data{$key} eq "<undef>") {
delete $self->{globals}->{$key};
}
else {
$self->{globals}->{$key} = $data{$key};
}
}
else {
if ($data{$key} eq "<undef>") {
delete $self->{$key};
}
else {
$self->{$key} = $data{$key};
}
}
}
return 1;
}
=item bool setVariable (hash %DATA)
Set one or more bot variables (things that describe your bot's personality).
This is equivalent to C<! var> in RiveScript code.
=cut
sub setVariable {
my ($self,%data) = @_;
foreach my $key (keys %data) {
if (!defined $data{$key}) {
$data{$key} = "<undef>";
}
if ($data{$key} eq "<undef>") {
delete $self->{bot}->{$key};
}
else {
$self->{bot}->{$key} = $data{$key};
}
}
return 1;
}
=item bool setSubstitution (hash %DATA)
Set one or more substitution patterns. The keys should be the original word, and
the value should be the word to substitute with it.
$rs->setSubstitution (
q{what's} => 'what is',
q{what're} => 'what are',
);
This is equivalent to C<! sub> in RiveScript code.
=cut
sub setSubstitution {
my ($self,%data) = @_;
foreach my $key (keys %data) {
if (!defined $data{$key}) {
$data{$key} = "<undef>";
}
if ($data{$key} eq "<undef>") {
delete $self->{subs}->{$key};
}
else {
$self->{subs}->{$key} = $data{$key};
}
}
return 1;
}
=item bool setPerson (hash %DATA)
Set a person substitution. This is equivalent to C<! person> in RiveScript code.
=cut
sub setPerson {
my ($self,%data) = @_;
foreach my $key (keys %data) {
if (!defined $data{$key}) {
$data{$key} = "<undef>";
}
if ($data{$key} eq "<undef>") {
delete $self->{person}->{$key};
}
else {
$self->{person}->{$key} = $data{$key};
}
}
return 1;
}
=item bool setUservar (string $USER, hash %DATA)
Set a variable for a user. C<$USER> should be their User ID, and C<%DATA> is a
hash containing variable/value pairs.
This is like C<E<lt>setE<gt>> for a specific user.
=cut
sub setUservar {
my ($self,$user,%data) = @_;
foreach my $key (keys %data) {
if (!defined $data{$key}) {
$data{$key} = "<undef>";
}
if ($data{$key} eq "<undef>") {
delete $self->{client}->{$user}->{$key};
}
else {
$self->{client}->{$user}->{$key} = $data{$key};
}
}
return 1;
}
=item string getUservar (string $USER, string $VAR)
This is an alias for getUservars, and is here because it makes more grammatical
sense.
=cut
sub getUservar {
# Alias for getUservars.
my $self = shift;
return $self->getUservars (@_);
}
=item data getUservars ([string $USER][, string $VAR])
Get all the variables about a user. If a username is provided, returns a hash
B<reference> containing that user's information. Else, a hash reference of all
the users and their information is returned.
You can optionally pass a second argument, C<$VAR>, to get a specific variable
that belongs to the user. For instance, C<getUservars ("soandso", "age")>.
This is like C<E<lt>getE<gt>> for a specific user or for all users.
=cut
sub getUservars {
my ($self,$user,$var) = @_;
$user = '' unless defined $user;
$var = '' unless defined $var;
# Did they want a specific variable?
if (length $user && length $var) {
if (exists $self->{client}->{$user}->{$var}) {
return $self->{client}->{$user}->{$var};
}
else {
return undef;
}
}
if (length $user) {
return $self->{client}->{$user};
}
else {
return $self->{client};
}
}
=item bool clearUservars ([string $USER])
Clears all variables about C<$USER>. If no C<$USER> is provided, clears all
variables about all users.
=cut
sub clearUservars {
my $self = shift;
my $user = shift || '';
if (length $user) {
foreach my $var (keys %{$self->{client}->{$user}}) {
delete $self->{client}->{$user}->{$var};
}
delete $self->{client}->{$user};
}
else {
foreach my $client (keys %{$self->{client}}) {
foreach my $var (keys %{$self->{client}->{$client}}) {
delete $self->{client}->{$client}->{$var};
}
delete $self->{client}->{$client};
}
}
return 1;
}
=item bool freezeUservars (string $USER)
Freeze the current state of variables for user C<$USER>. This will back up the
user's current state (their variables and reply history). This won't statically
prevent the user's state from changing; it merely saves its current state. Then
use thawUservars() to revert back to this previous state.
=cut
sub freezeUservars {
my ($self,$user) = @_;
$user = '' unless defined $user;
if (length $user && exists $self->{client}->{$user}) {
# Freeze their variables. First unfreeze the last copy if they
# exist.
if (exists $self->{frozen}->{$user}) {
$self->thawUservars ($user, discard => 1);
}
# Back up all our variables.
foreach my $var (keys %{$self->{client}->{$user}}) {
next if $var eq "__history__";
my $value = $self->{client}->{$user}->{$var};
$self->{frozen}->{$user}->{$var} = $value;
}
# Back up the history.
$self->{frozen}->{$user}->{__history__}->{input} = [
@{$self->{client}->{$user}->{__history__}->{input}},
];
$self->{frozen}->{$user}->{__history__}->{reply} = [
@{$self->{client}->{$user}->{__history__}->{reply}},
];
return 1;
}
return undef;
}
=item bool thawUservars (string $USER[, hash %OPTIONS])
If the variables for C<$USER> were previously frozen, this method will restore
them to the state they were in when they were last frozen. It will then delete
the stored cache by default. The following options are accepted as an additional
hash of parameters (these options are mutually exclusive and you shouldn't use
both of them at the same time. If you do, "discard" will win.):
discard: Don't restore the user's state from the frozen copy, just delete the
frozen copy.
keep: Keep the frozen copy even after restoring the user's state. With this
you can repeatedly thawUservars on the same user to revert their state
without having to keep freezing them again. On the next freeze, the
last frozen state will be replaced with the new current state.
Examples:
# Delete the frozen cache but don't modify the user's variables.
$rs->thawUservars ("soandso", discard => 1);
# Restore the user's state from cache, but don't delete the cache.
$rs->thawUservars ("soandso", keep => 1);
=cut
sub thawUservars {
my ($self,$user,%args) = @_;
$user = '' unless defined $user;
if (length $user && exists $self->{frozen}->{$user}) {
# What are we doing?
my $restore = 1;
my $discard = 1;
if (exists $args{discard}) {
# Just discard the variables.
$restore = 0;
$discard = 1;
}
elsif (exists $args{keep}) {
# Keep the cache afterwards.
$restore = 1;
$discard = 0;
}
# Restore the state?
if ($restore) {
# Clear the client's current information.
$self->clearUservars ($user);
# Restore all our variables.
foreach my $var (keys %{$self->{frozen}->{$user}}) {
next if $var eq "__history__";
my $value = $self->{frozen}->{$user}->{$var};
$self->{client}->{$user}->{$var} = $value;
}
# Restore the history.
$self->{client}->{$user}->{__history__}->{input} = [
@{$self->{frozen}->{$user}->{__history__}->{input}},
];
$self->{client}->{$user}->{__history__}->{reply} = [
@{$self->{frozen}->{$user}->{__history__}->{reply}},
];
}
# Discard the cache?
if ($discard) {
foreach my $var (keys %{$self->{frozen}->{$user}}) {
delete $self->{frozen}->{$user}->{$var};
}
}
return 1;
}
return undef;
}
=item string lastMatch (string $USER)
After fetching a reply for user C<$USER>, the C<lastMatch> method will return the
raw text of the trigger that the user has matched with their reply. This function
may return undef in the event that the user B<did not> match any trigger at all
(likely the last reply was "C<ERR: No Reply Matched>" as well).
=back
=cut
sub lastMatch {
my ($self,$user) = @_;
$user = '' unless defined $user;
# Get this user's last matched trigger.
if (length $user && exists $self->{client}->{$user}->{__lastmatch__}) {
return $self->{client}->{$user}->{__lastmatch__};
}
return undef;
}
################################################################################
## Interaction Methods ##
################################################################################
=head2 INTERACTION
=over 4
=item string reply (string $USER, string $MESSAGE)
Fetch a response to C<$MESSAGE> from user C<$USER>. RiveScript will take care of
lowercasing, running substitutions, and removing punctuation from the message.
Returns a response from the RiveScript brain.
=back
=cut
sub reply {
my ($self,$user,$msg) = @_;
$self->debug ("Get reply to [$user] $msg");
# Format their message.
$msg = $self->_formatMessage ($msg);
my $reply = '';
# If the BEGIN statement exists, consult it first.
if (exists $self->{topics}->{__begin__}->{request}) {
# Get a response.
my $begin = $self->_getreply ($user,'request',
context => 'begin',
step => 0, # Recursion redundancy counter
);
# Okay to continue?
if ($begin =~ /\{ok\}/i) {
$reply = $self->_getreply ($user,$msg,
context => 'normal',
step => 0,
);
$begin =~ s/\{ok\}/$reply/ig;
}
$reply = $begin;
# Run more tag substitutions.
$reply = $self->processTags ($user,$msg,$reply,[],[],0);
}
else {
# Just continue then.
$reply = $self->_getreply ($user,$msg,
context => 'normal',
step => 0,
);
}
# Save their reply history.
unshift (@{$self->{client}->{$user}->{__history__}->{input}}, $msg);
while (scalar @{$self->{client}->{$user}->{__history__}->{input}} > 9) {
pop (@{$self->{client}->{$user}->{__history__}->{input}});
}
unshift (@{$self->{client}->{$user}->{__history__}->{reply}}, $reply);
while (scalar @{$self->{client}->{$user}->{__history__}->{reply}} > 9) {
pop (@{$self->{client}->{$user}->{__history__}->{reply}});
}
return $reply;
}
sub _getreply {
my ($self,$user,$msg,%tags) = @_;
# Need to sort replies?
if (scalar keys %{$self->{sorted}} == 0) {
$self->issue ("ERR: You never called sortReplies()! Start doing that from now on!");
$self->sortReplies();
}
# Collect info on this user if we have it.
my $topic = 'random';
my @stars = ();
my @thatstars = (); # For %previous's.
my $reply = '';
if (exists $self->{client}->{$user}) {
$topic = $self->{client}->{$user}->{topic};
}
else {
$self->{client}->{$user}->{topic} = 'random';
}
# Avoid letting the user fall into a missing topic.
if (!exists $self->{topics}->{$topic}) {
$self->issue ("User $user was in an empty topic named '$topic'!");
$topic = 'random';
$self->{client}->{$user}->{topic} = 'random';
}
# Avoid deep recursion.
if ($tags{step} > $self->{depth}) {
my $ref = '';
if (exists $self->{syntax}->{$topic}->{$msg}->{ref}) {
$ref = " at $self->{syntax}->{$topic}->{$msg}->{ref}";
}
$self->issue ("ERR: Deep Recursion Detected$ref!");
return "ERR: Deep Recursion Detected$ref!";
}
# Are we in the BEGIN Statement?
if ($tags{context} eq 'begin') {
# Imply some defaults.
$topic = '__begin__';
}
# Track this user's history.
if (!exists $self->{client}->{$user}->{__history__}) {
$self->{client}->{$user}->{__history__}->{input} = [
'undefined', 'undefined', 'undefined', 'undefined',
'undefined', 'undefined', 'undefined', 'undefined',
'undefined',
];
$self->{client}->{$user}->{__history__}->{reply} = [
'undefined', 'undefined', 'undefined', 'undefined',
'undefined', 'undefined', 'undefined', 'undefined',
'undefined',
];
}
# Create a pointer for the matched data (be it %previous or +trigger).
my $matched = {};
my $matchedTrigger = undef;
my $foundMatch = 0;
# See if there are any %previous's in this topic, or any topic related to it. This
# should only be done the first time -- not during a recursive @/{@} redirection.
# This is because in a redirection, "lastreply" is still gonna be the same as it was
# the first time, causing an infinite loop.
if ($tags{step} == 0) {
my @allTopics = ($topic);
if (exists $self->{includes}->{$topic} || exists $self->{lineage}->{$topic}) {
(@allTopics) = $self->_getTopicTree ($topic,0);
}
foreach my $top (@allTopics) {
$self->debug ("Checking topic $top for any %previous's.");
if (exists $self->{sortsthat}->{$top}) {
$self->debug ("There's a %previous in this topic");
# Do we have history yet?
if (scalar @{$self->{client}->{$user}->{__history__}->{reply}} > 0) {
my $lastReply = $self->{client}->{$user}->{__history__}->{reply}->[0];
# Format the bot's last reply the same as the human's.
$lastReply = $self->_formatMessage ($lastReply);
$self->debug ("lastReply: $lastReply");
# See if we find a match.
foreach my $trig (@{$self->{sortsthat}->{$top}}) {
my $botside = $self->_reply_regexp ($user,$trig);
$self->debug ("Try to match lastReply ($lastReply) to $botside");
# Look for a match.
if ($lastReply =~ /^$botside$/i) {
# Found a match! See if our message is correct too.
(@thatstars) = ($lastReply =~ /^$botside$/i);
foreach my $subtrig (@{$self->{sortedthat}->{$top}->{$trig}}) {
my $humanside = $self->_reply_regexp ($user,$subtrig);
$self->debug ("Now try to match $msg to $humanside");
if ($msg =~ /^$humanside$/i) {
$self->debug ("Found a match!");
$matched = $self->{thats}->{$top}->{$trig}->{$subtrig};
$matchedTrigger = $top;
$foundMatch = 1;
# Get the stars.
(@stars) = ($msg =~ /^$humanside$/i);
last;
}
}
}
# Break if we've found a match.
last if $foundMatch;
}
}
}
# Break if we've found a match.
last if $foundMatch;
}
}
# Search their topic for a match to their trigger.
if (not $foundMatch) {
foreach my $trig (@{$self->{sorted}->{$topic}}) {
# Process the triggers.
my $regexp = $self->_reply_regexp ($user,$trig);
$self->debug ("Trying to match \"$msg\" against $trig ($regexp)");
if ($msg =~ /^$regexp$/i) {
$self->debug ("Found a match!");
# We found a match, but what if the trigger we matched belongs to
# an inherited topic? Check for that.
if (exists $self->{topics}->{$topic}->{$trig}) {
# No, the trigger does belong to our own topic.
$matched = $self->{topics}->{$topic}->{$trig};
}
else {
# Our topic doesn't have this trigger. Check inheritence.
$matched = $self->_findTriggerByInheritence ($topic,$trig,0);
}
$foundMatch = 1;
$matchedTrigger = $trig;
# Get the stars.
(@stars) = ($msg =~ /^$regexp$/i);
last;
}
}
}
# Store what trigger they matched on (if $matched is undef, this will be
# too, which is great).
$self->{client}->{$user}->{__lastmatch__} = $matchedTrigger;
for (defined $matched) {
# See if there are any hard redirects.
if (exists $matched->{redirect}) {
$self->debug ("Redirecting us to $matched->{redirect}");
my $redirect = $matched->{redirect};
$redirect = $self->processTags ($user,$msg,$redirect,[@stars],[@thatstars],$tags{step});
$self->debug ("Pretend user asked: $redirect");
$reply = $self->_getreply ($user,$redirect,
context => $tags{context},
step => ($tags{step} + 1),
);
last;
}
# Check the conditionals.
if (exists $matched->{condition}) {
$self->debug ("Checking conditionals");
for (my $i = 0; exists $matched->{condition}->{$i}; $i++) {
my ($cond,$potreply) = split(/\s*=>\s*/, $matched->{condition}->{$i}, 2);
my ($left,$eq,$right) = ($cond =~ /^(.+?)\s+(==|eq|\!=|ne|\<\>|\<|\<=|\>|\>=)\s+(.+?)$/i);
$self->debug ("\tLeft: $left; EQ: $eq; Right: $right");
# Process tags on all of these.
$left = $self->processTags ($user,$msg,$left,[@stars],[@thatstars],$tags{step});
$right = $self->processTags ($user,$msg,$right,[@stars],[@thatstars],$tags{step});
# Revert them to undefined values.
$left = 'undefined' if $left eq '';
$right = 'undefined' if $right eq '';
$self->debug ("\t\tCheck if \"$left\" $eq \"$right\"");
# Validate the expression.
my $match = 0;
if ($eq eq 'eq' || $eq eq '==') {
if ($left eq $right) {
$match = 1;
}
}
elsif ($eq eq 'ne' || $eq eq '!=' || $eq eq '<>') {
if ($left ne $right) {
$match = 1;
}
}
elsif ($eq eq '<') {
if ($left < $right) {
$match = 1;
}
}
elsif ($eq eq '<=') {
if ($left <= $right) {
$match = 1;
}
}
elsif ($eq eq '>') {
if ($left > $right) {
$match = 1;
}
}
elsif ($eq eq '>=') {
if ($left >= $right) {
$match = 1;
}
}
if ($match) {
# Condition is true.
$reply = $potreply;
last;
}
}
}
last if length $reply > 0;
# Process weights in the replies.
my @bucket = ();
$self->debug ("Processing responses to this trigger.");
for (my $rep = 0; exists $matched->{reply}->{$rep}; $rep++) {
my $text = $matched->{reply}->{$rep};
my $weight = 1;
if ($text =~ /{weight=(\d+)\}/i) {
$weight = $1;
if ($weight <= 0) {
$weight = 1;
$self->issue ("Can't have a weight < 0!");
}
}
for (my $i = 0; $i < $weight; $i++) {
push (@bucket,$text);
}
}
# Get a random reply.
$reply = $bucket [ int(rand(scalar(@bucket))) ];
last;
}
# Still no reply?
if ($foundMatch == 0) {
$reply = "ERR: No Reply Matched";
}
elsif (length $reply == 0) {
$reply = "ERR: No Reply Found";
}
$self->debug ("Reply: $reply");
# Process tags for the BEGIN Statement.
if ($tags{context} eq 'begin') {
if ($reply =~ /\{topic=(.+?)\}/i) {
# Set the user's topic.
$self->debug ("Topic set to $1");
$self->{client}->{$user}->{topic} = $1;
$reply =~ s/\{topic=(.+?)\}//ig;
}
while ($reply =~ /<set (.+?)=(.+?)>/i) {
# Set a user variable.
$self->debug ("Set uservar $1 => $2");
$self->{client}->{$user}->{$1} = $2;
$reply =~ s/<set (.+?)=(.+?)>//i;
}
}
else {
# Process more tags if not in BEGIN.
$reply = $self->processTags($user,$msg,$reply,[@stars],[@thatstars],$tags{step});
}
return $reply;
}
sub _findTriggerByInheritence {
my ($self,$topic,$trig,$depth) = @_;
# This sub was called because the user matched a trigger from the
# sorted array, but the trigger doesn't exist under the topic of
# which the user currently belongs. It probably was a trigger
# inherited/included from another topic. This subroutine finds that out,
# recursively, following the inheritence trail.
# Take care to prevent infinite recursion.
if ($depth > $self->{depth}) {
$self->issue("Deep recursion detected while following an inheritence trail (involving topic $topic and trigger $trig)");
return undef;
}
# Inheritence is more important than inclusion: triggers in one topic
# can override those in an inherited topic.
if (exists $self->{lineage}->{$topic}) {
foreach my $inherits (sort { $a cmp $b } keys %{$self->{lineage}->{$topic}}) {
# See if this inherited topic has our trigger.
if (exists $self->{topics}->{$inherits}->{$trig}) {
# Great!
return $self->{topics}->{$inherits}->{$trig};
}
else {
# Check what this topic inherits from.
my $match = $self->_findTriggerByInheritence (
$inherits, $trig, ($depth + 1),
);
if (defined $match) {
# Finally got a match.
return $match;
}
}
}
}
# See if this topic has an "includes".
if (exists $self->{includes}->{$topic}) {
foreach my $includes (sort { $a cmp $b } keys %{$self->{includes}->{$topic}}) {
# See if this included topic has our trigger.
if (exists $self->{topics}->{$includes}->{$trig}) {
# Great!
return $self->{topics}->{$includes}->{$trig};
}
else {
# Check what this topic includes from.
my $match = $self->_findTriggerByInheritence (
$includes, $trig, ($depth + 1),
);
if (defined $match) {
# Finally got a match.
return $match;
}
}
}
}
# Don't know what else we can do.
return undef;
}
sub _reply_regexp {
my ($self,$user,$regexp) = @_;
# If the trigger is simply /^\*$/ (+ *) then the * there needs to
# become (.*?) to match the blank string too.
$regexp =~ s/^\*$/<zerowidthstar>/i;
$regexp =~ s/\*/(.+?)/ig; # Convert * into (.+?)
$regexp =~ s/\#/(\\d+)/ig; # Convert # into ([0-9]+?)
$regexp =~ s/\_/(\\w+)/ig; # Convert _ into ([A-Za-z]+?)
$regexp =~ s/\{weight=\d+\}//ig; # Remove {weight} tags.
$regexp =~ s/<zerowidthstar>/(.*?)/i;
while ($regexp =~ /\[(.+?)\]/i) { # Optionals
my @parts = split(/\|/, $1);
my @new = ();
foreach my $p (@parts) {
$p = '\s*' . $p . '\s*';
push (@new,$p);
}
push (@new,'\s*');
# If this optional had a star or anything in it, e.g. [*],
# make that non-matching.
my $pipes = join("|",@new);
$pipes =~ s/\(\.\+\?\)/(?:.+?)/ig; # (.+?) --> (?:.+?)
$pipes =~ s/\(\\d\+\)/(?:\\d+)/ig; # (\d+) --> (?:\d+)
$pipes =~ s/\(\\w\+\)/(?:\\w+)/ig; # (\w+) --> (?:\w+)
my $rep = "(?:$pipes)";
$regexp =~ s/\s*\[(.+?)\]\s*/$rep/i;
}
# Filter in arrays.
while ($regexp =~ /\@(.+?)\b/) {
my $name = $1;
my $rep = '';
if (exists $self->{arrays}->{$name}) {
$rep = '(?:' . join ("|",@{$self->{arrays}->{$name}}) . ')';
}
$regexp =~ s/\@(.+?)\b/$rep/i;
}
# Filter in bot variables.
while ($regexp =~ /<bot (.+?)>/i) {
my $var = $1;
my $rep = '';
if (exists $self->{bot}->{$var}) {
$rep = $self->{bot}->{$var};
$rep =~ s/[^A-Za-z0-9 ]//ig;
$rep = lc($rep);
}
$regexp =~ s/<bot (.+?)>/$rep/i;
}
# Filter in user variables.
while ($regexp =~ /<get (.+?)>/i) {
my $var = $1;
my $rep = '';
if (exists $self->{client}->{$user}->{$var}) {
$rep = $self->{client}->{$user}->{$var};
$rep =~ s/[^A-Za-z0-9 ]//ig;
$rep = lc($rep);
}
$regexp =~ s/<get (.+?)>/$rep/i;
}
# Filter input tags.
$regexp =~ s/<input>/$self->{client}->{$user}->{__history__}->{input}->[0]/ig;
$regexp =~ s/<reply>/$self->{client}->{$user}->{__history__}->{reply}->[0]/ig;
while ($regexp =~ /<input([0-9])>/i) {
my $index = $1;
my (@arrInput) = @{$self->{client}->{$user}->{__history__}->{input}};
unshift (@arrInput,'');
my $line = $arrInput[$index];
$line = $self->_formatMessage ($line);
$regexp =~ s/<input$index>/$line/ig;
}
while ($regexp =~ /<reply([0-9])>/i) {
my $index = $1;
my (@arrReply) = @{$self->{client}->{$user}->{__history__}->{reply}};
unshift (@arrReply,'');
my $line = $arrReply[$index];
$line = $self->_formatMessage ($line);
$regexp =~ s/<reply$index>/$line/ig;
}
return $regexp;
}
sub processTags {
my ($self,$user,$msg,$reply,$st,$bst,$depth) = @_;
my (@stars) = (@{$st});
my (@botstars) = (@{$bst});
unshift (@stars,"");
unshift (@botstars,"");
if (scalar(@stars) == 1) {
push (@stars,'undefined');
}
if (scalar(@botstars) == 1) {
push (@botstars,'undefined');
}
my (@arrInput) = @{$self->{client}->{$user}->{__history__}->{input}};
my (@arrReply) = @{$self->{client}->{$user}->{__history__}->{reply}};
my $lastInput = $arrInput[0] || 'undefined';
my $lastReply = $arrReply[0] || 'undefined';
unshift(@arrInput,'');
unshift(@arrReply,'');
# Tag Shortcuts.
$reply =~ s/<person>/{person}<star>{\/person}/ig;
$reply =~ s/<\@>/{\@<star>}/ig;
$reply =~ s/<formal>/{formal}<star>{\/formal}/ig;
$reply =~ s/<sentence>/{sentence}<star>{\/sentence}/ig;
$reply =~ s/<uppercase>/{uppercase}<star>{\/uppercase}/ig;
$reply =~ s/<lowercase>/{lowercase}<star>{\/lowercase}/ig;
# Quick tags.
$reply =~ s/\{weight=(\d+)\}//ig; # Remove leftover {weight}s
if (scalar(@stars) > 0) {
$reply =~ s/<star>/$stars[1]/ig if defined $stars[1];
$reply =~ s/<star(\d+)>/(defined $stars[$1] ? $stars[$1] : '')/ieg;
}
if (scalar(@botstars) > 0) {
$reply =~ s/<botstar>/$botstars[1]/ig;
$reply =~ s/<botstar(\d+)>/(defined $botstars[$1] ? $botstars[$1] : '')/ieg;
}
$reply =~ s/<input>/$lastInput/ig;
$reply =~ s/<reply>/$lastReply/ig;
$reply =~ s/<input([1-9])>/$arrInput[$1]/ig;
$reply =~ s/<reply([1-9])>/$arrReply[$1]/ig;
$reply =~ s/<id>/$user/ig;
$reply =~ s/\\s/ /ig;
$reply =~ s/\\n/\n/ig;
$reply =~ s/\\/\\/ig;
$reply =~ s/\\#/#/ig;
while ($reply =~ /\{random\}(.+?)\{\/random\}/i) {
my $rand = $1;
my $output = '';
if ($rand =~ /\|/) {
my @tmp = split(/\|/, $rand);
$output = $tmp [ int(rand(scalar(@tmp))) ];
}
else {
my @tmp = split(/\s+/, $rand);
$output = $tmp [ int(rand(scalar(@tmp))) ];
}
$reply =~ s/\{random\}(.+?)\{\/random\}/$output/i;
}
while ($reply =~ /<bot (.+?)=(.+?)>/i) {
my ($what,$is) = ($1, $2);
$self->{bot}->{$what} = $is;
$reply =~ s/<bot (.+?)=(.+?)>//i;
}
while ($reply =~ /<env (.+?)=(.+?)>/i) {
my ($what,$is) = ($1, $2);
# Reserved?
my $reserved = 0;
foreach my $res (@{$self->{reserved}}) {
if ($res eq $what) {
$reserved = 1;
last;
}
}
if ($reserved) {
$self->{globals}->{$what} = $is;
}
else {
$self->{$what} = $is;
}
$reply =~ s/<env (.+?)=(.+?)>//i;
}
while ($reply =~ /<bot (.+?)>/i) {
my $val = (exists $self->{bot}->{$1} ? $self->{bot}->{$1} : 'undefined');
$reply =~ s/<bot (.+?)>/$val/i;
}
while ($reply =~ /<env (.+?)>/i) {
my $var = $1;
my $val = '';
if (exists $self->{globals}->{$var}) {
$val = $self->{globals}->{$var};
}
else {
my $reserved = 0;
foreach my $res (@{$self->{reserved}}) {
if ($res eq $var) {
$reserved = 1;
}
}
if (not $reserved) {
$val = (exists $self->{$var} ? $self->{$var} : 'undefined');
}
else {
$val = "(reserved)";
}
}
$reply =~ s/<env (.+?)>/$val/i;
}
while ($reply =~ /\{\!(.+?)\}/i) {
# Just stream this back through.
$self->stream ("! $1");
$reply =~ s/\{\!(.+?)\}//i;
}
while ($reply =~ /\{person\}(.+?)\{\/person\}/i) {
my $person = $1;
$person = $self->_personSub ($person);
$reply =~ s/\{person\}(.+?)\{\/person\}/$person/i;
}
while ($reply =~ /\{formal\}(.+?)\{\/formal\}/i) {
my $formal = $1;
$formal = $self->_stringUtil ('formal',$formal);
$reply =~ s/\{formal\}(.+?)\{\/formal\}/$formal/i;
}
while ($reply =~ /\{sentence\}(.+?)\{\/sentence\}/i) {
my $sentence = $1;
$sentence = $self->_stringUtil ('sentence',$sentence);
$reply =~ s/\{sentence\}(.+?)\{\/sentence\}/$sentence/i;
}
while ($reply =~ /\{uppercase\}(.+?)\{\/uppercase\}/i) {
my $upper = $1;
$upper = $self->_stringUtil ('upper',$upper);
$reply =~ s/\{uppercase\}(.+?)\{\/uppercase\}/$upper/i;
}
while ($reply =~ /\{lowercase\}(.+?)\{\/lowercase\}/i) {
my $lower = $1;
$lower = $self->_stringUtil ('lower',$lower);
$reply =~ s/\{lowercase\}(.+?)\{\/lowercase\}/$lower/i;
}
while ($reply =~ /<set (.+?)=(.+?)>/i) {
# Set a user variable.
$self->debug ("Set uservar $1 => $2");
$self->{client}->{$user}->{$1} = $2;
$reply =~ s/<set (.+?)=(.+?)>//i;
}
while ($reply =~ /<(add|sub|mult|div) (.+?)=(.+?)>/i) {
# Mathematic modifiers.
my $mod = lc($1);
my $var = $2;
my $value = $3;
my $output = '';
# Initialize the variable?
if (!exists $self->{client}->{$user}->{$var}) {
$self->{client}->{$user}->{$var} = 0;
}
# Only modify numeric variables.
if ($self->{client}->{$user}->{$var} !~ /^[0-9\-\.]+$/) {
$output = "[ERR: Can't Modify Non-Numeric Variable $var]";
}
elsif ($value =~ /^[^0-9\-\.]$/) {
$output = "[ERR: Math Can't \"$mod\" Non-Numeric Value $value]";
}
else {
# Modify the variable.
if ($mod eq 'add') {
$self->{client}->{$user}->{$var} += $value;
}
elsif ($mod eq 'sub') {
$self->{client}->{$user}->{$var} -= $value;
}
elsif ($mod eq 'mult') {
$self->{client}->{$user}->{$var} *= $value;
}
elsif ($mod eq 'div') {
# Don't divide by zero.
if ($value == 0) {
$output = "[ERR: Can't Divide By Zero]";
}
else {
$self->{client}->{$user}->{$var} /= $value;
}
}
}
$reply =~ s/<(add|sub|mult|div) (.+?)=(.+?)>/$output/i;
}
while ($reply =~ /<get (.+?)>/i) {
my $val = (exists $self->{client}->{$user}->{$1} ? $self->{client}->{$user}->{$1} : 'undefined');
$reply =~ s/<get (.+?)>/$val/i;
}
if ($reply =~ /\{topic=(.+?)\}/i) {
# Set the user's topic.
$self->debug ("Topic set to $1");
$self->{client}->{$user}->{topic} = $1;
$reply =~ s/\{topic=(.+?)\}//ig;
}
while ($reply =~ /\{\@(.+?)\}/i) {
my $at = $1;
$at =~ s/^\s+//ig;
$at =~ s/\s+$//ig;
my $subreply = $self->_getreply ($user,$at,
context => 'normal',
step => ($depth + 1),
);
$reply =~ s/\{\@(.+?)\}/$subreply/i;
}
while ($reply =~ /<call>(.+?)<\/call>/i) {
my ($obj,@args) = split(/\s+/, $1);
my $output = '';
# What language handles this object?
my $lang = exists $self->{objlangs}->{$obj} ? $self->{objlangs}->{$obj} : '';
if (length $lang) {
# Do we handle this?
if (exists $self->{handlers}->{$lang}) {
# Ok.
$output = &{ $self->{handlers}->{$lang} } ($self,"call",$obj,[@args]);
}
else {
$output = '[ERR: No Object Handler]';
}
}
else {
$output = '[ERR: Object Not Found]';
}
$reply =~ s/<call>(.+?)<\/call>/$output/i;
}
return $reply;
}
sub _formatMessage {
my ($self,$string) = @_;
# Lowercase it.
$string = lc($string);
# Run substitutions on it.
foreach my $pattern (@{$self->{sortlist}->{subs}}) {
my $result = $self->{subs}->{$pattern};
$result =~ tr/A-Za-z/N-ZA-Mn-za-m/;
my $qm = quotemeta($pattern);
$string =~ s/^$qm$/<rot13sub>$result<bus31tor>/ig;
$string =~ s/^$qm(\W+)/<rot13sub>$result<bus31tor>$1/ig;
$string =~ s/(\W+)$qm(\W+)/$1<rot13sub>$result<bus31tor>$2/ig;
$string =~ s/(\W+)$qm$/$1<rot13sub>$result<bus31tor>/ig;
}
while ($string =~ /<rot13sub>(.+?)<bus31tor>/i) {
my $rot13 = $1;
$rot13 =~ tr/A-Za-z/N-ZA-Mn-za-m/;
$string =~ s/<rot13sub>(.+?)<bus31tor>/$rot13/i;
}
# Format punctuation.
$string =~ s/[^A-Za-z0-9 ]//g;
$string =~ s/^\s+//g;
$string =~ s/\s+$//g;
return $string;
}
sub _stringUtil {
my ($self,$type,$string) = @_;
if ($type eq 'formal') {
$string =~ s/\b(\w+)\b/\L\u$1\E/ig;
}
elsif ($type eq 'sentence') {
$string =~ s/\b(\w)(.*?)(\.|\?|\!|$)/\u$1\L$2$3\E/ig;
}
elsif ($type eq 'upper') {
$string = uc($string);
}
elsif ($type eq 'lower') {
$string = lc($string);
}
return $string;
}
sub _personSub {
my ($self,$string) = @_;
# Substitute each of the sorted person sub arrays in order,
# using a one-way substitution algorithm (read: base13).
foreach my $pattern (@{$self->{sortlist}->{person}}) {
my $result = $self->{person}->{$pattern};
$result =~ tr/A-Za-z/N-ZA-Mn-za-m/;
my $qm = quotemeta($pattern);
$string =~ s/^$qm$/<rot13sub>$result<bus31tor>/ig;
$string =~ s/^$qm(\W+)/<rot13sub>$result<bus31tor>$1/ig;
$string =~ s/(\W+)$qm(\W+)/$1<rot13sub>$result<bus31tor>$2/ig;
$string =~ s/(\W+)$qm$/$1<rot13sub>$result<bus31tor>/ig;
}
# Now rot13-decode what's left.
while ($string =~ /<rot13sub>(.+?)<bus31tor>/i) {
my $rot13 = $1;
$rot13 =~ tr/A-Za-z/N-ZA-Mn-za-m/;
$string =~ s/<rot13sub>(.+?)<bus31tor>/$rot13/i;
}
return $string;
}
1;
__END__
=head1 RIVESCRIPT
This interpreter tries its best to follow RiveScript standards. Currently it
supports RiveScript 2.0 documents. A current copy of the RiveScript working
draft is included with this package: see L<RiveScript::WD>.
=head1 SEE ALSO
L<RiveScript::WD> - A current snapshot of the Working Draft that
defines the standards of RiveScript.
L<http://www.rivescript.com/> - The official homepage of RiveScript.
=head1 CHANGES
1.26 May 29 2012
- Added EXE_FILES to Makefile.PL so the rivescript utility installs
correctly.
1.24 May 15 2012
- Fixed: having a single-line, multiline comment, e.g. /* ... */
- Fixed: you can use <input> and <reply> in triggers now, instead of only
<input1>-<input9> and <reply1>-<reply9>
- When a trigger consists of nothing but multiple wildcard symbols, sort
the trigger by length, this way you can have '* * * * *' type triggers
still work correctly (each <star> tag would get one word, with the final
<star> collecting the remainder).
- Backported new feature from Python lib: you can now use <bot> and <env>
to SET variables (eg. <bot mood=happy>). The {!...} tag is deprecated.
- New feature: deparse() will return a Perl data structure representing all
of the RiveScript code parsed by the module so far. This way you can build
a user interface for editing replies without requiring a user to edit the
code directly.
- New method: write() will use deparse() to write a RiveScript document using
all of the in-memory triggers/responses/etc.
- Cleaned up the POD documentation, put POD code along side the Perl functions
it documents, removed useless bloat from the docs.
- POD documentation now only shows recent changes. For older changes, see the
"CHANGES" file in the distribution.
- Removed the `rsup` script from the distribution (it upgrades RiveScript 1.x
code to 2.x; there probably isn't any 1.x code out in the wild anyway).
1.22 Sep 22 2011
- Cleaned up the documentation of RiveScript; moved the JavaScript object
example to a separate document in the `docs' directory.
- Obsoleted the `rsdemo` command that used to ship with the distribution. In
its place is `rivescript`, which can also be used non-interactively so that a
third party, non-Perl application could still make use of RiveScript.
- RiveScript.pm is now dual licensed. It uses the GPLv2 for open source
applications as before, but you can contact the author for details if you
want to use RiveScript.pm in a closed source commercial application.
1.20 Jul 30 2009
- Added automatic syntax checking when parsing RiveScript code. Also added
'strict mode' - if true (default), a syntax error is a fatal error. If false,
a syntax error is a warning, and RiveScript aborts processing the file any
further.
- Changed the behavior of "inherits" a bit: a new type has been added called
"includes" which does what the old "inherits" does (mixes the trigger list
of both topics together into the same pool). The new "inherits" option though
causes the trigger list from the source topic to be higher in matching priority
than the trigger list of the inherited topic.
- Moving to a new versioning scheme: development releases will have odd
version numbers, stable (CPAN) versions will have even numbers.
- Fixed the Eliza brain; in many places a <star2> was used when there was only one
star in the trigger. Fixes lots of issues with Eliza.
- Bugfix: recursion depth limits weren't taken into account when the {@} tag
was responsible for a redirection. Fixed.
- Bugfix: there was a problem in the regular expression that counts real words
while sorting triggers, so that triggers with *'s in them weren't sorted
properly and would therefore cause matching issues.
- Bugfix: when the internal _getreply is called because of a recursive
redirection (@, {@}), the %previous tags should be ignored. They weren't.
since "lastreply" is always the same no matter how deeply recursive _getreply
is going, it could result in some infinite recursion in rare cases. Fixed.
- Bugfix: using a reserved name as a global variable wasn't working properly
and would crash RiveScript. Fixed.
1.19 Apr 12 2009
- Added support for defining custom object handlers for non-Perl programming
languages.
- All the methods like setGlobal, setVariable, setUservar, etc. will now
accept undef or "<undef>" as values - this will delete the variables.
- There are no reserved global variable names anymore. Now, if a variable name
would conflict with a reserved name, it is put into a "protected" space
elsewhere in the object. Still take note of which names are reserved though.
1.18 Dec 31 2008
- Added support for topics to inherit their triggers from other topics.
e.g. > topic alpha inherits beta
- Fixed some bugs related to !array with ^continue's, and expanded its
functionality therein.
- Updated the getUservars() function to optionally be able to get just a specific
variable from the user's data. Added getUservar() as a grammatically correct
alias to this new functionality.
- Added the functions freezeUservars() and thawUservars() to back up and
restore a user's variables.
- Added the function lastMatch(), which returns the text of the trigger that
matched the user's last message.
- The # command for RiveScript comments has been deprecated in revision 7 of
the RiveScript Working Draft. The Perl module will now emit warnings each
time the # comments are processed.
- Modified a couple of triggers in the default Eliza brain to improve matching
issues therein.
- +Triggers can contain user <get> tags now.
- Updated the RiveScript Working Draft.
=head1 AUTHOR
Noah Petherbridge, http://www.kirsle.net
=head1 KEYWORDS
bot, chatbot, chatterbot, chatter bot, reply, replies, script, aiml, alpha
=head1 COPYRIGHT AND LICENSE
The Perl RiveScript interpreter is dual licensed as of version 1.22.
For open source applications the module is using the GNU General Public
License. If you'd like to use the RiveScript module in a closed source or
commercial application, contact the author for more information.
RiveScript - Rendering Intelligence Very Easily
Copyright (C) 2011 Noah Petherbridge
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
=cut
|