├── .gitignore ├── LICENSE ├── NEWS ├── QR.jpg ├── README.md ├── README_zh.md ├── TODO ├── breadbot ├── __init__.py ├── core │ ├── __init__.py │ ├── chat.py │ ├── common.py │ └── memory.py ├── lib │ ├── __init__.py │ ├── dicts │ │ ├── stardict-lazyworm-ce-2.4.2 │ │ │ ├── lazyworm-ce.dict │ │ │ ├── lazyworm-ce.idx │ │ │ ├── lazyworm-ce.idx.oft │ │ │ └── lazyworm-ce.ifo │ │ └── stardict-lazyworm-ec-2.4.2 │ │ │ ├── lazyworm-ec.dict │ │ │ ├── lazyworm-ec.idx │ │ │ ├── lazyworm-ec.idx.oft │ │ │ └── lazyworm-ec.ifo │ ├── idea.py │ ├── import_data.py │ ├── stardict.py │ ├── teach.py │ └── web.py └── server │ ├── __init__.py │ ├── manage.py │ ├── server │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py │ ├── simple_api │ ├── __init__.py │ ├── apps.py │ ├── urls.py │ └── views.py │ └── wechat │ ├── __init__.py │ ├── apps.py │ ├── migrations │ └── __init__.py │ ├── templates │ └── wechat │ │ └── text_message_template.xml │ ├── urls.py │ └── views.py ├── clean.sh ├── files ├── bin │ └── breadbot ├── etc │ └── bread.cfg ├── logs │ └── .gitignore └── temp │ └── .gitignore ├── install.sh ├── requirements.txt ├── setup.cfg ├── setup.py ├── tox.ini └── uninstall.sh /.gitignore: -------------------------------------------------------------------------------- 1 | *.swp 2 | .eggs/ 3 | AUTHORS 4 | ChangeLog 5 | breadbot.egg-info/ 6 | build/ 7 | data/ 8 | .tox/ 9 | __pycache__/ 10 | .vscode/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. [http://fsf.org/] 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} {fullname} 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 [http://www.gnu.org/licenses/]. 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 | bread Copyright (C) 2017 ideamark 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 | [http://www.gnu.org/licenses/]. 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 | [http://www.gnu.org/philosophy/why-not-lgpl.html]. -------------------------------------------------------------------------------- /NEWS: -------------------------------------------------------------------------------- 1 | 2017-05-05 2 | - V1.0.0 3 | - First open source code 4 | 5 | 2017-05-08 6 | - V1.0.1 7 | - Add log function 8 | 9 | 2017-06-21 10 | - V1.0.2 11 | - Add 4908 new dialogs 12 | 13 | 2017-06-25 14 | - Version 1.0.3 15 | - Add 564 new dialogs 16 | - Add new Tag 'random' 17 | 18 | 2017-07-28 19 | - Version 1.0.4 20 | - Add 87326 new dialogs 21 | - Fix a bug of insert_data.py 22 | 23 | 2017-07-28 24 | - Version 1.0.5 25 | - Fix the bug of bool value in data 26 | 27 | 2017-07-31 28 | - V1.0.6 29 | - Rename yaml and database files 30 | - Merge random tag with answer tag 31 | - simplify question and answer tag names 32 | 33 | 2017-08-08 34 | - V1.0.7 35 | - Fix lots of bugs 36 | - Makes the code more clean 37 | 38 | 2017-08-10 39 | - V1.0.8 40 | - Make all the database to one 41 | - Make all the data files to one folder 42 | 43 | 2017-09-06 44 | - V1.1.0 45 | - Make all the code to a module package 46 | - More easy to install and configure 47 | - Created one console to control all functions. 48 | 49 | 2017-09-11 50 | - V1.1.1 51 | - Add tox with pep8 check 52 | 53 | 2017-09-15 54 | - V1.1.2 55 | - Move yaml folder to local 56 | - Add write cfg function 57 | 58 | 2017-09-18 59 | - V1.1.3 60 | - improve the white board and rename it as memory 61 | 62 | 2017-09-19 63 | - V1.1.4 64 | - Enhance the question searching function 65 | 66 | 2017-09-22 67 | - V1.1.5 68 | - Fix some bugs 69 | 70 | 2017-10-16 71 | - V1.2.0 72 | - Replace sqlite by mongodb 73 | - Clean up the core code 74 | 75 | 2017-10-30 76 | - V1.2.1 77 | - Fix some bugs of core code 78 | - Fix some bugs of data files 79 | - Add tools for data processing 80 | 81 | 2017-10-31 82 | - V1.2.2 83 | - Enhanced the core engine 84 | - Fix some bugs of data files 85 | 86 | 2017-11-10 87 | - V1.2.3 88 | - Improved the search nom function of core code 89 | - Improved the dialogue memory function to make it remember quesions 90 | 91 | 2017-11-12 92 | - V1.2.4 93 | - Fixed some bugs of core engine. 94 | 95 | 2017-11-14 96 | - V1.2.5 97 | - Fixed the bug of Chinese string processing. 98 | 99 | 2017-11-17 100 | - V1.2.6 101 | - Fixed many bugs of the data files 102 | - Fixed some bugs of the core engine 103 | 104 | 2017-11-22 105 | - V1.2.7 106 | - Fixed some bugs of core engine 107 | - Modify nom to klg 108 | 109 | 2017-11-26 110 | - V1.2.8 111 | - Added a new function: teach dialogue 112 | 113 | 2017-12-8 114 | - V1.2.9 115 | - Add shortcut to sec data files 116 | 117 | 2017-12-24 118 | - V1.3.0 119 | - Fix a bug of klg module 120 | - change project name "breadAI" to "breadbot" 121 | 122 | 2017-12-27 123 | - V1.3.1 124 | - Improved data insert function 125 | 126 | 2017-12-28 127 | - V1.3.2 128 | - Imporved data insert function 129 | - Changed the format of bread.cfg 130 | - Added drop database function in bin 131 | - Deleted non-print chars in data files (Thanks to kiwisky:) 132 | 133 | 2017-12-29 134 | - V1.3.3 135 | - Added mongodb info in bread.cfg 136 | - Fixed some bugs 137 | 138 | 2018-01-08 139 | - V1.3.4 140 | - Added the function of expanding abbreviation 141 | 142 | 2018-01-16 143 | - V1.3.5 144 | - Some bug fix 145 | 146 | 2018-01-17 147 | - V1.3.6 148 | - Improved super user module 149 | - Moved the log path to /var/log 150 | - Moved memory data to database and made it support multiple users 151 | 152 | 2018-02-08 153 | - V2.0.0 154 | - This is a new version for new year 155 | - Import jaro-winkler 156 | - Sped up the chat reply 157 | - Added a large number of corpus 158 | - Some bug fix 159 | - Added timeout for chat response 160 | - Built some useful commands for data processing 161 | - Expand corpus over 1000,000 162 | 163 | 2018-02-22 164 | - V2.0.1 165 | - Fixed some bugs. 166 | 167 | 2018-02-27 168 | - V2.0.2 169 | - Speed up the response 170 | 171 | 2018-03-12 172 | - V2.0.3 173 | - Add function of teach klg 174 | 175 | 2018-04-13 176 | - V2.0.4 177 | - Modified bread.cfg 178 | - Make some code simpler 179 | - Fixed some PEP8 errors 180 | 181 | 2018-04-16 182 | - V2.0.5 183 | - Replaced sdcv with googletrans 184 | 185 | 2018-04-24 186 | - V2.0.6 187 | - Strip all corpus into ideamark.github.io 188 | - Upgrade setup.py 189 | - Fix bugs of import_data function 190 | 191 | 2018-05-07 192 | - V2.0.7 193 | - Fix some setup bugs 194 | - Add new parament "public_ip" in bread.cfg 195 | 196 | 2018-05-08 197 | - V2.0.8 198 | - Modify teach function back to simple 199 | - Fix some PEP8 bugs 200 | 201 | 2018-05-09 202 | - V2.0.9 203 | - Add console log function 204 | - Changed some code style 205 | 206 | 2018-05-21 207 | - V2.1.0 208 | - Removed database 209 | - Make response faster and more accurate 210 | - Fixed bugs 211 | - Made corpus format simpler 212 | 213 | 2018-05-22 214 | - V2.1.1 215 | - Speed up response 216 | - Improved the function dialogues 217 | 218 | 2018-05-23 219 | - V2.1.2 220 | - Added corpus search function 221 | 222 | 2018-05-29 223 | - V2.1.3 224 | - Fixed bugs of memory function 225 | - Imporved transform function 226 | - Add port value in bread.cfg 227 | 228 | 2018-06-14 229 | - V2.1.4 230 | - Added the function of get public ip 231 | - Make links shorter by adding HTML 232 | 233 | 2018-06-18 234 | - V2.1.5 235 | - Removed some useless commands 236 | 237 | 2018-06-22 238 | - V2.1.6 239 | - Moved fuunctions from core 240 | 241 | 2018-06-23 242 | - V2.1.7 243 | - Add Chinese chatting 244 | 245 | 2018-06-26 246 | - V2.1.8 247 | - Modified the homepage function 248 | 249 | 2018-07-18 250 | - V2.1.9 251 | - Removed get public ip function for security 252 | - Added fast reinstall of setup.py 253 | 254 | 2018-08-13 255 | - V2.2.0 256 | - The homepage breadbot.fun is online 257 | 258 | 2018-08-14 259 | - V2.2.1 260 | - Modified some value names in bread.cfg 261 | 262 | 2018-11-13 263 | - V2.3.1 264 | - Fixed the googletrans bug 265 | - Improved setup.py 266 | 267 | 2018-11-15 268 | - V2.3.2 269 | - Replaced googletrans by goslate 270 | 271 | 2018-11-18 272 | - V2.3.3 273 | - Replaced goslate by google official API client 274 | 275 | 2019-01-02 276 | - V2.3.4 277 | - Fixed some installation bugs. 278 | 279 | 2019-09-02 280 | - V3.0.1 281 | - Introduced Redis database to improve reply speed 282 | - Improved Wiki data 283 | 284 | 2020-07-14 285 | - V3.0.3 286 | - Add stardict function. 287 | - refactor the func code. 288 | 289 | 2022-06-03 290 | - V3.1.0 291 | - Removed sudo limit. -------------------------------------------------------------------------------- /QR.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ideamark/breadbot/f310284740a4563190dc6e2d0ff0fbafb146a70a/QR.jpg -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Breadbot 2 | 3 | ## Overview 4 | Breadbot is a new chatterbot framwork at experimental stage which is aimed to simplify the development of chatterbot. 5 | 6 | * Open source code & huge amount of corpus 7 | * Wiki based corpus, easy to read & write 8 | * Minimalist design. Easy to deploy. Fast response 9 | 10 | Visit the homepage [Breadbot.Fun](http://breadbot.fun) for more info. 11 | 12 | ## Have a try 13 | * Download WeChat on your phone 14 | * Login WeChat and scan the QR code 15 | * ![QR](QR.jpg) 16 | * Talk to Breadbot 17 | 18 | ## Quick Install 19 | Breadbot works on Linux. Of cause u can let it work on other OS by modify the source code. 20 | * Download: 21 | * `git clone https://github.com/ideamark/breadbot` 22 | * Install: 23 | * First, make sure you have installed python3, python3-pip, python3-dev, gcc, redis-server. 24 | * run setup command: `./install.sh` 25 | * The corpus will be downloaded during installation. 26 | * Uninstall: 27 | * `./uninstall.sh` 28 | * Clean (not uninstall): 29 | * `./clean.sh` 30 | 31 | ## Let us start 32 | 1. Type `redis-server` to launch Redis on port 6379. 33 | 2. Type `~/.breadbot/bin/breadbot` to launch the local console. 34 | 3. Type `import` to import corpus data. 35 | 4. Then u can test Breadbot. Type `help` for more info. 36 | 37 | ## Corpus 38 | * All the corpus of Breadbot is on [Breadbot.Fun](http://breadbot.fun), which is a website and also a git repo. 39 | * The repo will be downloaded automatically when you setup Breadbot by `./install.sh`. 40 | 41 | ## Config 42 | * Just watch the only single config file: [bread.cfg](files/etc/bread.cfg) 43 | 44 | ## Super user mode 45 | * Super user mode is set for developers. 46 | * The local console is default set as super user. 47 | * If your WeChat ID is in [bread.cfg](files/etc/bread.cfg) super user list, u will get the super user functions. 48 | 49 | ## Import to your project 50 | * Need root permission. 51 | ```python 52 | from breadbot.core import response 53 | response('localuser', 'hello') 54 | ``` 55 | 56 | ## Connect to WeChat 57 | * Config your WeChat public platform account on [mp.weixin.qq.com](https://mp.weixin.qq.com). Create the Token and enter your server URL. 58 | * Then back to local server. Run the command `~/.breadbot/bin/breadbot start` to launch the server. Enter your Token and server IP. 59 | * After that, Breadbot will connect to WeChat public platform and u can chat to it on WeChat. 60 | 61 | ## Seek more 62 | * Author: Mark Yang (IdeaMark) 63 | * Email: ideamark@qq.com 64 | -------------------------------------------------------------------------------- /README_zh.md: -------------------------------------------------------------------------------- 1 | # 小面包 2 | 3 | ## 概览 4 | 小面包(Breadbot)是一款还在实验阶段的新式聊天机器人框架, 旨在大大简化聊天机器人的开发难度. 5 | 6 | * 同时开放源码和海量语料资源 7 | * Wiki 式语料组织, 更易阅读和编写 8 | * 极简设计风格, 一键部署, 快速响应 9 | 10 | 访问主页 [Breadbot.Fun](http://breadbot.fun) 获取更多信息。 11 | 12 | ## 试一试 13 | * 微信扫描下方二维码开始和小面包聊天! 14 | * ![QR](QR.jpg) 15 | 16 | ## 一键安装 17 | 小面包工作于 Linux,当然,你也可以通过修改代码使其工作于 Windows. 18 | * 下载: 19 | * `git clone https://gitee.com/ideamark/breadbot` 20 | * 安装: 21 | * 首先,确保你已经安装了 python3, python3-pip, gcc, redis-server. 22 | * 执行安装命令:`./install.sh` 23 | * 安装过程中会下载语料 24 | * 卸载: 25 | * `./uninstall.sh` 26 | * 清理缓存文件 (不是卸载): 27 | * `./clean.sh` 28 | 29 | ## 快速启动 30 | 1. 输入命令 `redis-server` 在本地 6379 端口启动 Redis 数据库。 31 | 2. 输入命令 `~/.breadbot/bin/breadbot` 启动小面包终端。 32 | 3. 输入命令 `import` 导入语料数据。 33 | 4. 然后你就可以和小面包对话了,输入`help` 可以查看更多信息。 34 | 35 | ## 语料 36 | * 小面包的全部语料都在 [Breadbot.Fun](http://breadbot.fun) 上,这是一个网站,同时也是个 Git 仓库。 37 | * 当你运行安装命令 `./install.sh` 的时候,这些语料会被自动下载到本地。 38 | 39 | ## 配置 40 | * 只需阅读唯一的配置文件 [bread.cfg](files/etc/bread.cfg) 即可一目了然。 41 | 42 | ## 超级用户 43 | * 超级用户是为了方便开发者设置的。 44 | * 本地终端已默认设置为超级用户。 45 | * 如果你的微信 ID 在 [bread.cfg](files/etc/bread.cfg) 的超级用户列表里,你就能使用超级用户相关功能。 46 | 47 | ## 导入到你的工程 48 | * 需要 root 权限 49 | ```python 50 | from breadbot.core import response 51 | response('localuser', 'hello') 52 | ``` 53 | 54 | ## 连接微信 55 | * 登录微信公众平台 [mp.weixin.qq.com](https://mp.weixin.qq.com),创建 Token 并输入你的服务器 URL. 56 | * 回到本地服务器,运行命令 `~/.breadbot/bin/breadbot start` 启动服务,输入你的 Token 和服务器 IP. 57 | * 然后,小面包就会连接到微信公众平台,你就可以通过微信和小面包聊天了。 58 | 59 | ## 更多 60 | * 作者:Mark Yang (IdeaMark) 61 | * 邮箱:ideamark@qq.com 62 | * 欢迎加入开发, 直接联系作者邮箱 63 | * 欢迎捐赠,支持中国开源事业 64 | -------------------------------------------------------------------------------- /TODO: -------------------------------------------------------------------------------- 1 | 1. The super user mode is broken, it will be fixed later. 2 | 2. Add the most important function: Sentence similarity matching. 3 | 3. Expand the wiki data. 4 | 4. Add test cases. 5 | 5. Add more documents. 6 | 6. Add cloud note system. 7 | -------------------------------------------------------------------------------- /breadbot/__init__.py: -------------------------------------------------------------------------------- 1 | from . import core 2 | from . import lib 3 | from . import server 4 | -------------------------------------------------------------------------------- /breadbot/core/__init__.py: -------------------------------------------------------------------------------- 1 | from . import chat 2 | from . import common 3 | from . import memory 4 | -------------------------------------------------------------------------------- /breadbot/core/chat.py: -------------------------------------------------------------------------------- 1 | import os 2 | import random 3 | import re 4 | import string 5 | 6 | from . import common 7 | from . import memory 8 | from breadbot import lib 9 | 10 | 11 | class Chat(object): 12 | def __init__(self, db): 13 | self.db = db 14 | 15 | def __search_ans(self, user, qus): 16 | is_super = common.is_super(user) 17 | qus = re.sub(r'[^\w\s]', '', qus) 18 | qus = qus.lower() 19 | ans_type = self.db.type(qus) 20 | if ans_type == 'set': 21 | ans = self.db.srandmember(qus, 1)[0] 22 | elif ans_type == 'string': 23 | ans = self.db.get(qus) 24 | else: 25 | ans = None 26 | return ans 27 | 28 | @common.time_limit(3) 29 | def __response(self, user, qus): 30 | qus = common.que_init(qus) 31 | ans = self.__search_ans(user, qus) 32 | if not ans: 33 | ans = self.__search_ans(user, qus) 34 | if not ans: 35 | #ans = common.dont_know() 36 | ans = lib.web.search_baidu(qus) 37 | return ans 38 | 39 | def response(self, user, qus): 40 | qus = common.init_input(qus) 41 | ans = '' 42 | 43 | if re.match('^next|n$', qus): 44 | ans = memory.Memory(user).get_longstr_mem() 45 | elif re.match('^help$', qus.lower()): 46 | ans = common.show_help(user) 47 | else: 48 | ans = lib.response(user, qus) 49 | 50 | if not ans: 51 | ans = self.__response(user, qus) 52 | memory.Memory(user).save_dialog(qus, ans) 53 | ans = memory.Memory(user).check_longstr(ans) 54 | return ans 55 | -------------------------------------------------------------------------------- /breadbot/core/common.py: -------------------------------------------------------------------------------- 1 | from configobj import ConfigObj 2 | import redis 3 | import os 4 | import platform 5 | import random 6 | import re 7 | import string 8 | from threading import Thread 9 | import time 10 | 11 | 12 | def show_help(user): 13 | text = \ 14 | 'translate \n' \ 15 | 'home (show home page)\n' \ 16 | 'next (show next words)\n' \ 17 | 'baidu (search baidu)\n' 18 | if is_super(user): 19 | text += \ 20 | '--------\n' \ 21 | 'idea (store an idea dialog)\n' \ 22 | 'teach (teach a dialog)\n' \ 23 | 'corpus (search corpus)\n' \ 24 | 'wiki (show wiki page)' 25 | return text 26 | 27 | 28 | def url_to_html(url, text='Link'): 29 | return '%s' % (url, text) 30 | 31 | 32 | def time_limit(secs): 33 | def dec(function): 34 | def dec2(*args, **kwargs): 35 | class TimeLimited(Thread): 36 | def __init__(self): 37 | Thread.__init__(self) 38 | self.result = dont_know() 39 | 40 | def run(self): 41 | self.result = function(*args, **kwargs) 42 | 43 | t = TimeLimited() 44 | t.start() 45 | t.join(secs) 46 | return t.result 47 | return dec2 48 | return dec 49 | 50 | 51 | def init_input(in_str): 52 | in_str = re.sub(r'\s', ' ', in_str) 53 | in_str = re.sub(' ', ' ', in_str) 54 | in_str = re.sub(' ', ' ', in_str) 55 | in_str = in_str.lower() 56 | in_str = in_str.strip() 57 | return in_str 58 | 59 | 60 | def expand_abbrev(in_str): 61 | if "'" not in in_str: 62 | return in_str 63 | in_str = re.sub("'m", ' am', in_str) 64 | in_str = re.sub("'s", ' is', in_str) 65 | in_str = re.sub("'re", ' are', in_str) 66 | in_str = re.sub("'ll", ' will', in_str) 67 | return in_str 68 | 69 | 70 | def que_init(in_str): 71 | in_str = expand_abbrev(in_str) 72 | in_str = re.sub('[%s]+' % string.punctuation, '', in_str) 73 | in_str = in_str.lower() 74 | return in_str 75 | 76 | 77 | def is_super(user): 78 | super_user_list = Cfg().get('wechat', 'super_users') 79 | if super_user_list and type(super_user_list) is list: 80 | for super_user in super_user_list: 81 | if user == super_user: 82 | return True 83 | return False 84 | 85 | 86 | def dont_know(): 87 | not_list = [ 88 | "Hmm...", 89 | "Sorry, I don't know"] 90 | res = random.choice(not_list) 91 | return res 92 | 93 | 94 | def get_home_dir(): 95 | os_platform = platform.system() 96 | if os_platform == 'Windows': 97 | return os.environ['USERPROFILE'] 98 | else: 99 | return os.environ['HOME'] 100 | 101 | 102 | class ChatLog(object): 103 | def __init__(self): 104 | self.log_dir = os.path.join( 105 | Cfg().get('local', 'log_path'), 106 | 'chat.log') 107 | 108 | def write(self, in_str): 109 | cur_time = time.strftime('[%Y-%m-%d %H:%M:%S] ', time.localtime()) 110 | text = cur_time + in_str 111 | f = open(self.log_dir, 'a') 112 | f.write(text + '\n') 113 | f.close() 114 | return text 115 | 116 | 117 | class ConsoleLog(object): 118 | def __init__(self): 119 | self.log_dir = os.path.join( 120 | Cfg().get('local', 'log_path'), 121 | 'console.log') 122 | 123 | def __write(self, tag, in_str): 124 | cur_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) 125 | text = '%s [%s] %s' % (cur_time, tag, in_str) 126 | f = open(self.log_dir, 'a') 127 | f.write(text + '\n') 128 | f.close() 129 | return text 130 | 131 | def info(self, in_str): 132 | print(in_str) 133 | self.__write('INFO', in_str) 134 | 135 | def warn(self, in_str): 136 | print(in_str) 137 | self.__write('WARN', in_str) 138 | 139 | def error(self, in_str): 140 | print(in_str) 141 | self.__write('ERROR', in_str) 142 | 143 | def debug(self, in_str): 144 | self.__write('DEBUG', in_str) 145 | 146 | 147 | class Cfg(object): 148 | def __init__(self): 149 | self.cfg = ConfigObj(os.path.join(get_home_dir(), '.breadbot/etc/bread.cfg')) 150 | 151 | def get(self, ctype, value): 152 | res = self.cfg[ctype][value] 153 | if (ctype, value) == ('local', 'data_paths') or \ 154 | (ctype, value) == ('wechat', 'allowed_ips') or \ 155 | (ctype, value) == ('wechat', 'super_users'): 156 | if type(res) is not list: 157 | res = [res] 158 | return res 159 | 160 | def write(self, ctype, value, key): 161 | if (ctype, value) == ('local', 'data_paths') or \ 162 | (ctype, value) == ('wechat', 'allowed_ips') or \ 163 | (ctype, value) == ('wechat', 'super_users'): 164 | if type(key) is not list: 165 | key = [key] 166 | old_key = self.get(ctype, value) 167 | key = old_key + key 168 | key = list(set(key)) 169 | self.cfg[ctype][value] = key 170 | self.cfg.write() 171 | 172 | 173 | def expand_path(path_list=[]): 174 | expand_path_list = [] 175 | for path in path_list: 176 | if not os.path.isdir(path): 177 | expand_path_list.append(path) 178 | continue 179 | for root, dirs, files in os.walk(path): 180 | if not files: 181 | continue 182 | for filename in files: 183 | if not filename: 184 | continue 185 | file_path = os.path.join(root, filename) 186 | expand_path_list.append(file_path) 187 | return expand_path_list 188 | 189 | 190 | def get_md_path_list(path_list=[]): 191 | if not path_list: 192 | path_list = Cfg().get('local', 'data_paths') 193 | path_list = expand_path(path_list) 194 | md_path_list = [] 195 | for path in path_list: 196 | if not os.path.exists(path): 197 | continue 198 | elif os.path.splitext(path)[-1] != '.md': 199 | continue 200 | else: 201 | md_path_list.append(path) 202 | return md_path_list 203 | 204 | 205 | def get_db(): 206 | os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = \ 207 | Cfg().get('local', 'google_app_credentials') 208 | db = redis.Redis(host='localhost', port=6379, 209 | db=0, decode_responses=True) 210 | return db 211 | -------------------------------------------------------------------------------- /breadbot/core/memory.py: -------------------------------------------------------------------------------- 1 | import json 2 | import os 3 | import re 4 | 5 | from . import common 6 | 7 | 8 | class Memory(object): 9 | 10 | def __init__(self, user): 11 | self.max_words = 800 12 | self.next_symble = '....' 13 | self.max_dialogs = 3 14 | self.user = user 15 | log_path = common.Cfg().get('local', 'mem_path') 16 | mem_name = '%s.log' % self.user 17 | self.mem_path = os.path.join(log_path, mem_name) 18 | self.__create_data() 19 | 20 | def __create_data(self): 21 | if not os.path.exists(self.mem_path): 22 | data = { 23 | 'dialog': [], 24 | 'long_str': { 25 | 'cur_block': 0, 26 | 'block_count': 0, 27 | 'content': [] 28 | } 29 | } 30 | with open(self.mem_path, 'w') as fp: 31 | json.dump(data, fp, indent=4) 32 | 33 | def __get_data(self): 34 | try: 35 | with open(self.mem_path, 'r') as fp: 36 | return json.load(fp) 37 | except Exception: 38 | self.__del_data() 39 | self.__create_data() 40 | with open(self.mem_path, 'r') as fp: 41 | return json.load(fp) 42 | 43 | def __del_data(self): 44 | if os.path.exists(self.mem_path): 45 | os.remove(self.mem_path) 46 | 47 | def __save_data(self, data): 48 | with open(self.mem_path, 'w') as fp: 49 | json.dump(data, fp, indent=4) 50 | 51 | def __split_longstr(self, in_str): 52 | in_str = str(in_str).encode('unicode-escape').decode() 53 | data = self.__get_data() 54 | block_count = len(in_str) // self.max_words 55 | if len(in_str) % self.max_words != 0: 56 | block_count += 1 57 | data['long_str']['block_count'] = block_count 58 | data['long_str']['cur_block'] = 1 59 | content = [ 60 | in_str[i:i + self.max_words] 61 | for i in range(0, len(in_str), self.max_words)] 62 | data['long_str']['content'] = content 63 | self.__save_data(data) 64 | 65 | def get_longstr_mem(self): 66 | data = self.__get_data() 67 | in_str_list = data['long_str']['content'] 68 | cur_block = int(data['long_str']['cur_block']) 69 | block_count = int(data['long_str']['block_count']) 70 | res = 'no more' 71 | if cur_block <= block_count and in_str_list: 72 | res = in_str_list[cur_block - 1] + self.next_symble 73 | data['long_str']['cur_block'] = str(cur_block + 1) 74 | if cur_block == block_count: 75 | res = res.replace(self.next_symble, '') 76 | res = res.replace(r'\n', '\n') 77 | res = res.replace(r'\r', '\r') 78 | self.__save_data(data) 79 | return res 80 | 81 | def check_longstr(self, in_str): 82 | in_str = str(in_str) 83 | if len(in_str) <= self.max_words or self.next_symble in in_str: 84 | return in_str 85 | elif 'http://' in in_str or 'https://' in in_str: 86 | return in_str 87 | elif re.match(u'[\u4e00-\u9fa5]+', in_str): 88 | return in_str 89 | else: 90 | self.__split_longstr(in_str) 91 | return self.get_longstr_mem() 92 | 93 | def save_dialog(self, in_str, res): 94 | in_str = str(in_str).encode('unicode-escape').decode() 95 | if in_str == 'n' or in_str == 'next': 96 | return 97 | res = str(res).encode('unicode-escape').decode() 98 | data = self.__get_data() 99 | dialog_list = data['dialog'] 100 | if len(dialog_list) >= self.max_dialogs: 101 | dialog_list.pop(0) 102 | dialog_list.append({'que': in_str, 'ans': res}) 103 | data['dialog'] = dialog_list 104 | self.__save_data(data) 105 | 106 | def get_dialog(self): 107 | data = self.__get_data() 108 | return data['dialog'] 109 | -------------------------------------------------------------------------------- /breadbot/lib/__init__.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | from breadbot.core import common 4 | from . import idea 5 | from . import import_data 6 | from . import stardict 7 | from . import teach 8 | from . import web 9 | 10 | def response(user, qus): 11 | ans = '' 12 | 13 | if re.match('^translate .*$', qus): 14 | content = re.sub('^translate ', '', qus) 15 | ans = stardict.translate(content) 16 | elif re.match('^home$', qus): 17 | ans = web.show_homepage() 18 | elif re.match('^wiki$', qus): 19 | ans = web.show_wiki() 20 | elif re.match('^baidu .*$', qus): 21 | content = re.sub('^baidu ', '', qus) 22 | ans = web.search_baidu(content) 23 | 24 | if common.is_super(user): 25 | if re.match('^idea .*$', qus): 26 | content = re.sub('^idea ', '', qus) 27 | ans = idea.Idea().store_idea(user, content) 28 | elif re.match('^teach .*$', qus): 29 | content = re.sub('^teach ', '', qus) 30 | ans = teach.Teach().do_teach(user, content) 31 | elif re.match('^corpus .*$', qus): 32 | content = re.sub('^corpus ', '', qus) 33 | ans = web.search_corpus(content) 34 | 35 | return ans 36 | -------------------------------------------------------------------------------- /breadbot/lib/dicts/stardict-lazyworm-ce-2.4.2/lazyworm-ce.idx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ideamark/breadbot/f310284740a4563190dc6e2d0ff0fbafb146a70a/breadbot/lib/dicts/stardict-lazyworm-ce-2.4.2/lazyworm-ce.idx -------------------------------------------------------------------------------- /breadbot/lib/dicts/stardict-lazyworm-ce-2.4.2/lazyworm-ce.idx.oft: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ideamark/breadbot/f310284740a4563190dc6e2d0ff0fbafb146a70a/breadbot/lib/dicts/stardict-lazyworm-ce-2.4.2/lazyworm-ce.idx.oft -------------------------------------------------------------------------------- /breadbot/lib/dicts/stardict-lazyworm-ce-2.4.2/lazyworm-ce.ifo: -------------------------------------------------------------------------------- 1 | StarDict's dict ifo file 2 | version=2.4.2 3 | wordcount=119592 4 | idxfilesize=2269830 5 | bookname=懒虫简明汉英词典 6 | author=懒虫 7 | description=胡正制作。 8 | date=2006.5.17 9 | sametypesequence=m 10 | -------------------------------------------------------------------------------- /breadbot/lib/dicts/stardict-lazyworm-ec-2.4.2/lazyworm-ec.idx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ideamark/breadbot/f310284740a4563190dc6e2d0ff0fbafb146a70a/breadbot/lib/dicts/stardict-lazyworm-ec-2.4.2/lazyworm-ec.idx -------------------------------------------------------------------------------- /breadbot/lib/dicts/stardict-lazyworm-ec-2.4.2/lazyworm-ec.idx.oft: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ideamark/breadbot/f310284740a4563190dc6e2d0ff0fbafb146a70a/breadbot/lib/dicts/stardict-lazyworm-ec-2.4.2/lazyworm-ec.idx.oft -------------------------------------------------------------------------------- /breadbot/lib/dicts/stardict-lazyworm-ec-2.4.2/lazyworm-ec.ifo: -------------------------------------------------------------------------------- 1 | StarDict's dict ifo file 2 | version=2.4.2 3 | wordcount=452185 4 | idxfilesize=10106758 5 | bookname=懒虫简明英汉词典 6 | author=懒虫 7 | description=胡正制作。 8 | date=2006.5.17 9 | sametypesequence=m 10 | -------------------------------------------------------------------------------- /breadbot/lib/idea.py: -------------------------------------------------------------------------------- 1 | import os 2 | import time 3 | from breadbot.core import common 4 | 5 | 6 | class Idea(object): 7 | 8 | def __init__(self): 9 | self.store_file = 'ideas.md' 10 | 11 | def store_idea(self, user, idea_str): 12 | if not common.is_super(user): 13 | return 14 | if not idea_str: 15 | return 16 | data_path = common.Cfg().get('local', 'data_paths')[0] 17 | file_path = os.path.join(data_path, self.store_file) 18 | time_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) 19 | text = '* %s %s\n' % (time_str, idea_str) 20 | with open(file_path, 'a') as fp: 21 | fp.write(text) 22 | return 'OK, idea is stored.' 23 | 24 | 25 | if __name__ == '__main__': 26 | Idea().store_idea('localuser', 'I think sunny is nice.') 27 | -------------------------------------------------------------------------------- /breadbot/lib/import_data.py: -------------------------------------------------------------------------------- 1 | import os 2 | import re 3 | 4 | from breadbot.core import common 5 | 6 | 7 | LOG = common.ConsoleLog() 8 | 9 | 10 | def get_path_list(): 11 | path_list = common.Cfg().get('local', 'data_paths') 12 | path_list = common.expand_path(path_list) 13 | path_list = common.get_md_path_list(path_list) 14 | return path_list 15 | 16 | 17 | def empty_db(db): 18 | for key in db.keys(): 19 | db.delete(key) 20 | LOG.info('Empty Database Done') 21 | 22 | 23 | def simpleQA(db, lines): 24 | qus = '' 25 | ans = '' 26 | for i, line in enumerate(lines): 27 | if not line: 28 | continue 29 | elif not qus and re.match('^## .*', line): 30 | qus = re.sub('^## +', '', line) 31 | qus = re.sub(r'[^\w\s]', '', qus) 32 | qus = re.sub(' *\n$', '', qus) 33 | qus = qus.lower() 34 | elif qus and line: 35 | ans += line 36 | if i >= len(lines) - 1: 37 | ans = re.sub('\n+$', '', ans) 38 | ans = ans.split('\n') 39 | db.sadd(qus, *set(ans)) 40 | qus = '' 41 | ans = '' 42 | for line2 in lines[i + 1:]: 43 | if not line2: 44 | continue 45 | elif re.match('^## .*', line2): 46 | ans = re.sub('\n+$', '', ans) 47 | ans = ans.split('\n') 48 | db.sadd(qus, *set(ans)) 49 | qus = '' 50 | ans = '' 51 | else: 52 | break 53 | 54 | 55 | def knowledgeQA(db, lines): 56 | qus = '' 57 | ans = '' 58 | for i, line in enumerate(lines): 59 | if not line: 60 | continue 61 | elif not qus and re.match('^## .*', line): 62 | qus = re.sub('^## +', '', line) 63 | qus = re.sub(r'[^\w\s]', '', qus) 64 | qus = re.sub(' *\n$', '', qus) 65 | qus = qus.lower() 66 | elif qus and line: 67 | ans += line 68 | if i >= len(lines) - 1: 69 | ans = re.sub('\n+$', '', ans) 70 | db.set(qus, ans) 71 | qus = '' 72 | ans = '' 73 | for line2 in lines[i + 1:]: 74 | if not line2: 75 | continue 76 | elif re.match('^## .*', line2): 77 | ans = re.sub('\n+$', '', ans) 78 | db.set(qus, ans) 79 | qus = '' 80 | ans = '' 81 | else: 82 | break 83 | 84 | 85 | def parser(db, lines): 86 | engine = '' 87 | start = False 88 | content = [] 89 | for line in lines: 90 | if re.match(r'^> *\[.*\].*$', line): 91 | line = re.sub(r'^> *\[', '', line) 92 | line = re.sub(r'\].*$', '', line) 93 | engine = line.split(' ')[0] 94 | status = line.split(' ')[1] 95 | if 'start' in status: 96 | start = True 97 | elif 'end' in status: 98 | start = False 99 | eval('%s(db, content)' % engine) 100 | del content[:] 101 | if start: 102 | content.append(line) 103 | 104 | 105 | def import_data(db): 106 | try: 107 | empty_db(db) 108 | path_list = get_path_list() 109 | 110 | for path in path_list: 111 | LOG.info('Import %s' % path) 112 | with open(path, 'r') as fp: 113 | lines = fp.readlines() 114 | parser(db, lines) 115 | 116 | LOG.info('All Data is Imported') 117 | return None 118 | 119 | except Exception as e: 120 | LOG.error(e) 121 | 122 | 123 | if __name__ == '__main__': 124 | user = 'localuser' 125 | db = common.get_db() 126 | import_data(db) 127 | -------------------------------------------------------------------------------- /breadbot/lib/stardict.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import struct 4 | import re 5 | 6 | from . import web 7 | 8 | dict_path = os.path.dirname(os.path.abspath(__file__)) 9 | 10 | def translate(word): 11 | if re.match('[\u4e00-\u9fa5]+', word): 12 | idx_file = open('%s/dicts/stardict-lazyworm-ce-2.4.2/lazyworm-ce.idx' % dict_path, 'rb') 13 | dict_file = open('%s/dicts/stardict-lazyworm-ce-2.4.2/lazyworm-ce.dict' % dict_path, 'rb') 14 | else: 15 | idx_file = open('%s/dicts/stardict-lazyworm-ec-2.4.2/lazyworm-ec.idx' % dict_path, 'rb') 16 | dict_file = open('%s/dicts/stardict-lazyworm-ec-2.4.2/lazyworm-ec.dict' % dict_path, 'rb') 17 | 18 | dict_idx = dict() 19 | 20 | while True: 21 | word_str = b'' 22 | one_byte = idx_file.read(1) 23 | 24 | if one_byte == b'': 25 | break 26 | 27 | while ord(one_byte) != 0: 28 | word_str += one_byte 29 | one_byte = idx_file.read(1) 30 | 31 | buffer = idx_file.read(8) 32 | word_data_offset, word_data_size = struct.unpack('!ii', buffer) 33 | dict_idx[word_str.decode()] = [word_data_offset, word_data_size] 34 | 35 | try: 36 | word_data_offset, word_data_size = dict_idx[word] 37 | dict_file.seek(word_data_offset) 38 | word_dict = dict_file.read(word_data_size).decode() 39 | return word_dict 40 | 41 | except: 42 | return web.search_baidu(word) 43 | 44 | finally: 45 | idx_file.close() 46 | dict_file.close() 47 | 48 | if __name__ == '__main__': 49 | word = sys.argv[1] 50 | print(translate(word)) 51 | -------------------------------------------------------------------------------- /breadbot/lib/teach.py: -------------------------------------------------------------------------------- 1 | import os 2 | from breadbot.core import common 3 | 4 | 5 | class Teach(object): 6 | 7 | def __init__(self): 8 | self.split_sym = ':' 9 | self.teach_file = 'teach.md' 10 | 11 | def do_teach(self, user, in_str): 12 | if not common.is_super(user): 13 | return 14 | if not in_str: 15 | return 16 | if self.split_sym not in in_str: 17 | return 18 | data_path = common.Cfg().get('local', 'data_paths')[0] 19 | file_path = os.path.join(data_path, self.teach_file) 20 | f = open(file_path, 'a') 21 | que = in_str.split(self.split_sym)[0] 22 | ans_list = in_str.split(self.split_sym)[1:] 23 | ans = self.split_sym.join(ans_list) 24 | que = common.init_input(que) 25 | ans = common.init_input(ans) 26 | text = '## %s\n%s\n\n' % (que, ans) 27 | f.write(text) 28 | f.close() 29 | return 'OK, I learned.' 30 | 31 | 32 | if __name__ == '__main__': 33 | Teach().do_teach('localuser', 'how to teach?:Just do teach func') 34 | -------------------------------------------------------------------------------- /breadbot/lib/web.py: -------------------------------------------------------------------------------- 1 | import os 2 | import re 3 | import urllib.parse 4 | import urllib.request 5 | 6 | from breadbot.core import common 7 | 8 | 9 | def search_baidu(keyword): 10 | if not keyword: 11 | return 12 | p = {'wd': keyword} 13 | url = 'http://www.baidu.com/s?' + urllib.parse.urlencode(p) 14 | return common.url_to_html(url) 15 | 16 | 17 | def search_corpus(keyword): 18 | if not keyword: 19 | return 20 | keyword = keyword.replace(' ', '+') 21 | url = 'https://github.com/ideamark/ideamark.github.io/search?q=' + keyword 22 | return common.url_to_html(url) 23 | 24 | 25 | def show_homepage(): 26 | url = 'http://breadbot.fun' 27 | name = 'Breadbot.Fun' 28 | return common.url_to_html(url, name) 29 | 30 | def show_wiki(): 31 | url = 'http://cloud.breadbot.fun:8080/#!wiki/index.md' 32 | name = 'Wiki' 33 | return common.url_to_html(url, name) 34 | -------------------------------------------------------------------------------- /breadbot/server/__init__.py: -------------------------------------------------------------------------------- 1 | import os 2 | import re 3 | 4 | from breadbot.core import common 5 | from . import manage 6 | 7 | 8 | def start(): 9 | token = common.Cfg().get('wechat', 'token') 10 | if not token: 11 | token = input('Please enter your wechat token: ') 12 | common.Cfg().write('wechat', 'token', token) 13 | 14 | host_ip = common.Cfg().get('wechat', 'host_ip') 15 | if not host_ip: 16 | host_ip = input('Please enter host IP: ') 17 | common.Cfg().write('wechat', 'host_ip', host_ip) 18 | 19 | port = common.Cfg().get('wechat', 'port') 20 | ma_path = manage.__file__ 21 | exe_list = ['python3', ma_path, 'runserver', 22 | ':'.join([host_ip, port])] 23 | exe_str = ' '.join(exe_list) 24 | os.system(exe_str) 25 | -------------------------------------------------------------------------------- /breadbot/server/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import os 3 | import sys 4 | 5 | if __name__ == '__main__': 6 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "server.settings") 7 | try: 8 | from django.core.management import execute_from_command_line 9 | except ImportError: 10 | # The above import may fail for some other reason. Ensure that the 11 | # issue is really that Django is missing to avoid masking other 12 | # exceptions on Python 2. 13 | try: 14 | import django 15 | except ImportError: 16 | raise ImportError( 17 | "Couldn't import Django. Are you sure it's installed and " 18 | "available on your PYTHONPATH environment variable? Did you " 19 | "forget to activate a virtual environment?" 20 | ) 21 | raise 22 | execute_from_command_line(sys.argv) 23 | -------------------------------------------------------------------------------- /breadbot/server/server/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ideamark/breadbot/f310284740a4563190dc6e2d0ff0fbafb146a70a/breadbot/server/server/__init__.py -------------------------------------------------------------------------------- /breadbot/server/server/settings.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | from breadbot import core 4 | 5 | """ 6 | Django settings for server project. 7 | 8 | Generated by 'django-admin startproject' using Django 1.10.5. 9 | 10 | For more information on this file, see 11 | https://docs.djangoproject.com/en/1.10/topics/settings/ 12 | 13 | For the full list of settings and their values, see 14 | https://docs.djangoproject.com/en/1.10/ref/settings/ 15 | """ 16 | 17 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 18 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 19 | 20 | 21 | # Quick-start development settings - unsuitable for production 22 | # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ 23 | 24 | # SECURITY WARNING: keep the secret key used in production secret! 25 | SECRET_KEY = '-qmj3-d)$%sz41wtot03va2u2izb@4bp_)nd$ohuy_!xjjwzqc' 26 | 27 | # SECURITY WARNING: don't run with debug turned on in production! 28 | DEBUG = True 29 | 30 | ALLOWED_HOSTS = \ 31 | core.common.Cfg().get('wechat', 'allowed_hosts') 32 | 33 | 34 | # Application definition 35 | 36 | INSTALLED_APPS = [ 37 | 'django.contrib.admin', 38 | 'django.contrib.auth', 39 | 'django.contrib.contenttypes', 40 | 'django.contrib.sessions', 41 | 'django.contrib.messages', 42 | 'django.contrib.staticfiles', 43 | 'wechat', 44 | 'simple_api', 45 | ] 46 | 47 | MIDDLEWARE = [ 48 | 'django.middleware.security.SecurityMiddleware', 49 | 'django.contrib.sessions.middleware.SessionMiddleware', 50 | 'django.middleware.common.CommonMiddleware', 51 | 'django.middleware.csrf.CsrfViewMiddleware', 52 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 53 | 'django.contrib.messages.middleware.MessageMiddleware', 54 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 55 | ] 56 | 57 | ROOT_URLCONF = 'server.urls' 58 | 59 | TEMPLATES = [ 60 | { 61 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 62 | 'DIRS': [], 63 | 'APP_DIRS': True, 64 | 'OPTIONS': { 65 | 'context_processors': [ 66 | 'django.template.context_processors.debug', 67 | 'django.template.context_processors.request', 68 | 'django.contrib.auth.context_processors.auth', 69 | 'django.contrib.messages.context_processors.messages', 70 | ], 71 | }, 72 | }, 73 | ] 74 | 75 | WSGI_APPLICATION = 'server.wsgi.application' 76 | 77 | 78 | # Database 79 | # https://docs.djangoproject.com/en/1.10/ref/settings/#databases 80 | 81 | # DATABASES = { 82 | # 'default': { 83 | # 'ENGINE': 'django.db.backends.sqlite3', 84 | # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 85 | # } 86 | # } 87 | 88 | 89 | # Password validation 90 | # https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators 91 | 92 | AUTH_PASSWORD_VALIDATORS = [ 93 | { 94 | 'NAME': 'django.contrib.auth.password_validation' 95 | '.UserAttributeSimilarityValidator', 96 | }, 97 | { 98 | 'NAME': 'django.contrib.auth.password_validation' 99 | '.MinimumLengthValidator', 100 | }, 101 | { 102 | 'NAME': 'django.contrib.auth.password_validation' 103 | '.CommonPasswordValidator', 104 | }, 105 | { 106 | 'NAME': 'django.contrib.auth.password_validation' 107 | '.NumericPasswordValidator', 108 | }, 109 | ] 110 | 111 | 112 | # Internationalization 113 | # https://docs.djangoproject.com/en/1.10/topics/i18n/ 114 | 115 | LANGUAGE_CODE = 'en-us' 116 | 117 | TIME_ZONE = 'UTC' 118 | 119 | USE_I18N = True 120 | 121 | USE_L10N = True 122 | 123 | USE_TZ = True 124 | 125 | 126 | # Static files (CSS, JavaScript, Images) 127 | # https://docs.djangoproject.com/en/1.10/howto/static-files/ 128 | 129 | STATIC_URL = '/static/' 130 | -------------------------------------------------------------------------------- /breadbot/server/server/urls.py: -------------------------------------------------------------------------------- 1 | """server URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/1.10/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.conf.urls import url, include 14 | 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) 15 | """ 16 | from django.conf.urls import url, include 17 | 18 | urlpatterns = [ 19 | url(r'^wechat', include('wechat.urls')), 20 | url(r'^simple_api', include('simple_api.urls')), 21 | ] 22 | -------------------------------------------------------------------------------- /breadbot/server/server/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for server project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "server.settings") 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /breadbot/server/simple_api/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ideamark/breadbot/f310284740a4563190dc6e2d0ff0fbafb146a70a/breadbot/server/simple_api/__init__.py -------------------------------------------------------------------------------- /breadbot/server/simple_api/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class SimpleApiConfig(AppConfig): 5 | default_auto_field = 'django.db.models.BigAutoField' 6 | name = 'simple_api' 7 | -------------------------------------------------------------------------------- /breadbot/server/simple_api/urls.py: -------------------------------------------------------------------------------- 1 | from django.conf.urls import url 2 | from .views import simpleAPI 3 | 4 | urlpatterns = [ 5 | url(r'^$', simpleAPI.as_view()), 6 | ] 7 | -------------------------------------------------------------------------------- /breadbot/server/simple_api/views.py: -------------------------------------------------------------------------------- 1 | from rest_framework.response import Response 2 | from rest_framework.views import APIView 3 | 4 | from breadbot import core 5 | 6 | 7 | db = core.common.get_db() 8 | 9 | class simpleAPI(APIView): 10 | 11 | def post(self, request): 12 | user = request.user.get_username() 13 | qus = request.data.get('question', '') 14 | ans = core.chat.Chat(db).response(user, qus) 15 | data = { 16 | 'user': user, 17 | 'answer': ans 18 | } 19 | return Response(data) -------------------------------------------------------------------------------- /breadbot/server/wechat/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ideamark/breadbot/f310284740a4563190dc6e2d0ff0fbafb146a70a/breadbot/server/wechat/__init__.py -------------------------------------------------------------------------------- /breadbot/server/wechat/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | 3 | 4 | class WechatConfig(AppConfig): 5 | name = 'wechat' 6 | -------------------------------------------------------------------------------- /breadbot/server/wechat/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ideamark/breadbot/f310284740a4563190dc6e2d0ff0fbafb146a70a/breadbot/server/wechat/migrations/__init__.py -------------------------------------------------------------------------------- /breadbot/server/wechat/templates/wechat/text_message_template.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | {{ currentTime }} 5 | 6 | {% autoescape off %} 7 | 8 | {% endautoescape %} 9 | 10 | -------------------------------------------------------------------------------- /breadbot/server/wechat/urls.py: -------------------------------------------------------------------------------- 1 | from django.conf.urls import url 2 | from .views import WeChat 3 | 4 | urlpatterns = [ 5 | url(r'^$', WeChat.as_view()), 6 | ] 7 | -------------------------------------------------------------------------------- /breadbot/server/wechat/views.py: -------------------------------------------------------------------------------- 1 | from django.http import HttpResponse 2 | from django.views.decorators.csrf import csrf_exempt 3 | from django.views.generic.base import View 4 | from django.template import loader, Context 5 | import hashlib 6 | import time 7 | from xml.etree import ElementTree as ET 8 | 9 | from breadbot import core 10 | 11 | 12 | db = core.common.get_db() 13 | 14 | 15 | class WeChat(View): 16 | 17 | @csrf_exempt 18 | def dispatch(self, *args, **kwargs): 19 | return super(WeChat, self).dispatch(*args, **kwargs) 20 | 21 | def get(self, request): 22 | token = core.common.Cfg().get('wechat', 'token') 23 | signature = request.GET.get('signature', None) 24 | timestamp = request.GET.get('timestamp', None) 25 | nonce = request.GET.get('nonce', None) 26 | echostr = request.GET.get('echostr', None) 27 | list = [token, timestamp, nonce] 28 | list.sort() 29 | hashcode = ''.join([s for s in list]) 30 | hashcode = hashlib.sha1(hashcode.encode('ascii')).hexdigest() 31 | if hashcode == signature: 32 | return HttpResponse(echostr) 33 | 34 | def post(self, request): 35 | str_xml = ET.fromstring(request.body) 36 | from_user = str_xml.find('FromUserName').text 37 | to_user = str_xml.find('ToUserName').text 38 | cur_time = str(int(time.time())) 39 | msg_type = str_xml.find('MsgType').text 40 | content = '...' 41 | if msg_type == 'text': 42 | content = str_xml.find('Content').text 43 | if '[Unsupported Message]' in content: 44 | res = 'Error: unknow message' 45 | else: 46 | res = core.chat.Chat(db).response(from_user, content) 47 | else: 48 | res = "Sorry, I can't chat by %s" % msg_type 49 | template = loader.get_template('wechat/text_message_template.xml') 50 | context = {'toUser': from_user, 51 | 'fromUser': to_user, 52 | 'currentTtime': cur_time, 53 | 'content': res} 54 | context_xml = template.render(context) 55 | log_str = '\nUser: %s\nAsk: %s\nAnswer: %s\n' % \ 56 | (from_user, content, res) 57 | core.common.ChatLog().write(log_str) 58 | return HttpResponse(context_xml) 59 | -------------------------------------------------------------------------------- /clean.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | rm -rf .eggs 4 | rm -rf AUTHORS 5 | rm -rf breadbot.egg-info 6 | rm -rf build 7 | rm -rf ChangeLog 8 | find -name "__pycache__" | xargs rm -rf 9 | echo "Done" 10 | -------------------------------------------------------------------------------- /files/bin/breadbot: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import os 3 | import sys 4 | 5 | from breadbot import core 6 | from breadbot import func 7 | from breadbot import serv 8 | 9 | 10 | user = 'localuser' 11 | db = core.common.get_db() 12 | 13 | 14 | def show_help(): 15 | print( 16 | '\n' 17 | ' start: start server\n' 18 | ' import: import data\n' 19 | ' count: count data\n' 20 | ' Ctr+C: stop server\n' 21 | ' help: display this help\n' 22 | ' q: exit this console\n' 23 | ) 24 | print(core.common.show_help(user)) 25 | 26 | 27 | def import_data(): 28 | func.import_data.import_data(db) 29 | 30 | 31 | def count_data(): 32 | print(len(db.keys())) 33 | 34 | 35 | def active(cmd): 36 | if cmd == 'help': 37 | show_help() 38 | elif cmd == 'start': 39 | serv.start() 40 | elif cmd == 'import': 41 | import_data() 42 | elif cmd == 'count': 43 | count_data() 44 | else: 45 | print(core.chat.Chat(db).response(user, cmd)) 46 | 47 | 48 | if __name__ == '__main__': 49 | 50 | if len(sys.argv) > 1: 51 | cmd = ' '.join(sys.argv[1:]) 52 | active(cmd) 53 | sys.exit(0) 54 | 55 | while True: 56 | cmd = input('>> ') 57 | if cmd == 'q' or cmd == 'exit': 58 | break 59 | elif cmd == '': 60 | continue 61 | else: 62 | active(cmd) 63 | -------------------------------------------------------------------------------- /files/etc/bread.cfg: -------------------------------------------------------------------------------- 1 | [local] 2 | # Home folder path 3 | home_path = '~/.breadbot/' 4 | 5 | # Corpus data file paths. Split them by ",". 6 | data_paths = '~/.breadbot/data/', 7 | 8 | # Log file path, should be a single path. 9 | log_path = '~/.breadbot/logs/' 10 | 11 | # Memory log file path, should be a single path. 12 | mem_path = '~/.breadbot/temp/' 13 | 14 | # The path of bread.cfg, should be a single path. 15 | cfg_path = '~/.breadbot/etc/' 16 | 17 | # The Breadbot bin path, should be a single path. 18 | bin_path = '~/.breadbot/bin/' 19 | 20 | # The Google app credentials path. Used for google translate API. Visit https://cloud.google.com/translate/docs/ for more info. 21 | google_app_credentials = 22 | 23 | 24 | [wechat] 25 | # The WeChat token. Ignore it if you run on localhost. 26 | token = 27 | 28 | # The port of the server. 29 | port = 80 30 | 31 | # The server host IP for WeChat connection. Enter 127.0.0.1 when run on localhost. 32 | host_ip = 33 | 34 | # The allowed host IPs or URLs. Split them by ",". 35 | allowed_hosts = 127.0.0.1, 36 | 37 | # The super users have more privileges to use Breadbot. Get the IDs from dia.log in your log path, Split them by ",". 38 | super_users = localuser, 39 | -------------------------------------------------------------------------------- /files/logs/.gitignore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ideamark/breadbot/f310284740a4563190dc6e2d0ff0fbafb146a70a/files/logs/.gitignore -------------------------------------------------------------------------------- /files/temp/.gitignore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ideamark/breadbot/f310284740a4563190dc6e2d0ff0fbafb146a70a/files/temp/.gitignore -------------------------------------------------------------------------------- /install.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | pip3 install --user -r requirements.txt 4 | python3 setup.py install 5 | cp -r files/ ~/.breadbot/ 6 | git clone https://github.com/ideamark/ideamark.github.io ~/.breadbot/data 7 | sed -in-place -e 's%~%'${HOME}'%g' ~/.breadbot/etc/bread.cfg -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | Django>=1.10.5 2 | configobj>=5.0.5 3 | flake8>=3.4.1 4 | redis>=4.3.3 5 | djangorestframework>=3.13.1 -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | name = breadbot 3 | version = 3.1.0 4 | author = Mark Yang (ideamark) 5 | author-email = ideamark@qq.com 6 | home-page = http://breadbot.fun 7 | description-file = README.md 8 | 9 | classifier = 10 | Operating System :: POSIX :: Linux 11 | Programming Language :: Python :: 3 12 | 13 | keywords = 14 | setup 15 | distutils 16 | 17 | [files] 18 | packages = 19 | breadbot 20 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | from setuptools import setup 3 | 4 | setup( 5 | setup_requires=['pbr>=0.1'], 6 | pbr=True,) -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = pep8 3 | minversion = 1.6 4 | skipsdist = True 5 | 6 | [testenv:pep8] 7 | commands = flake8 {posargs} 8 | 9 | [flake8] 10 | show-source = True 11 | ignore = H102, H237, H202, F401 12 | exclude = .git, .tox, etc, data 13 | -------------------------------------------------------------------------------- /uninstall.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | pip3 uninstall breadbot 4 | rm -rf ~/.breadbot/ 5 | echo "Done" --------------------------------------------------------------------------------