├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── app ├── pom.xml └── src │ └── main │ └── java │ └── org │ └── aimlang │ └── app │ └── TelegramBot.java ├── bots ├── pom.xml └── src │ └── main │ └── resources │ └── jokebot │ ├── aiml │ ├── jokes.aiml │ └── limericks.aiml │ ├── sets │ └── digit.txt │ ├── skills │ └── math.groovy │ └── system │ └── bot.properties ├── build.gradle ├── core ├── pom.xml └── src │ ├── main │ ├── java │ │ └── org │ │ │ └── aimlang │ │ │ └── core │ │ │ ├── bot │ │ │ ├── Bot.java │ │ │ ├── BotBuilder.java │ │ │ ├── BotConfiguration.java │ │ │ ├── BotImpl.java │ │ │ └── BotInfo.java │ │ │ ├── channels │ │ │ ├── Channel.java │ │ │ ├── ChannelType.java │ │ │ ├── ConsoleChannel.java │ │ │ └── TelegramChannel.java │ │ │ ├── chat │ │ │ ├── Chat.java │ │ │ ├── ChatCommand.java │ │ │ ├── ChatContext.java │ │ │ ├── ChatContextStorage.java │ │ │ ├── ChatContextStorageFactory.java │ │ │ ├── ChatHistory.java │ │ │ ├── ChatMessage.java │ │ │ └── InMemoryChatContextStorage.java │ │ │ ├── consts │ │ │ ├── AimlConst.java │ │ │ ├── AimlTag.java │ │ │ └── WildCard.java │ │ │ ├── core │ │ │ ├── AIMLProcessor.java │ │ │ ├── GraphMaster.java │ │ │ └── Named.java │ │ │ ├── entity │ │ │ ├── AimlCategory.java │ │ │ ├── AimlElement.java │ │ │ ├── AimlMap.java │ │ │ ├── AimlRandom.java │ │ │ ├── AimlSet.java │ │ │ ├── AimlSubstitution.java │ │ │ ├── AimlToken.java │ │ │ ├── AimlTokenType.java │ │ │ └── AimlTopic.java │ │ │ ├── exception │ │ │ ├── AimlExeption.java │ │ │ ├── BotNotInitializedException.java │ │ │ └── ChatNotStartedException.java │ │ │ ├── loaders │ │ │ ├── AimlLoader.java │ │ │ ├── FileLoader.java │ │ │ ├── Loader.java │ │ │ ├── MapLoader.java │ │ │ ├── SetLoader.java │ │ │ ├── SubstitutionLoader.java │ │ │ └── XmlLoader.java │ │ │ └── utils │ │ │ └── AppUtils.java │ └── resources │ │ ├── aiml-2.0.xsd │ │ ├── aiml.info │ │ ├── application.properties │ │ ├── banner.txt │ │ └── logback.xml │ └── test │ └── java │ └── org │ └── aimlang │ └── core │ ├── chat │ └── ChatContextTest.java │ └── core │ └── BotTest.java ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── pom.xml └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | *.jar 3 | *.war 4 | *.ear 5 | hs_err_pid* 6 | .DS_Store 7 | .DS_Store? 8 | ._* 9 | .Spotlight-V100 10 | .Trashes 11 | ehthumbs.db 12 | Thumbs.db 13 | *.ipr 14 | *.iml 15 | *.iws 16 | .gradle 17 | .idea 18 | /build/ 19 | /target/ 20 | **/target/ 21 | /log/ 22 | aiml-bots 23 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | jdk: 3 | - openjdk11 4 | script: 5 | - mvn clean package -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Aiml Java Interpreter 2 | [![Build Status](https://travis-ci.org/AIMLang/aiml-java-interpreter.svg?branch=master)](https://travis-ci.org/AIMLang/aiml-java-interpreter) 3 | [![License: GPL v3](https://img.shields.io/badge/License-GPL%20v3-blue.svg)](http://www.gnu.org/licenses/gpl-3.0) 4 | 5 | AIML 2.0 Interpreter for Java 6 | 7 | It is not contains full implementation of specification, basically it is still pet project for aimlang spec implementation. 8 | So please keep it in mind. 9 | 10 | ## 2. Build 11 | ### 2.1 Using Maven 12 | `mvn clean package` 13 | ## 2. Using Gradle 14 | `gradle clean fatJar` 15 | 16 | ## 3.Run 17 | `java -jar ./target/aiml.jar YourName` 18 | 19 | ## Dependencies 20 | - Lombok (1.18.16) 21 | - Logback (1.2.3) 22 | - Slf4j (1.7.25) 23 | - JUnit (5.1.0) 24 | 25 | ## Contacts 26 | anton@batiaev.com -------------------------------------------------------------------------------- /app/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | org.aimlang 7 | java-interpreter 8 | 1.0.0-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | app 13 | 14 | 15 | 16 | org.aimlang 17 | core 18 | 1.0.0-SNAPSHOT 19 | 20 | 21 | org.aimlang 22 | bots 23 | 1.0.0-SNAPSHOT 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /app/src/main/java/org/aimlang/app/TelegramBot.java: -------------------------------------------------------------------------------- 1 | package org.aimlang.app; 2 | 3 | import org.aimlang.core.channels.ConsoleChannel; 4 | import org.aimlang.core.channels.TelegramChannel; 5 | import org.aimlang.core.consts.AimlConst; 6 | 7 | import static org.aimlang.core.bot.BotBuilder.bot; 8 | import static org.aimlang.core.chat.ChatContextStorageFactory.inMemory; 9 | 10 | /** 11 | * @author batiaev 12 | * @since 30/06/15 13 | */ 14 | public class TelegramBot { 15 | 16 | public static void main(String[] args) { 17 | var botName = AimlConst.default_bot_name; 18 | // var provider = new TelegramChannel(args[0], args[1]); 19 | var provider = new ConsoleChannel(botName); 20 | bot(botName) 21 | .withContext(inMemory()) 22 | .fromSource(AimlConst.getRootPath()) 23 | .wakeUp() 24 | .buildChat(provider) 25 | .start(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /bots/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | org.aimlang 7 | java-interpreter 8 | 1.0.0-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | bots 13 | 14 | 15 | -------------------------------------------------------------------------------- /bots/src/main/resources/jokebot/aiml/jokes.aiml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | JOKE 6 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /bots/src/main/resources/jokebot/aiml/limericks.aiml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | LIMERICK 6 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /bots/src/main/resources/jokebot/sets/digit.txt: -------------------------------------------------------------------------------- 1 | 0 2 | 1 3 | 2 4 | 3 5 | 4 6 | 5 7 | 6 8 | 7 9 | 8 10 | 9 11 | -------------------------------------------------------------------------------- /bots/src/main/resources/jokebot/skills/math.groovy: -------------------------------------------------------------------------------- 1 | print "test" 2 | 3 | public class math { 4 | public int sum(int x, int y) { 5 | return x + y; 6 | } 7 | } -------------------------------------------------------------------------------- /bots/src/main/resources/jokebot/system/bot.properties: -------------------------------------------------------------------------------- 1 | firstname = Joke 2 | lastname = Bot 3 | language = en_US 4 | email = jokebot@aimlang.org 5 | gender = male 6 | version = 0.1 7 | birthplace = Russia, Moscow 8 | job = joke assistant 9 | species = robot 10 | birthday = 4 June 11 | birthdate = June 4, 2015 12 | sign = Gemini 13 | religion = Atheist 14 | botmaster = Anton Batiaev -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'java' 2 | apply plugin: 'idea' 3 | apply plugin: 'com.github.johnrengelman.shadow' 4 | 5 | idea { 6 | project { 7 | jdkName = '11' 8 | languageLevel = '11' 9 | vcs = 'Git' 10 | } 11 | } 12 | 13 | group = 'org.aimlang' 14 | version = '1.0-SNAPSHOT' 15 | 16 | ext { 17 | junitVersion = '5.1.0' 18 | logbackVersion = '1.2.3' 19 | lombokVersion = '1.18.16' 20 | slf4jVersion = '1.7.25' 21 | } 22 | 23 | sourceCompatibility = 11 24 | targetCompatibility = 11 25 | 26 | tasks.withType(JavaCompile) { 27 | options.encoding = 'UTF-8' 28 | } 29 | 30 | jar { 31 | manifest.attributes("Main-Class": "org.aimlang.core.App") 32 | manifest.attributes("Manifest-Version": 1.0) 33 | } 34 | 35 | task fatJar(type: Jar) { 36 | manifest.attributes("Main-Class": "org.aimlang.core.App") 37 | manifest.attributes("Manifest-Version": 1.0) 38 | baseName = 'aiml' 39 | version = '' 40 | from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } } 41 | with jar 42 | } 43 | repositories { 44 | mavenLocal() 45 | mavenCentral() 46 | } 47 | project.buildDir = 'target' 48 | buildscript { 49 | repositories { 50 | jcenter() 51 | } 52 | dependencies { 53 | classpath 'com.github.jengelman.gradle.plugins:shadow:2.0.1' 54 | } 55 | } 56 | 57 | dependencies { 58 | compile "ch.qos.logback:logback-classic:$logbackVersion" 59 | compile "org.projectlombok:lombok:$lombokVersion" 60 | testCompile "org.junit.jupiter:junit-jupiter-engine:$junitVersion" 61 | } -------------------------------------------------------------------------------- /core/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | org.aimlang 7 | java-interpreter 8 | 1.0.0-SNAPSHOT 9 | 10 | 4.0.0 11 | 12 | core 13 | 14 | 15 | org.telegram 16 | telegrambots 17 | ${telegrambots.version} 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /core/src/main/java/org/aimlang/core/bot/Bot.java: -------------------------------------------------------------------------------- 1 | package org.aimlang.core.bot; 2 | 3 | import org.aimlang.core.channels.Channel; 4 | import org.aimlang.core.chat.Chat; 5 | import org.aimlang.core.chat.ChatContext; 6 | import org.aimlang.core.chat.ChatContextStorage; 7 | import org.aimlang.core.core.Named; 8 | 9 | /** 10 | * Bot 11 | * 12 | * @author anton 13 | * @since 18/04/17 14 | */ 15 | public interface Bot extends Named { 16 | String getRespond(String phrase); 17 | 18 | Chat buildChat(Channel channel); 19 | 20 | ChatContextStorage getChatContextStorage(); 21 | 22 | void setChatContext(ChatContext context); 23 | 24 | boolean wakeUp(); 25 | } 26 | -------------------------------------------------------------------------------- /core/src/main/java/org/aimlang/core/bot/BotBuilder.java: -------------------------------------------------------------------------------- 1 | package org.aimlang.core.bot; 2 | 3 | import org.aimlang.core.chat.ChatContextStorage; 4 | import org.aimlang.core.consts.AimlConst; 5 | 6 | import java.io.File; 7 | 8 | import static org.aimlang.core.chat.ChatContextStorageFactory.inMemory; 9 | 10 | /** 11 | * Bot builder 12 | * 13 | * @author batiaev 14 | * @since 19/10/16 15 | */ 16 | public class BotBuilder { 17 | private final String botName; 18 | private ChatContextStorage context = inMemory(); 19 | private String rootPath = AimlConst.getRootPath(); 20 | 21 | private BotBuilder(String botName) { 22 | this.botName = botName; 23 | } 24 | 25 | public static BotBuilder bot() { 26 | return new BotBuilder(AimlConst.default_bot_name); 27 | } 28 | 29 | public static BotBuilder bot(String botName) { 30 | return new BotBuilder(botName); 31 | } 32 | 33 | public BotBuilder withContext(ChatContextStorage context) { 34 | this.context = context; 35 | return this; 36 | } 37 | 38 | public BotBuilder fromSource(String rootPath) { 39 | this.rootPath = rootPath; 40 | return this; 41 | } 42 | 43 | public BotImpl wakeUp() { 44 | var botPath = getBotPath(botName); 45 | var bot = new BotImpl(botName, botPath, context); 46 | if (!bot.wakeUp()) { 47 | throw new IllegalStateException( 48 | "Bot couldn't wake up, please check that '" + botPath + "' contains all required aiml files"); 49 | } 50 | return bot; 51 | } 52 | 53 | private String getBotPath(String name) { 54 | return rootPath + File.separator + name + File.separator; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /core/src/main/java/org/aimlang/core/bot/BotConfiguration.java: -------------------------------------------------------------------------------- 1 | package org.aimlang.core.bot; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | 5 | import java.io.File; 6 | import java.io.FileInputStream; 7 | import java.io.IOException; 8 | import java.util.Properties; 9 | 10 | /** 11 | * Bot configuration 12 | * 13 | * @author batiaev 14 | * @since 19/10/16 15 | */ 16 | @Slf4j 17 | public class BotConfiguration implements BotInfo { 18 | private static final String PROPERTIES = "bot.properties"; 19 | 20 | private final String rootDir; 21 | private final Properties prop; 22 | 23 | public BotConfiguration(String rootDir) { 24 | this.rootDir = rootDir; 25 | this.prop = loadBotInfo(getSystemConfig()); 26 | } 27 | 28 | @Override 29 | public String getFirstname() { 30 | return getValue("firstname"); 31 | } 32 | 33 | @Override 34 | public String getLastname() { 35 | return getValue("lastname"); 36 | } 37 | 38 | @Override 39 | public String getLanguage() { 40 | return getValue("language"); 41 | } 42 | 43 | @Override 44 | public String getEmail() { 45 | return getValue("email"); 46 | } 47 | 48 | @Override 49 | public String getGender() { 50 | return getValue("gender"); 51 | } 52 | 53 | @Override 54 | public String getVersion() { 55 | return getValue("version"); 56 | } 57 | 58 | @Override 59 | public String getBirthplace() { 60 | return getValue("birthplace"); 61 | } 62 | 63 | @Override 64 | public String getJob() { 65 | return getValue("job"); 66 | } 67 | 68 | @Override 69 | public String getSpecies() { 70 | return getValue("species"); 71 | } 72 | 73 | @Override 74 | public String getBirthday() { 75 | return getValue("birthday"); 76 | } 77 | 78 | @Override 79 | public String getBirthdate() { 80 | return getValue("birthdate"); 81 | } 82 | 83 | @Override 84 | public String getSign() { 85 | return getValue("sign"); 86 | } 87 | 88 | @Override 89 | public String getReligion() { 90 | return getValue("religion"); 91 | } 92 | 93 | @Override 94 | public String getBotmaster() { 95 | return getValue("botmaster"); 96 | } 97 | 98 | @Override 99 | public String getValue(String key) { 100 | return prop == null ? "" : prop.getProperty(key, ""); 101 | } 102 | 103 | private Properties loadBotInfo(String path) { 104 | log.debug("Load system config: " + path); 105 | Properties prop = new Properties(); 106 | if (!new File(path).exists()) return prop; 107 | 108 | try (FileInputStream in = new FileInputStream(path)) { 109 | prop.load(in); 110 | } catch (IOException e) { 111 | e.printStackTrace(); 112 | } 113 | return prop; 114 | } 115 | 116 | private String getSystemConfig() { 117 | return rootDir + "system" + File.separator + PROPERTIES; 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /core/src/main/java/org/aimlang/core/bot/BotImpl.java: -------------------------------------------------------------------------------- 1 | package org.aimlang.core.bot; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.aimlang.core.channels.ChannelType; 5 | import org.aimlang.core.channels.Channel; 6 | import org.aimlang.core.chat.Chat; 7 | import org.aimlang.core.chat.ChatContext; 8 | import org.aimlang.core.chat.ChatContextStorage; 9 | import org.aimlang.core.consts.AimlConst; 10 | import org.aimlang.core.core.GraphMaster; 11 | import org.aimlang.core.entity.AimlCategory; 12 | import org.aimlang.core.entity.AimlMap; 13 | import org.aimlang.core.entity.AimlSet; 14 | import org.aimlang.core.entity.AimlSubstitution; 15 | import org.aimlang.core.loaders.AimlLoader; 16 | import org.aimlang.core.loaders.MapLoader; 17 | import org.aimlang.core.loaders.SetLoader; 18 | import org.aimlang.core.loaders.SubstitutionLoader; 19 | 20 | import java.io.File; 21 | import java.nio.file.Files; 22 | import java.nio.file.Paths; 23 | import java.util.ArrayList; 24 | import java.util.Collections; 25 | import java.util.List; 26 | import java.util.Map; 27 | import java.util.regex.Pattern; 28 | 29 | /** 30 | * Class representing the AIML bot 31 | * 32 | * @author batiaev 33 | */ 34 | @Slf4j 35 | public class BotImpl implements Bot { 36 | 37 | private final GraphMaster brain; 38 | private final String rootDir; 39 | private final ChatContextStorage chatContextStorage; 40 | private ChatContext chatContext; 41 | private String name; 42 | 43 | public BotImpl(String name, String rootDir, ChatContextStorage chatContextStorage) { 44 | this.name = name; 45 | this.rootDir = rootDir; 46 | this.chatContextStorage = chatContextStorage; 47 | this.chatContext = this.chatContextStorage.getContext(name, ChannelType.CONSOLE); 48 | var aimlSets = loadSets(); 49 | var aimlMaps = loadMaps(); 50 | var aimlCategories = loadAiml(); 51 | brain = new GraphMaster(preprocess(aimlCategories, aimlSets), aimlSets, aimlMaps, loadSubstitutions(), 52 | new BotConfiguration(rootDir)); 53 | } 54 | 55 | private List preprocess(List categories, Map aimlSets) { 56 | var processed = new ArrayList(); 57 | for (AimlCategory aimlCategory : categories) { 58 | var pattern = aimlCategory.getPattern(); 59 | var regexp = Pattern.compile("(.+?)"); 60 | var matcher = regexp.matcher(pattern); 61 | if (matcher.find()) { 62 | var setName = matcher.group(1); 63 | var setValues = aimlSets.get(setName + ".txt"); 64 | if (setValues != null) { 65 | for (String s : setValues) { 66 | var first = matcher.replaceFirst(s); 67 | var cloned = aimlCategory.clone(); 68 | cloned.setPattern(first); 69 | processed.add(cloned); 70 | } 71 | } 72 | } else { 73 | processed.add(aimlCategory); 74 | } 75 | } 76 | return processed; 77 | } 78 | 79 | @Override 80 | public ChatContextStorage getChatContextStorage() { 81 | return chatContextStorage; 82 | } 83 | 84 | @Override 85 | public void setChatContext(ChatContext chatContext) { 86 | this.chatContext = chatContext; 87 | } 88 | 89 | @Override 90 | public String getName() { 91 | return name; 92 | } 93 | 94 | @Override 95 | public boolean wakeUp() { 96 | return validate(getRootDir()) && validate(getAimlFolder()); 97 | } 98 | 99 | @Override 100 | public String getRespond(String phrase) { 101 | return multisentenceRespond(phrase, chatContext); 102 | } 103 | 104 | @Override 105 | public Chat buildChat(Channel channel) { 106 | setChatContext(getChatContextStorage().getContext(null, channel.getType())); 107 | return new Chat(this, channel); 108 | } 109 | 110 | public void setName(String name) { 111 | this.name = name; 112 | } 113 | 114 | public String getBrainStats() { 115 | return brain.getStat(); 116 | } 117 | 118 | public String multisentenceRespond(String request, ChatContext state) { 119 | var sentences = brain.sentenceSplit(request); 120 | var response = new StringBuilder(); 121 | for (String sentence : sentences) 122 | response.append(" ").append(respond(sentence, state)); 123 | return (response.length() == 0) 124 | ? AimlConst.error_bot_response 125 | : response.toString().trim(); 126 | } 127 | 128 | public String respond(final String request, ChatContext state) { 129 | var stars = new ArrayList(); 130 | var pattern = brain.match(request, state.topic(), state.that(), stars); 131 | return brain.respond(stars, pattern, state.topic(), state.that(), state.getPredicates()); 132 | } 133 | 134 | private List loadAiml() { 135 | var loader = new AimlLoader(); 136 | return loader.loadFiles(getAimlFolder()); 137 | } 138 | 139 | private Map loadSets() { 140 | var sets = new File(getSetsFolder()); 141 | if (!sets.exists()) { 142 | log.warn("Sets not found!"); 143 | return Collections.emptyMap(); 144 | } 145 | var files = sets.listFiles(); 146 | if (files == null || files.length == 0) 147 | return Collections.emptyMap(); 148 | 149 | var loader = new SetLoader(); 150 | 151 | var data = loader.loadAll(files); 152 | int count = data.keySet().stream().mapToInt(s -> data.get(s).size()).sum(); 153 | 154 | log.info("Loaded {} set records from {} files.", count, files.length); 155 | return data; 156 | } 157 | 158 | private Map loadMaps() { 159 | var maps = new File(getMapsFolder()); 160 | if (!maps.exists()) { 161 | log.warn("Maps not found!"); 162 | return Collections.emptyMap(); 163 | } 164 | var files = maps.listFiles(); 165 | if (files == null || files.length == 0) return Collections.emptyMap(); 166 | 167 | var loader = new MapLoader<>(); 168 | 169 | var data = loader.loadAll(files); 170 | int count = data.keySet() 171 | .stream() 172 | .mapToInt(s -> data.get(s).size()) 173 | .sum(); 174 | 175 | log.info("Loaded " + count + " map records from " + files.length + " files."); 176 | return data; 177 | } 178 | 179 | private Map loadSubstitutions() { 180 | var maps = new File(getSubstitutionsFolder()); 181 | if (!maps.exists()) { 182 | log.warn("Maps not found!"); 183 | return Collections.emptyMap(); 184 | } 185 | var files = maps.listFiles(); 186 | if (files == null || files.length == 0) 187 | return Collections.emptyMap(); 188 | 189 | var loader = new SubstitutionLoader(); 190 | 191 | var data = loader.loadAll(files); 192 | int count = data.keySet().stream().mapToInt(s -> data.get(s).size()).sum(); 193 | 194 | log.info("Loaded " + count + " substitutions from " + files.length + " files."); 195 | return data; 196 | } 197 | 198 | private boolean validate(String folder) { 199 | if (folder == null || folder.isEmpty()) 200 | return false; 201 | var botsFolder = Paths.get(folder); 202 | if (Files.notExists(botsFolder)) { 203 | log.warn("BotImpl folder " + folder + " not found!"); 204 | return false; 205 | } 206 | return true; 207 | } 208 | 209 | private String getRootDir() { 210 | return rootDir; 211 | } 212 | 213 | private String getAimlFolder() { 214 | return getRootDir() + "aiml"; 215 | } 216 | 217 | private String getSubstitutionsFolder() { 218 | return getRootDir() + "substitutions"; 219 | } 220 | 221 | private String getSetsFolder() { 222 | return getRootDir() + "sets"; 223 | } 224 | 225 | private String getMapsFolder() { 226 | return getRootDir() + "maps"; 227 | } 228 | 229 | private String getSkillsFolder() { 230 | return getRootDir() + "skills"; 231 | } 232 | } 233 | -------------------------------------------------------------------------------- /core/src/main/java/org/aimlang/core/bot/BotInfo.java: -------------------------------------------------------------------------------- 1 | package org.aimlang.core.bot; 2 | 3 | /** 4 | * Bot info 5 | * 6 | * @author batiaev 7 | * @since 7/6/15 8 | */ 9 | public interface BotInfo { 10 | 11 | String getFirstname(); 12 | 13 | String getLastname(); 14 | 15 | String getLanguage(); 16 | 17 | String getEmail(); 18 | 19 | String getGender(); 20 | 21 | String getVersion(); 22 | 23 | String getBirthplace(); 24 | 25 | String getJob(); 26 | 27 | String getSpecies(); 28 | 29 | String getBirthday(); 30 | 31 | String getBirthdate(); 32 | 33 | String getSign(); 34 | 35 | String getReligion(); 36 | 37 | String getBotmaster(); 38 | 39 | String getValue(String param); 40 | } 41 | -------------------------------------------------------------------------------- /core/src/main/java/org/aimlang/core/channels/Channel.java: -------------------------------------------------------------------------------- 1 | package org.aimlang.core.channels; 2 | 3 | import org.aimlang.core.chat.ChatMessage; 4 | 5 | import java.util.function.Consumer; 6 | 7 | /** 8 | * Communication channel 9 | * 10 | * @author batiaev 11 | * @since 18/10/16 12 | */ 13 | public interface Channel { 14 | void subscribe(Consumer messageHandler); 15 | 16 | void write(ChatMessage message); 17 | 18 | ChannelType getType(); 19 | 20 | default void close() {} 21 | } 22 | -------------------------------------------------------------------------------- /core/src/main/java/org/aimlang/core/channels/ChannelType.java: -------------------------------------------------------------------------------- 1 | package org.aimlang.core.channels; 2 | 3 | /** 4 | * ChannelType 5 | * 6 | * @author anton 7 | * @since 19/04/17 8 | */ 9 | public enum ChannelType { 10 | CONSOLE, 11 | VK, 12 | FACEBOOK, 13 | REST, 14 | WEBSOCKET, 15 | TELEGRAM 16 | } 17 | -------------------------------------------------------------------------------- /core/src/main/java/org/aimlang/core/channels/ConsoleChannel.java: -------------------------------------------------------------------------------- 1 | package org.aimlang.core.channels; 2 | 3 | import org.aimlang.core.bot.Bot; 4 | import org.aimlang.core.chat.ChatMessage; 5 | 6 | import java.io.BufferedReader; 7 | import java.io.IOException; 8 | import java.io.InputStreamReader; 9 | import java.util.function.Consumer; 10 | 11 | import static org.aimlang.core.channels.ChannelType.CONSOLE; 12 | 13 | /** 14 | * Console provider 15 | * 16 | * @author batiaev 17 | * @since 18/10/16 18 | */ 19 | public class ConsoleChannel implements Channel { 20 | 21 | private final BufferedReader reader; 22 | private final String botName; 23 | 24 | public static ConsoleChannel chatWith(Bot bot) { 25 | return new ConsoleChannel(bot.getName()); 26 | } 27 | 28 | public ConsoleChannel(String botName) { 29 | this.botName = botName; 30 | reader = new BufferedReader(new InputStreamReader(System.in)); 31 | } 32 | 33 | @Override 34 | public void subscribe(Consumer messageHandler) { 35 | while (true) { 36 | String textLine = null; 37 | try { 38 | textLine = reader.readLine(); 39 | } catch (IOException e) { 40 | e.printStackTrace(); 41 | } 42 | messageHandler.accept(new ChatMessage("console", "default", textLine)); 43 | } 44 | } 45 | 46 | @Override 47 | public void write(ChatMessage message) { 48 | System.out.println(botName + ": " + message.getMessage()); 49 | } 50 | 51 | @Override 52 | public ChannelType getType() { 53 | return CONSOLE; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /core/src/main/java/org/aimlang/core/channels/TelegramChannel.java: -------------------------------------------------------------------------------- 1 | package org.aimlang.core.channels; 2 | 3 | import org.aimlang.core.chat.ChatMessage; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | import org.telegram.telegrambots.bots.TelegramLongPollingBot; 7 | import org.telegram.telegrambots.meta.api.methods.send.SendMessage; 8 | import org.telegram.telegrambots.meta.api.objects.Update; 9 | import org.telegram.telegrambots.meta.exceptions.TelegramApiException; 10 | 11 | import java.util.function.Consumer; 12 | 13 | public class TelegramChannel extends TelegramLongPollingBot implements Channel { 14 | private static final Logger log = LoggerFactory.getLogger(TelegramChannel.class); 15 | private final String username; 16 | private final String token; 17 | private Consumer messageConsumer; 18 | 19 | public TelegramChannel(String username, String token) { 20 | this.username = username; 21 | this.token = token; 22 | } 23 | 24 | @Override 25 | public void subscribe(Consumer messageHandler) { 26 | this.messageConsumer = messageHandler; 27 | } 28 | 29 | @Override 30 | public void close() { 31 | this.onClosing(); 32 | } 33 | 34 | @Override 35 | public void onUpdateReceived(Update update) { 36 | if (update.hasMessage() && update.getMessage().hasText()) { 37 | String chatId = update.getMessage().getChatId().toString(); 38 | messageConsumer.accept(new ChatMessage( 39 | update.getMessage().getFrom().getId().toString(), 40 | chatId, 41 | update.getMessage().getText() 42 | ) 43 | ); 44 | } 45 | } 46 | 47 | @Override 48 | public void write(ChatMessage message) { 49 | var sendMessage = SendMessage.builder() 50 | .chatId(message.getChatId()) 51 | .text(message.getMessage()) 52 | .build(); 53 | try { 54 | this.sendApiMethod(sendMessage); 55 | } catch (TelegramApiException e) { 56 | log.error("Exception when sending message: ", e); 57 | } 58 | } 59 | 60 | @Override 61 | public ChannelType getType() { 62 | return ChannelType.TELEGRAM; 63 | } 64 | 65 | @Override 66 | public String getBotUsername() { 67 | return username; 68 | } 69 | 70 | @Override 71 | public String getBotToken() { 72 | return token; 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /core/src/main/java/org/aimlang/core/chat/Chat.java: -------------------------------------------------------------------------------- 1 | package org.aimlang.core.chat; 2 | 3 | import org.aimlang.core.bot.BotImpl; 4 | import org.aimlang.core.channels.Channel; 5 | import org.aimlang.core.consts.AimlConst; 6 | 7 | import java.util.Optional; 8 | 9 | import static java.lang.String.format; 10 | 11 | /** 12 | * Chat 13 | * 14 | * @author batiaev 15 | * @since 6/18/15 16 | */ 17 | public class Chat { 18 | private final static String DEFAULT_NICKNAME = "Human"; 19 | private final BotImpl bot; 20 | private final Channel channel; 21 | private ChatContext state; 22 | private boolean started; 23 | 24 | public Chat(BotImpl bot, Channel channel) { 25 | this.bot = bot; 26 | this.channel = channel; 27 | } 28 | 29 | public void start() { 30 | start(DEFAULT_NICKNAME); 31 | } 32 | 33 | public void start(String nickname) { 34 | String chatId = ""; 35 | channel.write(new ChatMessage(nickname, chatId, "Welcome to chat with " + bot.getName() + ".\n" + nickname + ": ")); 36 | started = true; 37 | state = new ChatContext(nickname); 38 | channel.subscribe(this::handle); 39 | } 40 | 41 | private void handle(ChatMessage message) { 42 | if (started) 43 | process(message) 44 | .ifPresent(channel::write); 45 | } 46 | 47 | private Optional process(ChatMessage msg) { 48 | var textLine = msg.getMessage(); 49 | var message = textLine == null || textLine.isEmpty() ? AimlConst.null_input : textLine.trim(); 50 | msg = msg.response(message); 51 | if (message.startsWith("/")) { 52 | return parseCommand(msg); 53 | } else { 54 | String response = bot.multisentenceRespond(message, state); 55 | state.newState(message, response); 56 | return Optional.of(new ChatMessage(msg.getUserId(), msg.getChatId(), response)); 57 | } 58 | } 59 | 60 | public void stop() { 61 | started = false; 62 | channel.close(); 63 | } 64 | 65 | private Optional parseCommand(final ChatMessage msg) { 66 | var command = msg.getMessage(); 67 | switch (command) { 68 | case ChatCommand.exit: 69 | case ChatCommand.quit: 70 | stop(); 71 | System.exit(0); 72 | case ChatCommand.stat: 73 | return Optional.of(msg.response(bot.getBrainStats())); 74 | case ChatCommand.reload: 75 | bot.wakeUp(); 76 | return Optional.of(msg.response(format("Bot %s reloaded", bot.getName()))); 77 | case "/connect russian": 78 | case "/c russian": 79 | bot.setName("russian"); 80 | bot.wakeUp(); 81 | return Optional.of(msg.response(format("Connected to bot %s", bot.getName()))); 82 | case "/connect alice2": 83 | case "/c alice2": 84 | bot.setName("alice2"); 85 | bot.wakeUp(); 86 | return Optional.of(msg.response(format("Connected to bot %s", bot.getName()))); 87 | case "/debug on": 88 | case "/debug true": 89 | AimlConst.debug = true; 90 | return Optional.empty(); 91 | case "/debug off": 92 | case "/debug false": 93 | AimlConst.debug = false; 94 | return Optional.empty(); 95 | default: 96 | var response = bot.multisentenceRespond(command, state); 97 | state.newState(command, response); 98 | return Optional.of(msg.response(response)); 99 | } 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /core/src/main/java/org/aimlang/core/chat/ChatCommand.java: -------------------------------------------------------------------------------- 1 | package org.aimlang.core.chat; 2 | 3 | /** 4 | * ChatCommand 5 | * 6 | * @author batiaev 7 | * @since 25/06/15 8 | */ 9 | public class ChatCommand { 10 | public static final String exit = "/exit"; 11 | public static final String quit = "/quit"; 12 | public static final String q = "\\q"; 13 | public static final String stat = "/stat"; 14 | public static final String reload = "/reload"; 15 | public static final String connect = "/connect"; 16 | public static final String debug = "/debug"; 17 | } 18 | -------------------------------------------------------------------------------- /core/src/main/java/org/aimlang/core/chat/ChatContext.java: -------------------------------------------------------------------------------- 1 | package org.aimlang.core.chat; 2 | 3 | import org.aimlang.core.consts.AimlConst; 4 | 5 | import java.util.HashMap; 6 | import java.util.Map; 7 | import java.util.UUID; 8 | 9 | /** 10 | * Chat context 11 | * 12 | * @author batiaev 13 | * @author Marco Piovesan 14 | * Added predicates on 29/08/16 15 | * @since 18/06/15 16 | */ 17 | public class ChatContext { 18 | private final UUID chatUid; 19 | private final ChatHistory history; 20 | private String request = ""; 21 | private String topic = AimlConst.default_topic; 22 | private String that = AimlConst.default_that; 23 | private final Map predicates = new HashMap<>(); 24 | 25 | public ChatContext(String userName) { 26 | chatUid = UUID.randomUUID(); 27 | history = new ChatHistory(chatUid, userName); 28 | } 29 | 30 | public void newState(String request, String respond) { 31 | this.request = request; 32 | this.that = respond; 33 | history.addRequest(this.request); 34 | history.addRespond(this.that); 35 | } 36 | 37 | public String topic() { 38 | if (predicates.containsKey("topic")) { 39 | setTopic(predicates.get("topic")); 40 | } 41 | return topic; 42 | } 43 | 44 | public String that() { 45 | return that; 46 | } 47 | 48 | public String request() { 49 | return request; 50 | } 51 | 52 | public String respond() { 53 | return that; 54 | } 55 | 56 | public void setTopic(String topic) { 57 | this.topic = topic; 58 | } 59 | 60 | public void setRespond(String respond) { 61 | this.that = respond; 62 | } 63 | 64 | public void setRequest(String request) { 65 | this.request = request; 66 | } 67 | 68 | public Map getPredicates() { 69 | return predicates; 70 | } 71 | 72 | } 73 | -------------------------------------------------------------------------------- /core/src/main/java/org/aimlang/core/chat/ChatContextStorage.java: -------------------------------------------------------------------------------- 1 | package org.aimlang.core.chat; 2 | 3 | import org.aimlang.core.channels.ChannelType; 4 | 5 | /** 6 | * ChatContextStorage 7 | * 8 | * @author anton 9 | * @since 19/04/17 10 | */ 11 | public interface ChatContextStorage { 12 | ChatContext getContext(String userId, ChannelType channelType); 13 | } 14 | -------------------------------------------------------------------------------- /core/src/main/java/org/aimlang/core/chat/ChatContextStorageFactory.java: -------------------------------------------------------------------------------- 1 | package org.aimlang.core.chat; 2 | 3 | public class ChatContextStorageFactory { 4 | public static InMemoryChatContextStorage inMemory() { 5 | return new InMemoryChatContextStorage(); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /core/src/main/java/org/aimlang/core/chat/ChatHistory.java: -------------------------------------------------------------------------------- 1 | package org.aimlang.core.chat; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Date; 5 | import java.util.UUID; 6 | 7 | /** 8 | * ChatHistory 9 | * 10 | * @author batiaev 11 | * @since 18/06/15 12 | */ 13 | public class ChatHistory { 14 | private final UUID chatUid; 15 | private final Date startDate; 16 | private final String userName; 17 | private ArrayList requests; 18 | private ArrayList responds; 19 | 20 | public ChatHistory(UUID chatUid, String user) { 21 | this.chatUid = chatUid; 22 | startDate = new Date(); 23 | userName = user; 24 | requests = new ArrayList<>(); 25 | responds = new ArrayList<>(); 26 | } 27 | 28 | public boolean addRequest(String record) { 29 | return requests.add(record); 30 | } 31 | 32 | public boolean addRespond(String record) { 33 | return responds.add(record); 34 | } 35 | 36 | public String getRequest(int index) { 37 | return requests.get(index); 38 | } 39 | 40 | public String getRespond(int index) { 41 | return responds.get(index); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /core/src/main/java/org/aimlang/core/chat/ChatMessage.java: -------------------------------------------------------------------------------- 1 | package org.aimlang.core.chat; 2 | 3 | import java.util.Objects; 4 | 5 | public class ChatMessage { 6 | private final String userId; 7 | private final String chatId; 8 | private final String message; 9 | 10 | public ChatMessage(String userId, String chatId, String message) { 11 | this.userId = userId; 12 | this.chatId = chatId; 13 | this.message = message; 14 | } 15 | 16 | public ChatMessage response(String message) { 17 | return new ChatMessage(userId, chatId, message); 18 | } 19 | 20 | public String getUserId() { 21 | return userId; 22 | } 23 | 24 | public String getChatId() { 25 | return chatId; 26 | } 27 | 28 | public String getMessage() { 29 | return message; 30 | } 31 | 32 | @Override 33 | public String toString() { 34 | return "Message{" + 35 | "userId='" + userId + '\'' + 36 | ", chatId='" + chatId + '\'' + 37 | ", message='" + message + '\'' + 38 | '}'; 39 | } 40 | 41 | @Override 42 | public boolean equals(Object o) { 43 | if (this == o) return true; 44 | if (o == null || getClass() != o.getClass()) return false; 45 | ChatMessage message1 = (ChatMessage) o; 46 | return Objects.equals(userId, message1.userId) && Objects.equals(chatId, message1.chatId) && Objects.equals(message, message1.message); 47 | } 48 | 49 | @Override 50 | public int hashCode() { 51 | return Objects.hash(userId, chatId, message); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /core/src/main/java/org/aimlang/core/chat/InMemoryChatContextStorage.java: -------------------------------------------------------------------------------- 1 | package org.aimlang.core.chat; 2 | 3 | import org.aimlang.core.channels.ChannelType; 4 | 5 | import java.util.HashMap; 6 | import java.util.Map; 7 | 8 | /** 9 | * InMemoryChatContextStorage 10 | * 11 | * @author batiaev 12 | * @since 24/05/17 13 | */ 14 | public class InMemoryChatContextStorage implements ChatContextStorage { 15 | private final Map> contexts; 16 | 17 | public InMemoryChatContextStorage() { 18 | contexts = new HashMap<>(); 19 | } 20 | 21 | @Override 22 | public ChatContext getContext(String userId, ChannelType channelType) { 23 | var userContexts = contexts.get(userId); 24 | if (userContexts == null || userContexts.isEmpty()) { 25 | var context = new ChatContext(userId); 26 | userContexts = new HashMap<>(); 27 | userContexts.put(channelType, context); 28 | contexts.put(userId, userContexts); 29 | return context; 30 | } else { 31 | return userContexts.computeIfAbsent(channelType, k -> new ChatContext(userId)); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /core/src/main/java/org/aimlang/core/consts/AimlConst.java: -------------------------------------------------------------------------------- 1 | package org.aimlang.core.consts; 2 | 3 | import java.io.File; 4 | import java.nio.file.Path; 5 | 6 | /** 7 | * Aiml constants 8 | * 9 | * @author batiaev 10 | * @since 6/17/15 11 | */ 12 | public class AimlConst { 13 | 14 | public static final String AIML_FILE_SUFFIX = ".aiml"; 15 | 16 | private static String root_path = Path.of("./bots/src/main/resources".replace("/",File.separator)) 17 | .toAbsolutePath().toString(); 18 | public static final String default_bot_name = "jokebot"; 19 | public static final String error_bot_response = "Something is wrong with my brain."; 20 | public static final String default_bot_response = "I have no answer for that."; 21 | public static final String default_topic = "unknown"; 22 | public static final String default_that = "unknown"; 23 | public static final String null_input = "#NORESP"; 24 | public static boolean debug = false; 25 | 26 | public static String getRootPath() { 27 | return root_path; 28 | } 29 | 30 | public static void setRootPath(String newRootPath) { 31 | root_path = newRootPath; 32 | } 33 | } -------------------------------------------------------------------------------- /core/src/main/java/org/aimlang/core/consts/AimlTag.java: -------------------------------------------------------------------------------- 1 | package org.aimlang.core.consts; 2 | 3 | /** 4 | * Aiml tags 5 | * 6 | * @author batiaev 7 | * @since 13/06/15 8 | */ 9 | public class AimlTag { 10 | 11 | public static final String xml = ""; 12 | public static final String aiml = "aiml"; 13 | public static final String category = "category"; 14 | public static final String topic = "topic"; 15 | public static final String pattern = "pattern"; 16 | public static final String template = "template"; 17 | public static final String random = "random"; 18 | public static final String li = "li"; 19 | public static final String star = "star"; 20 | public static final String index = "index"; 21 | public static final String bot = "bot"; 22 | public static final String set = "set"; 23 | public static final String get = "get"; 24 | public static final String think = "think"; 25 | public static final String srai = "srai"; 26 | public static final String sraix = "sraix"; 27 | public static final String map = "map"; 28 | public static final String that = "that"; 29 | public static final String condition = "condition"; 30 | public static final String loop = "loop"; 31 | public static final String learn = "learn"; 32 | public static final String learnf = "learnf"; 33 | public static final String eval = "eval"; 34 | public static final String text = "#text"; 35 | public static final String comment = "#comment"; 36 | //Attributes 37 | public static final String name = "name"; 38 | 39 | public static String getCloseTag(String name) { 40 | return ""; 41 | } 42 | 43 | public static String getOpenTag(String name) { 44 | return "<" + name + ">"; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /core/src/main/java/org/aimlang/core/consts/WildCard.java: -------------------------------------------------------------------------------- 1 | package org.aimlang.core.consts; 2 | 3 | /** 4 | * Wildcards 5 | * 6 | * @author batiaev 7 | * @since 19/06/15 8 | */ 9 | public enum WildCard { 10 | ZeroMore("^"), 11 | OneMore("*"), 12 | ZeroMorePriority("#"), 13 | OneMorePriority("_"); 14 | 15 | private final String sumbol; 16 | 17 | WildCard(String sumbol) { 18 | this.sumbol = sumbol; 19 | } 20 | 21 | public String get() { 22 | return sumbol; 23 | } 24 | } -------------------------------------------------------------------------------- /core/src/main/java/org/aimlang/core/core/AIMLProcessor.java: -------------------------------------------------------------------------------- 1 | package org.aimlang.core.core; 2 | 3 | import org.aimlang.core.bot.BotInfo; 4 | import org.aimlang.core.consts.AimlConst; 5 | import org.aimlang.core.consts.AimlTag; 6 | import org.aimlang.core.entity.AimlCategory; 7 | import org.aimlang.core.utils.AppUtils; 8 | import org.aimlang.core.consts.WildCard; 9 | import org.slf4j.Logger; 10 | import org.w3c.dom.Element; 11 | import org.w3c.dom.NamedNodeMap; 12 | import org.w3c.dom.Node; 13 | import org.w3c.dom.NodeList; 14 | 15 | import java.util.*; 16 | import java.util.regex.Matcher; 17 | import java.util.regex.Pattern; 18 | 19 | import static org.aimlang.core.consts.AimlTag.*; 20 | import static org.slf4j.LoggerFactory.getLogger; 21 | 22 | /** 23 | * The core AIML parser and interpreter. 24 | * Implements the AIML 2.0 specification as described in 25 | * AIML 2.0 Working Draft document 26 | * https://docs.google.com/document/d/1wNT25hJRyupcG51aO89UcQEiG-HkXRXusukADpFnDs4/pub 27 | * https://playground.pandorabots.com/en/tutorial/ 28 | * http://blog.pandorabots.com/aiaas-aiml-2-0-support/ 29 | * http://www.alicebot.org/documentation/aiml101.html 30 | * http://itc.ua/articles/kvest_tyuringa_7667/ 31 | * http://www.eblong.com/zarf/markov/chan.c 32 | * 33 | * @author anton 34 | * @author Marco 35 | * @since 19/10/16 36 | */ 37 | public class AIMLProcessor { 38 | private static final Logger log = getLogger(AIMLProcessor.class); 39 | 40 | private final List categories; 41 | private final Map> topics; 42 | private Map predicates; 43 | private BotInfo botInfo; 44 | 45 | public AIMLProcessor(List categories, BotInfo botInfo) { 46 | this.predicates = new HashMap<>(); 47 | this.topics = convert(categories); 48 | this.categories = categories; 49 | this.botInfo = botInfo; 50 | } 51 | 52 | private Map> convert(List categories) { 53 | var topics = new HashMap>(); 54 | for (AimlCategory aimlCategory : categories) { 55 | Map topicCategories; 56 | if (topics.containsKey(aimlCategory.getTopic())) { 57 | topicCategories = topics.get(aimlCategory.getTopic()); 58 | } else { 59 | topicCategories = new HashMap<>(); 60 | topics.put(aimlCategory.getTopic(), topicCategories); 61 | } 62 | topicCategories.put(aimlCategory.getPattern(), aimlCategory); 63 | } 64 | return topics; 65 | } 66 | 67 | public String match(final String input, String topic, String that, List stars) { 68 | var request = input.toUpperCase(); 69 | var patterns = patterns(topic); 70 | if (!AimlConst.default_topic.equals(topic)) 71 | patterns.addAll(patterns(AimlConst.default_topic)); 72 | 73 | var result = WildCard.OneMore.get(); 74 | for (String pattern : patterns) { 75 | if (WildCard.OneMore.get().equals(pattern) 76 | || WildCard.OneMorePriority.get().equals(pattern) 77 | || WildCard.ZeroMore.get().equals(pattern) 78 | || WildCard.ZeroMorePriority.get().equals(pattern)) 79 | result = pattern; 80 | else if (isMatching(request, pattern, stars)) 81 | return pattern; 82 | } 83 | return result; 84 | } 85 | 86 | public String template(List stars, String pattern, String topic, String that, Map predicates) { 87 | this.predicates = predicates; 88 | var category = category(topic, pattern); 89 | if (category == null) 90 | category = category(AimlConst.default_topic, WildCard.OneMore.get()); 91 | return category == null ? AimlConst.default_bot_response : getTemplateValue(category.getTemplate(), stars); 92 | } 93 | 94 | public int getTopicCount() { 95 | return topics.size(); 96 | } 97 | 98 | public int getCategoriesCount() { 99 | return categories.size(); 100 | } 101 | 102 | private boolean isMatching(String input, String pattern, List stars) { 103 | input = input.trim(); 104 | var regex = pattern.trim(); 105 | regex = regex.replace(WildCard.OneMorePriority.get(), "(.+)"); 106 | regex = regex.replace(WildCard.OneMore.get(), "(.+)"); 107 | regex = regex.replace(WildCard.ZeroMorePriority.get(), "(.*)"); 108 | regex = regex.replace(WildCard.ZeroMore.get(), "(.*)"); 109 | 110 | var p = Pattern.compile(regex); 111 | var m = p.matcher(input); 112 | if (m.matches()) { 113 | for (int i = 0; i <= m.groupCount(); i++) { 114 | if (i > 0) //skip first group because that is contain full input 115 | stars.add(m.group(i).toLowerCase()); 116 | } 117 | return true; 118 | } 119 | return false; 120 | } 121 | 122 | private String getTemplateValue(Node node, List stars) { 123 | var result = new StringBuilder(); 124 | var childNodes = node.getChildNodes(); 125 | for (int i = 0; i < childNodes.getLength(); ++i) { 126 | result.append(recurseParse(childNodes.item(i), stars)); 127 | } 128 | return (result.length() == 0) ? AimlConst.default_bot_response : result.toString(); 129 | } 130 | 131 | private String recurseParse(Node node, List stars) { 132 | node.normalize(); 133 | var nodeName = node.getNodeName(); 134 | switch (nodeName) { 135 | case text: 136 | return textParse(node); 137 | case template: 138 | return getTemplateValue(node, stars); 139 | case random: 140 | return randomParse(node); 141 | case srai: 142 | return sraiParse(node, stars); 143 | case set: 144 | setParse(node, stars); 145 | return "";//FIXME? 146 | case bot: 147 | return botInfoParse(node); 148 | case star: 149 | return starParse(node, stars); 150 | case think: 151 | getTemplateValue(node, stars); 152 | return ""; 153 | } 154 | return ""; 155 | } 156 | 157 | private String starParse(Node node, List stars) { 158 | if (stars.isEmpty()) return ""; 159 | if (node.hasAttributes()) { 160 | Element element = (Element) node; 161 | try { 162 | int index = Integer.parseInt(element.getAttribute("index")) - 1; 163 | if (stars.size() > index) 164 | return stars.get(index); 165 | } catch (Exception e) { 166 | log.error("Invalid index format {}: {}", element.getAttribute("index"), e.getLocalizedMessage()); 167 | } 168 | } else if (node.hasChildNodes()) { 169 | var childNodes = node.getChildNodes(); 170 | if (childNodes.getLength() == 1) { 171 | var item = childNodes.item(0); 172 | if (index.equals(item.getNodeName())) { 173 | String sIndex = item.getNodeValue(); 174 | try { 175 | int index = Integer.parseInt(sIndex) - 1; 176 | if (stars.size() > index) 177 | return stars.get(index); 178 | } catch (Exception e) { 179 | log.error("Invalid index format {}: {}", sIndex, e.getLocalizedMessage()); 180 | } 181 | } 182 | } 183 | } 184 | return stars.get(0); 185 | } 186 | 187 | private String botInfoParse(Node node) { 188 | var param = node.getAttributes().getNamedItem("name").getNodeValue(); 189 | return botInfo.getValue(param); 190 | } 191 | 192 | private String textParse(Node node) { 193 | return node.getNodeValue().replaceAll("(\r\n|\n\r|\r|\n)", "").replaceAll(" ", " "); 194 | } 195 | 196 | private void setParse(Node node, List stars) { 197 | var attributes = node.getAttributes(); 198 | if (attributes.getLength() > 0) { 199 | var node1 = attributes.getNamedItem("getName"); 200 | if (node1 == null) return; 201 | var key = node1.getNodeValue(); 202 | var value = getTemplateValue(node, stars); 203 | predicates.put(key, value); 204 | } 205 | } 206 | 207 | private String sraiParse(Node node, List stars) { 208 | var category = category(AimlConst.default_topic, AppUtils.node2String(node)); 209 | return category != null ? getTemplateValue(category.getTemplate(), stars) : AimlConst.error_bot_response; 210 | } 211 | 212 | private String randomParse(Node node) { 213 | var values = new ArrayList(); 214 | var childNodes = node.getChildNodes(); 215 | for (int i = 0; i < childNodes.getLength(); ++i) { 216 | if (childNodes.item(i).getNodeName().equals(AimlTag.li)) 217 | values.add(AppUtils.node2String(childNodes.item(i))); 218 | } 219 | 220 | return AppUtils.getRandom(values); 221 | } 222 | 223 | private Set patterns(String topic) { 224 | if (topics.containsKey(topic)) { 225 | return topics.get(topic).keySet(); 226 | } else { 227 | topics.put(topic, new HashMap<>()); 228 | return Collections.emptySet(); 229 | } 230 | } 231 | 232 | private AimlCategory category(String topic, String pattern) { 233 | return topics.get(topic).get(pattern); 234 | } 235 | } -------------------------------------------------------------------------------- /core/src/main/java/org/aimlang/core/core/GraphMaster.java: -------------------------------------------------------------------------------- 1 | package org.aimlang.core.core; 2 | 3 | import org.aimlang.core.bot.BotInfo; 4 | import org.aimlang.core.entity.AimlCategory; 5 | import org.aimlang.core.entity.AimlMap; 6 | import org.aimlang.core.entity.AimlSet; 7 | import org.aimlang.core.entity.AimlSubstitution; 8 | 9 | import java.util.List; 10 | import java.util.Map; 11 | 12 | /** 13 | * The AIML Pattern matching algorithm and data structure. 14 | * Brain of bot. 15 | * 16 | * @author anton 17 | * @author Marco 18 | * Predicates are passed to AIMLProcessor 19 | */ 20 | public class GraphMaster { 21 | private final Map sets; 22 | private final Map maps; 23 | private final Map substitutions; 24 | private final AIMLProcessor processor; 25 | 26 | public GraphMaster(List categories, Map sets, Map maps, 27 | Map substitutions, BotInfo botInfo) { 28 | this.sets = sets; 29 | this.maps = maps; 30 | this.substitutions = substitutions; 31 | this.processor = new AIMLProcessor(categories, botInfo); 32 | } 33 | 34 | public String getStat() { 35 | return "Brain contain " 36 | + processor.getTopicCount() + " topics, " 37 | + processor.getCategoriesCount() + " categories, " 38 | + sets.size() + " sets, " 39 | + maps.size() + " maps, " 40 | + substitutions.size() + " substitutions."; 41 | } 42 | 43 | /** 44 | * Split an input into an array of sentences based on sentence-splitting characters. 45 | * 46 | * @param line input text 47 | * @return array of sentences 48 | */ 49 | public String[] sentenceSplit(String line) { 50 | line = line.replace("。", ".") 51 | .replace("?", "?") 52 | .replace("!", "!") 53 | .replaceAll("(\r\n|\n\r|\r|\n)", " "); 54 | var result = line.split("[.!?]"); 55 | for (int i = 0; i < result.length; i++) 56 | result[i] = result[i].trim(); 57 | return result; 58 | } 59 | 60 | public String respond(List stars, String pattern, String topic, String that, Map predicates) { 61 | return processor.template(stars, pattern, topic, that, predicates); 62 | } 63 | 64 | public String match(String request, String topic, String that, List stars) { 65 | return processor.match(request, topic, that, stars); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /core/src/main/java/org/aimlang/core/core/Named.java: -------------------------------------------------------------------------------- 1 | package org.aimlang.core.core; 2 | 3 | /** 4 | * Named 5 | * 6 | * @author anton 7 | * @since 19/10/16 8 | */ 9 | public interface Named { 10 | String getName(); 11 | } 12 | -------------------------------------------------------------------------------- /core/src/main/java/org/aimlang/core/entity/AimlCategory.java: -------------------------------------------------------------------------------- 1 | package org.aimlang.core.entity; 2 | 3 | import org.aimlang.core.consts.AimlTag; 4 | import org.w3c.dom.Node; 5 | 6 | import java.util.ArrayList; 7 | import java.util.List; 8 | import java.util.Objects; 9 | 10 | /** 11 | * Aiml category 12 | * 13 | * @author anton 14 | * @since 21/06/15 15 | */ 16 | public class AimlCategory implements AimlElement { 17 | private String topic = ""; 18 | private String pattern = ""; 19 | private Node template = null; 20 | private List templateData = new ArrayList<>(); 21 | private String that = ""; 22 | 23 | @Override 24 | public String getType() { 25 | return AimlTag.category; 26 | } 27 | 28 | public String getTopic() { 29 | return topic; 30 | } 31 | 32 | public String getPattern() { 33 | return pattern; 34 | } 35 | 36 | public Node getTemplate() { 37 | return template; 38 | } 39 | 40 | public List getTemplateData() { 41 | return templateData; 42 | } 43 | 44 | public String getThat() { 45 | return that; 46 | } 47 | 48 | public void setTopic(String topic) { 49 | this.topic = topic; 50 | } 51 | 52 | public void setPattern(String pattern) { 53 | this.pattern = pattern; 54 | } 55 | 56 | public void setTemplate(Node template) { 57 | this.template = template; 58 | } 59 | 60 | public void setTemplateData(List templateData) { 61 | this.templateData = templateData; 62 | } 63 | 64 | public void setThat(String that) { 65 | this.that = that; 66 | } 67 | 68 | public boolean equals(Object o) { 69 | if (o == this) { 70 | return true; 71 | } else if (!(o instanceof AimlCategory)) { 72 | return false; 73 | } else { 74 | AimlCategory other = (AimlCategory) o; 75 | return Objects.equals(topic, other.getTopic()) 76 | && Objects.equals(pattern, other.getPattern()) 77 | && Objects.equals(template, other.getTemplate()) 78 | && Objects.equals(that, other.getThat()); 79 | } 80 | } 81 | 82 | @Override 83 | public AimlCategory clone() { 84 | AimlCategory category = new AimlCategory(); 85 | category.setTopic(topic); 86 | category.setPattern(pattern); 87 | category.setTemplate(template); 88 | category.setTemplateData(templateData); 89 | category.setThat(that); 90 | return category; 91 | } 92 | 93 | public int hashCode() { 94 | int result = 1; 95 | result = 31 * result + (topic == null ? 0 : topic.hashCode()); 96 | result = 31 * result + (pattern == null ? 0 : pattern.hashCode()); 97 | result = 31 * result + (template == null ? 0 : template.hashCode()); 98 | result = 31 * result + (that == null ? 0 : that.hashCode()); 99 | return result; 100 | } 101 | 102 | public String toString() { 103 | return "AimlCategory(topic=" + topic + ", pattern=" + pattern + ", template=" + template + ", that=" + that + ")"; 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /core/src/main/java/org/aimlang/core/entity/AimlElement.java: -------------------------------------------------------------------------------- 1 | package org.aimlang.core.entity; 2 | 3 | /** 4 | * Abstract aiml element 5 | * 6 | * @author anton 7 | * @since 21/10/16 8 | */ 9 | public interface AimlElement extends Cloneable { 10 | String getType(); 11 | } 12 | -------------------------------------------------------------------------------- /core/src/main/java/org/aimlang/core/entity/AimlMap.java: -------------------------------------------------------------------------------- 1 | package org.aimlang.core.entity; 2 | 3 | import org.aimlang.core.core.Named; 4 | 5 | import java.util.HashMap; 6 | import java.util.Map; 7 | 8 | import static org.aimlang.core.consts.AimlTag.map; 9 | 10 | /** 11 | * Implements AIML Map 12 | * A map is a function from one string set to another. 13 | * Elements of the domain are called keys and elements of the range are called values. 14 | * 15 | * @author anton 16 | * @since 19/10/16 17 | */ 18 | public class AimlMap extends HashMap implements Named, AimlElement { 19 | protected final String name; 20 | 21 | public AimlMap(String name, Map data) { 22 | super(data); 23 | this.name = name; 24 | } 25 | 26 | @Override 27 | public String getName() { 28 | return name; 29 | } 30 | 31 | @Override 32 | public String getType() { 33 | return map; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /core/src/main/java/org/aimlang/core/entity/AimlRandom.java: -------------------------------------------------------------------------------- 1 | package org.aimlang.core.entity; 2 | 3 | import org.aimlang.core.consts.AimlTag; 4 | import org.aimlang.core.utils.AppUtils; 5 | 6 | import java.util.List; 7 | 8 | /** 9 | * Aiml random tag 10 | * 11 | * @author anton 12 | * @since 21/10/16 13 | */ 14 | public class AimlRandom implements AimlElement { 15 | private final List options; 16 | 17 | public AimlRandom(List options) { 18 | this.options = options; 19 | } 20 | 21 | @Override 22 | public String getType() { 23 | return AimlTag.random; 24 | } 25 | 26 | public String getValue() { 27 | return AppUtils.getRandom(options); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /core/src/main/java/org/aimlang/core/entity/AimlSet.java: -------------------------------------------------------------------------------- 1 | package org.aimlang.core.entity; 2 | 3 | import org.aimlang.core.consts.AimlTag; 4 | import org.aimlang.core.core.Named; 5 | 6 | import java.util.HashSet; 7 | import java.util.Set; 8 | 9 | /** 10 | * Implements AIML Sets 11 | * 12 | * @author anton 13 | * @since 19/10/16 14 | */ 15 | public class AimlSet extends HashSet implements Named, AimlElement { 16 | private final String name; 17 | 18 | public AimlSet(String name, Set data) { 19 | super(data); 20 | this.name = name; 21 | } 22 | 23 | @Override 24 | public String getName() { 25 | return name; 26 | } 27 | 28 | @Override 29 | public String getType() { 30 | return AimlTag.set; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /core/src/main/java/org/aimlang/core/entity/AimlSubstitution.java: -------------------------------------------------------------------------------- 1 | package org.aimlang.core.entity; 2 | 3 | import java.util.Map; 4 | 5 | /** 6 | * Implements AIML Map 7 | * 8 | * A map is a function from one string set to another. 9 | * Elements of the domain are called keys and elements of the range are called values. 10 | * 11 | * @author anton 12 | * @since 19/10/16 13 | */ 14 | public class AimlSubstitution extends AimlMap { 15 | 16 | public AimlSubstitution(String name, Map data) { 17 | super(name, data); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /core/src/main/java/org/aimlang/core/entity/AimlToken.java: -------------------------------------------------------------------------------- 1 | package org.aimlang.core.entity; 2 | 3 | /** 4 | * AimlToken 5 | * 6 | * @author anton 7 | * @since 07/06/17 8 | */ 9 | public class AimlToken { 10 | private String value; 11 | } 12 | -------------------------------------------------------------------------------- /core/src/main/java/org/aimlang/core/entity/AimlTokenType.java: -------------------------------------------------------------------------------- 1 | package org.aimlang.core.entity; 2 | 3 | /** 4 | * AimlTokenType 5 | * 6 | * @author anton 7 | * @since 07/06/17 8 | */ 9 | public enum AimlTokenType { 10 | TEMPLATE("template"), 11 | PATTERN("pattern"), 12 | TOPIC("topic"), 13 | WORD("word"); 14 | 15 | private String code; 16 | 17 | AimlTokenType(String code) { 18 | this.code = code; 19 | } 20 | 21 | public String getCode() { 22 | return code; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /core/src/main/java/org/aimlang/core/entity/AimlTopic.java: -------------------------------------------------------------------------------- 1 | package org.aimlang.core.entity; 2 | 3 | import org.aimlang.core.consts.AimlTag; 4 | 5 | import java.util.List; 6 | 7 | /** 8 | * Aiml Topic 9 | * 10 | * @author anton 11 | * @since 21/10/16 12 | */ 13 | public class AimlTopic implements AimlElement { 14 | private List categories; 15 | private String name; 16 | 17 | @Override 18 | public String getType() { 19 | return AimlTag.topic; 20 | } 21 | 22 | public List getCategories() { 23 | return categories; 24 | } 25 | 26 | public void setCategories(List categories) { 27 | this.categories = categories; 28 | } 29 | 30 | public String getName() { 31 | return name; 32 | } 33 | 34 | public void setName(String name) { 35 | this.name = name; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /core/src/main/java/org/aimlang/core/exception/AimlExeption.java: -------------------------------------------------------------------------------- 1 | package org.aimlang.core.exception; 2 | 3 | /** 4 | * AimlExeption 5 | * 6 | * @author anton 7 | * @since 19/04/17 8 | */ 9 | public class AimlExeption extends Exception { 10 | public AimlExeption(String s) { 11 | super(s); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /core/src/main/java/org/aimlang/core/exception/BotNotInitializedException.java: -------------------------------------------------------------------------------- 1 | package org.aimlang.core.exception; 2 | 3 | /** 4 | * BotNotInitializedException 5 | * 6 | * @author anton 7 | * @since 19/04/17 8 | */ 9 | public class BotNotInitializedException extends AimlExeption { 10 | public BotNotInitializedException(String s) { 11 | super(s); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /core/src/main/java/org/aimlang/core/exception/ChatNotStartedException.java: -------------------------------------------------------------------------------- 1 | package org.aimlang.core.exception; 2 | 3 | /** 4 | * ChatNotStartedException 5 | * 6 | * @author anton 7 | * @since 19/04/17 8 | */ 9 | public class ChatNotStartedException extends AimlExeption { 10 | public ChatNotStartedException(String s) { 11 | super(s); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /core/src/main/java/org/aimlang/core/loaders/AimlLoader.java: -------------------------------------------------------------------------------- 1 | package org.aimlang.core.loaders; 2 | 3 | import org.aimlang.core.consts.AimlConst; 4 | import org.aimlang.core.consts.AimlTag; 5 | import org.aimlang.core.entity.AimlCategory; 6 | import org.slf4j.Logger; 7 | import org.w3c.dom.Element; 8 | import org.w3c.dom.Node; 9 | import org.w3c.dom.NodeList; 10 | 11 | import java.io.File; 12 | import java.util.ArrayList; 13 | import java.util.Collections; 14 | import java.util.List; 15 | 16 | import static org.aimlang.core.utils.AppUtils.node2String; 17 | import static org.slf4j.LoggerFactory.getLogger; 18 | 19 | /** 20 | * Aiml loader 21 | * 22 | * @author anton 23 | * @since 21/06/15 24 | */ 25 | public class AimlLoader { 26 | private static final Logger log = getLogger(AimlLoader.class); 27 | 28 | private final XmlLoader loader; 29 | 30 | public AimlLoader() { 31 | this.loader = new XmlLoader(); 32 | } 33 | 34 | /** 35 | * Loading all aiml files from folder 36 | * 37 | * @param aimlDir folder contain all aiml files 38 | * @return list of loaded categories 39 | */ 40 | public List loadFiles(String aimlDir) { 41 | var categories = new ArrayList(); 42 | var aimls = new File(aimlDir); 43 | var files = aimls.listFiles(); 44 | if (files == null || files.length == 0) { 45 | log.warn("Not files in folder {} ", aimlDir); 46 | return categories; 47 | } 48 | int countNotAimlFiles = 0; 49 | for (File file : files) { 50 | if (file.getName().endsWith(AimlConst.AIML_FILE_SUFFIX)) 51 | categories.addAll(loadFile(file)); 52 | else 53 | ++countNotAimlFiles; 54 | } 55 | if (countNotAimlFiles != 0) 56 | log.warn("Founded {} not aiml files in folder {}", countNotAimlFiles, aimlDir); 57 | log.info("Loaded {} categories", categories.size()); 58 | return categories; 59 | } 60 | 61 | /** 62 | * Loading single aiml file 63 | * 64 | * @param aimlFile aiml file 65 | */ 66 | private List loadFile(File aimlFile) { 67 | var aimlRoot = loader.load(aimlFile); 68 | if (aimlRoot == null) 69 | return Collections.emptyList(); 70 | 71 | if (!aimlRoot.getNodeName().equals(AimlTag.aiml)) { 72 | log.warn(aimlFile.getName() + " is not AIML file"); 73 | return Collections.emptyList(); 74 | } 75 | var aimlVersion = aimlRoot.getAttribute("version"); 76 | log.debug("Load aiml " + aimlFile.getName() + (aimlVersion.isEmpty() ? "" : " [v." + aimlVersion + "]")); 77 | 78 | return aimlParser(aimlRoot.getChildNodes()); 79 | } 80 | 81 | private List aimlParser(NodeList nodes) { 82 | var categories = new ArrayList(); 83 | for (int i = 0; i < nodes.getLength(); ++i) { 84 | var node = nodes.item(i); 85 | 86 | var nodeName = node.getNodeName(); 87 | switch (nodeName) { 88 | case AimlTag.text: 89 | case AimlTag.comment: 90 | break; 91 | case AimlTag.topic: 92 | categories.addAll(parseTopic(node)); 93 | break; 94 | case AimlTag.category: 95 | if (!categories.add(parseCategory(node))) 96 | log.debug(node2String(node)); 97 | break; 98 | default: 99 | log.warn("Wrong structure: tag contain " + nodeName + " tag"); 100 | } 101 | } 102 | return categories; 103 | } 104 | 105 | private List parseTopic(Node node) { 106 | var categories = new ArrayList(); 107 | var childNodes = node.getChildNodes(); 108 | for (int i = 0; i < childNodes.getLength(); ++i) { 109 | var childNodeName = childNodes.item(i).getNodeName(); 110 | switch (childNodeName) { 111 | case AimlTag.text: 112 | case AimlTag.comment: 113 | break; 114 | case AimlTag.category: 115 | categories.add(parseCategory(childNodes.item(i), getAttribute(node, AimlTag.name))); 116 | break; 117 | default: 118 | log.warn("Wrong structure: tag contain " + childNodeName + " tag"); 119 | } 120 | } 121 | return categories; 122 | } 123 | 124 | private String getAttribute(Node node, String attributeName) { 125 | return node.getAttributes() 126 | .getNamedItem(attributeName) 127 | .getNodeValue(); 128 | } 129 | 130 | private AimlCategory parseCategory(Node node) { 131 | return parseCategory(node, AimlConst.default_topic); 132 | } 133 | 134 | private AimlCategory parseCategory(Node node, String topic) { 135 | var category = new AimlCategory(); 136 | category.setTopic(topic); 137 | var childNodes = node.getChildNodes(); 138 | for (int i = 0; i < childNodes.getLength(); ++i) { 139 | var childNode = childNodes.item(i); 140 | childNode.normalize(); 141 | var childNodeName = childNode.getNodeName(); 142 | switch (childNodeName) { 143 | case AimlTag.text: 144 | case AimlTag.comment: 145 | break; 146 | case AimlTag.pattern: 147 | category.setPattern(node2String(childNode)); 148 | break; 149 | case AimlTag.template: 150 | category.setTemplate(childNode); 151 | break; 152 | case AimlTag.topic: 153 | category.setTopic(node2String(childNode)); 154 | break; 155 | case AimlTag.that: 156 | category.setThat(node2String(childNode)); 157 | break; 158 | default: 159 | log.warn("Wrong structure: tag contain " + childNodeName + " tag"); 160 | } 161 | } 162 | return category; 163 | } 164 | } 165 | -------------------------------------------------------------------------------- /core/src/main/java/org/aimlang/core/loaders/FileLoader.java: -------------------------------------------------------------------------------- 1 | package org.aimlang.core.loaders; 2 | 3 | import java.io.File; 4 | import java.util.Map; 5 | 6 | /** 7 | * File loader 8 | * 9 | * @param type of result data 10 | * @author anton 11 | * @since 19/10/16 12 | */ 13 | public interface FileLoader extends Loader { 14 | T load(File file); 15 | 16 | Map loadAll(File... files); 17 | } 18 | -------------------------------------------------------------------------------- /core/src/main/java/org/aimlang/core/loaders/Loader.java: -------------------------------------------------------------------------------- 1 | package org.aimlang.core.loaders; 2 | 3 | import java.util.Map; 4 | 5 | /** 6 | * Abstract interface for any types of loader specified by two types: type of source and type of results 7 | * 8 | * @param source type of data 9 | * @param result type of data 10 | * @author anton 11 | * @since 25/10/16 12 | */ 13 | public interface Loader { 14 | /** 15 | * @param source of data 16 | * @return data from ${source} 17 | */ 18 | R load(S source); 19 | 20 | /** 21 | * Load from collection of sources 22 | * 23 | * @param sources of data 24 | * @return map with sources names as keys and result data as values 25 | */ 26 | Map loadAll(S... sources); 27 | } 28 | -------------------------------------------------------------------------------- /core/src/main/java/org/aimlang/core/loaders/MapLoader.java: -------------------------------------------------------------------------------- 1 | package org.aimlang.core.loaders; 2 | 3 | import org.aimlang.core.entity.AimlMap; 4 | import org.slf4j.Logger; 5 | 6 | import java.io.File; 7 | import java.io.IOException; 8 | import java.nio.file.Files; 9 | import java.util.HashMap; 10 | import java.util.Map; 11 | import java.util.stream.Stream; 12 | 13 | import static org.slf4j.LoggerFactory.getLogger; 14 | 15 | /** 16 | * Map loader 17 | * 18 | * @author antonF 19 | * @since 19/10/16 20 | */ 21 | public class MapLoader implements FileLoader { 22 | private static final Logger log = getLogger(MapLoader.class); 23 | 24 | @Override 25 | public T load(File file) { 26 | 27 | if (file == null) { 28 | log.error("File is null"); 29 | return null; 30 | } 31 | if (!file.exists()) { 32 | log.error("File {} is not exist", file.getAbsolutePath()); 33 | return null; 34 | } 35 | 36 | var data = new AimlMap(file.getName(), loadFile(file)); 37 | 38 | log.info("Loaded {} records from {}", data.size(), file.getName()); 39 | return (T) data; 40 | } 41 | 42 | @Override 43 | public Map loadAll(File... files) { 44 | var data = new HashMap(); 45 | for (File file : files) 46 | data.put(file.getName(), load(file)); 47 | log.info("Loaded {} files", data.size()); 48 | return data; 49 | } 50 | 51 | protected Map loadFile(File file) { 52 | var data = new HashMap(); 53 | try (Stream stream = Files.lines(file.toPath())) { 54 | stream.forEach(s -> parseRow(data, s)); 55 | } catch (IOException e) { 56 | e.printStackTrace(); 57 | } 58 | return data; 59 | } 60 | 61 | protected void parseRow(final Map data, final String row) { 62 | var splitStr = row.toUpperCase().trim().split(":"); 63 | if (splitStr.length == 2) 64 | data.put(splitStr[0], splitStr[1]); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /core/src/main/java/org/aimlang/core/loaders/SetLoader.java: -------------------------------------------------------------------------------- 1 | package org.aimlang.core.loaders; 2 | 3 | import org.aimlang.core.entity.AimlSet; 4 | import org.slf4j.Logger; 5 | 6 | import java.io.File; 7 | import java.io.IOException; 8 | import java.nio.file.Files; 9 | import java.util.Collections; 10 | import java.util.HashMap; 11 | import java.util.Map; 12 | import java.util.Set; 13 | import java.util.stream.Collectors; 14 | import java.util.stream.Stream; 15 | 16 | import static org.slf4j.LoggerFactory.getLogger; 17 | 18 | /** 19 | * Set loader 20 | * 21 | * @author anton 22 | * @since 19/10/16 23 | */ 24 | public class SetLoader implements FileLoader { 25 | private static final Logger log = getLogger(SetLoader.class); 26 | 27 | @Override 28 | public AimlSet load(File file) { 29 | 30 | if (file == null) { 31 | log.error("File is null"); 32 | return null; 33 | } 34 | if (!file.exists()) { 35 | log.error("File {} is not exist", file.getAbsolutePath()); 36 | return null; 37 | } 38 | 39 | final AimlSet data = new AimlSet(file.getName(), loadFile(file)); 40 | 41 | log.info("Loaded {} records from {}", data.size(), file.getName()); 42 | return data; 43 | } 44 | 45 | @Override 46 | public Map loadAll(File... files) { 47 | var data = new HashMap(); 48 | for (File file : files) 49 | data.put(file.getName(), load(file)); 50 | log.info("Loaded {} files", data.size()); 51 | return data; 52 | } 53 | 54 | private Set loadFile(File file) { 55 | try (Stream stream = Files.lines(file.toPath())) { 56 | return stream.map(s -> s.toUpperCase().trim()).collect(Collectors.toSet()); 57 | } catch (IOException e) { 58 | e.printStackTrace(); 59 | } 60 | return Collections.emptySet(); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /core/src/main/java/org/aimlang/core/loaders/SubstitutionLoader.java: -------------------------------------------------------------------------------- 1 | package org.aimlang.core.loaders; 2 | 3 | import org.aimlang.core.entity.AimlMap; 4 | import org.aimlang.core.entity.AimlSubstitution; 5 | 6 | import java.io.File; 7 | import java.util.Map; 8 | 9 | /** 10 | * Substitution loader 11 | * 12 | * @author anton 13 | * @since 19/10/16 14 | */ 15 | public class SubstitutionLoader extends MapLoader { 16 | @Override 17 | public AimlSubstitution load(File file) { 18 | AimlMap map = super.load(file); 19 | return new AimlSubstitution(map.getName(), map); 20 | } 21 | 22 | @Override 23 | public Map loadAll(File... files) { 24 | return super.loadAll(files); 25 | } 26 | 27 | @Override 28 | protected Map loadFile(File file) { 29 | return super.loadFile(file); 30 | } 31 | 32 | @Override 33 | protected void parseRow(final Map data, final String row) { 34 | var splitStr = row.toUpperCase().trim().split(","); 35 | if (splitStr.length < 2) return; 36 | var first = splitStr[0]; 37 | var second = splitStr[1]; 38 | if (first.length() >= 2 && second.length() >= 2) 39 | data.put(removeBraces(first), removeBraces(second)); 40 | } 41 | 42 | private String removeBraces(String value) { 43 | return value.substring(1, value.length() - 2).trim(); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /core/src/main/java/org/aimlang/core/loaders/XmlLoader.java: -------------------------------------------------------------------------------- 1 | package org.aimlang.core.loaders; 2 | 3 | import org.slf4j.Logger; 4 | import org.w3c.dom.Document; 5 | import org.w3c.dom.Element; 6 | import org.xml.sax.SAXException; 7 | 8 | import javax.xml.parsers.DocumentBuilder; 9 | import javax.xml.parsers.DocumentBuilderFactory; 10 | import javax.xml.parsers.ParserConfigurationException; 11 | import java.io.File; 12 | import java.io.IOException; 13 | import java.util.HashMap; 14 | import java.util.Map; 15 | 16 | import static org.slf4j.LoggerFactory.getLogger; 17 | 18 | /** 19 | * Load root element from xml file 20 | * 21 | * @author batiaev 22 | * @since 25/10/16 23 | */ 24 | public class XmlLoader implements FileLoader { 25 | private static final Logger log = getLogger(XmlLoader.class); 26 | 27 | @Override 28 | public Element load(File file) { 29 | var dbFactory = DocumentBuilderFactory.newInstance(); 30 | DocumentBuilder dBuilder; 31 | Document doc = null; 32 | try { 33 | dBuilder = dbFactory.newDocumentBuilder(); 34 | doc = dBuilder.parse(file); 35 | } catch (ParserConfigurationException | SAXException | IOException e) { 36 | e.printStackTrace(); 37 | } 38 | if (doc == null) return null; 39 | 40 | var rootElement = doc.getDocumentElement(); 41 | rootElement.normalize(); 42 | return rootElement; 43 | } 44 | 45 | @Override 46 | public Map loadAll(File... files) { 47 | var data = new HashMap(); 48 | for (File file : files) 49 | data.put(file.getName(), load(file)); 50 | log.info("Loaded {} files", data.size()); 51 | return data; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /core/src/main/java/org/aimlang/core/utils/AppUtils.java: -------------------------------------------------------------------------------- 1 | package org.aimlang.core.utils; 2 | 3 | import org.w3c.dom.Node; 4 | 5 | import javax.xml.transform.OutputKeys; 6 | import javax.xml.transform.TransformerException; 7 | import javax.xml.transform.TransformerFactory; 8 | import javax.xml.transform.dom.DOMSource; 9 | import javax.xml.transform.stream.StreamResult; 10 | import java.io.StringWriter; 11 | import java.util.List; 12 | import java.util.Random; 13 | 14 | /** 15 | * Additional utils 16 | * 17 | * @author anton 18 | * @since 21/10/16 19 | */ 20 | public class AppUtils { 21 | private static final Random random = new Random(); 22 | 23 | public static E getRandom(List collection) { 24 | return collection.get(random.nextInt(collection.size())); 25 | } 26 | 27 | public static String node2String(Node node) { 28 | var nodeName = node.getNodeName(); 29 | var sw = new StringWriter(); 30 | try { 31 | var t = TransformerFactory.newInstance().newTransformer(); 32 | t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); 33 | t.setOutputProperty(OutputKeys.INDENT, "yes"); 34 | t.transform(new DOMSource(node), new StreamResult(sw)); 35 | } catch (TransformerException te) { 36 | System.out.println("nodeToString Transformer Exception"); 37 | } 38 | return sw.toString() 39 | .replaceAll("(\r\n|\n\r|\r|\n)", " ") 40 | .replaceAll("> ", ">") 41 | .replaceFirst("<" + nodeName + ">", "") 42 | .replaceFirst("", ""); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /core/src/main/resources/aiml-2.0.xsd: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | That tag 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | Bot tag 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | Set tag 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | Category of received question 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 | Category of received question 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | Category of received question 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | AIML root element 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | -------------------------------------------------------------------------------- /core/src/main/resources/aiml.info: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | WORD 8 | $WORD 9 | _ 10 | * 11 | ^ 12 | # 13 | 14 | PROPERTY_NAME 15 | 16 | 17 | equal pattern 18 | equal pattern 19 | 46 | 47 | -------------------------------------------------------------------------------- /core/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | app.debug=true -------------------------------------------------------------------------------- /core/src/main/resources/banner.txt: -------------------------------------------------------------------------------- 1 | 2 | . _ ___ __ __ _ __ _ _ 3 | /\\ / \ |_ _| \/ | | \ \ \ \ 4 | ( ( ) / _ \ | || |\/| | | \ \ \ \ 5 | \\/ / ___ \ | || | | | |___ ) ) ) ) 6 | ' /_/ \_\___|_| |_|_____|/ / / / 7 | =============================/_/_/_/ 8 | :: Spring Boot :: (v1.5.3.RELEASE) 9 | -------------------------------------------------------------------------------- /core/src/main/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | DEBUG 12 | 13 | 14 | ${ENCODER_PATTERN} 15 | 16 | 17 | 18 | 19 | 20 | INFO 21 | 22 | ${PATH}/console.log 23 | 24 | ${PATH}/console_${ROLLING_PATTERN} 25 | 15 26 | 27 | true 28 | 29 | ${ENCODER_PATTERN} 30 | UTF-8 31 | true 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /core/src/test/java/org/aimlang/core/chat/ChatContextTest.java: -------------------------------------------------------------------------------- 1 | package org.aimlang.core.chat; 2 | 3 | import org.aimlang.core.consts.AimlConst; 4 | import org.junit.jupiter.api.Test; 5 | 6 | import static java.lang.String.format; 7 | import static org.junit.jupiter.api.Assertions.assertEquals; 8 | import static org.junit.jupiter.api.Assertions.assertTrue; 9 | 10 | /** 11 | * ChatContextTest 12 | * 13 | * @author batiaev 14 | * @since 6/22/15 15 | */ 16 | public class ChatContextTest { 17 | 18 | @Test 19 | public void testTopic() { 20 | var state = new ChatContext("test"); 21 | assertEquals(state.topic(), AimlConst.default_topic, "Default Topic = unknown, result = " + state.topic()); 22 | var newTopic = "new topic"; 23 | state.setTopic(newTopic); 24 | assertEquals(state.topic(), newTopic, "Topic = " + newTopic + ", result = " + state.topic()); 25 | } 26 | 27 | @Test 28 | public void testThat() { 29 | var state = new ChatContext("test"); 30 | assertEquals(state.that(), AimlConst.default_that, "Default That = unknown, result = " + state.that()); 31 | var newThat = "new topic"; 32 | state.setTopic(newThat); 33 | assertEquals(state.topic(), newThat, "That = " + newThat + ", result = " + state.topic()); 34 | } 35 | 36 | @Test 37 | public void testNewState() { 38 | var state = new ChatContext("test"); 39 | var testRequest = "test request"; 40 | var testRespond = "test respond"; 41 | state.newState(testRequest, testRespond); 42 | assertTrue(state.request().equals(testRequest) && state.respond().equals(testRespond), 43 | format("New state {request = %s, respond = %s}, result: {request = %s, respond = %s}", 44 | testRequest, testRespond, state.request(), state.respond())); 45 | } 46 | 47 | @Test 48 | public void testRequest() { 49 | var state = new ChatContext("test"); 50 | assertEquals("", state.request(), "Default Request = \"\", result = " + state.request()); 51 | var newRequest = "new Request"; 52 | state.setRequest(newRequest); 53 | assertEquals(state.request(), newRequest, "Request = " + newRequest + ", result = " + state.request()); 54 | } 55 | 56 | @Test 57 | public void testRespond() { 58 | var state = new ChatContext("test"); 59 | assertEquals(state.respond(), AimlConst.default_that, "Default Respond = unknown, result = " + state.respond()); 60 | var newRespond = "new Respond"; 61 | state.setRespond(newRespond); 62 | assertEquals(state.respond(), newRespond, "Respond = " + newRespond + ", result = " + state.respond()); 63 | } 64 | 65 | @Test 66 | public void testSetTopic() { 67 | var state = new ChatContext("test"); 68 | var newTopic = "new topic"; 69 | state.setTopic(newTopic); 70 | assertEquals(state.topic(), newTopic, "Set topic = " + newTopic + ", result = " + state.topic()); 71 | } 72 | 73 | @Test 74 | public void testSetRespond() { 75 | var state = new ChatContext("test"); 76 | var newRespond = "new respond"; 77 | state.setRespond(newRespond); 78 | assertEquals(state.respond(), newRespond, "Set respond = " + newRespond + ", result = " + state.respond()); 79 | } 80 | 81 | @Test 82 | public void testSetRequest() { 83 | var state = new ChatContext("test"); 84 | var newRequest = "new request"; 85 | state.setRequest(newRequest); 86 | assertEquals(state.request(), newRequest, "Set request = " + newRequest + ", result = " + state.request()); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /core/src/test/java/org/aimlang/core/core/BotTest.java: -------------------------------------------------------------------------------- 1 | package org.aimlang.core.core; 2 | 3 | import org.aimlang.core.bot.BotImpl; 4 | import org.aimlang.core.chat.ChatContext; 5 | 6 | import java.util.List; 7 | 8 | import static org.junit.jupiter.api.Assertions.assertTrue; 9 | 10 | /** 11 | * BotTest 12 | * 13 | * @author batiaev 14 | * @since 22/06/15 15 | */ 16 | public class BotTest {//FIXME 17 | // private BotImpl bot; 18 | // private BotRepository botRepository = new BotRepository(new InMemoryChatContextStorage()); 19 | 20 | // @BeforeEach 21 | // public void setUp() { 22 | // bot = (BotImpl) botRepository.get("russian"); 23 | // assertTrue(bot.wakeUp()); 24 | // } 25 | 26 | // @Test 27 | // public void testMultisentenceRespond() { 28 | // var request = "Как дела?"; 29 | // var correctResponds = List.of("отлично", "восхитительно", "замечательно", "прекрасно", "превосходно", "изумительно"); 30 | // var respond = bot.multisentenceRespond(request, new ChatContext("Human")).trim(); 31 | // assertTrue(correctResponds.contains(respond), "Request = " + request + ", Respond = " + respond); 32 | // } 33 | 34 | // @Test 35 | // public void testMultisentenceRespondWithRandom() { 36 | // var request = "Привет"; 37 | // var respond = bot.multisentenceRespond(request, new ChatContext("Human")).trim(); 38 | // var answers = "Здравствуй;Здравствуйте;Мое почтение!;Здарова;Приветствую;Привет;Доброго времени суток".split(";"); 39 | // boolean result = false; 40 | // for (String answer : answers) { 41 | // if (respond.equals(answer)) { 42 | // result = true; 43 | // break; 44 | // } 45 | // } 46 | // assertTrue(result, "Request = " + request + ", Respond = " + respond); 47 | // } 48 | 49 | // @Test 50 | // public void testMultisentenceRespondWithSrai() { 51 | // String request = "Здравствуй"; 52 | // String respond = bot.multisentenceRespond(request, new ChatContext("Human")).trim(); 53 | // String[] answers = "Здравствуй;Здравствуйте;Мое почтение!;Здарова;Приветствую;Привет;Доброго времени суток".split(";"); 54 | // boolean result = false; 55 | // for (String answer : answers) { 56 | // if (respond.equals(answer)) { 57 | // result = true; 58 | // break; 59 | // } 60 | // } 61 | // assertTrue(result, "Request = " + request + ", Respond = " + respond); 62 | // } 63 | } 64 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AIMLang/aiml-java-interpreter/8561d971156a5f8f3b2898ea9836351ec8f65dda/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Sun Oct 21 16:27:08 MSK 2018 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-3.5-bin.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn ( ) { 37 | echo "$*" 38 | } 39 | 40 | die ( ) { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save ( ) { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | org.aimlang 8 | java-interpreter 9 | 1.0.0-SNAPSHOT 10 | 11 | core 12 | app 13 | bots 14 | 15 | pom 16 | 17 | 18 | 11 19 | 1.7.25 20 | 1.18.24 21 | 5.8.2 22 | 1.2.11 23 | 6.0.1 24 | UTF-8 25 | 26 | 27 | 2015 28 | 29 | 30 | 31 | org.projectlombok 32 | lombok 33 | ${lombok.version} 34 | provided 35 | 36 | 37 | org.junit.jupiter 38 | junit-jupiter-engine 39 | ${junit.version} 40 | test 41 | 42 | 43 | ch.qos.logback 44 | logback-classic 45 | ${logback.version} 46 | 47 | 48 | 49 | 50 | 51 | Anton Batiaev 52 | batiaev 53 | anton@batiaev.com 54 | 55 | Java Developer 56 | 57 | 58 | 59 | 60 | 61 | scm:git:ssh://git@github.com:AIMLang/aiml-java-interpreter.git 62 | HEAD 63 | 64 | 65 | 66 | 67 | 68 | org.apache.maven.plugins 69 | maven-compiler-plugin 70 | 71 | ${java.version} 72 | ${java.version} 73 | 74 | 75 | 76 | org.apache.maven.plugins 77 | maven-assembly-plugin 78 | 3.3.0 79 | 80 | aiml 81 | false 82 | 83 | jar-with-dependencies 84 | 85 | 86 | 87 | org.aimlang.app.TelegramBot 88 | 89 | 90 | 91 | 92 | 93 | make-assembly 94 | package 95 | 96 | single 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'aiml-java-interpreter' 2 | 3 | include 'core' 4 | include 'app' 5 | include 'bots' --------------------------------------------------------------------------------