├── .gitignore ├── LICENSE ├── README.md ├── bot.py ├── bot_backend.py ├── chatsettings.py ├── config.py.example ├── mwt.py ├── ratelimited.py ├── requirements-userbot.txt ├── requirements.txt ├── userbot_backend.py ├── userfilter.py └── utils.py /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__/ 2 | *.py[cod] 3 | config.py 4 | *.pickle 5 | *.session 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Antibotbot for Telegram groups 2 | [![License: GPL v3](https://img.shields.io/badge/License-GPL%20v3-blue.svg)](./LICENSE) 3 | 4 | The bot is currently running as [@ArchCNAntiSpamBot](http://telegram.me/ArchCNAntiSpamBot). 5 | 6 | To run the bot yourself, you will need: 7 | - Python 3.8+ 8 | - The [python-telegram-bot](https://github.com/python-telegram-bot/python-telegram-bot) module 9 | 10 | ## Deploying 11 | ### With bot api only 12 | 1. Copy `config.py.example` to `config.py`. 13 | 2. Get a bot [token](https://core.telegram.org/bots#6-botfather). 14 | 3. Change TOKEN to the one you just got and SALT to whatever string you want inside [config.py](https://github.com/isjerryxiao/AntiSpamBot/blob/master/config.py.example#L2). 15 | 4. You're ready to go. Install requirements with `pip3 install -r requirements.txt` 16 | and then launch the bot with `python3 bot.py`. 17 | 18 | ### With mtproto userbot api 19 | #### This is only useful when you have an admin account with no add_new_admin permission. 20 | 1. Get a bot token and modify TOKEN as well as SALT inside config.py as mentioned above. 21 | 2. Get the [API ID and hash](https://docs.telethon.dev/en/latest/basic/signing-in.html#signing-in) for your telegram user account. 22 | 3. Put your api_id and hash [here](https://github.com/isjerryxiao/AntiSpamBot/blob/master/config.py.example#L52). 23 | 4. Set [USER_BOT_BACKEND](https://github.com/isjerryxiao/AntiSpamBot/blob/master/config.py.example#L51) to `True`. 24 | 5. You're ready to go. Install requirements with `pip3 install -r requirements-userbot.txt` 25 | and then launch the bot with `python3 bot.py`. 26 | -------------------------------------------------------------------------------- /bot.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | from typing import List, Any, Callable, Tuple, Set 4 | 5 | from config import (SALT, WORKERS, AT_ADMINS_RATELIMIT, STORE_CHAT_MESSAGES, 6 | GARBAGE_COLLECTION_INTERVAL, PICKLE_FILE, PERMIT_RELOAD, 7 | USER_BOT_BACKEND, DEBUG) 8 | from chatsettings import CHAT_SETTINGS as CHAT_SETTINGS_DEFAULT, CHAT_SETTINGS_HELP 9 | from importlib import reload 10 | import userfilter 11 | assert not [k for k in CHAT_SETTINGS_DEFAULT if k not in CHAT_SETTINGS_HELP] 12 | 13 | import logging 14 | from ratelimited import mqbot 15 | from telegram import Update, User, Bot, Message 16 | from telegram.ext import CallbackContext, Job, PicklePersistence 17 | 18 | from telegram import InlineKeyboardMarkup, InlineKeyboardButton 19 | from telegram.ext import (Updater, CommandHandler, MessageHandler, Filters, 20 | CallbackQueryHandler, run_async) 21 | from telegram.ext.filters import InvertedFilter 22 | 23 | from datetime import datetime, timedelta 24 | from time import time 25 | from telegram.error import (TelegramError, Unauthorized, BadRequest, 26 | TimedOut, ChatMigrated, NetworkError) 27 | 28 | from mwt import MWT 29 | from utils import print_traceback, find_cjk_letters 30 | from random import choice, randint, shuffle 31 | from hashlib import md5, sha256 32 | from threading import Lock 33 | 34 | 35 | logging.basicConfig(level=logging.INFO,format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') 36 | logger = logging.getLogger('antispambot') 37 | 38 | import subprocess 39 | def get_gitver() -> str: 40 | try: 41 | p = subprocess.run(['git', 'describe', '--tags'], 42 | env={"LANG": "C"}, 43 | stdin=subprocess.DEVNULL, 44 | stdout=subprocess.PIPE, 45 | stderr=subprocess.DEVNULL, 46 | encoding='utf-8') 47 | assert p.returncode == 0 48 | ver: str = p.stdout.strip() 49 | except Exception: 50 | ver: str = "Unknown" 51 | return ver 52 | VER: str = get_gitver() 53 | 54 | def error_callback(update: Update, context:CallbackContext) -> None: 55 | error: Exception = context.error 56 | try: 57 | raise error 58 | except Exception: 59 | print_traceback(debug=DEBUG) 60 | 61 | def collect_error(func: Callable) -> Callable: 62 | ''' 63 | designed to fix a bug in the telegram library 64 | ''' 65 | def wrapped(*args, **kwargs): 66 | try: 67 | return func(*args, **kwargs) 68 | except Exception: 69 | print_traceback(debug=DEBUG) 70 | return wrapped 71 | 72 | def filter_old_updates(func: Callable[[Update, CallbackContext], Callable]) -> Callable: 73 | ''' 74 | do not process very old updates 75 | ''' 76 | def wrapped(update: Update, context: CallbackContext, *args, **kwargs) -> Any: 77 | msg: Message = update.effective_message 78 | sent_time: datetime = msg.edit_date if msg.edit_date else msg.date 79 | seconds_from_now: float = (datetime.now(tz=sent_time.tzinfo) - sent_time).total_seconds() 80 | if int(seconds_from_now) > 5*60: 81 | logger.warning(f'Not processing update {update.update_id} since it\'s too old ({int(seconds_from_now)}).') 82 | return 83 | else: 84 | return func(update, context, *args, **kwargs) 85 | return wrapped 86 | 87 | 88 | def fName(user: User, atuser: bool = True, markdown: bool = True) -> str: 89 | name: str = user.full_name 90 | if markdown: 91 | mdtext: str = user.mention_markdown(name=user.full_name) 92 | return mdtext 93 | elif user.username: 94 | if atuser: 95 | name += " (@{})".format(user.username) 96 | else: 97 | name += " ({})".format(user.username) 98 | return name 99 | 100 | @MWT(timeout=60*60) 101 | def getAdminIds(bot: Bot, chat_id: int) -> List[int]: 102 | admin_ids = list() 103 | for chat_member in bot.get_chat_administrators(chat_id): 104 | admin_ids.append(chat_member.user.id) 105 | return admin_ids 106 | 107 | @MWT(timeout=60*60) 108 | def getAdminUsernames(bot: Bot, chat_id: int, markdown: bool = False) -> List[str]: 109 | admins = list() 110 | for chat_member in bot.get_chat_administrators(chat_id): 111 | if markdown: 112 | if chat_member.user.id != bot.id: 113 | admins.append(chat_member.user.mention_markdown(name=chat_member.user.name)) 114 | else: 115 | if chat_member.user.username and chat_member.user.username != bot.username: 116 | admins.append(chat_member.user.username) 117 | return admins 118 | 119 | @run_async 120 | @collect_error 121 | @filter_old_updates 122 | def start(update: Update, context: CallbackContext) -> None: 123 | logger.debug(f"Start from {update.message.from_user.id}") 124 | if update.message.chat.type == 'private' and update.effective_user.id in PERMIT_RELOAD: 125 | reload(userfilter) 126 | logger.info(f'[!] userfilter module reloaded by {update.effective_user.id}') 127 | update.message.reply_text('reloaded') 128 | return 129 | update.message.reply_text((f'你好{update.message.from_user.first_name}' 130 | ',机器人目前功能如下:\n' 131 | '1.新加群用户需要在一定时间内点击' 132 | '按钮验证,否则将被封禁一段时间。\n' 133 | '若该用户为群成员邀请,则邀请人也可以帮助验证。\n' 134 | '2.新加群的bot需要拉入用户或管理员确认。\n' 135 | '3.防刷屏功能: 当短时间内加入用户超过一定数量时,' 136 | '机器人会尽可能少地发送消息以防影响正常聊天。\n' 137 | '要让其正常工作,请将这个机器人添加进一个群组,' 138 | '设为管理员并打开封禁权限。\n\n' 139 | '管理员可使用 /settings 自定义设置。\n' 140 | '使用 /ban 封禁用户。'), 141 | isgroup=update.message.chat.type != 'private') 142 | 143 | @run_async 144 | @collect_error 145 | @filter_old_updates 146 | def source(update: Update, context: CallbackContext) -> None: 147 | logger.debug(f"Source from {update.message.from_user.id}") 148 | update.message.reply_text(f'Source code: https://github.com/isjerryxiao/AntiSpamBot\nVersion: {VER}', 149 | isgroup=update.message.chat.type != 'private') 150 | 151 | class chatSettings: 152 | def __init__(self, datadict): 153 | self.__data = dict() 154 | for k in CHAT_SETTINGS_DEFAULT: 155 | d = datadict.get(k, None) 156 | self.__data[k] = d 157 | def get(self, name): 158 | if name in CHAT_SETTINGS_DEFAULT: 159 | ret = self.__data.get(name, None) 160 | if ret is None: 161 | return CHAT_SETTINGS_DEFAULT[name] 162 | else: 163 | return ret 164 | def choice(self, name): 165 | data = self.get(name) 166 | if type(data) is list: 167 | return choice(data) 168 | def get_clg_accecpt_deny(self): 169 | l = self.choice('CLG_QUESTIONS') 170 | return (l[0], l[1], l[2:]) 171 | def __process(self, name: str, inputstr: str) -> str: 172 | if name == 'WELCOME_WORDS': 173 | uinput = [l[:4000] for l in inputstr.split('\n') if l] 174 | self.__data[name] = uinput 175 | elif name == 'CLG_QUESTIONS': 176 | uinput = [l for l in inputstr.split('\n') if l] 177 | if len(uinput) < 3 or len(self.get(name)) >= 10: 178 | return False 179 | uinput[0] = uinput[0][:4000] 180 | uinput = uinput[:50+1] 181 | for i in range(1, len(uinput)): 182 | uinput[i] = uinput[i][:200] 183 | if not self.__data.get(name, None): 184 | self.__data[name] = CHAT_SETTINGS_DEFAULT[name].copy() 185 | self.__data[name].append(uinput) 186 | elif name in ('CHALLENGE_SUCCESS', 'PERMISSION_DENY'): 187 | uinput = [l[:30] for l in inputstr.split('\n') if l] 188 | self.__data[name] = uinput 189 | elif name in ('CHALLENGE_TIMEOUT', 'MIN_CLG_TIME', 'UNBAN_TIMEOUT', 'FLOOD_LIMIT'): 190 | try: 191 | seconds = int(inputstr) 192 | if name == 'CHALLENGE_TIMEOUT': 193 | if seconds > 3600 or seconds < 1: 194 | raise ValueError 195 | elif name == 'MIN_CLG_TIME': 196 | if seconds < 0 or seconds > self.get('CHALLENGE_TIMEOUT'): 197 | raise ValueError 198 | elif name == 'UNBAN_TIMEOUT': 199 | if seconds > 86400 or seconds < 0: 200 | seconds = 0 201 | elif name == 'FLOOD_LIMIT': 202 | if seconds < 0 or seconds > 1000: 203 | seconds = 1 204 | else: 205 | raise NotImplementedError(f"{name} is unknown") 206 | except ValueError: 207 | return False 208 | else: 209 | self.__data[name] = seconds 210 | elif name in ('DEL_LEAVE_MSG',): 211 | self.__data[name] = not self.get(name) 212 | else: 213 | raise NotImplementedError(f"{name} is unknown") 214 | return name 215 | def delete_clg_question(self, index: int) -> Any: 216 | name = 'CLG_QUESTIONS' 217 | if not self.__data.get(name, None): 218 | self.__data[name] = CHAT_SETTINGS_DEFAULT[name].copy() 219 | if index >= 0 and len(self.__data[name]) > index and len(self.__data[name]) >= 2: 220 | return self.__data[name].pop(index) 221 | else: 222 | return False 223 | def put(self, name: str, inputstr: str) -> Any: 224 | if not inputstr: 225 | self.__data[name] = None 226 | return True 227 | elif name in CHAT_SETTINGS_DEFAULT: 228 | return self.__process(name, inputstr) 229 | def to_dict(self) -> dict: 230 | return self.__data 231 | 232 | FLD_LOCKS = dict() 233 | class restUser: 234 | def __init__(self, user_id: int, join_msgid: int, clg_msgid: int, uinvite_id: int, flooding: bool = False): 235 | self.user_id = user_id 236 | self.join_msgid = join_msgid 237 | self.clg_msgid = clg_msgid 238 | self.uinvite_id = uinvite_id 239 | self.flooding = flooding 240 | self.time = int(time()) 241 | class UserManager: 242 | def __init__(self, chat_id: int) -> None: 243 | self._cver = self.ver 244 | self._chat_id = chat_id 245 | self._nfusers = dict() 246 | self._fldusers = dict() 247 | 248 | self.fldmsg_id = None 249 | self.fldmsg_callbacks = [None, ] 250 | @property 251 | def ver(self): 252 | return '0.0.2' 253 | def add(self, ruser: restUser) -> None: 254 | if self._nfusers.pop(ruser.user_id, None): 255 | logger.debug(f'User {ruser.user_id} is already in nfusers, chat {self._chat_id}') 256 | if self._fldusers.pop(ruser.user_id, None): 257 | logger.debug(f'User {ruser.user_id} is already in fldusers, chat {self._chat_id}') 258 | if ruser.flooding: 259 | self._fldusers[ruser.user_id] = ruser 260 | else: 261 | self._nfusers[ruser.user_id] = ruser 262 | def get(self, user_id: int) -> restUser: 263 | return self.__get_pop(0, user_id) 264 | def pop(self, user_id: int) -> restUser: 265 | return self.__get_pop(1, user_id) 266 | def __len__(self): 267 | return len(self._nfusers) + len(self._fldusers) 268 | def __get_pop(self, action: int, user_id: int) -> restUser: 269 | us = (self._fldusers, self._nfusers) 270 | if action == 0: 271 | for u in us: 272 | if (ret := u.get(user_id, None)): 273 | return ret 274 | elif action == 1: 275 | for u in us: 276 | if (ret := u.pop(user_id, None)): 277 | return ret 278 | return None 279 | 280 | def challenge_gen_pw(user_id: int, join_msgid: int, real: bool = True) -> str: 281 | if real: 282 | action = 'pass' 283 | else: 284 | action = str(time()) 285 | pw = "{}{}{}{}".format(SALT, user_id, join_msgid, action) 286 | pw_sha256 = sha256(pw.encode('utf-8', errors='ignore')).hexdigest() 287 | pw_sha256_md5 = md5(pw_sha256.encode('utf-8', errors='ignore')).hexdigest() 288 | # telegram limits callback_data to 64 bytes max, we need to be brief 289 | callback = pw_sha256_md5[:8] 290 | return callback 291 | 292 | def challange_hash(user_id: int, chat_id: int, join_msgid: int) -> str: 293 | hashes = [str(hash(str(i))) for i in (user_id, chat_id, join_msgid)] 294 | identity = hash(''.join(hashes)) 295 | return str(identity) 296 | 297 | @run_async 298 | @collect_error 299 | def ban_user(update: Update, context: CallbackContext) -> None: 300 | if not update.message: 301 | return 302 | if update.effective_chat.type in ('private', 'channel'): 303 | return 304 | if update.message.from_user.id not in getAdminIds(context.bot, update.message.chat.id): 305 | return 306 | if not (repl_msg := update.message.reply_to_message): 307 | update.message.reply_text("Please reply to a message.") 308 | return 309 | if repl_msg.new_chat_members: 310 | user_ids = [user.id for user in repl_msg.new_chat_members] 311 | else: 312 | if repl_msg.from_user.id == context.bot.id: 313 | # trying to be user friendly but reqiures a lot more code :( 314 | try: 315 | assert (rmarkup := repl_msg.reply_markup) and (kbd := rmarkup.inline_keyboard) \ 316 | and type((btn := kbd[0][0])) is InlineKeyboardButton and (data := btn.callback_data) 317 | assert data.startswith('clg ') 318 | data = data.split(' ') 319 | if not len(data) in (3,4): 320 | raise RuntimeError 321 | user_ids = [int(data[1]),] 322 | except AssertionError: 323 | user_ids = list() 324 | except Exception: 325 | user_ids = list() 326 | print_traceback(debug=DEBUG) 327 | else: 328 | user_ids = [repl_msg.from_user.id,] 329 | chat_id: int = update.message.chat.id 330 | user_ids: List[int] = [uid for uid in user_ids if uid not in getAdminIds(context.bot, chat_id)] 331 | if not user_ids: 332 | update.message.reply_text("Cannot ban an admin.") 333 | return 334 | u_mgr: UserManager = context.chat_data.setdefault('u_mgr', UserManager(chat_id)) 335 | fldlock: Lock = FLD_LOCKS.setdefault(chat_id, Lock()) 336 | for user_id in user_ids: 337 | rest_user = u_mgr.get(user_id) 338 | if not rest_user: 339 | # The user has no pending challenge 340 | kick_user(context, chat_id, user_id, reason="explicitly kicked") 341 | sto_msgs: List[Tuple[int, int, int]] = context.chat_data.get('stored_messages', list()) 342 | msgids_to_delete: Set[int] = set([u_m_t[1] for u_m_t in sto_msgs if u_m_t[0] == user_id]) 343 | msgids_to_delete.add(repl_msg.message_id) 344 | for _mid in msgids_to_delete: 345 | delete_message(context, chat_id, _mid) 346 | else: 347 | # Remove old job first, then take action 348 | mjobs: tuple = context.job_queue.get_jobs_by_name(challange_hash(rest_user.user_id, chat_id, rest_user.join_msgid)) 349 | if len(mjobs) == 1: 350 | mjob: Job = mjobs[0] 351 | mjob.schedule_removal() 352 | else: 353 | for mjob in mjobs: 354 | mjob.schedule_removal() 355 | logger.error(f'There is {len(mjobs)} pending job(s) for {rest_user.user_id} in the group {chat_id}') 356 | if DEBUG: 357 | try: 358 | raise Exception 359 | except Exception: 360 | print_traceback(debug=DEBUG) 361 | # ban user 362 | kick_user(context, chat_id, user_id, reason="explicitly kicked before challenge") 363 | # delete join msg and challenge message 364 | u_mgr.pop(rest_user.user_id) 365 | if rest_user.flooding: 366 | fldlock.acquire() 367 | try: 368 | if len(u_mgr._fldusers) == 0 and u_mgr.fldmsg_id: 369 | delete_message(context, chat_id=chat_id, message_id=u_mgr.fldmsg_id) 370 | u_mgr.fldmsg_id = None 371 | finally: 372 | fldlock.release() 373 | else: 374 | delete_message(context, chat_id=chat_id, message_id=rest_user.clg_msgid) 375 | delete_message(context, chat_id=chat_id, message_id=rest_user.join_msgid) 376 | def delete_notice(_: CallbackContext) -> None: 377 | delete_message(context, chat_id=chat_id, message_id=update.message.message_id) 378 | context.job_queue.run_once(delete_notice, 2) 379 | 380 | @run_async 381 | @collect_error 382 | def challenge_verification(update: Update, context: CallbackContext) -> None: 383 | bot: Bot = context.bot 384 | chat_id: int = update.callback_query.message.chat.id 385 | user: User = update.callback_query.from_user 386 | message_id: int = update.callback_query.message.message_id 387 | data: str = update.callback_query.data 388 | fldlock: Lock = FLD_LOCKS.setdefault(chat_id, Lock()) 389 | u_mgr: UserManager = context.chat_data.setdefault('u_mgr', UserManager(chat_id)) 390 | settings = chatSettings(context.chat_data.get('chat_settings', dict())) 391 | if not data: 392 | logger.error('Empty Inline challenge data.') 393 | return 394 | args: List[str] = data.split() 395 | if args and len(args) == 3: 396 | args.append('') 397 | if not (args and len(args) == 4): 398 | logger.error(f'Wrong Inline challenge data length. {data}') 399 | return 400 | (btn_callback, invite_ruid) = args[2:] # args: ['clg', r_user_id, btn_callback, invite_ruid] 401 | # invite_ruid is '' if the restricted user is not a bot 402 | if invite_ruid: 403 | try: 404 | r_user_id = int(invite_ruid) 405 | except ValueError: 406 | logger.error(f'Bad invite_uid, {data}') 407 | bot.answer_callback_query(callback_query_id=update.callback_query.id, text="Fail") 408 | return 409 | else: 410 | r_user_id = user.id 411 | rest_user: restUser = u_mgr.get(r_user_id) 412 | 413 | naughty_user: bool = False 414 | flooding: bool = False 415 | wrong_captcha: bool = False 416 | 417 | if not rest_user: 418 | naughty_user = True 419 | else: 420 | if invite_ruid: 421 | if not rest_user.flooding: 422 | flooding = False 423 | else: 424 | wrong_captcha = True # ?? 425 | else: 426 | if rest_user.flooding: 427 | flooding = True 428 | else: 429 | wrong_captcha = True 430 | 431 | if wrong_captcha: 432 | bot.answer_callback_query(callback_query_id=update.callback_query.id, text="Not your captcha") 433 | return 434 | 435 | if flooding: 436 | naughty_user = False 437 | else: 438 | if user.id in (rest_user.uinvite_id, rest_user.user_id, *(adminids := getAdminIds(bot, chat_id))): 439 | naughty_user = False 440 | else: 441 | naughty_user = True 442 | 443 | if not naughty_user: 444 | # Remove old job first, then take action 445 | if settings.get('CHALLENGE_TIMEOUT') > 0: 446 | mjobs: tuple = context.job_queue.get_jobs_by_name(challange_hash(rest_user.user_id, chat_id, rest_user.join_msgid)) 447 | if len(mjobs) == 1: 448 | mjob: Job = mjobs[0] 449 | mjob.schedule_removal() 450 | else: 451 | for mjob in mjobs: 452 | mjob.schedule_removal() 453 | logger.error(f'There is {len(mjobs)} pending job(s) for {rest_user.user_id} in the group {chat_id}') 454 | if DEBUG: 455 | try: 456 | raise Exception 457 | except Exception: 458 | print_traceback(debug=DEBUG) 459 | 460 | # whether the captcha is correct or not 461 | if data == u_mgr.fldmsg_callbacks[0]: 462 | captcha_corrent = True 463 | elif not flooding and btn_callback == challenge_gen_pw(rest_user.user_id, rest_user.join_msgid): 464 | captcha_corrent = True 465 | else: 466 | captcha_corrent = False 467 | 468 | if not captcha_corrent: 469 | if (kick_by_admin := not flooding and user.id in adminids): 470 | bot.answer_callback_query(callback_query_id=update.callback_query.id, 471 | text=f'Banned for {UNBAN_TIMEOUT} seconds' \ 472 | if (UNBAN_TIMEOUT := settings.get('UNBAN_TIMEOUT')) > 0 else \ 473 | 'Banned permanently', 474 | show_alert=True) 475 | kick_user(context, chat_id, r_user_id, 'Kicked by admin' if kick_by_admin else 'Challange failed') 476 | def then_unban(_: CallbackContext) -> None: 477 | unban_user(context, chat_id, r_user_id, reason='Unban timeout reached.') 478 | if (UNBAN_TIMEOUT := settings.get('UNBAN_TIMEOUT')) > 0: 479 | context.job_queue.run_once(then_unban, UNBAN_TIMEOUT, name='unban_job') 480 | else: 481 | unban_user(context, chat_id, r_user_id, reason='Challenge passed.') 482 | bot.answer_callback_query(callback_query_id=update.callback_query.id, 483 | text=settings.choice('CHALLENGE_SUCCESS'), 484 | show_alert=True) 485 | # delete messages 486 | u_mgr.pop(rest_user.user_id) 487 | if flooding: 488 | fldlock.acquire() 489 | try: 490 | if len(u_mgr._fldusers) == 0 and u_mgr.fldmsg_id: 491 | delete_message(context, chat_id=chat_id, message_id=u_mgr.fldmsg_id) 492 | u_mgr.fldmsg_id = None 493 | finally: 494 | fldlock.release() 495 | else: 496 | delete_message(context, chat_id=chat_id, message_id=message_id) 497 | if not captcha_corrent: 498 | delete_message(context, chat_id=chat_id, message_id=rest_user.join_msgid) 499 | 500 | else: 501 | logger.info((f"Naughty user {fName(user, markdown=False)} {user.id=} clicked a button" 502 | f" from the group {chat_id}")) 503 | bot.answer_callback_query(callback_query_id=update.callback_query.id, 504 | text=settings.choice('PERMISSION_DENY'), 505 | show_alert=True) 506 | 507 | def simple_challenge(context, chat_id, user, invite_user, join_msgid) -> None: 508 | bot: Bot = context.bot 509 | fldlock: Lock = FLD_LOCKS.setdefault(chat_id, Lock()) 510 | u_mgr: UserManager = context.chat_data.setdefault('u_mgr', UserManager(chat_id)) 511 | settings = chatSettings(context.chat_data.get('chat_settings', dict())) 512 | MIN_CLG_TIME = settings.get('MIN_CLG_TIME') 513 | CLG_TIMEOUT = settings.get('CHALLENGE_TIMEOUT') 514 | try: 515 | RCLG_TIMEOUT = (lambda score: \ 516 | (userfilter.MAX_SCORE-score)/userfilter.MAX_SCORE*(CLG_TIMEOUT-MIN_CLG_TIME)+MIN_CLG_TIME) \ 517 | (userfilter.spam_score(user.full_name)) 518 | RCLG_TIMEOUT = int(RCLG_TIMEOUT) 519 | except Exception: 520 | RCLG_TIMEOUT = CLG_TIMEOUT 521 | print_traceback(debug=DEBUG) 522 | (CLG_QUESTION, CLG_ACCEPT, CLG_DENY) = settings.get_clg_accecpt_deny() 523 | # flooding protection 524 | FLOOD_LIMIT = settings.get('FLOOD_LIMIT') 525 | if FLOOD_LIMIT == 0: 526 | flag_flooding = False 527 | elif FLOOD_LIMIT == 1: 528 | flag_flooding = True 529 | else: 530 | if len(u_mgr) + 1 >= FLOOD_LIMIT: 531 | flag_flooding = True 532 | else: 533 | flag_flooding = False 534 | flag_flooding = flag_flooding and not user.is_bot 535 | def organize_btns(buttons: List[InlineKeyboardButton]) -> List[List[InlineKeyboardButton]]: 536 | ''' 537 | Shuffle buttons and put them into a 2d array 538 | ''' 539 | shuffle(buttons) 540 | output = [list(),] 541 | LENGTH_PER_LINE = 20 542 | MAXIMUM_PER_LINE = 4 543 | clength = LENGTH_PER_LINE 544 | for btn in buttons: 545 | l = len(btn.text) + len(find_cjk_letters(btn.text)) # cjk letters has a length of 2 546 | clength -= l 547 | if clength < 0 or len(output[-1]) >= MAXIMUM_PER_LINE: 548 | clength = LENGTH_PER_LINE - l 549 | output.append([btn]) 550 | else: 551 | output[-1].append(btn) 552 | return output 553 | try: 554 | if restrict_user(context, chat_id=chat_id, user_id=user.id, extra=((' [flooding]' if flag_flooding else '') + \ 555 | (' [bot]' if user.is_bot else ''))): 556 | if flag_flooding: 557 | fldlock.acquire() 558 | try: 559 | if u_mgr.fldmsg_id and flag_flooding: 560 | logger.debug(f'Deleting flooding captcha {u_mgr.fldmsg_id} in {chat_id}') 561 | delete_message(context, chat_id, u_mgr.fldmsg_id) 562 | buttons = [ 563 | InlineKeyboardButton(text=CLG_ACCEPT, callback_data = (\ 564 | f"clg {user.id} {challenge_gen_pw(user.id, join_msgid)}" + \ 565 | (f" {user.id}" if not flag_flooding else ''))), 566 | *[InlineKeyboardButton(text=fake_btn_text, callback_data = (\ 567 | f"clg {user.id} {challenge_gen_pw(user.id, join_msgid, real=False)}" + \ 568 | (f" {user.id}" if not flag_flooding else ''))) 569 | for fake_btn_text in CLG_DENY] 570 | ] 571 | callback_datalist = [btn.callback_data for btn in buttons] 572 | buttons = organize_btns(buttons) 573 | for _ in range(3): 574 | try: 575 | msg: Message = bot.send_message(chat_id=chat_id, 576 | reply_to_message_id=join_msgid, 577 | text=('' if not flag_flooding else \ 578 | f'待验证用户: {len(u_mgr)+1}名\n') + \ 579 | settings.choice('WELCOME_WORDS').replace( 580 | '%time%', f"{RCLG_TIMEOUT}") + \ 581 | f"\n{CLG_QUESTION}", 582 | reply_markup=InlineKeyboardMarkup(buttons), 583 | disable_notification=True, 584 | isgroup=False) # These messages are essential and should not be delayed. 585 | except TelegramError: 586 | pass 587 | else: 588 | break 589 | else: 590 | raise TelegramError(f'Send challenge message failed 3 times for {user.id}') 591 | if flag_flooding: 592 | u_mgr.fldmsg_id = msg.message_id 593 | u_mgr.fldmsg_callbacks = callback_datalist 594 | bot_invite_uid = None if flag_flooding else invite_user.id 595 | u_mgr.add(restUser(user.id, join_msgid, msg.message_id, bot_invite_uid, flooding=flag_flooding)) 596 | finally: 597 | if flag_flooding: 598 | fldlock.release() 599 | # User restricted and buttons sent, now search for this user's previous messages and delete them 600 | sto_msgs: List[Tuple[int, int, int]] = context.chat_data.get('stored_messages', list()) 601 | msgids_to_delete: Set[int] = set([u_m_t[1] for u_m_t in sto_msgs if u_m_t[0] == user.id and int(u_m_t[1]) > int(join_msgid)]) 602 | for _mid in msgids_to_delete: 603 | delete_message(context, chat_id, _mid) 604 | # kick them after timeout 605 | def kick_then_unban(_: CallbackContext) -> None: 606 | def then_unban(_: CallbackContext) -> None: 607 | unban_user(context, chat_id, user.id, reason='Unban timeout reached.') 608 | if kick_user(context, chat_id, user.id, reason='Challange timeout.'): 609 | if (UNBAN_TIMEOUT := settings.get('UNBAN_TIMEOUT')) > 0: 610 | context.job_queue.run_once(then_unban, UNBAN_TIMEOUT, name='unban_job') 611 | u_mgr.pop(user.id) 612 | # delete messages 613 | if flag_flooding: 614 | fldlock.acquire() 615 | try: 616 | if len(u_mgr) == 0 and u_mgr.fldmsg_id: 617 | delete_message(context, chat_id=chat_id, message_id=u_mgr.fldmsg_id) 618 | u_mgr.fldmsg_id = None 619 | finally: 620 | fldlock.release() 621 | else: 622 | delete_message(context, chat_id=chat_id, message_id=msg.message_id) 623 | delete_message(context, chat_id=chat_id, message_id=join_msgid) 624 | context.job_queue.run_once(kick_then_unban, RCLG_TIMEOUT if RCLG_TIMEOUT > 0 else 0, 625 | name=challange_hash(user.id, chat_id, join_msgid)) 626 | else: 627 | raise TelegramError('') 628 | except TelegramError: 629 | bot.send_message(chat_id=chat_id, 630 | text="发现新加入的成员: {0} ,但机器人不是管理员导致无法实施有效行动。" 631 | "请将机器人设为管理员并打开封禁权限。".format(fName(user, markdown=True)), 632 | parse_mode="Markdown") 633 | logger.error((f"Cannot restrict {user.id} and {invite_user.id} in " 634 | f"the group {chat_id}{' [bot]' if user.is_bot else ''}")) 635 | 636 | 637 | @run_async 638 | @collect_error 639 | @filter_old_updates 640 | def at_admins(update: Update, context: CallbackContext) -> None: 641 | chat_type: str = update.message.chat.type 642 | if chat_type in ('private', 'channel'): 643 | return 644 | bot: Bot = context.bot 645 | chat_id: int = update.message.chat.id 646 | last_at_admins: float = context.chat_data.setdefault('last_at_admins', 0.0) 647 | if time() - last_at_admins < AT_ADMINS_RATELIMIT: 648 | notice: Message = update.message.reply_text(f"请再等待{AT_ADMINS_RATELIMIT - (time() - last_at_admins): .3f}秒") 649 | def delete_notice(_: CallbackContext) -> None: 650 | for _msg_id in (update.message.message_id, notice.message_id): 651 | delete_message(context, chat_id=chat_id, message_id=_msg_id) 652 | logger.debug((f"Deleted at_admin spam messages {update.message.message_id} and " 653 | f"{notice.message_id} from {update.message.from_user.id}")) 654 | context.job_queue.run_once(delete_notice, 5) 655 | else: 656 | admins: List[str] = getAdminUsernames(bot, chat_id, markdown=True) 657 | if admins: 658 | update.message.reply_text(" ".join(admins), parse_mode='Markdown') 659 | context.chat_data["last_at_admins"]: float = time() 660 | logger.debug(f"At_admin sent from {update.message.from_user.id} {chat_id}") 661 | 662 | def write_settings(update: Update, context: CallbackContext) -> None: 663 | settings_call = context.chat_data.get('settings_call', None) 664 | if settings_call is None: 665 | return 666 | if update.message.from_user.id not in getAdminIds(context.bot, update.message.chat_id): 667 | return 668 | try: 669 | lasttime = float(settings_call[0]) 670 | caller_uid = int(settings_call[1]) 671 | item = str(settings_call[2]) 672 | except Exception: 673 | context.chat_data['settings_call'] = None 674 | return 675 | if caller_uid != update.message.from_user.id: 676 | return 677 | if time() - lasttime > 120.0: 678 | context.chat_data['settings_call'] = None 679 | return 680 | params = [line.strip() for line in update.message.text.split('\n') if line] 681 | if len(params) == 0: 682 | return 683 | if item not in CHAT_SETTINGS_DEFAULT: 684 | return 685 | settings = chatSettings(context.chat_data.get('chat_settings', dict())) 686 | ret = settings.put(item, '\n'.join(params)) 687 | context.chat_data['settings_call'] = None 688 | if ret: 689 | settings_menu(update, context, additional_text="设置成功\n\n") 690 | context.chat_data['chat_settings'] = settings.to_dict() 691 | ppersistence.flush() 692 | else: 693 | settings_menu(update, context, additional_text="您的输入有误,请重试\n\n") 694 | 695 | @run_async 696 | @collect_error 697 | @filter_old_updates 698 | def settings_menu(update: Update, context: CallbackContext, additional_text: str = '') -> None: 699 | chat_type: str = update.message.chat.type 700 | if chat_type == 'channel': 701 | return 702 | elif chat_type == 'private': 703 | update.message.reply_text('设置仅在群聊中可用', isgroup=False) 704 | return 705 | if update.message.from_user.id in getAdminIds(context.bot, update.message.chat.id): 706 | buttons = [ 707 | [InlineKeyboardButton(text=CHAT_SETTINGS_HELP[item][0], callback_data = f"settings {item}")] 708 | for item in CHAT_SETTINGS_DEFAULT] 709 | update.message.reply_text(text=f"{additional_text}请选择一项设置", 710 | reply_markup=InlineKeyboardMarkup(buttons)) 711 | 712 | @run_async 713 | @collect_error 714 | @filter_old_updates 715 | def settings_cancel(update: Update, context: CallbackContext) -> None: 716 | if update.message.from_user.id in getAdminIds(context.bot, update.message.chat.id): 717 | settings_call = context.chat_data.get('settings_call', None) 718 | if settings_call: 719 | context.chat_data['settings_call'] = None 720 | update.message.reply_text('取消成功') 721 | else: 722 | update.message.reply_text('今日无事可做') 723 | 724 | @run_async 725 | @collect_error 726 | def settings_callback(update: Update, context: CallbackContext) -> None: 727 | user: User = update.callback_query.from_user 728 | chat_id: int = update.callback_query.message.chat.id 729 | callback_answered: bool = False 730 | if user.id in getAdminIds(context.bot, chat_id): 731 | message: int = update.callback_query.message 732 | data: str = update.callback_query.data 733 | 734 | args: List[str] = data.split() 735 | if not args: 736 | return 737 | elif len(args) == 1: 738 | # show menu 739 | update.callback_query.answer() 740 | buttons = [ 741 | [InlineKeyboardButton(text=CHAT_SETTINGS_HELP[item][0], callback_data = f"settings {item}")] 742 | for item in CHAT_SETTINGS_DEFAULT] 743 | message.edit_text(text="请选择一项设置", 744 | reply_markup=InlineKeyboardMarkup(buttons)) 745 | return 746 | elif len(args) not in (2, 3): 747 | logger.error(f'Wrong Inline settings data length. {data=}') 748 | update.callback_query.answer() 749 | return 750 | else: 751 | if args[1] not in CHAT_SETTINGS_DEFAULT: 752 | update.callback_query.answer(f'Unexpected {args[1]}') 753 | return 754 | item = args[1] 755 | setting_type: str = CHAT_SETTINGS_HELP.get(item)[2] 756 | settings = chatSettings(context.chat_data.get('chat_settings', dict())) 757 | helptext = f"设置项: {CHAT_SETTINGS_HELP.get(item)[0]}\n" 758 | helptext += "当前设置: " 759 | current_value = settings.get(item) 760 | buttons = [[InlineKeyboardButton(text="恢复默认", callback_data = f"{' '.join(args[:2])} default")]] 761 | # handle default 762 | if len(args) == 3 and args[2] == 'default': 763 | callback_answered = True 764 | if settings.put(item, ''): 765 | context.chat_data['chat_settings'] = settings.to_dict() 766 | ppersistence.flush() 767 | update.callback_query.answer('成功', show_alert=True) 768 | # refresh 769 | settings = chatSettings(context.chat_data.get('chat_settings', dict())) 770 | current_value = settings.get(item) 771 | else: 772 | update.callback_query.answer('失败', show_alert=True) 773 | if setting_type == "array": 774 | assert item == 'CLG_QUESTIONS' 775 | # handle delete 776 | if len(args) == 3 and args[2] not in ('set', 'default'): 777 | try: 778 | index = int(args[2]) 779 | except ValueError: 780 | logger.error(f'Unexpected CLG_QUESTIONS index {data=}') 781 | return 782 | callback_answered = True 783 | if settings.delete_clg_question(index): 784 | context.chat_data['chat_settings'] = settings.to_dict() 785 | ppersistence.flush() 786 | update.callback_query.answer('成功', show_alert=True) 787 | # refresh 788 | settings = chatSettings(context.chat_data.get('chat_settings', dict())) 789 | current_value = settings.get(item) 790 | else: 791 | update.callback_query.answer('失败', show_alert=True) 792 | if len(current_value) < 30: 793 | buttons += [[InlineKeyboardButton(text="添加新项", callback_data = f"{' '.join(args[:2])} set")]] 794 | for i in range(len(current_value)): 795 | name = current_value[i][0] 796 | corr_answ = current_value[i][1] 797 | fals_answ = current_value[i][2:] 798 | if len(current_value) > 1: 799 | buttons.append([InlineKeyboardButton(text=f"删除 {i+1}:{name[:20]}", 800 | callback_data = f"{' '.join(args[:2])} {i}")]) 801 | helptext += f"\n问题{i+1: >2d} :{name}\n正确答案: {corr_answ}" 802 | for f in fals_answ: 803 | helptext += f"\n错误答案: {f}" 804 | elif setting_type == "bool": 805 | buttons += [[InlineKeyboardButton(text="切换状态", callback_data = f"{' '.join(args[:2])} set")]] 806 | helptext += f"\n状态: {'已启用' if current_value else '已禁用'}" 807 | elif setting_type in ("str", "int"): 808 | buttons += [[InlineKeyboardButton(text="更改", callback_data = f"{' '.join(args[:2])} set")]] 809 | if type(current_value) is list: 810 | current_value = '\n'.join([f"备选项: {x}" for x in current_value]) 811 | helptext += '\n' 812 | helptext += str(current_value) 813 | else: 814 | raise RuntimeError("should not reach here") 815 | buttons.append( 816 | [InlineKeyboardButton(text='返回', callback_data='settings')] 817 | ) 818 | helptext += '\n\n' 819 | helptext += f"设置说明:\n{CHAT_SETTINGS_HELP.get(item, [None, None])[1]}" 820 | if len(args) == 3 and args[2] == 'set': 821 | if setting_type == "bool": 822 | callback_answered = True 823 | if settings.put(item, 'dummy'): 824 | context.chat_data['chat_settings'] = settings.to_dict() 825 | ppersistence.flush() 826 | update.callback_query.answer('成功', show_alert=True) 827 | # refresh 828 | settings = chatSettings(context.chat_data.get('chat_settings', dict())) 829 | current_value = settings.get(item) 830 | newhelptext = f"状态: {'已启用' if current_value else '已禁用'}" 831 | l_helptext = [newhelptext if line.startswith('状态:') else line for line in helptext.split('\n')] 832 | helptext = '\n'.join(l_helptext) 833 | else: 834 | update.callback_query.answer('失败', show_alert=True) 835 | reply_markup = InlineKeyboardMarkup(buttons) 836 | else: 837 | helptext += "\n\n您正在设置新选项\n请在120秒内回复格式正确的内容,/cancel 取消设置。" 838 | context.chat_data['settings_call'] = [time(), user.id, item] 839 | reply_markup = None 840 | else: 841 | reply_markup = InlineKeyboardMarkup(buttons) 842 | if not callback_answered: 843 | update.callback_query.answer() 844 | helptext = helptext[:4096] 845 | if message.text == helptext and message.reply_markup is not None and reply_markup is not None: 846 | if len(message.reply_markup.inline_keyboard) == len(reply_markup.inline_keyboard): 847 | return 848 | message.edit_text(helptext, reply_markup=reply_markup) 849 | else: 850 | update.callback_query.answer() 851 | 852 | @run_async 853 | @collect_error 854 | @filter_old_updates 855 | def new_messages(update: Update, context: CallbackContext) -> None: 856 | if not (update.effective_user and update.effective_message and update.effective_message.chat): 857 | return 858 | chat_type: str = update.effective_message.chat.type 859 | if chat_type in ('private', 'channel'): 860 | return 861 | sto_msgs: List[Tuple[int, int, int]] = context.chat_data.setdefault('stored_messages', list()) 862 | sto_msgs.append((update.effective_user.id, update.effective_message.message_id, int(time()))) 863 | while len(sto_msgs) > STORE_CHAT_MESSAGES: 864 | sto_msgs.pop(0) 865 | if update.message and update.message.text: 866 | write_settings(update, context) 867 | 868 | @run_async 869 | @collect_error 870 | @filter_old_updates 871 | def left_member(update: Update, context: CallbackContext) -> None: 872 | if not (update.message and update.message.chat): 873 | return 874 | chat_type: str = update.message.chat.type 875 | if chat_type in ('private', 'channel'): 876 | return 877 | chat_id: int = update.message.chat_id 878 | msg_id: int = update.message.message_id 879 | settings = chatSettings(context.chat_data.get('chat_settings', dict())) 880 | DEL_LEAVE_MSG = settings.get('DEL_LEAVE_MSG') 881 | if DEL_LEAVE_MSG: 882 | logger.debug(f'Deleted left_member message {msg_id} for {chat_id}') 883 | delete_message(context, chat_id, msg_id) 884 | else: 885 | logger.debug(f'Not deleting left_member message {msg_id} for {chat_id}') 886 | 887 | @run_async 888 | @collect_error 889 | @filter_old_updates 890 | def new_members(update: Update, context: CallbackContext) -> None: 891 | if not (update.message and update.message.chat): 892 | return 893 | chat_type: str = update.message.chat.type 894 | if chat_type in ('private', 'channel'): 895 | return 896 | bot: Bot = context.bot 897 | chat_id: int = update.message.chat_id 898 | assert update.message.new_chat_members 899 | users: List[User] = update.message.new_chat_members 900 | invite_user: User = update.message.from_user 901 | for user in users: 902 | if user.id == bot.id: 903 | logger.info(f"Myself joined the group {chat_id}") 904 | else: 905 | logger.debug(f"{user.id} joined the group {chat_id}") 906 | if invite_user.id != user.id and invite_user.id in getAdminIds(bot, chat_id): 907 | # An admin invited him. 908 | logger.info((f"{'bot ' if user.is_bot else ''}{user.id} invited by admin " 909 | f"{invite_user.id} into the group {chat_id}")) 910 | else: 911 | simple_challenge(context, chat_id, user, invite_user, update.effective_message.message_id) 912 | 913 | def do_garbage_collection(context: CallbackContext) -> None: 914 | u_freed: int = 0 915 | m_freed: int = 0 916 | u_checked: int = 0 917 | m_checked: int = 0 918 | all_chat_data = updater.dispatcher.chat_data 919 | logger.debug('gc: check for abandoned keys') 920 | for chat_id in all_chat_data: 921 | for key in [k for k in all_chat_data[chat_id]]: 922 | if key in ('my_msg', 'rest_users'): 923 | d = all_chat_data[chat_id].pop(key, None) 924 | logger.warning(f'Update pickle: Removed {{{key}: {d}}} for {chat_id}') 925 | logger.debug('gc: reinit old versions of u_mgr') 926 | for chat_id in all_chat_data: 927 | u_mgr: UserManager = all_chat_data[chat_id].get('u_mgr', None) 928 | if u_mgr and u_mgr._cver != u_mgr.ver: 929 | all_chat_data[chat_id].pop('u_mgr', None) 930 | logger.warning(f'Update u_mgr: reinit {u_mgr._cver} to {u_mgr.ver} for {chat_id}') 931 | del u_mgr 932 | logger.debug('gc: check for outdated rest_users and sto_msgs') 933 | for chat_id in all_chat_data: 934 | u_mgr: UserManager = all_chat_data[chat_id].get('u_mgr', None) 935 | if u_mgr: 936 | for _ulist in (u_mgr._nfusers, u_mgr._fldusers): 937 | for k in (_culist := _ulist.copy()): 938 | u_checked += 1 939 | _u = _culist.get(k, None) 940 | t = _u.time if _u else 0 941 | if int(time()) - t > 7200: 942 | _ulist.pop(k, None) 943 | u_freed += 1 944 | sto_msgs: list = all_chat_data[chat_id].get('stored_messages', None) 945 | if type(sto_msgs) is list: 946 | to_rm = list() 947 | try: 948 | for item in sto_msgs: 949 | m_checked += 1 950 | if len(item) == 3: 951 | stime = item[2] 952 | if int(time()) - stime > 7200: 953 | to_rm.append(item) 954 | except Exception: 955 | print_traceback(debug=DEBUG) 956 | for item in to_rm: 957 | m_freed += 1 958 | try: 959 | sto_msgs.remove(item) 960 | except Exception: 961 | print_traceback(debug=DEBUG) 962 | logger.info((f'Scheduled garbage collection checked {u_checked} users, {m_checked} messages, ' 963 | f'freed {u_freed} users, {m_freed} messages.')) 964 | 965 | if __name__ == '__main__': 966 | ppersistence = PicklePersistence(filename=PICKLE_FILE, store_user_data=False, on_flush=True) 967 | updater = Updater(bot=mqbot, workers=WORKERS, persistence=ppersistence, use_context=True) 968 | 969 | if USER_BOT_BACKEND: 970 | from userbot_backend import (kick_user, restrict_user, unban_user, delete_message, 971 | userbot_updater) 972 | else: 973 | from bot_backend import kick_user, restrict_user, unban_user, delete_message 974 | updater.job_queue.start() 975 | updater.job_queue.run_repeating(do_garbage_collection, GARBAGE_COLLECTION_INTERVAL, first=5) 976 | updater.dispatcher.add_error_handler(error_callback) 977 | updater.dispatcher.add_handler(CommandHandler('start', start)) 978 | updater.dispatcher.add_handler(CommandHandler('source', source)) 979 | updater.dispatcher.add_handler(CommandHandler('admins', at_admins)) 980 | updater.dispatcher.add_handler(CommandHandler('admin', at_admins)) 981 | updater.dispatcher.add_handler(CommandHandler('settings', settings_menu)) 982 | updater.dispatcher.add_handler(CommandHandler('cancel', settings_cancel)) 983 | updater.dispatcher.add_handler(CommandHandler('ban', ban_user)) 984 | updater.dispatcher.add_handler(CallbackQueryHandler(challenge_verification, pattern=r'clg')) 985 | updater.dispatcher.add_handler(CallbackQueryHandler(settings_callback, pattern=r'settings')) 986 | updater.dispatcher.add_handler(MessageHandler(Filters.status_update.new_chat_members, new_members)) 987 | updater.dispatcher.add_handler(MessageHandler(Filters.status_update.left_chat_member, left_member)) 988 | updater.dispatcher.add_handler(MessageHandler(InvertedFilter(Filters.status_update & \ 989 | Filters.update.channel_posts), new_messages)) 990 | if USER_BOT_BACKEND: 991 | logger.info('Antispambot started with userbot backend.') 992 | try: 993 | userbot_updater.start() 994 | updater.start_polling() 995 | updater.idle() 996 | finally: 997 | userbot_updater.stop() 998 | else: 999 | logger.info('Antispambot started.') 1000 | updater.start_polling() 1001 | updater.idle() 1002 | -------------------------------------------------------------------------------- /bot_backend.py: -------------------------------------------------------------------------------- 1 | # This is the bot api backend of kick_user, restrict_user, unban_user, delete_message 2 | import logging 3 | logger = logging.getLogger('antispambot.backend') 4 | 5 | from typing import List, Callable 6 | from telegram import Bot, ChatPermissions 7 | from telegram.ext import CallbackContext 8 | from telegram.error import (TelegramError, Unauthorized, BadRequest, 9 | TimedOut, ChatMigrated, NetworkError) 10 | 11 | from utils import print_traceback 12 | from datetime import datetime, timedelta 13 | 14 | from config import DEBUG 15 | 16 | def kick_user(context: CallbackContext, chat_id: int, kick_id: int, reason: str = '') -> bool: 17 | bot: Bot = context.bot 18 | try: 19 | if bot.kick_chat_member(chat_id=chat_id, user_id=kick_id, until_date=datetime.utcnow()+timedelta(days=367)): 20 | logger.info(f"Kicked {kick_id} in the group {chat_id}{', reason: ' if reason else ''}{reason}") 21 | else: 22 | raise TelegramError('kick_chat_member returned bad status') 23 | except TelegramError as err: 24 | logger.error(f"Cannot kick {kick_id} in the group {chat_id}, {err}") 25 | except Exception: 26 | print_traceback(DEBUG) 27 | else: 28 | return True 29 | return False 30 | 31 | 32 | def _export_chat_permissions() -> List[ChatPermissions]: 33 | CHAT_PERMISSIONS_TUPLE: tuple = ( 34 | 'can_send_messages', 35 | 'can_send_media_messages', 36 | 'can_send_polls', 37 | 'can_send_other_messages', 38 | 'can_add_web_page_previews', 39 | 'can_change_info', 40 | 'can_invite_users', 41 | 'can_pin_messages' 42 | ) 43 | permissons = [ChatPermissions(), ChatPermissions()] 44 | for i in (0, 1): 45 | for p in CHAT_PERMISSIONS_TUPLE: 46 | setattr(permissons[i], p, bool(i)) 47 | return permissons 48 | 49 | (CHAT_PERMISSION_RO, CHAT_PERMISSION_RW) = _export_chat_permissions() 50 | 51 | 52 | def retry_on_network_error(func: Callable) -> Callable: 53 | NET_RETRY = 3 54 | def wrapped(*args, **kwargs) -> bool: 55 | for t in range(NET_RETRY): 56 | try: 57 | return func(*args, **kwargs) 58 | except NetworkError as err: 59 | logger.info(f"Network issue {err} in {func.__name__}") 60 | continue 61 | else: 62 | logger.warning(f"Aborting, failed {t+1} times in {func.__name__}") 63 | return False 64 | return wrapped 65 | 66 | @retry_on_network_error 67 | def restrict_user(context: CallbackContext, chat_id: int, user_id: int, extra: str = '') -> bool: 68 | try: 69 | if context.bot.restrict_chat_member(chat_id=chat_id, user_id=user_id, 70 | permissions = CHAT_PERMISSION_RO, 71 | until_date=datetime.utcnow()+timedelta(days=367)): 72 | logger.info(f"Restricted {user_id} in the group {chat_id}{extra}") 73 | else: 74 | raise TelegramError('restrict_chat_member returned bad status') 75 | except NetworkError: 76 | raise 77 | except TelegramError as err: 78 | logger.error(f"Cannot restrict {user_id} in the group {chat_id}, {err}") 79 | except Exception: 80 | print_traceback(DEBUG) 81 | else: 82 | return True 83 | return False 84 | 85 | @retry_on_network_error 86 | def unban_user(context: CallbackContext, chat_id: int, user_id: int, reason: str = '') -> bool: 87 | try: 88 | if context.bot.restrict_chat_member(chat_id=chat_id, user_id=user_id, 89 | permissions = CHAT_PERMISSION_RW, 90 | until_date=datetime.utcnow()+timedelta(days=367)): 91 | logger.info(f"Unbanned {user_id} in the group {chat_id}{', reason: ' if reason else ''}{reason}") 92 | else: 93 | raise TelegramError('restrict_chat_member returned bad status') 94 | except NetworkError: 95 | raise 96 | except TelegramError as err: 97 | logger.error(f"Cannot unban {user_id} in the group {chat_id}, {err}") 98 | except Exception: 99 | print_traceback(DEBUG) 100 | else: 101 | return True 102 | return False 103 | 104 | @retry_on_network_error 105 | def delete_message(context: CallbackContext, chat_id: int, message_id: int) -> bool: 106 | try: 107 | if context.bot.delete_message(chat_id=chat_id, message_id=message_id): 108 | logger.debug(f"Deleted message {message_id} in the group {chat_id}") 109 | else: 110 | raise TelegramError('delete_message returned bad status') 111 | except NetworkError: 112 | raise 113 | except TelegramError as err: 114 | logger.error(f"Cannot delete message {message_id} in the group {chat_id}, {err}") 115 | except Exception: 116 | print_traceback(DEBUG) 117 | else: 118 | return True 119 | return False 120 | -------------------------------------------------------------------------------- /chatsettings.py: -------------------------------------------------------------------------------- 1 | # These options can be changed per group 2 | CHAT_SETTINGS = { 3 | 'WELCOME_WORDS': [ 4 | '新入群的用户,请在 %time% 秒内回答如下问题', 5 | ], 6 | 7 | 'CLG_QUESTIONS': [ 8 | ['archlinux 是一个 什么 GNU/Linux 发行版', '滚动', '滑动', '移动', '转动', '跳动', '活动', '浮动', '不动'], 9 | ['您进群的目的是什么', '学习交流', '发小广告', '垃圾信息', '炸群爆破'], 10 | ], 11 | 12 | 'CHALLENGE_SUCCESS': [ 13 | "验证成功。", 14 | ], 15 | 16 | 'PERMISSION_DENY': [ 17 | "您无需验证", 18 | "瞎点什么,没你什么事!", 19 | "点你妹!你就这么想被口球吗?", 20 | ], 21 | 22 | 'CHALLENGE_TIMEOUT': 5*60, 23 | 'MIN_CLG_TIME': 15, 24 | 'UNBAN_TIMEOUT': 5*60, 25 | 'FLOOD_LIMIT': 5, 26 | 'DEL_LEAVE_MSG': True, 27 | } 28 | 29 | CHAT_SETTINGS_HELP = { 30 | 'WELCOME_WORDS': ("欢迎词", "设置欢迎词,其中%time%代表验证时间限制(秒),多个选择请分多行输入", "str"), 31 | 'CLG_QUESTIONS': ("验证问题", "设置验证问题,格式为:\n问题\n正确答案\n错误答案\n(多个错误答案)", "array"), 32 | 'CHALLENGE_SUCCESS': ("验证成功消息", "验证成功时的弹窗消息,应为一段文字,多个选择请分多行输入", "str"), 33 | 'PERMISSION_DENY': ("无需验证消息", "无需验证时的弹窗消息,应为一段文字,多个选择请分多行输入", "str"), 34 | 'CHALLENGE_TIMEOUT': ("验证超时时间", "验证超时时间,单位为秒,范围为1到3600", "int"), 35 | 'MIN_CLG_TIME': ("动态最小验证时间", "动态验证时间的最小值,单位为秒,范围为0到验证超时时间", "int"), 36 | 'UNBAN_TIMEOUT': ("解封时间", "超时或者验证失败后的解封时间,单位为秒,设置为0或大于86400即为永久封禁", "int"), 37 | 'FLOOD_LIMIT': ("防止刷屏", "在验证超时时间内,超过一定数量的加群触发刷屏防护。设置为0为禁用,1为始终启用", "int"), 38 | 'DEL_LEAVE_MSG': ("删除退群消息", "删除用户被移除或退群的消息", "bool"), 39 | } 40 | -------------------------------------------------------------------------------- /config.py.example: -------------------------------------------------------------------------------- 1 | # please change token and salt 2 | TOKEN: str = "token_here" 3 | SALT: str = "whatever" 4 | WORKERS: int = 32 5 | 6 | AT_ADMINS_RATELIMIT: int = 5*60 7 | # memorize some chat messages in case that some users 8 | # send messages before the bot restricts them 9 | STORE_CHAT_MESSAGES: int = 100 10 | # do garbage collection every 86400 seconds 11 | GARBAGE_COLLECTION_INTERVAL: int = 86400 12 | PICKLE_FILE: str = 'antispambot.pickle' 13 | 14 | # permit users with the following user_id to reload 15 | # the filter module by sending /start to the bot 16 | # example: [76527312, 21876387] 17 | PERMIT_RELOAD: list = [None,] 18 | 19 | # use userbot backend. DO NOT change if you don't know what it is. 20 | USER_BOT_BACKEND: bool = False 21 | API_ID: int = 00000 # Your api id 22 | API_HASH: str = 'Your api hash' 23 | 24 | DEBUG: bool = False 25 | -------------------------------------------------------------------------------- /mwt.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Source: http://code.activestate.com/recipes/325905-memoize-decorator-with-timeout/#c1 3 | 4 | import time 5 | 6 | class MWT(object): 7 | """Memoize With Timeout""" 8 | _caches = {} 9 | _timeouts = {} 10 | 11 | def __init__(self,timeout=2): 12 | self.timeout = timeout 13 | 14 | def collect(self): 15 | """Clear cache of results which have timed out""" 16 | for func in self._caches: 17 | cache = {} 18 | for key in self._caches[func]: 19 | if (time.time() - self._caches[func][key][1]) < self._timeouts[func]: 20 | cache[key] = self._caches[func][key] 21 | self._caches[func] = cache 22 | 23 | def __call__(self, f): 24 | self.cache = self._caches[f] = {} 25 | self._timeouts[f] = self.timeout 26 | 27 | def func(*args, **kwargs): 28 | kw = sorted(kwargs.items()) 29 | key = (args, tuple(kw)) 30 | try: 31 | v = self.cache[key] 32 | #print("cache") 33 | if (time.time() - v[1]) > self.timeout: 34 | raise KeyError 35 | except KeyError: 36 | #print("new") 37 | v = self.cache[key] = f(*args,**kwargs),time.time() 38 | return v[0] 39 | func.func_name = f.__name__ 40 | 41 | return func -------------------------------------------------------------------------------- /ratelimited.py: -------------------------------------------------------------------------------- 1 | # rate limited bot 2 | 3 | from telegram import Bot 4 | from telegram.utils.request import Request 5 | from time import time, sleep 6 | from threading import Lock 7 | 8 | from config import TOKEN, WORKERS 9 | 10 | 11 | 12 | class Delayed: 13 | ''' 14 | I want my return code back 15 | Do not be afraid, we have more than enough threads. 16 | ''' 17 | 18 | def __init__(self, burst_limit=30, time_limit_ms=1000): 19 | self.burst_limit = burst_limit 20 | self.time_limit = time_limit_ms / 1000 21 | self._times = [] 22 | self._lock = Lock() 23 | def __call__(self, func, *args, **kwargs): 24 | try: 25 | self._lock.acquire() 26 | # delay routine 27 | now = time() 28 | t_delta = now - self.time_limit # calculate early to improve perf. 29 | if self._times and t_delta > self._times[-1]: 30 | # if last call was before the limit time-window 31 | # used to impr. perf. in long-interval calls case 32 | self._times = [now] 33 | else: 34 | # collect last in current limit time-window 35 | self._times = [t for t in self._times if t >= t_delta] 36 | self._times.append(now) 37 | finally: 38 | self._lock.release() # to prevent dead lock 39 | if len(self._times) >= self.burst_limit: # if throughput limit was hit 40 | sleep(self._times[1] - t_delta) 41 | return func(*args, **kwargs) 42 | def delayed(self, func): 43 | ''' 44 | @Delayed().delayed 45 | ''' 46 | def wrapped(*args, **kwargs): 47 | return self(func, *args, **kwargs) 48 | return wrapped 49 | 50 | class DelayedMessage: 51 | def __init__(self, 52 | all_burst_limit=30, 53 | all_time_limit_ms=1000, 54 | group_burst_limit=20, 55 | group_time_limit_ms=60000): 56 | self._all_delay = Delayed(all_burst_limit, all_time_limit_ms) 57 | self._group_delay = Delayed(group_burst_limit, group_time_limit_ms) 58 | 59 | def delayed(self, func): 60 | ''' 61 | @DelayedMessage().delayed 62 | ''' 63 | def wrapped(*args, **kwargs): 64 | dl = self._group_delay if kwargs.pop('isgroup', True) else self._all_delay 65 | return dl(func, *args, **kwargs) 66 | return wrapped 67 | 68 | delayed_message = DelayedMessage() 69 | delayed_actions = Delayed(burst_limit=10, time_limit_ms=10000) 70 | class MQBot(Bot): 71 | '''A subclass of Bot which delegates send method handling to MQ''' 72 | def __init__(self, *args, **kwargs): 73 | super(MQBot, self).__init__(*args, **kwargs) 74 | 75 | @delayed_message.delayed 76 | def send_message(self, *args, **kwargs): 77 | '''Wrapped method would accept new `queued` and `isgroup` 78 | OPTIONAL arguments''' 79 | return super(MQBot, self).send_message(*args, **kwargs) 80 | 81 | @delayed_actions.delayed 82 | def kick_chat_member(self, *args, **kwargs): 83 | return super(MQBot, self).kick_chat_member(*args, **kwargs) 84 | 85 | @delayed_actions.delayed 86 | def restrict_chat_member(self, *args, **kwargs): 87 | return super(MQBot, self).restrict_chat_member(*args, **kwargs) 88 | 89 | @delayed_actions.delayed 90 | def delete_message(self, *args, **kwargs): 91 | return super(MQBot, self).delete_message(*args, **kwargs) 92 | 93 | mqbot = MQBot(TOKEN, request=Request(con_pool_size=WORKERS+4)) 94 | -------------------------------------------------------------------------------- /requirements-userbot.txt: -------------------------------------------------------------------------------- 1 | python-telegram-bot==12.7 2 | Telethon==1.14.0 3 | typeguard==2.7.1 4 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | python-telegram-bot==12.7 2 | -------------------------------------------------------------------------------- /userbot_backend.py: -------------------------------------------------------------------------------- 1 | # This is the userbot api backend of kick_user, restrict_user, unban_user, delete_message 2 | from typing import Union, Any, Coroutine 3 | import logging 4 | logger = logging.getLogger('antispambot.userbot_backend') 5 | 6 | from config import API_ID, API_HASH 7 | 8 | from typeguard import typechecked 9 | 10 | from telethon import TelegramClient, events 11 | from telethon.tl.types import PeerUser, PeerChat, PeerChannel 12 | from telethon.tl.types import InputPeerUser, InputPeerChat, InputPeerChannel 13 | from telegram.ext import CallbackContext 14 | from utils import print_traceback, background 15 | from time import sleep 16 | from threading import Lock 17 | 18 | session_name: str = 'antispam' 19 | client = TelegramClient(session_name, API_ID, API_HASH) 20 | 21 | from config import DEBUG 22 | 23 | 24 | class myCoro: 25 | def __init__(self, coro, *args, **kwargs): 26 | self.__coro = coro 27 | self.__args = args 28 | self.__kwargs = kwargs 29 | def get(self): 30 | return self.__coro(*self.__args, **self.__kwargs) 31 | 32 | @typechecked 33 | def async_run(coro: myCoro, timeout: int = 8, retry: int = 10) -> Any: 34 | tries = 0 35 | @typechecked 36 | def waitfor_task() -> Any: 37 | mlock = Lock() 38 | mlock.acquire() 39 | def done_callback(_): 40 | try: 41 | mlock.release() 42 | except RuntimeError: 43 | logger.error(f"Timed out task {task} exited.") 44 | task = client.loop.create_task(coro.get()) 45 | task.add_done_callback(done_callback) 46 | if mlock.acquire(timeout=timeout): 47 | return task 48 | else: 49 | cancel = task.cancel() 50 | mlock.release() 51 | logger.error(f"Timed out waiting for task {task}: {timeout} [{tries+1}/{retry}], {cancel=}") 52 | return None 53 | while True: 54 | task = waitfor_task() 55 | if task is not None: 56 | return task.result() 57 | else: 58 | tries += 1 59 | if tries >= retry: 60 | return None 61 | 62 | @client.on(events.NewMessage) 63 | async def my_event_handler(event): 64 | pass 65 | 66 | @background 67 | @typechecked 68 | def client_init() -> None: 69 | async def __client_init() -> None: 70 | logger.info('Getting dialogs') 71 | await client.get_dialogs() 72 | logger.info('Done getting dialogs') 73 | client.start() 74 | client.loop.create_task(__client_init()) 75 | client.run_until_disconnected() 76 | 77 | class userbot_updater: 78 | def __init__(self) -> None: 79 | pass 80 | @staticmethod 81 | def start() -> None: 82 | client_init() 83 | @staticmethod 84 | def stop() -> None: 85 | async_run(myCoro(client.disconnect)) 86 | while client.loop.is_running(): 87 | sleep(1) 88 | 89 | 90 | @typechecked 91 | async def get_input_entity(user_id: int, chat: Union[int, PeerChat, PeerChannel]) -> InputPeerUser: 92 | MESSAGES_TO_GET = 10 93 | try: 94 | return await client.get_input_entity(PeerUser(user_id)) 95 | except ValueError: 96 | await client.get_messages(chat, MESSAGES_TO_GET) 97 | return await client.get_input_entity(PeerUser(user_id)) 98 | 99 | 100 | @typechecked 101 | async def userbot_kick_user(chat_id: int, user_id: int) -> bool: 102 | try: 103 | await client.edit_permissions( 104 | await client.get_input_entity(chat_id), 105 | await get_input_entity(user_id, chat_id), 106 | until_date = 0, 107 | view_messages = False, 108 | send_messages = False, 109 | send_media = False, 110 | send_stickers = False, 111 | send_gifs = False, 112 | send_games = False, 113 | send_inline = False, 114 | send_polls = False, 115 | change_info = False, 116 | invite_users = False, 117 | pin_messages = False 118 | ) 119 | return True 120 | except Exception: 121 | print_traceback(debug=DEBUG) 122 | return False 123 | 124 | @typechecked 125 | async def userbot_restrict_user(chat_id: int, user_id: int) -> bool: 126 | try: 127 | await client.edit_permissions( 128 | await client.get_input_entity(chat_id), 129 | await get_input_entity(user_id, chat_id), 130 | until_date = 0, 131 | view_messages = True, 132 | send_messages = False, 133 | send_media = False, 134 | send_stickers = False, 135 | send_gifs = False, 136 | send_games = False, 137 | send_inline = False, 138 | send_polls = False, 139 | change_info = False, 140 | invite_users = False, 141 | pin_messages = False 142 | ) 143 | return True 144 | except Exception: 145 | print_traceback(debug=DEBUG) 146 | return False 147 | 148 | @typechecked 149 | async def userbot_unban_user(chat_id: int, user_id: int) -> bool: 150 | try: 151 | await client.edit_permissions( 152 | await client.get_input_entity(chat_id), 153 | await get_input_entity(user_id, chat_id), 154 | until_date = 0 155 | ) 156 | return True 157 | except Exception: 158 | print_traceback(debug=DEBUG) 159 | return False 160 | 161 | @typechecked 162 | async def userbot_delete_message(chat_id: int, message_id: int) -> bool: 163 | try: 164 | await client.delete_messages( 165 | await client.get_input_entity(chat_id), 166 | [message_id,], 167 | revoke = True 168 | ) 169 | return True 170 | except Exception: 171 | print_traceback(debug=DEBUG) 172 | return False 173 | 174 | @typechecked 175 | def kick_user(context: CallbackContext, chat_id: int, user_id: Union[int, str], reason: str = '') -> bool: 176 | user_id = int(user_id) 177 | ret = async_run(myCoro(userbot_kick_user, chat_id, user_id)) 178 | if ret: 179 | logger.info(f"Kicked {user_id} in the group {chat_id}{', reason: ' if reason else ''}{reason}") 180 | else: 181 | logger.error(f"Cannot kick {user_id} in the group {chat_id}") 182 | return ret 183 | 184 | @typechecked 185 | def restrict_user(context: CallbackContext, chat_id: int, user_id: Union[int, str], extra: str = '') -> bool: 186 | user_id = int(user_id) 187 | ret = async_run(myCoro(userbot_restrict_user, chat_id, user_id)) 188 | if ret: 189 | logger.info(f"Restricted {user_id} in the group {chat_id}{extra}") 190 | else: 191 | logger.error(f"Cannot restrict {user_id} in the group {chat_id}") 192 | return ret 193 | 194 | @typechecked 195 | def unban_user(context: CallbackContext, chat_id: int, user_id: Union[int, str], reason: str = '') -> bool: 196 | user_id = int(user_id) 197 | ret = async_run(myCoro(userbot_unban_user, chat_id, user_id)) 198 | if ret: 199 | logger.info(f"Unbanned {user_id} in the group {chat_id}{', reason: ' if reason else ''}{reason}") 200 | else: 201 | logger.error(f"Cannot unban {user_id} in the group {chat_id}") 202 | return ret 203 | 204 | @typechecked 205 | def delete_message(context: CallbackContext, chat_id: int, message_id: Union[int, str]) -> bool: 206 | message_id = int(message_id) 207 | ret = async_run(myCoro(userbot_delete_message, chat_id, message_id)) 208 | if ret: 209 | logger.debug(f"Deleted message {message_id} in the group {chat_id}") 210 | else: 211 | logger.error(f"Cannot delete message {message_id} in the group {chat_id}") 212 | return ret 213 | -------------------------------------------------------------------------------- /userfilter.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | from re import compile 4 | from utils import find_cjk_letters, print_traceback 5 | 6 | MAX_SCORE = 100 7 | ACCEPTABLE_CJK_LENGTH = 10 8 | 9 | RULES = [ 10 | {'type': 'search', 'regex': '(?i)q[^aw]{0,2}q', 'score': 90}, 11 | {'type': 'search', 'regex': '(?i)[^a-z]vx[^a-z]', 'score': 90}, 12 | {'type': 'search', 'regex': '微.{0,2}信' , 'score': 90}, 13 | {'type': 'search', 'regex': '电.{0,2}报' , 'score': 50}, 14 | {'type': 'search', 'regex': '拉.{0,2}人' , 'score': 90}, 15 | {'type': 'search', 'regex': '币.{0,2}圈' , 'score': 90}, 16 | {'type': 'search', 'regex': '优.{0,2}质' , 'score': 30}, 17 | {'type': 'search', 'regex': '广.{0,2}告' , 'score': 90}, 18 | {'type': 'search', 'regex': '出.{0,2}售' , 'score': 90}, 19 | {'type': 'search', 'regex': '售.{0,2}卖' , 'score': 90}, 20 | {'type': 'search', 'regex': '客.{0,2}服' , 'score': 30}, 21 | {'type': 'search', 'regex': '(加|增).{0,2}粉' , 'score': 90}, 22 | {'type': 'search', 'regex': '点.{0,2}赞' , 'score': 90}, 23 | {'type': 'search', 'regex': '评.{0,2}论' , 'score': 90}, 24 | {'type': 'search', 'regex': '小.{0,2}号' , 'score': 30}, 25 | {'type': 'search', 'regex': '批.{0,2}量' , 'score': 90}, 26 | ] 27 | 28 | for r in RULES: 29 | r['compiled'] = getattr(compile(r['regex']), r['type']) 30 | 31 | def _length_score(full_name: str) -> int: 32 | try: 33 | num_cjk = len(find_cjk_letters(full_name)) 34 | except Exception: 35 | num_cjk = 0 36 | print_traceback() 37 | if num_cjk <= ACCEPTABLE_CJK_LENGTH: 38 | return 0 39 | else: 40 | return int(2.2**(num_cjk - ACCEPTABLE_CJK_LENGTH)) 41 | 42 | def spam_score(full_name: str) -> int: 43 | ''' 44 | returns a int score between 0 to 100 according to predefined RULES 45 | ''' 46 | score = 0 47 | score += _length_score(full_name) 48 | if score >= MAX_SCORE: 49 | return MAX_SCORE 50 | for r in RULES: 51 | if r['compiled'](full_name): 52 | score += r['score'] 53 | if score >= MAX_SCORE: 54 | return MAX_SCORE 55 | return score 56 | 57 | if __name__ == "__main__": 58 | import sys 59 | n = sys.argv[1] 60 | print("name:", n, "score:", spam_score(n)) 61 | -------------------------------------------------------------------------------- /utils.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import sys 3 | import traceback 4 | from threading import Thread 5 | from re import compile as re_compile 6 | logger = logging.getLogger('antispambot.utils') 7 | 8 | def print_traceback(debug: bool = False) -> None: 9 | if debug is True: 10 | logger.critical("[debug on] Exception caught.\nPrinting stack traceback\n" + format_exc_plus()) 11 | else: 12 | logger.critical("Exception caught.\nPrinting stack traceback\n" + traceback.format_exc()) 13 | 14 | def format_exc_plus(): 15 | """ 16 | Print the usual traceback information, followed by a listing of all the 17 | local variables in each frame. 18 | from Python Cookbook by David Ascher, Alex Martelli 19 | """ 20 | ret = str() 21 | tb = sys.exc_info()[2] 22 | while True: 23 | if not tb.tb_next: 24 | break 25 | tb = tb.tb_next 26 | stack = [] 27 | f = tb.tb_frame 28 | while f: 29 | stack.append(f) 30 | f = f.f_back 31 | stack.reverse() 32 | ret += traceback.format_exc() 33 | ret += "\nLocals by frame, innermost last\n" 34 | for frame in stack: 35 | ret += "Frame %s in %s at line %s\n" % (frame.f_code.co_name, 36 | frame.f_code.co_filename, 37 | frame.f_lineno) 38 | for key, value in frame.f_locals.items( ): 39 | ret += "\t%20s = " % key 40 | # We have to be VERY careful not to cause a new error in our error 41 | # printer! Calling str( ) on an unknown object could cause an 42 | # error we don't want, so we must use try/except to catch it -- 43 | # we can't stop it from happening, but we can and should 44 | # stop it from propagating if it does happen! 45 | try: 46 | ret += str(value) 47 | except: 48 | ret += "" 49 | ret += '\n' 50 | return ret 51 | 52 | def background(func): 53 | def wrapped(*args, **kwargs): 54 | tr = Thread(target=func, args=args, kwargs=kwargs) 55 | tr.daemon = True 56 | tr.start() 57 | return tr 58 | return wrapped 59 | 60 | __Ha = [[0x2E80, 0x2E99], # Han # So [26] CJK RADICAL REPEAT, CJK RADICAL RAP 61 | [0x2E9B, 0x2EF3], # Han # So [89] CJK RADICAL CHOKE, CJK RADICAL C-SIMPLIFIED TURTLE 62 | [0x2F00, 0x2FD5], # Han # So [214] KANGXI RADICAL ONE, KANGXI RADICAL FLUTE 63 | 0x3005, # Han # Lm IDEOGRAPHIC ITERATION MARK 64 | 0x3007, # Han # Nl IDEOGRAPHIC NUMBER ZERO 65 | [0x3021, 0x3029], # Han # Nl [9] HANGZHOU NUMERAL ONE, HANGZHOU NUMERAL NINE 66 | [0x3038, 0x303A], # Han # Nl [3] HANGZHOU NUMERAL TEN, HANGZHOU NUMERAL THIRTY 67 | 0x303B, # Han # Lm VERTICAL IDEOGRAPHIC ITERATION MARK 68 | [0x3400, 0x4DB5], # Han # Lo [6582] CJK UNIFIED IDEOGRAPH-3400, CJK UNIFIED IDEOGRAPH-4DB5 69 | [0x4E00, 0x9FC3], # Han # Lo [20932] CJK UNIFIED IDEOGRAPH-4E00, CJK UNIFIED IDEOGRAPH-9FC3 70 | [0xF900, 0xFA2D], # Han # Lo [302] CJK COMPATIBILITY IDEOGRAPH-F900, CJK COMPATIBILITY IDEOGRAPH-FA2D 71 | [0xFA30, 0xFA6A], # Han # Lo [59] CJK COMPATIBILITY IDEOGRAPH-FA30, CJK COMPATIBILITY IDEOGRAPH-FA6A 72 | [0xFA70, 0xFAD9], # Han # Lo [106] CJK COMPATIBILITY IDEOGRAPH-FA70, CJK COMPATIBILITY IDEOGRAPH-FAD9 73 | [0x20000, 0x2A6D6], # Han # Lo [42711] CJK UNIFIED IDEOGRAPH-20000, CJK UNIFIED IDEOGRAPH-2A6D6 74 | [0x2F800, 0x2FA1D], # Han # Lo [542] CJK COMPATIBILITY IDEOGRAPH-2F800, CJK COMPATIBILITY IDEOGRAPH-2FA1D 75 | [0xFF00, 0xFFEF]] # Halfwidth and Fullwidth Forms - added 76 | def __build_re(): 77 | # https://stackoverflow.com/questions/34587346/python-check-if-a-string-contains-chinese-character/34587468 78 | L = [] 79 | for i in __Ha: 80 | if isinstance(i, list): 81 | f, t = i 82 | try: 83 | f = chr(f) 84 | t = chr(t) 85 | L.append(f'{f}-{t}') 86 | except Exception: 87 | print_traceback(debug=True) 88 | # A narrow python build, so can't use chars > 65535 without surrogate pairs! 89 | else: 90 | try: 91 | L.append(chr(i)) 92 | except Exception: 93 | print_traceback(debug=True) 94 | 95 | RE = f"[{''.join(L)}]" 96 | return re_compile(RE) 97 | 98 | _CJKRE = __build_re() 99 | 100 | def find_cjk_letters(text: str) -> list: 101 | return _CJKRE.findall(text) 102 | --------------------------------------------------------------------------------