├── .gitignore ├── LICENSE ├── README.md ├── helper_const.py.sample ├── helper_database.py ├── helper_global.py ├── helper_main.py ├── helper_string.py ├── i18n ├── en-US.json ├── pt-BR.json └── zh-CN.json ├── messagequeue.py └── modules ├── callback_query.py ├── cancel_cmd.py ├── channel_msg.py ├── clean_cmd.py ├── help_cmd.py ├── inline_query.py ├── option_cmd.py ├── private_msg.py ├── register_cmd.py ├── sql_cmd.py └── start_cmd.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | ### Python template 3 | # Byte-compiled / optimized / DLL files 4 | __pycache__/ 5 | *.py[cod] 6 | *$py.class 7 | 8 | # C extensions 9 | *.so 10 | 11 | # Distribution / packaging 12 | .Python 13 | env/ 14 | build/ 15 | develop-eggs/ 16 | dist/ 17 | downloads/ 18 | eggs/ 19 | .eggs/ 20 | lib/ 21 | lib64/ 22 | parts/ 23 | sdist/ 24 | var/ 25 | wheels/ 26 | *.egg-info/ 27 | .installed.cfg 28 | *.egg 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *,cover 49 | .hypothesis/ 50 | 51 | # Translations 52 | *.mo 53 | *.pot 54 | 55 | # Django stuff: 56 | *.log 57 | local_settings.py 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # pyenv 76 | .python-version 77 | 78 | # celery beat schedule file 79 | celerybeat-schedule 80 | 81 | # SageMath parsed files 82 | *.sage.py 83 | 84 | # dotenv 85 | .env 86 | 87 | # virtualenv 88 | .venv 89 | venv/ 90 | ENV/ 91 | 92 | # Spyder project settings 93 | .spyderproject 94 | 95 | # Rope project settings 96 | .ropeproject 97 | 98 | # ignore DB file 99 | *.db 100 | 101 | helper_const.py 102 | nohup.out 103 | -------------------------------------------------------------------------------- /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 | . -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Channel Helper Bot 2 | 3 | Channel Helper Bot 是一个 Telegram Bot,用于给频道添加简单的评论功能。Channel Helper Bot 的功能包括:在频道中创建评论区、收集用户评论和显示最近评论等。使用 Channel Helper Bot 能够为频道提供一个评论的平台,实现轻度的社交功能,有助于促进频道主与关注者、关注者和关注者之间直接的交流和沟通。 4 | 5 | ## 特性 6 | 7 | ### 简单的评论管理 8 | 9 | 在频道主发布了新的消息后,仅需要通过简单的操作即可呼出评论区。当频道消息对应的评论区出现在频道中时,关注者即可进行评论操作。 10 | 11 | 在自动模式下,频道主发布完消息后,无需任何操作,评论区会自动出现。 12 | 13 | 在手动模式下,频道主发布完消息后,仅需要以 `/command` 指令回复发布的消息,就可出现评论区。 14 | 15 | ### 方便的评论过程 16 | 17 | 每一个评论区都有两个按钮,“添加评论”和“显示所有评论”。点击按钮即自动跳转到 Channel Helper Bot 页面,按照提示进行操作即可完成评论和浏览。 18 | 19 | 在点击“添加评论”之后,即进入评论模式,向 bot 写下想说的话即可发布评论。如需退出评论模式,请使用 `/cancel` 命令。 20 | 21 | 在点击“显示所有评论”之后,bot 会在私聊页面显示一个可翻页的评论区,用户能够查看所有之前的评论信息(支持查看贴纸、图片、视频、文件等),管理员可以在这里进行删除消息、封禁用户的操作。 22 | 23 | ### 轻松的配置流程 24 | 25 | 配置过程十分简单,频道主只需几个步骤即可轻松完成 Channel Helper Bot 的配置。 26 | 27 | 1. 将 bot 添加为频道的管理员,同时 bot 需要足够的权限进行消息的发送和编辑。 28 | 29 | 2. 向 bot 私聊发送 `/register` 命令,按照 bot 的指示从频道中转发一条消息,用以记录频道的相关信息。 30 | 31 | 3. 发布一条消息看看吧!如果自动呼出评论区了则说明配置成功。(注:默认情况下 bot 为自动模式) 32 | 33 | 4. 如果您需要修改配置(模式、最近消息条数等),请向 bot 发送 `/option`命令,按照提示进行配置。 34 | 35 | ### 智慧的一物多用 36 | 37 | Channel Helper Bot 并不满足于只服务一个频道。任何人都可以通过配置来添加和使用 Channel Helper Bot。同时 bot 本身也是开源的,您可以根据自己的需要另行部署。[@jogle_channel_bot](https://t.me/jogle_channel_bot) 是作者进行部署的最新版 Bot,欢迎使用。 38 | 39 | ## 部署 40 | 41 | 为了能运行 Channel Helper Bot,需要准备一个 Python 3 的环境,并需要使用 pip安装相应的依赖。 42 | 43 | ### 安装依赖 44 | 45 | `pip3 install python-telegram-bot` 46 | 47 | ### 配置文件 48 | 49 | 请将 `helper_const.py.sample` 重命名为 `helper_const.py`,并填写其中的配置项目。 50 | 51 | | 配置项目 | 类型 | 含义 52 | |----------------------|---------------|-------------------------------------------------- 53 | | BOT_TOKEN | (str) | Telegram Bot 的 token 54 | | BOT_OWNER | (list of int) | bot 管理员的 userID 55 | | MIN_REFRESH_INTERVAL | (int) | 最小刷新时间间隔,单位为秒 56 | | MODULE_NAME | (list of str) | 启用的模块名称(如无特殊需求,则不需要更改这项) 57 | | DATABASE_DIR | (str) | 数据库存放位置 58 | ------------------------------------------------------------------------------------------ 59 | 60 | ### 运行 bot 61 | 62 | `python3 helper_main.py` 63 | 64 | ## 致谢 65 | 66 | Channel Helper Bot 使用了 [python-telegram-bot](https://github.com/python-telegram-bot/python-telegram-bot) 的 Bot API。 67 | -------------------------------------------------------------------------------- /helper_const.py.sample: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ Channel Helper Bot """ 5 | """ helper_const.py """ 6 | """ Copyright 2018, Jogle Lew """ 7 | 8 | BOT_TOKEN = 'Bot Token Here' 9 | BOT_OWNER = [Bot Owner 1 UserID, Bot Owner 2 UserID] 10 | MIN_REFRESH_INTERVAL = 3 11 | MODULE_NAME = ['start_cmd', 'help_cmd', 'cancel_cmd', 'sql_cmd', 'clean_cmd', 'register_cmd', 'option_cmd', 'channel_msg', 'private_msg', 'callback_query', 'inline_query'] 12 | DATABASE_DIR = "." 13 | DEFAULT_LANG = "zh-CN" 14 | LANG_LIST = ["zh-CN", "pt-BR", "en-US"] 15 | LANG_WIDTH = 3 16 | DEFAULT_BUTTONS = ["👍", "👎"] 17 | -------------------------------------------------------------------------------- /helper_database.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ Channel Helper Bot """ 5 | """ helper_database.py """ 6 | """ Copyright 2018, Jogle Lew """ 7 | import os 8 | import sqlite3 9 | import helper_const 10 | import helper_global 11 | from threading import Lock 12 | 13 | def init_database(filepath): 14 | conn = sqlite3.connect(filepath, check_same_thread=False) 15 | helper_global.assign("database", conn) 16 | cursor = conn.cursor() 17 | cursor.execute( 18 | """ 19 | CREATE TABLE config ( 20 | chat_id text PRIMARY KEY, 21 | lang text, 22 | mode int, 23 | recent int, 24 | username text, 25 | admin_id text, 26 | notify int, 27 | button int 28 | ); 29 | """ 30 | ) 31 | cursor.execute( 32 | """ 33 | CREATE TABLE reflect ( 34 | chat_id text, 35 | msg_id text, 36 | comment_id text, 37 | PRIMARY KEY (chat_id, msg_id) 38 | ); 39 | """ 40 | ) 41 | cursor.execute( 42 | """ 43 | CREATE TABLE button ( 44 | chat_id text, 45 | msg_id text, 46 | options text, 47 | PRIMARY KEY (chat_id, msg_id) 48 | ); 49 | """ 50 | ) 51 | cursor.execute( 52 | """ 53 | CREATE TABLE record ( 54 | chat_id text, 55 | msg_id text, 56 | username text, 57 | name text, 58 | type text, 59 | content text, 60 | media_id text, 61 | date text, 62 | user_id text, 63 | ori_msg_id text 64 | ); 65 | """ 66 | ) 67 | cursor.execute( 68 | """ 69 | CREATE TABLE blacklist ( 70 | chat_id text, 71 | user_id text, 72 | name text, 73 | PRIMARY KEY (chat_id, user_id) 74 | ); 75 | """ 76 | ) 77 | cursor.execute( 78 | """ 79 | CREATE TABLE reaction ( 80 | chat_id text, 81 | msg_id text, 82 | user_id text, 83 | option int, 84 | PRIMARY KEY (chat_id, msg_id, user_id) 85 | ); 86 | """ 87 | ) 88 | cursor.execute("CREATE INDEX record_chat_id_msg_id on record (chat_id, msg_id);") 89 | cursor.execute("CREATE INDEX record_user_id_ori_msg_id on record (user_id, ori_msg_id);") 90 | conn.commit() 91 | 92 | 93 | def execute(sql, params): 94 | lock.acquire() 95 | try: 96 | conn = helper_global.value("database", None) 97 | if conn is None: 98 | return 99 | cursor = conn.cursor() 100 | result = cursor.execute(sql, params) 101 | conn.commit() 102 | except Exception as e: 103 | lock.release() 104 | raise e 105 | lock.release() 106 | return result 107 | 108 | 109 | def get_channel_config(chat_id): 110 | script = "SELECT * FROM config WHERE chat_id = ?" 111 | params = [str(chat_id)] 112 | result = list(execute(script, params)) 113 | if len(result) == 0: 114 | return None 115 | return result[0] 116 | 117 | 118 | def delete_channel_config(chat_id): 119 | script = "DELETE FROM config WHERE chat_id = ?" 120 | params = [str(chat_id)] 121 | result = list(execute(script, params)) 122 | return result 123 | 124 | 125 | def get_all_channel_config(): 126 | script = "SELECT * FROM config" 127 | params = [] 128 | result = list(execute(script, params)) 129 | return result 130 | 131 | 132 | def add_channel_config(channel_id, lang, mode, recent, channel_username, admin_id, notify, button): 133 | script = "INSERT INTO config VALUES (?, ?, ?, ?, ?, ?, ?, ?)" 134 | params = [str(channel_id), lang, mode, recent, channel_username, str(admin_id), notify, button] 135 | execute(script, params) 136 | 137 | 138 | def update_config_by_channel(channel_id, item, value): 139 | script = "UPDATE config SET %s = ? WHERE chat_id = ?" % item 140 | params = [value, str(channel_id)] 141 | execute(script, params) 142 | 143 | 144 | def add_button_options(chat_id, msg_id, options): 145 | script = "DELETE FROM button WHERE chat_id = ? AND msg_id = ?" 146 | params = [str(chat_id), str(msg_id)] 147 | execute(script, params) 148 | script = "INSERT INTO button VALUES (?, ?, ?)" 149 | params = [str(chat_id), str(msg_id), " ".join(options)] 150 | execute(script, params) 151 | 152 | 153 | def get_button_options(chat_id, msg_id): 154 | script = "SELECT options FROM button WHERE chat_id = ? AND msg_id = ?" 155 | params = [str(chat_id), str(msg_id)] 156 | result = list(execute(script, params)) 157 | if len(result) > 0: 158 | return result[0][0].split() 159 | script = "SELECT options FROM button WHERE chat_id = ? AND msg_id = ?" 160 | params = [str(chat_id), str(0)] 161 | result = list(execute(script, params)) 162 | if len(result) > 0: 163 | return result[0][0].split() 164 | return helper_const.DEFAULT_BUTTONS 165 | 166 | 167 | def get_default_button_options(chat_id): 168 | script = "SELECT options FROM button WHERE chat_id = ? AND msg_id = ?" 169 | params = [str(chat_id), str(0)] 170 | result = list(execute(script, params)) 171 | if len(result) == 0: 172 | return helper_const.DEFAULT_BUTTONS 173 | return result[0][0].split() 174 | 175 | 176 | def add_reflect(chat_id, msg_id, comment_id): 177 | script = "DELETE FROM reflect WHERE chat_id = ? AND msg_id = ?" 178 | params = [str(chat_id), str(msg_id)] 179 | execute(script, params) 180 | script = "INSERT INTO reflect VALUES (?, ?, ?)" 181 | params = [str(chat_id), str(msg_id), str(comment_id)] 182 | execute(script, params) 183 | 184 | 185 | def check_reflect(chat_id, msg_id): 186 | script = "SELECT * FROM reflect WHERE chat_id = ? AND msg_id = ?" 187 | params = [str(chat_id), str(msg_id)] 188 | result = list(execute(script, params)) 189 | if len(result) == 0: 190 | return False 191 | return True 192 | 193 | 194 | def get_reflect_by_msg_id(chat_id, msg_id_or_comment_id): 195 | script = "SELECT * FROM reflect WHERE chat_id = ? AND (msg_id = ? OR comment_id = ?)" 196 | params = [str(chat_id), str(msg_id_or_comment_id), str(msg_id_or_comment_id)] 197 | result = list(execute(script, params)) 198 | if len(result) == 0: 199 | return None 200 | return result[0] 201 | 202 | 203 | def delete_reflect(chat_id, msg_id): 204 | script = "DELETE FROM reflect WHERE chat_id = ? AND msg_id = ?" 205 | params = [str(chat_id), str(msg_id)] 206 | execute(script, params) 207 | 208 | 209 | def add_record(channel_id, msg_id, username, name, msg_type, msg_content, media_id, date, user_id, ori_msg_id): 210 | if len(name) > 15: 211 | name = name[:15] + "..." 212 | script = "SELECT * FROM record WHERE user_id = ? AND ori_msg_id = ?" 213 | params = [str(user_id), str(ori_msg_id)] 214 | result = list(execute(script, params)) 215 | if len(result) == 0: 216 | script = "INSERT INTO record VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" 217 | params = [str(channel_id), str(msg_id), username, name, msg_type, msg_content, media_id, date, str(user_id), str(ori_msg_id)] 218 | execute(script, params) 219 | return 0 220 | else: 221 | script = "UPDATE record SET type = ?, content = ?, media_id = ? WHERE user_id = ? AND ori_msg_id = ?" 222 | params = [msg_type, msg_content, media_id, str(user_id), str(ori_msg_id)] 223 | execute(script, params) 224 | return 1 225 | 226 | 227 | def get_comment_id(channel_id, msg_id): 228 | script = "SELECT comment_id FROM reflect WHERE chat_id = ? and msg_id = ?" 229 | params = [str(channel_id), str(msg_id)] 230 | result = list(execute(script, params)) 231 | if len(result) == 0: 232 | return None 233 | comment_id = int(result[0][0]) 234 | return comment_id 235 | 236 | 237 | def get_origin_post(channel_id, msg_id): 238 | script = "SELECT comment_id FROM reflect WHERE chat_id = ? and msg_id = ?" 239 | params = [str(channel_id), str(msg_id)] 240 | result = list(execute(script, params)) 241 | if len(result) == 0: 242 | return None 243 | comment_id = result[0][0] 244 | return comment_id 245 | 246 | 247 | def get_recent_records(channel_id, msg_id, recent, offset=0): 248 | script = "SELECT *, ROWID FROM record WHERE chat_id = ? and msg_id = ? ORDER BY date DESC LIMIT ? OFFSET ?" 249 | params = [str(channel_id), str(msg_id), recent, offset * recent] 250 | result = list(execute(script, params)) 251 | return result 252 | 253 | 254 | def get_record_by_rowid(row_id): 255 | script = "SELECT * FROM record WHERE ROWID = ?" 256 | params = [row_id] 257 | result = list(execute(script, params)) 258 | return result 259 | 260 | 261 | def delete_record_by_rowid(row_id): 262 | script = "DELETE FROM record WHERE ROWID = ?" 263 | params = [row_id] 264 | result = list(execute(script, params)) 265 | return result 266 | 267 | 268 | def get_base_offset_by_rowid(channel_id, msg_id, row_id): 269 | script = "SELECT count(*) FROM record WHERE chat_id = ? AND msg_id = ? AND ROWID >= ?" 270 | params = [str(channel_id), str(msg_id), row_id] 271 | result = list(execute(script, params)) 272 | return result[0][0] 273 | 274 | 275 | def get_prev_rowid(channel_id, msg_id, row_id): 276 | script = "SELECT ROWID FROM record WHERE chat_id = ? AND msg_id = ? AND ROWID > ? ORDER BY ROWID ASC LIMIT 1" 277 | params = [str(channel_id), str(msg_id), row_id] 278 | result = list(execute(script, params)) 279 | if result is not None and len(result) == 1: 280 | return result[0][0] 281 | return -1 282 | 283 | 284 | def get_next_rowid(channel_id, msg_id, row_id): 285 | script = "SELECT ROWID FROM record WHERE chat_id = ? AND msg_id = ? AND ROWID < ? ORDER BY ROWID DESC LIMIT 1" 286 | params = [str(channel_id), str(msg_id), row_id] 287 | result = list(execute(script, params)) 288 | if result is not None and len(result) == 1: 289 | return result[0][0] 290 | return -1 291 | 292 | 293 | def get_channel_info_by_user(user_id): 294 | script = "SELECT chat_id, username FROM config WHERE admin_id = ?" 295 | params = [str(user_id)] 296 | result = list(execute(script, params)) 297 | return result 298 | 299 | 300 | def ban_user(channel_id, user_id, name): 301 | script = "INSERT INTO blacklist VALUES (?, ?, ?)" 302 | params = [str(channel_id), str(user_id), name] 303 | result = list(execute(script, params)) 304 | return result 305 | 306 | 307 | def unban_user(channel_id, user_id, name): 308 | script = "DELETE FROM blacklist WHERE chat_id = ? AND user_id = ?" 309 | params = [str(channel_id), str(user_id)] 310 | result = list(execute(script, params)) 311 | return result 312 | 313 | 314 | def check_ban(channel_id, user_id): 315 | script = "SELECT * FROM blacklist WHERE chat_id = ? AND user_id = ?" 316 | params = [str(channel_id), str(user_id)] 317 | result = list(execute(script, params)) 318 | return len(result) > 0 319 | 320 | 321 | def add_reaction(channel_id, msg_id, user_id, like_id): 322 | script = "SELECT count(*) FROM reaction WHERE chat_id = ? AND msg_id = ? AND user_id = ?" 323 | params = [str(channel_id), str(msg_id), str(user_id)] 324 | result = list(execute(script, params))[0][0] 325 | if result == 0: 326 | script = "INSERT INTO reaction VALUES(?, ?, ?, ?)" 327 | params = [str(channel_id), str(msg_id), str(user_id), like_id] 328 | else: 329 | script = "UPDATE reaction SET option = ? WHERE chat_id = ? AND msg_id = ? AND user_id = ?" 330 | params = [like_id, str(channel_id), str(msg_id), str(user_id)] 331 | execute(script, params) 332 | 333 | 334 | def get_reaction_stat(channel_id, msg_id): 335 | script = "SELECT option, count(*) FROM reaction WHERE chat_id = ? AND msg_id = ? GROUP BY option" 336 | params = [str(channel_id), str(msg_id)] 337 | result = list(execute(script, params)) 338 | r = {} 339 | for like_id, count in result: 340 | r[like_id] = count 341 | return r 342 | 343 | 344 | def clear_reaction(channel_id, msg_id): 345 | script = "DELETE FROM reaction WHERE chat_id = ? AND msg_id = ?" 346 | params = [str(channel_id), str(msg_id)] 347 | result = list(execute(script, params)) 348 | return result 349 | 350 | 351 | lock = Lock() 352 | filepath = os.path.join(helper_const.DATABASE_DIR, "data.db") 353 | if not os.path.exists(filepath): 354 | init_database(filepath) 355 | else: 356 | conn = sqlite3.connect(filepath, check_same_thread=False) 357 | helper_global.assign("database", conn) 358 | 359 | -------------------------------------------------------------------------------- /helper_global.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ Channel Helper Bot """ 5 | """ helper_global.py """ 6 | """ Copyright 2018, Jogle Lew """ 7 | import helper_const 8 | from threading import Lock 9 | from telegram import InlineKeyboardButton, InlineKeyboardMarkup 10 | 11 | lock = Lock() 12 | 13 | class GlobalVar: 14 | var_set = {} 15 | 16 | 17 | def assign(var_name, var_value, lang=helper_const.DEFAULT_LANG): 18 | lock.acquire() 19 | if not lang in GlobalVar.var_set: 20 | GlobalVar.var_set[lang] = {} 21 | GlobalVar.var_set[lang][var_name] = var_value 22 | lock.release() 23 | 24 | 25 | def value(var_name, default_value, lang=helper_const.DEFAULT_LANG): 26 | if lang == "all": 27 | result = "" 28 | for lang_item in helper_const.LANG_LIST: 29 | result += value(var_name, default_value, lang=lang_item) + "\n\n" 30 | return result 31 | if not lang in GlobalVar.var_set: 32 | lang = helper_const.DEFAULT_LANG 33 | lock.acquire() 34 | if not var_name in GlobalVar.var_set[lang]: 35 | GlobalVar.var_set[lang][var_name] = default_value 36 | result = GlobalVar.var_set[lang][var_name] 37 | lock.release() 38 | return result 39 | 40 | 41 | def get_sender_name(message): 42 | real_sender = message.from_user 43 | if message.forward_from: 44 | real_sender = message.forward_from 45 | username = real_sender.first_name 46 | if real_sender.last_name: 47 | username = username + " " + real_sender.last_name 48 | if message.forward_from_chat: 49 | username = message.forward_from_chat.title 50 | return username 51 | 52 | 53 | def records_to_str(records, lang): 54 | s = value("comment_header", "", lang=lang) + "\n" 55 | if records is None or len(records) == 0: 56 | s += value("comment_empty", "", lang=lang) 57 | return s 58 | records = records[::-1] 59 | for record in records: 60 | username = record[2] 61 | name = record[3].replace('<', '<').replace('>', '>') 62 | msg_type = record[4] 63 | msg_content = record[5] 64 | s += ("%s: " % name) 65 | if not msg_type == "text": 66 | s += ("[%s] " % msg_type) 67 | s += msg_content + "\n" 68 | return s 69 | 70 | 71 | def records_to_buttons(records, channel_id, msg_id): 72 | b = [] 73 | if records is None or len(records) == 0: 74 | return b 75 | records = records[::-1] 76 | for idx, record in enumerate(records): 77 | username = record[2] 78 | name = record[3] 79 | msg_type = record[4] 80 | msg_content = record[5] 81 | row_id = record[10] 82 | s = ("%s: " % name) 83 | if not msg_type == "text": 84 | s += ("[%s] " % msg_type) 85 | s += msg_content 86 | button = [[ 87 | InlineKeyboardButton( 88 | s, 89 | callback_data="msg_detail,%d,%d,%d" % (channel_id, msg_id, row_id) 90 | ) 91 | ]] 92 | b += button 93 | return b 94 | 95 | 96 | def parse_entity(src, entity_list): 97 | if entity_list is None or len(entity_list) == 0: 98 | return src.replace('<', '<').replace('>', '>') 99 | 100 | head = 0 101 | p_str = "" 102 | for entity in entity_list: 103 | begin_str = '' 104 | end_str = '' 105 | if entity.type == 'bold': 106 | begin_str = '' 107 | end_str = '' 108 | elif entity.type == 'code': 109 | begin_str = '' 110 | end_str = '' 111 | elif entity.type == 'italic': 112 | begin_str = '' 113 | end_str = '' 114 | elif entity.type == 'strikethrough': 115 | begin_str = '' 116 | end_str = '' 117 | elif entity.type == 'pre': 118 | begin_str = '
'
119 |             end_str = '
' 120 | elif entity.type == 'text_link': 121 | begin_str = '' % entity.url 122 | end_str = '' 123 | p_str += src[head:entity.offset].replace('<', '<').replace('>', '>') 124 | p_str += begin_str 125 | p_str += src[entity.offset:(entity.offset + entity.length)].replace('<', '<').replace('>', '>') 126 | p_str += end_str 127 | head = entity.offset + entity.length 128 | p_str += src[head:] 129 | return p_str 130 | 131 | 132 | def send_intro_template(bot, chat_id, lang, key, text_key): 133 | # Prepare Keyboard 134 | lang_list = helper_const.LANG_LIST 135 | width = helper_const.LANG_WIDTH 136 | current_lang = lang 137 | motd_keyboard = [[ 138 | InlineKeyboardButton( 139 | lang_list[width * idx + delta] + (" (*)" if lang_list[width * idx + delta] == current_lang else ""), 140 | callback_data="%s|%s" % (key, lang_list[width * idx + delta]) 141 | ) for delta in range(width) 142 | ] for idx in range(len(lang_list) // width)] + [[ 143 | InlineKeyboardButton( 144 | lang_list[idx] + (" (*)" if lang_list[idx] == current_lang else ""), 145 | callback_data="%s|%s" % (key, lang_list[idx]) 146 | ) 147 | for idx in range(width * (len(lang_list) // width), len(lang_list))]] 148 | 149 | motd_markup = InlineKeyboardMarkup(motd_keyboard) 150 | bot.send_message( 151 | chat_id=chat_id, 152 | text=value(text_key, "", lang=current_lang), 153 | reply_markup=motd_markup 154 | ) 155 | -------------------------------------------------------------------------------- /helper_main.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ Channel Helper Bot """ 5 | """ helper_main.py """ 6 | """ Copyright 2018, Jogle Lew """ 7 | import json 8 | import logging 9 | import traceback 10 | import importlib 11 | import datetime 12 | import helper_global 13 | import helper_database 14 | import telegram 15 | import telegram.bot 16 | import messagequeue as mq 17 | from telegram.ext import Updater, CommandHandler 18 | from telegram.utils.request import Request 19 | from ninesix import Logger 20 | 21 | # config logger 22 | logger = Logger("channel_helper", log_level=0, preserve=True) 23 | 24 | # import constant, strings, database 25 | helper_const = importlib.import_module('helper_const') 26 | helper_string = importlib.import_module('helper_string') 27 | helper_database = importlib.import_module('helper_database') 28 | 29 | # load admin list 30 | helper_global.assign('admin_list', []) 31 | 32 | 33 | def reload_admin_list(): 34 | global admin_list 35 | admin_list = helper_const.BOT_OWNER 36 | helper_global.assign('admin_list', admin_list) 37 | 38 | 39 | reload_admin_list() 40 | logger.msg("Admin List: " + str(helper_global.value('admin_list', [])), "main", log_level=100) 41 | 42 | # config bot 43 | class MQBot(telegram.bot.Bot): 44 | '''A subclass of Bot which delegates send method handling to MQ''' 45 | def __init__(self, *args, is_queued_def=True, mqueue=None, **kwargs): 46 | super(MQBot, self).__init__(*args, **kwargs) 47 | # below 2 attributes should be provided for decorator usage 48 | self._is_messages_queued_default = is_queued_def 49 | self._msg_queue = mqueue or mq.MessageQueue() 50 | 51 | def __del__(self): 52 | try: 53 | self._msg_queue.stop() 54 | except: 55 | pass 56 | super(MQBot, self).__del__() 57 | 58 | @mq.queuedmessage 59 | def send_message(self, *args, **kwargs): 60 | '''Wrapped method would accept new `queued` and `isgroup` 61 | OPTIONAL arguments''' 62 | return super(MQBot, self).send_message(*args, **kwargs) 63 | 64 | @mq.queuedmessage 65 | def send_audio(self, *args, **kwargs): 66 | '''Wrapped method would accept new `queued` and `isgroup` 67 | OPTIONAL arguments''' 68 | return super(MQBot, self).send_audio(*args, **kwargs) 69 | 70 | @mq.queuedmessage 71 | def send_document(self, *args, **kwargs): 72 | '''Wrapped method would accept new `queued` and `isgroup` 73 | OPTIONAL arguments''' 74 | return super(MQBot, self).send_document(*args, **kwargs) 75 | 76 | @mq.queuedmessage 77 | def send_photo(self, *args, **kwargs): 78 | '''Wrapped method would accept new `queued` and `isgroup` 79 | OPTIONAL arguments''' 80 | return super(MQBot, self).send_photo(*args, **kwargs) 81 | 82 | @mq.queuedmessage 83 | def send_sticker(self, *args, **kwargs): 84 | '''Wrapped method would accept new `queued` and `isgroup` 85 | OPTIONAL arguments''' 86 | return super(MQBot, self).send_sticker(*args, **kwargs) 87 | 88 | @mq.queuedmessage 89 | def send_video(self, *args, **kwargs): 90 | '''Wrapped method would accept new `queued` and `isgroup` 91 | OPTIONAL arguments''' 92 | return super(MQBot, self).send_video(*args, **kwargs) 93 | 94 | @mq.queuedmessage 95 | def send_voice(self, *args, **kwargs): 96 | '''Wrapped method would accept new `queued` and `isgroup` 97 | OPTIONAL arguments''' 98 | return super(MQBot, self).send_voice(*args, **kwargs) 99 | 100 | @mq.queuedmessage 101 | def edit_message_text(self, *args, **kwargs): 102 | '''Wrapped method would accept new `queued` and `isgroup` 103 | OPTIONAL arguments''' 104 | return super(MQBot, self).edit_message_text(*args, **kwargs) 105 | 106 | @mq.queuedmessage 107 | def edit_message_reply_markup(self, *args, **kwargs): 108 | '''Wrapped method would accept new `queued` and `isgroup` 109 | OPTIONAL arguments''' 110 | return super(MQBot, self).edit_message_reply_markup(*args, **kwargs) 111 | 112 | @mq.queuedmessage 113 | def get_chat_administrators(self, *args, **kwargs): 114 | '''Wrapped method would accept new `queued` and `isgroup` 115 | OPTIONAL arguments''' 116 | return super(MQBot, self).get_chat_administrators(*args, **kwargs) 117 | 118 | 119 | q = mq.MessageQueue(all_burst_limit=3, all_time_limit_ms=3000) 120 | request = Request(con_pool_size=8) 121 | bot = MQBot(token=helper_const.BOT_TOKEN, request=request, mqueue=q) 122 | logger.msg(bot.get_me(), tag="main", log_level=100) 123 | bot_username = bot.get_me().username 124 | helper_global.value('bot', bot) 125 | helper_global.value('bot_username', bot_username) 126 | updater = Updater(bot=bot, request_kwargs={'read_timeout': 6, 'connect_timeout': 7}, use_context=False) 127 | dispatcher = updater.dispatcher 128 | job_queue = updater.job_queue 129 | 130 | 131 | def check_admin(check_id): 132 | admin_list = helper_global.value('admin_list', []) 133 | if check_id in admin_list: 134 | return True 135 | return False 136 | 137 | 138 | # initial reload command 139 | def bot_reload(bot, update): 140 | global helper_const 141 | global helper_string 142 | global helper_database 143 | global command_module 144 | if not check_admin(update.message.from_user.id): 145 | permission_denied = helper_global.value("permission_denied_text", "") 146 | bot.send_message(chat_id=update.message.chat_id, text=permission_denied) 147 | return 148 | 149 | ## update constant 150 | helper_const = importlib.reload(helper_const) 151 | helper_string = importlib.reload(helper_string) 152 | helper_database = importlib.reload(helper_database) 153 | reload_admin_list() 154 | 155 | ## remove old handlers 156 | for current_module in command_module: 157 | dispatcher.remove_handler(current_module._handler) 158 | 159 | ## reload modules and update handlers 160 | try: 161 | command_module = [] 162 | for module_name in helper_const.MODULE_NAME: 163 | logger.msg("Reloading module \"%s\"..." % module_name, tag="main", log_level=100) 164 | current_module = importlib.import_module("modules." + module_name) 165 | current_module = importlib.reload(current_module) 166 | command_module.append(current_module) 167 | dispatcher.add_handler(current_module._handler) 168 | 169 | success_text = helper_global.value("reload_cmd_success", "") 170 | bot.send_message(chat_id=update.message.chat_id, text=success_text) 171 | except Exception as e: 172 | failed_text = helper_global.value("reload_cmd_failed", "") 173 | bot.send_message(chat_id=update.message.chat_id, text=failed_text) 174 | bot.send_message(chat_id=update.message.chat_id, text=traceback.print_exc()) 175 | 176 | reload_handler = CommandHandler('reload', bot_reload) 177 | dispatcher.add_handler(reload_handler) 178 | 179 | # initial other commands 180 | command_module = [] 181 | for module_name in helper_const.MODULE_NAME: 182 | logger.msg("Loading module \"%s\"..." % module_name, tag="main", log_level=100) 183 | current_module = importlib.import_module("modules." + module_name) 184 | command_module.append(current_module) 185 | dispatcher.add_handler(current_module._handler) 186 | 187 | def error(bot, update, error): 188 | logger.msg("Update: %s, Error: %s" % (update, error), tag="error", log_level=100) 189 | 190 | 191 | dispatcher.add_error_handler(error) 192 | 193 | updater.start_polling() 194 | -------------------------------------------------------------------------------- /helper_string.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ Channel Helper Bot """ 5 | """ helper_string.py """ 6 | """ Copyright 2018, Jogle Lew """ 7 | 8 | import json 9 | import helper_const 10 | import helper_global 11 | 12 | lang_config = helper_const.LANG_LIST 13 | 14 | for lang_code in lang_config: 15 | with open("i18n/%s.json" % lang_code, "r") as f: 16 | lang_dict = json.load(f) 17 | for item, value in lang_dict.items(): 18 | helper_global.assign(item, value, lang=lang_code) 19 | -------------------------------------------------------------------------------- /i18n/en-US.json: -------------------------------------------------------------------------------- 1 | { 2 | "development_text": "This feature is under development...", 3 | "permission_denied_text": "No Permission", 4 | "reload_cmd_success": "Reloaded. Good luck.", 5 | "reload_cmd_failed": "Problem occurred when reloading.", 6 | "start_cmd_text": "This is Jogle Lew's Channel Helper Bot. Use /help command for more information.", 7 | "help_cmd_text": "Thanks for choosing Channel Helper Bot. This bot can manage and display comments in your channel, providing a new way of communication between channel owner and subscribers. The code of Channel Helper Bot is available on Github: https://github.com/JogleLew/channel-helper-bot\nBy using this bot, you allow the bot send, edit and delete messages in your channel, as well as collect and store users' comments. \nHow to use:\n1. Add this bot to your channel as an admin. \n2. Send /register command to enable the comment feature in your channel\n3. Done. Use /option command to config", 8 | "add_comment": "Add Comment", 9 | "show_all_comments": "Show All Comments", 10 | "comment_header": "===== Comments =====", 11 | "comment_empty": "", 12 | "start_comment_mode": "[Enter Comment Mode] leave a comment by sending me a message. Use Inline Query to reply a comment. Use /cancel to quit comment mode", 13 | "stop_comment_mode": "[Quit Comment Mode]", 14 | "comment_success": "[Comment Successfully]", 15 | "comment_edit_success": "[Edit Successfully]", 16 | "prev_page": "Prev Page", 17 | "next_page": "Next Page", 18 | "no_prev_page": "No previous page", 19 | "no_next_page": "No next page", 20 | "register_cmd_text": "Please make sure you add this bot to your channel as an admin (Channel Settings -> Add Admin -> Search bot's username -> Click), and grant the permissions of Send, Edit and Delete Messages to the bot. Then forward an original message (the message itself shouldn't be an forwarded message) from your channel to the bot.", 21 | "register_cmd_invalid": "This message contains no channel info. Please forward me an original message from your channel.", 22 | "register_cmd_not_admin": "You are not the channel admin, so you're not allowed to register.", 23 | "register_cmd_no_permission": "Permission check error. Make sure you grant the permissions of Send, Edit and Delete Messages to the bot and register again.", 24 | "register_cmd_no_info": "This bot cannot access your channel. Please check whether the bot is an admin of your channel.", 25 | "register_cmd_failed": "Registration Failed. Maybe you've already registered. Please contact the developer @JogleLew for further assistance.", 26 | "register_cmd_success": "Registered Successfully. Default config is applied to your channel. Use /option command to modify your config.", 27 | "option_no_channel": "No registration info found. Please use /register command first.", 28 | "option_delete": "Delete registration", 29 | "option_record_deleted": "Registration record is deleted. Thanks for your using!", 30 | "option_back": "Go back", 31 | "option_finish": "Finish", 32 | "option_finished": "Config updated.", 33 | "option_choose_channel": "Please choose a channel to config.", 34 | "option_choose_item": "Now, you can modify these items\nmode: working mode of the bot\nrecent: the maximum number of comments shown in channel\nnotify: receive notifications when new comments occur\nlang: language of comment buttons and text in your channel\nbutton: how to display Like buttons", 35 | "option_choose_mode_value": "There are 3 modes.\nMode 0: Manual Mode. No commment message will appear automatically, unless the channel admin reply the channel post with /comment .\nMode 1: Auto Mode. The bot adds comment message automatically, without modifying original post. \nMode 2: Auto Mode (beta). The bot modifies the channel post to add comment buttons, or add comment message if failed. Using this mode can reduce the number of blank comment message.\nPlease choose the working mode: ", 36 | "option_choose_recent_value": "In a comment message, only the most recent comments appear. Please choose the number of shown comments:", 37 | "option_choose_notify_value": "You can choose whether you will receive a notification if new comment comes. 0 stands for no, 1 stands for yes.", 38 | "option_choose_lang_value": "Choose the language of comment buttons and text in your channel. Take effect when the next message is coming", 39 | "option_choose_button_value": "Please choose whether and how Like buttons work. \n0: Like buttons never appear.\n1: Like buttons appear automatically, default buttons are %s. You can send /defaultbuttons + blank-seperated text in your channel to change the default buttons.\n2: manual mode. You can customize buttons in this mode.\nIn mode 1 and mode 2, reply the channel post with /comment + blank-seperated text, then new Like buttons will be added/replaced below the channel post. e.g. If you use the command \"/comment I ❤️ you\", you will get 3 buttons: \"I\", \"❤️\" and \"you\"", 40 | "option_update_success": "Config updated", 41 | "option_update_failed": "Failed to update config", 42 | "clean_cmd_start": "Now checking, Please wait...", 43 | "clean_cmd_deleted": "Registration record deleted", 44 | "clean_cmd_set": "Auto schedule set", 45 | "fwd_source": "From: ", 46 | "prev_msg": "Prev Comment", 47 | "next_msg": "Next Comment", 48 | "no_message_detail": "No comment detail found", 49 | "back_to_msg_list": "Back to comment list", 50 | "msg_from": "From: ", 51 | "delete_msg": "Delete Comment", 52 | "delete_success": "Comment deleted.", 53 | "ban_user": "Ban User", 54 | "unban_user": "Unban User", 55 | "user_banned": "User banned.", 56 | "user_banned_failed": "Failed to ban this user. This user might have been banned.", 57 | "user_unbanned": "User unbanned.", 58 | "banned_prompt": "You are not allowed to leave comments in this channel.", 59 | "new_comment_message": "New comment received.", 60 | "new_reply_message": "New reply received.", 61 | "target_message": "Target message: ", 62 | "like_recorded": "You %s it.", 63 | "comment_refreshing": "Refreshing...", 64 | "reply_to": "Reply to ", 65 | "reply_prompt": "Write comment first, then choose a comment to reply.", 66 | "jump_to_comment": "Go to Comments" 67 | } 68 | -------------------------------------------------------------------------------- /i18n/pt-BR.json: -------------------------------------------------------------------------------- 1 | { 2 | "development_text": "Esta função ainda está em desenvolvimento...", 3 | "permission_denied_text": "Sem permissão", 4 | "reload_cmd_success": "Recarregado. Boa sorte.", 5 | "reload_cmd_failed": "Ocorreu um problema ao recarregar.", 6 | "start_cmd_text": "Este é o bot Channel Helper de Jogle Lew. Use o comando /help para obter mais informações.", 7 | "help_cmd_text": "Obrigado por escolher o bot Channel Helper. Esse bot pode gerenciar e exibir comentários em seu canal, fornecendo uma nova maneira de comunicação entre o dono e seus inscritos. O código do Channel Helper Bot está disponível no Github: https://github.com/JogleLew/channel-helper-bot\nAo usar esse bot, você permite que ele envie, edite e exclua mensagens em seu canal, além de coletar e armazene os comentários dos usuários. \nComo usar: \n1. Adicione este bot ao seu canal como administrador. \n2. Envie /register para ativar o recurso de comentário no seu canal\n3. Pronto. Use o comando /option para configurar", 8 | "add_comment": "Comentar", 9 | "show_all_comments": "Todos os comentários", 10 | "comment_header": "===== Comentários =====", 11 | "comment_empty": "", 12 | "start_comment_mode": "[Modo de comentário] Deixe um comentário enviando uma mensagem. Envie /cancel para sair deste modo.", 13 | "stop_comment_mode": "[Saiu do Modo de comentário]", 14 | "comment_success": "[Comentário enviado]", 15 | "comment_edit_success": "[Editado com sucesso]", 16 | "prev_page": "Página anterior", 17 | "next_page": "Próxima página", 18 | "no_prev_page": "Nenhuma página anterior", 19 | "no_next_page": "Nenhuma página seguinte", 20 | "register_cmd_text": "Certifique-se de adicionar este bot ao seu canal como administrador (Configurações do canal -> Adicionar administrador -> Pesquisar nome de usuário do bot -> Clique) e conceda as permissões para o bot de enviar, editar e excluir mensagens. Em seguida, encaminhe uma mensagem do seu canal para o bot.", 21 | "register_cmd_invalid": "Esta mensagem não contém informações do canal. Envie-me uma mensagem original do seu canal.", 22 | "register_cmd_not_admin": "Você não é o administrador do canal, portanto não tem permissão para se registrar.", 23 | "register_cmd_no_permission": "Erro na verificação de permissão. Certifique-se de conceder as permissões de enviar, editar e excluir mensagens ao bot e tente se registrar novamente.", 24 | "register_cmd_no_info": "Este bot não pode acessar seu canal. Verifique se o bot é um administrador do seu canal. ", 25 | "register_cmd_failed": "Falha no registro. Entre em contato com o desenvolvedor @JogleLew para obter ajuda.", 26 | "register_cmd_success": "Registrado com sucesso. A configuração padrão foi aplicada ao seu canal. Use o comando /option para modificar sua configuração.", 27 | "option_no_channel": "Nenhuma informação de registro encontrada. Por favor, use o comando /register antes.", 28 | "option_delete": "Excluir registro", 29 | "option_record_deleted": "O registro foi excluído. Obrigado pela sua utilização!", 30 | "option_back": "Voltar", 31 | "option_finish": "Concluir", 32 | "option_finished": "Configuração atualizada.", 33 | "option_choose_channel": "Por favor, escolha um canal para configurar.", 34 | "option_choose_item": "Agora, você pode modificar estes itens\nmode: modo de trabalho do bot\nrecent: o número máximo de comentários mostrados no canal\nnotify: receber notificações quando novos comentários ocorrerem\nlang: idioma dos botões de comentários e texto em seu canal", 35 | "option_choose_mode_value": "Existem 3 modos.\nModo 0: Modo manual. Nenhuma mensagem de comentário será exibida automaticamente, a menos que o administrador do canal responda à postagem do canal com /comment.\nModo 1: Modo automático. O bot adiciona mensagem de comentário automaticamente, sem modificar a postagem original.\nModo 2: Modo Automático (beta). O bot modifica a postagem do canal para adicionar botões de comentário ou adiciona a mensagem de comentário, se falhar. O uso desse modo pode reduzir o número de mensagens de comentários em branco.\nPor favor, escolha o modo de funcionamento: ", 36 | "option_choose_recent_value": "Em uma mensagem de comentário, apenas os comentários mais recentes serão exibidos. Por favor, escolha o número de comentários mostrados:", 37 | "option_choose_notify_value": "Você pode escolher se receberá uma notificação quando houver um novo comentário. 0 significa não, 1 significa sim.", 38 | "option_choose_lang_value": "Escolha o idioma dos botões de comentários e do texto em seu canal. Entrará em vigor quando a próxima mensagem for postada", 39 | "option_choose_button_value": "Por favor, escolha se e como os botões de reação irão funcionar.\n0: Os botões nunca aparecem.\n1: Os botões aparecem automaticamente. Os botões padrão são %s.\n2: Modo Manual. Você pode personalizar botões neste modo.\nPara escolher os botões de cada postagem (somente no modo 1 e no modo 2), responda à postagem do canal com /comment + \"caracteres separados com espaço\". Por exemplo, se você usar o comando \"/comment Eu ❤️ você\", a postagem terá 3 botões: \"Eu\", \"❤️\" e \"você\"", 40 | "option_update_success": "Configuração atualizada", 41 | "option_update_failed": "Falha ao atualizar a configuração", 42 | "clean_cmd_start": "Verificando. Por favor, aguarde...", 43 | "clean_cmd_deleted": "Registro excluído", 44 | "clean_cmd_set": "Agendamento automático definido", 45 | "fwd_source": "De: ", 46 | "prev_msg": "Comentário anterior", 47 | "next_msg": "Próximo comentário", 48 | "no_message_detail": "Nenhum comentário encontrado", 49 | "back_to_msg_list": "Voltar à lista de comentários", 50 | "msg_from": "De: ", 51 | "delete_msg": "Excluir comentário", 52 | "delete_success": "Comentário excluído.", 53 | "ban_user": "Banir usuário", 54 | "unban_user": "Desbanir usuário", 55 | "user_banned": "Usuário banido.", 56 | "user_banned_failed": "Falha ao banir este usuário. Este usuário pode já ter sido banido.", 57 | "user_unbanned": "Usuário desbanido.", 58 | "banned_prompt": "Você não tem permissão para comentar neste canal.", 59 | "new_comment_message": "Novo comentário recebido.", 60 | "new_reply_message": "Nova resposta recebida.", 61 | "target_message": "Mensagem de destino: ", 62 | "like_recorded": "Você enviou %s.", 63 | "comment_refreshing": "Atualizando...", 64 | "reply_to": "Responder para ", 65 | "jump_to_comment": "Go to Comments" 66 | } 67 | -------------------------------------------------------------------------------- /i18n/zh-CN.json: -------------------------------------------------------------------------------- 1 | { 2 | "development_text": "该功能正在开发中...", 3 | "permission_denied_text": "你怕不是假的 jogle", 4 | "reload_cmd_success": "重启好了,很棒棒哦!", 5 | "reload_cmd_failed": "嗯,好像出现了一些问题呢…", 6 | "start_cmd_text": "这是由 JogleLew 开发的频道回复助手 Bot 。你可以使用 /help 命令查看详细使用说明。", 7 | "help_cmd_text": "欢迎使用 Channel Helper Bot,本 bot 可以为您的频道提供回复和展示评论信息的入口,从而为频道提供互动的平台。\nGithub链接:https://github.com/JogleLew/channel-helper-bot\n使用此 bot 即为允许本 bot 在您的频道内进行发送、编辑和删除操作,并收集和存储评论信息。\n使用步骤:\n1. 将此 bot 添加为频道管理员。\n2. 使用 /register 命令登记您的频道信息。\n3. 完成。如需更改配置请使用 /option 命令。", 8 | "add_comment": "添加评论", 9 | "show_all_comments": "显示所有评论", 10 | "comment_header": "===== 评论区 =====", 11 | "comment_empty": "", 12 | "start_comment_mode": "[进入评论模式] 向我发送消息即可进行评论。使用 Inline Query 可以回复一条评论。使用 /cancel 命令可以中止评论模式。", 13 | "stop_comment_mode": "[退出评论模式]", 14 | "comment_success": "[评论成功]", 15 | "comment_edit_success": "[编辑评论成功]", 16 | "prev_page": "上一页", 17 | "next_page": "下一页", 18 | "no_prev_page": "没有上一页了", 19 | "no_next_page": "没有下一页了", 20 | "register_cmd_text": "请先将本 bot 添加为频道的管理员(注:只需要在频道设置中添加管理员,搜索本 bot 的 username,点击添加即可),并授予 bot 发送、编辑、删除消息的权限。然后从您的频道中转发一条消息(这条消息不能是转发的别处的消息)给我,以便我获取频道的 ID。", 21 | "register_cmd_invalid": "这条消息中似乎不包含频道信息呢...请从您的频道中转发一条消息给我", 22 | "register_cmd_not_admin": "您看起来不是频道的管理员呢,本 bot 无法为您进行登记", 23 | "register_cmd_no_permission": "检测到您没有给本 bot 提供发送、编辑、删除消息的权限。修改完权限后,请重新执行登记操作。", 24 | "register_cmd_no_info": "本 bot 无法获取您的频道信息,请检查是否已经将本 bot 添加为频道管理员。", 25 | "register_cmd_failed": "频道信息记录失败,您可能已经注册过。如有问题请联系管理员 @JogleLew", 26 | "register_cmd_success": "您的频道信息已成功记录,并启用了默认的评论设置。如需修改配置,请使用 /option 命令。", 27 | "option_no_channel": "您还没有登记过频道信息,请先使用 /register 命令完成登记。", 28 | "option_delete": "删除频道记录", 29 | "option_record_deleted": "频道记录已删除,感谢您的使用!", 30 | "option_back": "返回", 31 | "option_finish": "完成配置", 32 | "option_finished": "配置已完成", 33 | "option_choose_channel": "请选择一个频道以进行配置", 34 | "option_choose_item": "请选择一个项目以进行配置\nmode: bot 的工作模式\nrecent: 在频道中显示的评论数量\nnotify: 新评论提醒\nlang: 评论功能使用的语言\nbutton: 点赞按钮显示方式", 35 | "option_choose_mode_value": "本 bot 有三种工作模式\n模式 0: 手动模式。当频道中新增消息时,bot 不会自动创建评论消息。当频道管理员使用 /comment 回复需要评论的原始消息时,bot 才会创建评论消息。\n模式 1: 自动模式。当频道中新增消息时,bot 自动创建评论消息。该模式能保持原始频道消息不被修改。\n模式 2: 自动模式(beta)。当频道中新增消息时,bot 会尝试编辑原消息,显示添加评论按钮。如果编辑失败则直接创建评论消息。该模式能尽可能减少频道里的评论区数量。\n请选择您所需要的工作模式:", 36 | "option_choose_recent_value": "在频道中仅显示最近的若干条评论内容。请选择频道显示评论的最近条目数量:", 37 | "option_choose_notify_value": "您可以选择当频道收到新评论时是否开启提醒功能。0代表关闭,1代表开启。将在从下一条消息开始生效。", 38 | "option_choose_lang_value": "请选择频道中评论功能采用的语言。", 39 | "option_choose_button_value": "请选择评论区点赞按钮显示的方式。\n0代表永不显示\n1代表自动显示,默认为%s。在您的频道内发送 /defaultbuttons + 用空格分隔的内容可以修改默认按钮。\n2代表手动模式,可以自行设定显示内容\n当处于模式1或模式2时,在频道内使用 /comment + 用空格分隔的内容,即可在频道内添加或更换点赞按钮。(如使用 /comment 我 ❤️ 你,则相应的消息会出现\"我\"、\"❤️\"、\"你\"的三个点赞按钮)", 40 | "option_update_success": "配置更新成功", 41 | "option_update_failed": "配置更新失败", 42 | "clean_cmd_start": "正在进行检查,请稍候...", 43 | "clean_cmd_deleted": "删除记录成功", 44 | "clean_cmd_set": "设置成功", 45 | "fwd_source": "消息来源: ", 46 | "prev_msg": "上一条消息", 47 | "next_msg": "下一条消息", 48 | "no_message_detail": "未找到消息", 49 | "back_to_msg_list": "返回消息列表", 50 | "msg_from": "消息来源:", 51 | "delete_msg": "删除消息", 52 | "delete_success": "消息删除成功", 53 | "ban_user": "封禁用户", 54 | "unban_user": "解封用户", 55 | "user_banned": "已封禁该用户", 56 | "user_banned_failed": "封禁失败,该用户可能已被封禁", 57 | "user_unbanned": "用户已解封", 58 | "banned_prompt": "频道管理员不允许你进行评论操作", 59 | "new_comment_message": "您收到了新的评论", 60 | "new_reply_message": "您收到了一条评论回复", 61 | "target_message": "目标消息:", 62 | "like_recorded": "您觉得这很 %s", 63 | "comment_refreshing": "评论区刷新中...", 64 | "reply_to": "回复 ", 65 | "reply_prompt": "先填写回复信息,再选择需要回复的评论", 66 | "jump_to_comment": "跳转到评论区" 67 | } 68 | -------------------------------------------------------------------------------- /messagequeue.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # 3 | # Module author: 4 | # Tymofii A. Khodniev (thodnev) 5 | # 6 | # A library that provides a Python interface to the Telegram Bot API 7 | # Copyright (C) 2015-2020 8 | # Leandro Toledo de Souza 9 | # 10 | # This program is free software: you can redistribute it and/or modify 11 | # it under the terms of the GNU Lesser Public License as published by 12 | # the Free Software Foundation, either version 3 of the License, or 13 | # (at your option) any later version. 14 | # 15 | # This program is distributed in the hope that it will be useful, 16 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | # GNU Lesser Public License for more details. 19 | # 20 | # You should have received a copy of the GNU Lesser Public License 21 | # along with this program. If not, see [http://www.gnu.org/licenses/] 22 | """ Channel Helper Bot """ 23 | """ helper_main.py """ 24 | """ Copyright 2020, Jogle Lew """ 25 | """A throughput-limiting message processor for Telegram bots.""" 26 | from telegram.utils import promise 27 | 28 | import functools 29 | import time 30 | import threading 31 | import queue as q 32 | import uuid 33 | from datetime import datetime 34 | from ninesix import Logger 35 | 36 | 37 | class DelayPriorityQueueError(RuntimeError): 38 | """Indicates processing errors.""" 39 | pass 40 | 41 | 42 | class DelayPriorityQueue(threading.Thread): 43 | """ 44 | Processes callbacks from queue with specified throughput limits. Creates a separate thread to 45 | process callbacks with delays. 46 | 47 | Attributes: 48 | burst_limit (:obj:`int`): Number of maximum callbacks to process per time-window. 49 | time_limit (:obj:`int`): Defines width of time-window used when each processing limit is 50 | calculated. 51 | exc_route (:obj:`callable`): A callable, accepting 1 positional argument; used to route 52 | exceptions from processor thread to main thread; 53 | name (:obj:`str`): Thread's name. 54 | 55 | Args: 56 | queue (:obj:`Queue`, optional): Used to pass callbacks to thread. Creates ``Queue`` 57 | implicitly if not provided. 58 | burst_limit (:obj:`int`, optional): Number of maximum callbacks to process per time-window 59 | defined by :attr:`time_limit_ms`. Defaults to 30. 60 | time_limit_ms (:obj:`int`, optional): Defines width of time-window used when each 61 | processing limit is calculated. Defaults to 1000. 62 | exc_route (:obj:`callable`, optional): A callable, accepting 1 positional argument; used to 63 | route exceptions from processor thread to main thread; is called on `Exception` 64 | subclass exceptions. If not provided, exceptions are routed through dummy handler, 65 | which re-raises them. 66 | autostart (:obj:`bool`, optional): If :obj:`True`, processor is started immediately after 67 | object's creation; if :obj:`False`, should be started manually by `start` method. 68 | Defaults to :obj:`True`. 69 | name (:obj:`str`, optional): Thread's name. Defaults to ``'DelayPriorityQueue-N'``, where N is 70 | sequential number of object created. 71 | 72 | """ 73 | 74 | _instcnt = 0 # instance counter 75 | 76 | def __init__(self, 77 | queue=None, 78 | burst_limit=30, 79 | time_limit_ms=1000, 80 | exc_route=None, 81 | autostart=True, 82 | name=None): 83 | self._queue = queue if queue is not None else q.PriorityQueue() 84 | self.prior_dict = {} 85 | self.prior_date = datetime.today().strftime("%Y-%m-%d") 86 | self.lock = threading.Lock() 87 | self.burst_limit = burst_limit 88 | self.time_limit = time_limit_ms / 1000 89 | self.exc_route = (exc_route if exc_route is not None else self._default_exception_handler) 90 | self.__exit_req = False # flag to gently exit thread 91 | self.__class__._instcnt += 1 92 | if name is None: 93 | name = '{}-{}'.format(self.__class__.__name__, self.__class__._instcnt) 94 | super().__init__(name=name) 95 | self.daemon = False 96 | if autostart: # immediately start processing 97 | super().start() 98 | 99 | def run(self): 100 | """ 101 | Do not use the method except for unthreaded testing purposes, the method normally is 102 | automatically called by autostart argument. 103 | 104 | """ 105 | 106 | times = [] # used to store each callable processing time 107 | while True: 108 | item = self._queue.get() 109 | if self.__exit_req: 110 | return # shutdown thread 111 | # delay routine 112 | now = time.perf_counter() 113 | t_delta = now - self.time_limit # calculate early to improve perf. 114 | if times and t_delta > times[-1]: 115 | # if last call was before the limit time-window 116 | # used to impr. perf. in long-interval calls case 117 | times = [now] 118 | else: 119 | # collect last in current limit time-window 120 | times = [t for t in times if t >= t_delta] 121 | times.append(now) 122 | if len(times) >= self.burst_limit: # if throughput limit was hit 123 | time.sleep(times[1] - t_delta) 124 | # finally process one 125 | try: 126 | priority, uuid, func, args, kwargs = item 127 | func(*args, **kwargs) 128 | except Exception as exc: # re-route any exceptions 129 | self.exc_route(exc) # to prevent thread exit 130 | 131 | def stop(self, timeout=None): 132 | """Used to gently stop processor and shutdown its thread. 133 | 134 | Args: 135 | timeout (:obj:`float`): Indicates maximum time to wait for processor to stop and its 136 | thread to exit. If timeout exceeds and processor has not stopped, method silently 137 | returns. :attr:`is_alive` could be used afterwards to check the actual status. 138 | ``timeout`` set to :obj:`None`, blocks until processor is shut down. 139 | Defaults to :obj:`None`. 140 | 141 | """ 142 | 143 | self.__exit_req = True # gently request 144 | self._queue.put(None) # put something to unfreeze if frozen 145 | super().join(timeout=timeout) 146 | 147 | @staticmethod 148 | def _default_exception_handler(exc): 149 | """ 150 | Dummy exception handler which re-raises exception in thread. Could be possibly overwritten 151 | by subclasses. 152 | 153 | """ 154 | 155 | raise exc 156 | 157 | def __call__(self, func, *args, **kwargs): 158 | """Used to process callbacks in throughput-limiting thread through queue. 159 | 160 | Args: 161 | func (:obj:`callable`): The actual function (or any callable) that is processed through 162 | queue. 163 | *args (:obj:`list`): Variable-length `func` arguments. 164 | **kwargs (:obj:`dict`): Arbitrary keyword-arguments to `func`. 165 | 166 | """ 167 | 168 | if not self.is_alive() or self.__exit_req: 169 | raise DelayPriorityQueueError('Could not process callback in stopped thread') 170 | current_date = datetime.today().strftime("%Y-%m-%d") 171 | if current_date != self.prior_date: 172 | self.prior_date = current_date 173 | self.lock.acquire() 174 | self.prior_dict = {} 175 | self.lock.release() 176 | channel_id = func.kwargs.get("chat_id", 0) if "chat_id" in func.kwargs else (func.args[0] if len(func.args) > 0 else 0) 177 | channel_id = str(channel_id) 178 | self.lock.acquire() 179 | if not channel_id in self.prior_dict: 180 | self.prior_dict[channel_id] = 0 181 | self.prior_dict[channel_id] += 1 182 | priority = self.prior_dict[channel_id] 183 | self.lock.release() 184 | logger = Logger.logger 185 | logger.msg({ 186 | "channel_id": channel_id, 187 | "priority": priority 188 | }, tag="queue", log_level=20) 189 | self._queue.put((priority, uuid.uuid1(), func, args, kwargs)) 190 | 191 | 192 | # The most straightforward way to implement this is to use 2 sequential delay 193 | # queues, like on classic delay chain schematics in electronics. 194 | # So, message path is: 195 | # msg --> group delay if group msg, else no delay --> normal msg delay --> out 196 | # This way OS threading scheduler cares of timings accuracy. 197 | # (see time.time, time.clock, time.perf_counter, time.sleep @ docs.python.org) 198 | class MessageQueue: 199 | """ 200 | Implements callback processing with proper delays to avoid hitting Telegram's message limits. 201 | Contains two ``DelayPriorityQueue``, for group and for all messages, interconnected in delay chain. 202 | Callables are processed through *group* ``DelayPriorityQueue``, then through *all* ``DelayPriorityQueue`` for 203 | group-type messages. For non-group messages, only the *all* ``DelayPriorityQueue`` is used. 204 | 205 | Args: 206 | all_burst_limit (:obj:`int`, optional): Number of maximum *all-type* callbacks to process 207 | per time-window defined by :attr:`all_time_limit_ms`. Defaults to 30. 208 | all_time_limit_ms (:obj:`int`, optional): Defines width of *all-type* time-window used when 209 | each processing limit is calculated. Defaults to 1000 ms. 210 | group_burst_limit (:obj:`int`, optional): Number of maximum *group-type* callbacks to 211 | process per time-window defined by :attr:`group_time_limit_ms`. Defaults to 20. 212 | group_time_limit_ms (:obj:`int`, optional): Defines width of *group-type* time-window used 213 | when each processing limit is calculated. Defaults to 60000 ms. 214 | exc_route (:obj:`callable`, optional): A callable, accepting one positional argument; used 215 | to route exceptions from processor threads to main thread; is called on ``Exception`` 216 | subclass exceptions. If not provided, exceptions are routed through dummy handler, 217 | which re-raises them. 218 | autostart (:obj:`bool`, optional): If :obj:`True`, processors are started immediately after 219 | object's creation; if :obj:`False`, should be started manually by :attr:`start` method. 220 | Defaults to :obj:`True`. 221 | 222 | """ 223 | 224 | def __init__(self, 225 | all_burst_limit=30, 226 | all_time_limit_ms=1000, 227 | group_burst_limit=20, 228 | group_time_limit_ms=60000, 229 | exc_route=None, 230 | autostart=True): 231 | # create according delay queues, use composition 232 | self._all_delayq = DelayPriorityQueue( 233 | burst_limit=all_burst_limit, 234 | time_limit_ms=all_time_limit_ms, 235 | exc_route=exc_route, 236 | autostart=autostart) 237 | self._group_delayq = DelayPriorityQueue( 238 | burst_limit=group_burst_limit, 239 | time_limit_ms=group_time_limit_ms, 240 | exc_route=exc_route, 241 | autostart=autostart) 242 | 243 | def start(self): 244 | """Method is used to manually start the ``MessageQueue`` processing.""" 245 | self._all_delayq.start() 246 | self._group_delayq.start() 247 | 248 | def stop(self, timeout=None): 249 | self._group_delayq.stop(timeout=timeout) 250 | self._all_delayq.stop(timeout=timeout) 251 | 252 | stop.__doc__ = DelayPriorityQueue.stop.__doc__ or '' # reuse docstring if any 253 | 254 | def __call__(self, promise, is_group_msg=False): 255 | """ 256 | Processes callables in throughput-limiting queues to avoid hitting limits (specified with 257 | :attr:`burst_limit` and :attr:`time_limit`. 258 | 259 | Args: 260 | promise (:obj:`callable`): Mainly the ``telegram.utils.promise.Promise`` (see Notes for 261 | other callables), that is processed in delay queues. 262 | is_group_msg (:obj:`bool`, optional): Defines whether ``promise`` would be processed in 263 | group*+*all* ``DelayPriorityQueue``s (if set to :obj:`True`), or only through *all* 264 | ``DelayPriorityQueue`` (if set to :obj:`False`), resulting in needed delays to avoid 265 | hitting specified limits. Defaults to :obj:`False`. 266 | 267 | Note: 268 | Method is designed to accept ``telegram.utils.promise.Promise`` as ``promise`` 269 | argument, but other callables could be used too. For example, lambdas or simple 270 | functions could be used to wrap original func to be called with needed args. In that 271 | case, be sure that either wrapper func does not raise outside exceptions or the proper 272 | :attr:`exc_route` handler is provided. 273 | 274 | Returns: 275 | :obj:`callable`: Used as ``promise`` argument. 276 | 277 | """ 278 | 279 | if not is_group_msg: # ignore middle group delay 280 | self._all_delayq(promise) 281 | else: # use middle group delay 282 | self._group_delayq(self._all_delayq, promise) 283 | return promise 284 | 285 | 286 | def queuedmessage(method): 287 | """A decorator to be used with :attr:`telegram.Bot` send* methods. 288 | 289 | Note: 290 | As it probably wouldn't be a good idea to make this decorator a property, it has been coded 291 | as decorator function, so it implies that first positional argument to wrapped MUST be 292 | self. 293 | 294 | The next object attributes are used by decorator: 295 | 296 | Attributes: 297 | self._is_messages_queued_default (:obj:`bool`): Value to provide class-defaults to 298 | ``queued`` kwarg if not provided during wrapped method call. 299 | self._msg_queue (:class:`telegram.ext.messagequeue.MessageQueue`): The actual 300 | ``MessageQueue`` used to delay outbound messages according to specified time-limits. 301 | 302 | Wrapped method starts accepting the next kwargs: 303 | 304 | Args: 305 | queued (:obj:`bool`, optional): If set to :obj:`True`, the ``MessageQueue`` is used to 306 | process output messages. Defaults to `self._is_queued_out`. 307 | isgroup (:obj:`bool`, optional): If set to :obj:`True`, the message is meant to be 308 | group-type(as there's no obvious way to determine its type in other way at the moment). 309 | Group-type messages could have additional processing delay according to limits set 310 | in `self._out_queue`. Defaults to :obj:`False`. 311 | 312 | Returns: 313 | ``telegram.utils.promise.Promise``: In case call is queued or original method's return 314 | value if it's not. 315 | 316 | """ 317 | 318 | @functools.wraps(method) 319 | def wrapped(self, *args, **kwargs): 320 | queued = kwargs.pop('queued', self._is_messages_queued_default) 321 | isgroup = kwargs.pop('isgroup', False) 322 | if queued: 323 | prom = promise.Promise(method, (self, ) + args, kwargs) 324 | return self._msg_queue(prom, isgroup) 325 | return method(self, *args, **kwargs) 326 | 327 | return wrapped 328 | -------------------------------------------------------------------------------- /modules/callback_query.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ Channel Helper Bot """ 5 | """ callback_query.py """ 6 | """ Copyright 2018, Jogle Lew """ 7 | import helper_const 8 | import helper_global 9 | import helper_database 10 | import modules.option_cmd as option_cmd 11 | import modules.private_msg as private_msg 12 | import telegram 13 | from telegram import InlineKeyboardButton, InlineKeyboardMarkup, \ 14 | InputMediaAudio, InputMediaDocument, InputMediaPhoto, InputMediaVideo 15 | from telegram.ext import CallbackQueryHandler 16 | from ninesix import Logger 17 | 18 | def show_msg(bot, update, origin_message_id, chat_id, args): 19 | channel_id = int(args[1]) 20 | msg_id = int(args[2]) 21 | recent = int(args[3]) 22 | offset = int(args[4]) 23 | ori_chat_id = int(args[5]) 24 | 25 | config = helper_database.get_channel_config(channel_id) 26 | if config is None: 27 | return 28 | channel_lang = config[1] 29 | channel_username = config[4] 30 | 31 | if offset < 0: 32 | bot.answer_callback_query( 33 | callback_query_id=update.callback_query.id, 34 | text=helper_global.value("no_next_page", "", lang=channel_lang) 35 | ) 36 | return 37 | 38 | records = helper_database.get_recent_records(channel_id, msg_id, recent, offset) 39 | 40 | # Prepare Keyboard 41 | msg_buttons = helper_global.records_to_buttons(records, channel_id, msg_id) 42 | motd_keyboard = msg_buttons + [[ 43 | InlineKeyboardButton( 44 | helper_global.value("prev_page", "Prev Page", lang=channel_lang), 45 | callback_data="msg,%d,%d,%d,%d,%d" % (channel_id, msg_id, recent, offset + 1, ori_chat_id) 46 | ), 47 | InlineKeyboardButton( 48 | helper_global.value("next_page", "Next Page", lang=channel_lang), 49 | callback_data="msg,%d,%d,%d,%d,%d" % (channel_id, msg_id, recent, offset - 1, ori_chat_id) 50 | ) 51 | ]] 52 | motd_markup = InlineKeyboardMarkup(motd_keyboard) 53 | 54 | if offset > 0 and len(records) == 0: 55 | bot.answer_callback_query( 56 | callback_query_id=update.callback_query.id, 57 | text=helper_global.value("no_prev_page", "", lang=channel_lang) 58 | ) 59 | return 60 | 61 | prompt_text = helper_global.value("comment_header", "", lang=channel_lang) 62 | if channel_username is not None and len(channel_username) > 0: 63 | prompt_text = "https://t.me/%s/%a\n" % (channel_username, msg_id) + prompt_text 64 | bot.send_message( 65 | chat_id=ori_chat_id, 66 | text=prompt_text, 67 | parse_mode=telegram.ParseMode.HTML, 68 | reply_markup=motd_markup 69 | ) 70 | bot.delete_message( 71 | chat_id=chat_id, 72 | message_id=origin_message_id 73 | ) 74 | 75 | 76 | def msg_detail(bot, update, chat_id, origin_message_id, args): 77 | channel_id = int(args[1]) 78 | msg_id = int(args[2]) 79 | row_id = int(args[3]) 80 | 81 | config = helper_database.get_channel_config(channel_id) 82 | if config is None: 83 | return 84 | channel_lang = config[1] 85 | recent = config[3] 86 | admin_id = config[5] 87 | 88 | if row_id < 0: 89 | bot.answer_callback_query( 90 | callback_query_id=update.callback_query.id, 91 | text=helper_global.value("no_message_detail", "No Message", lang=channel_lang) 92 | ) 93 | return 94 | 95 | records = helper_database.get_record_by_rowid(row_id) 96 | 97 | if records is None or len(records) == 0: 98 | bot.answer_callback_query( 99 | callback_query_id=update.callback_query.id, 100 | text=helper_global.value("no_message_detail", "No Message", lang=channel_lang) 101 | ) 102 | return 103 | 104 | record = records[0] 105 | 106 | username = record[2] 107 | name = record[3] 108 | msg_type = record[4] 109 | msg_content = record[5] 110 | media_id= record[6] 111 | user_id = int(record[8]) 112 | 113 | base_offset = helper_database.get_base_offset_by_rowid(channel_id, msg_id, row_id) 114 | offset = base_offset // recent 115 | 116 | msg_from_button = [ 117 | [ 118 | InlineKeyboardButton( 119 | helper_global.value("msg_from", "Message From: ", lang=channel_lang) + name, 120 | callback_data="blank" 121 | ) 122 | ] 123 | ] 124 | admin_operation_button = [ 125 | [ 126 | InlineKeyboardButton( 127 | helper_global.value("delete_msg", "Delete Message", lang=channel_lang), 128 | callback_data="msg_delete,%d,%d,%d,%d,%d,%d" % (row_id, channel_id, msg_id, recent, offset, chat_id) 129 | ), 130 | InlineKeyboardButton( 131 | helper_global.value("unban_user", "Unban User", lang=channel_lang), 132 | callback_data="user_unban,%d,%d,%s,%d,%d" % (channel_id, user_id, "", msg_id, row_id) 133 | ) if helper_database.check_ban(channel_id, user_id) else \ 134 | InlineKeyboardButton( 135 | helper_global.value("ban_user", "Ban User", lang=channel_lang), 136 | callback_data="user_ban,%d,%d,%s,%d,%d" % (channel_id, user_id, "", msg_id, row_id) 137 | ) 138 | ] 139 | ] if str(chat_id) == str(admin_id) else [] 140 | motd_keyboard = msg_from_button + admin_operation_button + [ 141 | [ 142 | InlineKeyboardButton( 143 | helper_global.value("prev_msg", "Prev Message", lang=channel_lang), 144 | callback_data="msg_detail,%d,%d,%d" % (channel_id, msg_id, helper_database.get_next_rowid(channel_id, msg_id, row_id)) 145 | ), 146 | InlineKeyboardButton( 147 | helper_global.value("next_msg", "Next Message", lang=channel_lang), 148 | callback_data="msg_detail,%d,%d,%d" % (channel_id, msg_id, helper_database.get_prev_rowid(channel_id, msg_id, row_id)) 149 | ) 150 | ], 151 | [ 152 | InlineKeyboardButton( 153 | helper_global.value("back_to_msg_list", "Back to message list", lang=channel_lang), 154 | callback_data="msg,%d,%d,%d,%d,%d" % (channel_id, msg_id, recent, offset, chat_id) 155 | ) 156 | ] 157 | ] 158 | motd_markup = InlineKeyboardMarkup(motd_keyboard) 159 | 160 | if msg_type == "text": 161 | bot.send_message( 162 | chat_id=chat_id, 163 | text=msg_content, 164 | parse_mode='HTML', 165 | reply_markup=motd_markup 166 | ) 167 | bot.delete_message( 168 | chat_id=chat_id, 169 | message_id=origin_message_id 170 | ) 171 | elif msg_type == "audio" or msg_type == "document" or msg_type == "photo" or msg_type == "video" or msg_type == "sticker" or msg_type == "voice": 172 | send_func = { 173 | "audio": bot.send_audio, 174 | "document": bot.send_document, 175 | "photo": bot.send_photo, 176 | "video": bot.send_video, 177 | "sticker": bot.send_sticker, 178 | "voice": bot.send_voice 179 | } 180 | send_func[msg_type]( 181 | chat_id, 182 | media_id, 183 | caption=msg_content, 184 | parse_mode='HTML', 185 | reply_markup=motd_markup 186 | ) 187 | bot.delete_message( 188 | chat_id=chat_id, 189 | message_id=origin_message_id 190 | ) 191 | else: 192 | bot.send_message( 193 | chat_id=chat_id, 194 | text="[%s] %s" % (msg_type, msg_content), 195 | parse_mode='HTML', 196 | reply_markup=motd_markup 197 | ) 198 | bot.delete_message( 199 | chat_id=chat_id, 200 | message_id=origin_message_id 201 | ) 202 | 203 | 204 | def option_finish(bot, lang, chat_id, origin_message_id): 205 | bot.edit_message_text( 206 | chat_id=chat_id, 207 | message_id=origin_message_id, 208 | text=helper_global.value("option_finished", "", lang=lang) 209 | ) 210 | 211 | 212 | def option_item(bot, update, lang, chat_id, origin_message_id, args): 213 | # Prepare Keyboard 214 | motd_keyboard = [[ 215 | InlineKeyboardButton( 216 | "mode", 217 | callback_data="option|%s,%s,mode" % (lang, args[1]) 218 | ), 219 | InlineKeyboardButton( 220 | "recent", 221 | callback_data="option|%s,%s,recent" % (lang, args[1]) 222 | ), 223 | InlineKeyboardButton( 224 | "notify", 225 | callback_data="option|%s,%s,notify" % (lang, args[1]) 226 | ) 227 | ]] + [[ 228 | InlineKeyboardButton( 229 | "lang", 230 | callback_data="option|%s,%s,lang" % (lang, args[1]) 231 | ), 232 | InlineKeyboardButton( 233 | "button", 234 | callback_data="option|%s,%s,button" % (lang, args[1]) 235 | ) 236 | ]] + [[ 237 | InlineKeyboardButton( 238 | helper_global.value("option_delete", "", lang=lang), 239 | callback_data="option_delete|%s,%s" % (lang, args[1]) 240 | ) 241 | ]] + [[ 242 | InlineKeyboardButton( 243 | helper_global.value("option_finish", "", lang=lang), 244 | callback_data="option_finish|%s" % lang 245 | ) 246 | ]] 247 | 248 | motd_markup = InlineKeyboardMarkup(motd_keyboard) 249 | 250 | bot.answer_callback_query( 251 | callback_query_id=update.callback_query.id 252 | ) 253 | bot.edit_message_text( 254 | chat_id=chat_id, 255 | message_id=origin_message_id, 256 | text=helper_global.value("option_choose_item", "", lang=lang), 257 | reply_markup=motd_markup 258 | ) 259 | 260 | 261 | def option_key(bot, update, key, values, lang, chat_id, origin_message_id, args): 262 | config = helper_database.get_channel_config(args[1]) 263 | if config is None or len(config) == 0: 264 | return 265 | key2idx = { 266 | "lang": 1, 267 | "mode": 2, 268 | "recent": 3, 269 | "notify": 6, 270 | "button": 7 271 | } 272 | # Prepare Keyboard 273 | width = helper_const.LANG_WIDTH 274 | motd_keyboard = [[ 275 | InlineKeyboardButton( 276 | values[idx * width + delta] + (" (*)" if str(values[idx * width + delta]) == str(config[key2idx[key]]) else ""), 277 | callback_data="option|%s,%s,%s,%s" % (lang, args[1], key, values[idx * width + delta]) 278 | ) for delta in range(width) 279 | ] for idx in range(len(values) // width)] + [[ 280 | InlineKeyboardButton( 281 | values[idx] + (" (*)" if str(values[idx]) == str(config[key2idx[key]]) else ""), 282 | callback_data="option|%s,%s,%s,%s" % (lang, args[1], key, values[idx]) 283 | ) 284 | for idx in range(width * (len(values) // width), len(values))]] + [[ 285 | InlineKeyboardButton( 286 | helper_global.value("option_back", "", lang=lang), 287 | callback_data="option|%s,%s" % (lang, args[1]) 288 | ) 289 | ]] 290 | 291 | motd_markup = InlineKeyboardMarkup(motd_keyboard) 292 | 293 | text = helper_global.value("option_choose_%s_value" % key, "", lang=lang) 294 | if key == "button": 295 | text = text % (", ".join(helper_database.get_default_button_options(args[1]))) 296 | bot.answer_callback_query( 297 | callback_query_id=update.callback_query.id 298 | ) 299 | bot.edit_message_text( 300 | chat_id=chat_id, 301 | message_id=origin_message_id, 302 | text=text, 303 | reply_markup=motd_markup 304 | ) 305 | 306 | 307 | def option_delete(bot, lang, chat_id, origin_message_id, args): 308 | channel_id = args[1] 309 | helper_database.delete_channel_config(channel_id) 310 | bot.edit_message_text( 311 | chat_id=chat_id, 312 | message_id=origin_message_id, 313 | text=helper_global.value("option_record_deleted", "", lang=lang) 314 | ) 315 | 316 | 317 | def option_update(bot, update, lang, chat_id, origin_message_id, args): 318 | try: 319 | helper_database.update_config_by_channel(args[1], args[2], args[3]) 320 | bot.answer_callback_query( 321 | callback_query_id=update.callback_query.id, 322 | text=helper_global.value("option_update_success", "", lang=lang) 323 | ) 324 | except: 325 | bot.answer_callback_query( 326 | callback_query_id=update.callback_query.id, 327 | text=helper_global.value("option_update_failed", "", lang=lang) 328 | ) 329 | option_item(bot, update, lang, chat_id, origin_message_id, args) 330 | 331 | 332 | def option_index(bot, update, lang, chat_id, origin_message_id, args): 333 | records = helper_database.get_channel_info_by_user(chat_id) 334 | if records is None or len(records) == 0: 335 | bot.send_message( 336 | chat_id=chat_id, 337 | text=helper_global.value("option_no_channel", "", lang=lang) 338 | ) 339 | return 340 | 341 | #Prepare keyboard 342 | lang_list = helper_const.LANG_LIST 343 | width = helper_const.LANG_WIDTH 344 | current_lang = lang 345 | key = "option" 346 | motd_keyboard = [[ 347 | InlineKeyboardButton( 348 | "@" + record[1] if record[1] else "id: " + str(record[0]), 349 | callback_data="option|%s,%s" % (lang, record[0]) 350 | ) 351 | ] for record in records] + [[ 352 | InlineKeyboardButton( 353 | helper_global.value("option_finish", "", lang), 354 | callback_data="option_finish|%s" % lang 355 | ) 356 | ]] + [[ 357 | InlineKeyboardButton( 358 | lang_list[width * idx + delta] + (" (*)" if lang_list[width * idx + delta] == current_lang else ""), 359 | callback_data="%s|%s" % (key, lang_list[width * idx + delta]) 360 | ) for delta in range(width) 361 | ] for idx in range(len(lang_list) // width)] + [[ 362 | InlineKeyboardButton( 363 | lang_list[idx] + (" (*)" if lang_list[idx] == current_lang else ""), 364 | callback_data="%s|%s" % (key, lang_list[idx]) 365 | ) 366 | for idx in range(width * (len(lang_list) // width), len(lang_list))]] 367 | 368 | motd_markup = InlineKeyboardMarkup(motd_keyboard) 369 | bot.answer_callback_query( 370 | callback_query_id=update.callback_query.id 371 | ) 372 | bot.edit_message_text( 373 | chat_id=chat_id, 374 | message_id=origin_message_id, 375 | text=helper_global.value("option_choose_channel", "", lang=lang), 376 | reply_markup=motd_markup 377 | ) 378 | 379 | 380 | def msg_delete(bot, update, chat_id, origin_message_id, args): 381 | row_id = int(args[1]) 382 | channel_id = int(args[2]) 383 | msg_id = int(args[3]) 384 | msg_args = ["msg"] + args[2:] 385 | config = helper_database.get_channel_config(channel_id) 386 | if config is None: 387 | return 388 | channel_lang = config[1] 389 | helper_database.delete_record_by_rowid(row_id) 390 | bot.answer_callback_query( 391 | callback_query_id=update.callback_query.id, 392 | text=helper_global.value("delete_success", "", lang=channel_lang) 393 | ) 394 | private_msg.update_dirty_msg(channel_id, msg_id) 395 | show_msg(bot, update, origin_message_id, chat_id, msg_args) 396 | 397 | 398 | def user_ban(bot, update, chat_id, origin_message_id, args): 399 | channel_id = int(args[1]) 400 | user_id = int(args[2]) 401 | name = args[3] 402 | msg_id = int(args[4]) 403 | row_id = int(args[5]) 404 | config = helper_database.get_channel_config(channel_id) 405 | if config is None: 406 | return 407 | channel_lang = config[1] 408 | try: 409 | helper_database.ban_user(channel_id, user_id, name) 410 | except: 411 | bot.answer_callback_query( 412 | callback_query_id=update.callback_query.id, 413 | text=helper_global.value("user_banned_failed", "", lang=channel_lang) 414 | ) 415 | bot.answer_callback_query( 416 | callback_query_id=update.callback_query.id, 417 | text=helper_global.value("user_banned", "", lang=channel_lang) 418 | ) 419 | msg_detail(bot, update, chat_id, origin_message_id, ["msg_detail", channel_id, msg_id, row_id]) 420 | 421 | 422 | def user_unban(bot, update, chat_id, origin_message_id, args): 423 | channel_id = int(args[1]) 424 | user_id = int(args[2]) 425 | name = args[3] 426 | msg_id = int(args[4]) 427 | row_id = int(args[5]) 428 | config = helper_database.get_channel_config(channel_id) 429 | if config is None: 430 | return 431 | channel_lang = config[1] 432 | helper_database.unban_user(channel_id, user_id, name) 433 | bot.answer_callback_query( 434 | callback_query_id=update.callback_query.id, 435 | text=helper_global.value("user_unbanned", "", lang=channel_lang) 436 | ) 437 | msg_detail(bot, update, chat_id, origin_message_id, ["msg_detail", channel_id, msg_id, row_id]) 438 | 439 | 440 | def reaction(bot, update, chat_id, origin_message_id, user_id, args): 441 | channel_id = int(args[1]) 442 | msg_id = int(args[2]) 443 | like_id = int(args[3]) 444 | config = helper_database.get_channel_config(channel_id) 445 | if config is None: 446 | return 447 | channel_lang, mode = config[1], config[2] 448 | buttons = helper_database.get_button_options(channel_id, msg_id) 449 | helper_database.add_reaction(channel_id, msg_id, user_id, like_id) 450 | private_msg.update_dirty_msg(channel_id, msg_id, update_mode=(2 if mode == 3 else 0)) 451 | bot.answer_callback_query( 452 | callback_query_id=update.callback_query.id, 453 | text=helper_global.value("like_recorded", "", lang=channel_lang) % buttons[like_id] 454 | ) 455 | 456 | 457 | def intro_template(bot, update, lang, chat_id, origin_message_id, key, text_key): 458 | lang_list = helper_const.LANG_LIST 459 | width = helper_const.LANG_WIDTH 460 | current_lang = lang 461 | motd_keyboard = [[ 462 | InlineKeyboardButton( 463 | lang_list[width * idx + delta] + (" (*)" if lang_list[width * idx + delta] == current_lang else ""), 464 | callback_data="%s|%s" % (key, lang_list[width * idx + delta]) 465 | ) for delta in range(width) 466 | ] for idx in range(len(lang_list) // width)] + [[ 467 | InlineKeyboardButton( 468 | lang_list[idx] + (" (*)" if lang_list[idx] == current_lang else ""), 469 | callback_data="%s|%s" % (key, lang_list[idx]) 470 | ) 471 | for idx in range(width * (len(lang_list) // width), len(lang_list))]] 472 | 473 | motd_markup = InlineKeyboardMarkup(motd_keyboard) 474 | bot.answer_callback_query( 475 | callback_query_id=update.callback_query.id 476 | ) 477 | bot.edit_message_text( 478 | chat_id=chat_id, 479 | message_id=origin_message_id, 480 | text=helper_global.value(text_key, "", lang=current_lang), 481 | reply_markup=motd_markup 482 | ) 483 | 484 | 485 | def callback_query(bot, update): 486 | logger = Logger.logger 487 | callback_data = update.callback_query.data 488 | if update.callback_query.message is None: 489 | bot.answer_callback_query( 490 | callback_query_id=update.callback_query.id 491 | ) 492 | return 493 | origin_message_id = update.callback_query.message.message_id 494 | chat_id = update.callback_query.message.chat_id 495 | user_id = update.callback_query.from_user.id 496 | args = callback_data.split(',') 497 | logger.msg({ 498 | "channel_id": chat_id, 499 | "msg_id": origin_message_id, 500 | "user_id": user_id, 501 | "callback": callback_data 502 | }, tag="callback", log_level=90) 503 | if "|" in args[0]: 504 | lang = args[0].split("|")[1] 505 | if args[0] == 'msg': 506 | show_msg(bot, update, origin_message_id, chat_id, args) 507 | elif args[0] == 'msg_detail': 508 | msg_detail(bot, update, chat_id, origin_message_id, args) 509 | elif args[0] == 'msg_delete': 510 | msg_delete(bot, update, chat_id, origin_message_id, args) 511 | elif args[0] == 'user_ban': 512 | user_ban(bot, update, chat_id, origin_message_id, args) 513 | elif args[0] == 'user_unban': 514 | user_unban(bot, update, chat_id, origin_message_id, args) 515 | elif args[0] == 'like': 516 | reaction(bot, update, chat_id, origin_message_id, user_id, args) 517 | elif args[0].startswith('register'): 518 | item = args[0].split("|")[0] 519 | item_config = { 520 | "register": "register_cmd_text", 521 | "register_invalid": "register_cmd_invalid", 522 | "register_not_admin": "register_cmd_not_admin", 523 | "register_no_permission": "register_cmd_no_permission", 524 | "register_no_info": "register_cmd_no_info", 525 | "register_failed": "register_cmd_failed", 526 | "register_success": "register_cmd_success", 527 | } 528 | intro_template(bot, update, lang, chat_id, origin_message_id, item, item_config[item]) 529 | elif args[0].startswith('start'): 530 | intro_template(bot, update, lang, chat_id, origin_message_id, "start", "start_cmd_text") 531 | elif args[0].startswith('help'): 532 | intro_template(bot, update, lang, chat_id, origin_message_id, "help", "help_cmd_text") 533 | elif args[0].startswith('option_no_channel'): 534 | intro_template(bot, update, lang, chat_id, origin_message_id, "option_no_channel", "option_no_channel") 535 | elif args[0].startswith('option_delete'): 536 | option_delete(bot, lang, chat_id, origin_message_id, args) 537 | elif args[0].startswith('option_finish'): 538 | option_finish(bot, lang, chat_id, origin_message_id) 539 | elif args[0].startswith('option'): 540 | if len(args) == 1: 541 | option_index(bot, update, lang, chat_id, origin_message_id, args) 542 | if len(args) == 2: 543 | option_item(bot, update, lang, chat_id, origin_message_id, args) 544 | elif len(args) == 3: 545 | item_config = { 546 | "mode": ["0", "1", "2"], 547 | "recent": ["5", "10", "15", "20"], 548 | "notify": ["0", "1"], 549 | "lang": helper_const.LANG_LIST, 550 | "button": ["0", "1", "2"] 551 | } 552 | key = args[2] 553 | values = item_config[key] 554 | option_key(bot, update, key, values, lang, chat_id, origin_message_id, args) 555 | elif len(args) == 4: 556 | option_update(bot, update, lang, chat_id, origin_message_id, args) 557 | else: 558 | bot.answer_callback_query( 559 | callback_query_id=update.callback_query.id 560 | ) 561 | 562 | 563 | _handler = CallbackQueryHandler(callback_query) 564 | -------------------------------------------------------------------------------- /modules/cancel_cmd.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ Channel Helper Bot """ 5 | """ cancel_cmd.py """ 6 | """ Copyright 2018, Jogle Lew """ 7 | import helper_global 8 | import helper_database 9 | from telegram.ext import CommandHandler 10 | from ninesix import Logger 11 | 12 | def cancel(bot, update): 13 | logger = Logger.logger 14 | chat_id = update.message.chat_id 15 | channel_id = helper_global.value(str(chat_id) + "_status", "0,0").split(",")[0] 16 | logger.msg({ 17 | "channel_id": channel_id, 18 | "user_id": chat_id 19 | }, tag="cancel", log_level=80) 20 | config = helper_database.get_channel_config(channel_id) 21 | if config is None: 22 | lang = "all" 23 | else: 24 | lang = config[1] 25 | helper_global.assign(str(chat_id) + "_status", "0,0") 26 | help_text = helper_global.value("stop_comment_mode", "", lang=lang) 27 | bot.send_message(chat_id=chat_id, text=help_text) 28 | 29 | 30 | _handler = CommandHandler('cancel', cancel) 31 | -------------------------------------------------------------------------------- /modules/channel_msg.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ Channel Helper Bot """ 5 | """ channel_msg.py """ 6 | """ Copyright 2018, Jogle Lew """ 7 | import helper_const 8 | import helper_global 9 | import helper_database 10 | import telegram 11 | from telegram.utils.helpers import effective_message_type 12 | from telegram.ext import MessageHandler, Filters 13 | if telegram.__version__ < '13.0': 14 | from telegram.ext import BaseFilter 15 | else: 16 | from telegram.ext import MessageFilter as BaseFilter 17 | from telegram import InlineKeyboardButton, InlineKeyboardMarkup 18 | from ninesix import Logger 19 | 20 | parse_entity = helper_global.parse_entity 21 | 22 | def add_comment(bot, chat_id, config, message_id, media_group_id=None): 23 | logger = Logger.logger 24 | logger.msg({ 25 | "channel_id": chat_id, 26 | "msg_id": message_id, 27 | "action": "normal comment" 28 | }, tag="channel", log_level=80) 29 | channel_lang = config[1] 30 | recent = config[3] 31 | 32 | if helper_database.check_reflect(chat_id, message_id): 33 | return 34 | 35 | # Avoid duplicated comment for media group 36 | if media_group_id: 37 | last_media_group = helper_global.value(str(chat_id) + '_last_media_group', '0') 38 | # print(last_media_group) 39 | if last_media_group == media_group_id: 40 | return 41 | helper_global.assign(str(chat_id) + '_last_media_group', media_group_id) 42 | 43 | # Prepare Keyboard 44 | motd_keyboard = [[ 45 | InlineKeyboardButton( 46 | helper_global.value("add_comment", "Add Comment", lang=channel_lang), 47 | url="http://telegram.me/%s?start=add_%d_%d" % (helper_global.value('bot_username', ''), chat_id, message_id) 48 | ), 49 | InlineKeyboardButton( 50 | helper_global.value("show_all_comments", "Show All", lang=channel_lang), 51 | url="http://telegram.me/%s?start=show_%s_%d" % (helper_global.value('bot_username', ''), chat_id, message_id) 52 | ) 53 | ]] 54 | motd_markup = InlineKeyboardMarkup(motd_keyboard) 55 | 56 | records = helper_database.get_recent_records(chat_id, message_id, recent) 57 | 58 | comment_message = bot.send_message( 59 | chat_id=chat_id, 60 | text=helper_global.records_to_str(records, channel_lang), 61 | reply_to_message_id=message_id, 62 | reply_markup=motd_markup, 63 | parse_mode=telegram.ParseMode.HTML 64 | ).result() 65 | helper_database.add_reflect(chat_id, message_id, comment_message.message_id) 66 | 67 | 68 | def add_compact_comment(bot, chat_id, config, message_id, message): 69 | logger = Logger.logger 70 | logger.msg({ 71 | "channel_id": chat_id, 72 | "msg_id": message_id, 73 | "action": "compact comment" 74 | }, tag="channel", log_level=80) 75 | channel_lang = config[1] 76 | 77 | # Fallback media group message 78 | if message.media_group_id: 79 | add_comment(bot, chat_id, config, message_id, media_group_id=message.media_group_id) 80 | return 81 | 82 | if message.forward_from or message.forward_from_chat: 83 | new_message = deforward(bot, message, channel_lang) 84 | message_id = new_message.message_id 85 | message = new_message 86 | 87 | # Prepare Keyboard 88 | motd_keyboard = [[ 89 | InlineKeyboardButton( 90 | helper_global.value("add_comment", "Add Comment", lang=channel_lang), 91 | url="http://telegram.me/%s?start=add_%d_%d" % (helper_global.value('bot_username', ''), chat_id, message_id) 92 | ), 93 | InlineKeyboardButton( 94 | helper_global.value("show_all_comments", "Show All", lang=channel_lang), 95 | url="http://telegram.me/%s?start=show_%s_%d" % (helper_global.value('bot_username', ''), chat_id, message_id) 96 | ) 97 | ]] 98 | motd_markup = InlineKeyboardMarkup(motd_keyboard) 99 | 100 | try: 101 | bot.edit_message_reply_markup( 102 | chat_id=chat_id, 103 | message_id=message_id, 104 | reply_markup=motd_markup 105 | ).result() 106 | except telegram.error.BadRequest: 107 | logger.msg({ 108 | "channel_id": chat_id, 109 | "msg_id": message_id, 110 | "action": "compact -> normal" 111 | }, tag="channel", log_level=80) 112 | add_comment(bot, chat_id, config, message_id) 113 | except: 114 | pass 115 | 116 | 117 | def add_inplace_comment(bot, chat_id, config, message_id, message, buttons): 118 | logger = Logger.logger 119 | logger.msg({ 120 | "channel_id": chat_id, 121 | "msg_id": message_id, 122 | "action": "inplace comment" 123 | }, tag="channel", log_level=80) 124 | channel_lang = config[1] 125 | 126 | # Fallback media group message 127 | if message.media_group_id: 128 | return 129 | 130 | if message.forward_from or message.forward_from_chat: 131 | new_message = deforward(bot, message, channel_lang) 132 | message_id = new_message.message_id 133 | message = new_message 134 | 135 | # Prepare Keyboard 136 | if buttons and len(buttons) > 0: 137 | helper_database.add_button_options(chat_id, message_id, buttons) 138 | helper_database.clear_reaction(chat_id, message_id) 139 | 140 | motd_keyboard = [[ 141 | InlineKeyboardButton( 142 | value, 143 | callback_data="like,%s,%s,%d" % (chat_id, message_id, idx) 144 | ) 145 | for idx, value in enumerate(buttons)]] + ([[ 146 | InlineKeyboardButton( 147 | helper_global.value("add_comment", "Add Comment", lang=channel_lang), 148 | url="http://telegram.me/%s?start=add_%d_%d" % (helper_global.value('bot_username', ''), chat_id, message_id) 149 | ), 150 | InlineKeyboardButton( 151 | helper_global.value("show_all_comments", "Show All", lang=channel_lang), 152 | url="http://telegram.me/%s?start=show_%s_%d" % (helper_global.value('bot_username', ''), chat_id, message_id) 153 | ) 154 | ]]) 155 | motd_markup = InlineKeyboardMarkup(motd_keyboard) 156 | 157 | try: 158 | bot.edit_message_reply_markup( 159 | chat_id=chat_id, 160 | message_id=message_id, 161 | reply_markup=motd_markup 162 | ).result() 163 | except: 164 | return 165 | helper_database.add_reflect(chat_id, message_id, avoidNone(message.caption if message.caption else message.text)) 166 | 167 | 168 | def avoidNone(s): 169 | if s: 170 | return str(s) 171 | return '' 172 | 173 | 174 | def deforward(bot, msg, lang): 175 | logger = Logger.logger 176 | chat_id = msg.chat_id 177 | message_id = msg.message_id 178 | logger.msg({ 179 | "channel_id": chat_id, 180 | "msg_id": message_id, 181 | "action": "messaage deforward" 182 | }, tag="channel", log_level=80) 183 | 184 | # Generate forward info 185 | has_msg_link = False 186 | if msg.forward_from: 187 | # Check username existence 188 | if msg.forward_from.username: 189 | forward_info = helper_global.value('fwd_source', 'Forwarded from:', lang=lang) + '@%s' % msg.forward_from.username 190 | else: 191 | forward_info = helper_global.value('fwd_source', 'Forwarded from:', lang=lang) + '%s' % ( 192 | msg.forward_from.id, 193 | msg.forward_from.first_name + " " + avoidNone(msg.forward_from.last_name) 194 | ) 195 | elif msg.forward_from_chat: 196 | # Check channel public/private 197 | if msg.forward_from_chat.username: 198 | forward_info = helper_global.value('fwd_source', 'Forwarded from:', lang=lang) + 'https://t.me/%s/%s' % ( 199 | msg.forward_from_chat.username, 200 | msg.forward_from_message_id 201 | ) 202 | has_msg_link = True 203 | else: 204 | forward_info = helper_global.value('fwd_source', 'Forwarded from:', lang=lang) + msg.forward_from_chat.title 205 | 206 | message_type = effective_message_type(msg) 207 | new_msg = None 208 | 209 | # Ignore media group 210 | if msg.media_group_id: 211 | return msg 212 | 213 | # Handle by message type 214 | if message_type == 'text': 215 | has_content_link = False 216 | for entity in msg.entities: 217 | if entity.type == 'url' or entity.type == 'text_link': 218 | has_content_link = True 219 | break 220 | new_msg = bot.send_message( 221 | chat_id=chat_id, 222 | text=parse_entity(avoidNone(msg.text), msg.entities) + '\n\n' + forward_info, 223 | parse_mode='HTML', 224 | disable_notification=True, 225 | disable_web_page_preview=(not has_content_link and has_msg_link) 226 | ).result() 227 | elif message_type == 'audio': 228 | new_msg = bot.send_audio( 229 | chat_id=chat_id, 230 | audio=msg.audio.file_id, 231 | caption=parse_entity(avoidNone(msg.caption), msg.caption_entities) + '\n\n' + forward_info, 232 | parse_mode='HTML', 233 | disable_notification=True 234 | ).result() 235 | elif message_type == 'document': 236 | new_msg = bot.send_document( 237 | chat_id=chat_id, 238 | document=msg.document.file_id, 239 | caption=parse_entity(avoidNone(msg.caption), msg.caption_entities) + '\n\n' + forward_info, 240 | parse_mode='HTML', 241 | disable_notification=True 242 | ).result() 243 | elif message_type == 'photo': 244 | new_msg = bot.send_photo( 245 | chat_id=chat_id, 246 | photo=msg.photo[-1].file_id, 247 | caption=parse_entity(avoidNone(msg.caption), msg.caption_entities) + '\n\n' + forward_info, 248 | parse_mode='HTML', 249 | disable_notification=True 250 | ).result() 251 | elif message_type == 'sticker': 252 | new_msg = bot.send_sticker( 253 | chat_id=chat_id, 254 | sticker=msg.sticker.file_id, 255 | disable_notification=True 256 | ).result() 257 | elif message_type == 'video': 258 | new_msg = bot.send_video( 259 | chat_id=chat_id, 260 | video=msg.video.file_id, 261 | caption=parse_entity(avoidNone(msg.caption), msg.caption_entities) + '\n\n' + forward_info, 262 | parse_mode='HTML', 263 | disable_notification=True 264 | ).result() 265 | elif message_type == 'voice': 266 | new_msg = bot.send_voice( 267 | chat_id=chat_id, 268 | voice=msg.voice.file_id, 269 | caption=parse_entity(avoidNone(msg.caption), msg.caption_entities) + '\n\n' + forward_info, 270 | parse_mode='HTML', 271 | disable_notification=True 272 | ).result() 273 | 274 | if new_msg: 275 | bot.delete_message(chat_id=chat_id, message_id=message_id) 276 | return new_msg 277 | return msg 278 | 279 | 280 | def add_like_buttons(bot, channel_lang, config, chat_id, message_id, message, buttons): 281 | logger = Logger.logger 282 | logger.msg({ 283 | "channel_id": chat_id, 284 | "msg_id": message_id, 285 | "action": "add like buttons" 286 | }, tag="channel", log_level=80) 287 | flag = 1 288 | ref = helper_database.get_reflect_by_msg_id(chat_id, message_id) 289 | if ref is not None: 290 | flag = 0 291 | message_id = ref[1] 292 | 293 | # Fallback media group message 294 | if message.media_group_id: 295 | add_comment(bot, chat_id, config, message_id, media_group_id=message.media_group_id) 296 | return 297 | 298 | if message.forward_from or message.forward_from_chat: 299 | new_message = deforward(bot, message, channel_lang) 300 | message_id = new_message.message_id 301 | message = new_message 302 | 303 | # Prepare Keyboard 304 | helper_database.add_button_options(chat_id, message_id, buttons) 305 | helper_database.clear_reaction(chat_id, message_id) 306 | motd_keyboard = [[ 307 | InlineKeyboardButton( 308 | value, 309 | callback_data="like,%s,%s,%d" % (chat_id, message_id, idx) 310 | ) 311 | for idx, value in enumerate(buttons)]] + ([[ 312 | InlineKeyboardButton( 313 | helper_global.value("add_comment", "Add Comment", lang=channel_lang), 314 | url="http://telegram.me/%s?start=add_%d_%d" % (helper_global.value('bot_username', ''), chat_id, message_id) 315 | ), 316 | InlineKeyboardButton( 317 | helper_global.value("show_all_comments", "Show All", lang=channel_lang), 318 | url="http://telegram.me/%s?start=show_%s_%d" % (helper_global.value('bot_username', ''), chat_id, message_id) 319 | ) 320 | ]] if flag == 1 else [[]]) 321 | motd_markup = InlineKeyboardMarkup(motd_keyboard) 322 | 323 | bot.edit_message_reply_markup( 324 | chat_id=chat_id, 325 | message_id=message_id, 326 | reply_markup=motd_markup 327 | ) 328 | 329 | 330 | def channel_post_msg(bot, update): 331 | logger = Logger.logger 332 | message = update.channel_post 333 | if message is None: 334 | return 335 | chat_id = message.chat_id 336 | message_id = message.message_id 337 | config = helper_database.get_channel_config(chat_id) 338 | if config is None: 339 | return 340 | lang, mode, recent, button_mode = config[1], config[2], config[3], config[7] 341 | 342 | # Manual Mode 343 | if message.reply_to_message is not None and message.text.startswith("/comment"): 344 | logger.msg({ 345 | "channel_id": chat_id, 346 | "msg_id": message_id, 347 | "mode": mode, 348 | "button": button_mode, 349 | "action": "/comment" 350 | }, tag="channel", log_level=90) 351 | message_id = message.reply_to_message.message_id 352 | bot.delete_message(chat_id=chat_id, message_id=message.message_id) 353 | if not helper_database.check_reflect(chat_id, message_id) and message.reply_to_message.reply_markup is None: 354 | add_compact_comment(bot, chat_id, config, message_id, message.reply_to_message) 355 | if not button_mode == 0: 356 | buttons = message.text.split()[1:] 357 | if button_mode == 1 and len(buttons) == 0: 358 | buttons = helper_database.get_default_button_options(chat_id) 359 | add_like_buttons(bot, lang, config, chat_id, message_id, message, buttons) 360 | 361 | # Force Comment for Special Cases 362 | elif message.reply_to_message is not None and message.text == "/forcecomment": 363 | logger.msg({ 364 | "channel_id": chat_id, 365 | "msg_id": message_id, 366 | "mode": mode, 367 | "button": button_mode, 368 | "action": "/forcecomment" 369 | }, tag="channel", log_level=90) 370 | message_id = message.reply_to_message.message_id 371 | bot.delete_message(chat_id=chat_id, message_id=message.message_id) 372 | helper_database.delete_reflect(chat_id, message_id) 373 | add_compact_comment(bot, chat_id, config, message_id, message.reply_to_message) 374 | 375 | # Set default buttons 376 | elif message.text is not None and message.text.startswith("/defaultbuttons"): 377 | logger.msg({ 378 | "channel_id": chat_id, 379 | "msg_id": message_id, 380 | "mode": mode, 381 | "button": button_mode, 382 | "action": "/defaultbuttons" 383 | }, tag="channel", log_level=90) 384 | buttons = message.text.split()[1:] 385 | bot.delete_message(chat_id=chat_id, message_id=message.message_id) 386 | helper_database.add_button_options(chat_id, 0, buttons) 387 | 388 | # Auto Comment Mode 389 | elif mode == 1: 390 | logger.msg({ 391 | "channel_id": chat_id, 392 | "msg_id": message_id, 393 | "mode": mode, 394 | "button": button_mode, 395 | "action": "new channel post" 396 | }, tag="channel", log_level=90) 397 | add_comment(bot, chat_id, config, message_id, media_group_id=message.media_group_id) 398 | if button_mode == 1: 399 | add_like_buttons(bot, lang, config, chat_id, message_id, message, helper_database.get_default_button_options(chat_id)) 400 | elif mode == 2: 401 | logger.msg({ 402 | "channel_id": chat_id, 403 | "msg_id": message_id, 404 | "mode": mode, 405 | "button": button_mode, 406 | "action": "new channel post" 407 | }, tag="channel", log_level=90) 408 | if button_mode == 1: 409 | add_like_buttons(bot, lang, config, chat_id, message_id, message, helper_database.get_default_button_options(chat_id)) 410 | else: 411 | add_compact_comment(bot, chat_id, config, message_id, message) 412 | elif mode == 3: 413 | logger.msg({ 414 | "channel_id": chat_id, 415 | "msg_id": message_id, 416 | "mode": mode, 417 | "button": button_mode, 418 | "action": "new channel post" 419 | }, tag="channel", log_level=90) 420 | add_inplace_comment(bot, chat_id, config, message_id, message, (helper_database.get_default_button_options(chat_id) if button_mode == 1 else [])) 421 | 422 | 423 | class FilterChannelPost(BaseFilter): 424 | def filter(self, message): 425 | return message.chat.type == "channel" 426 | 427 | 428 | channel_post_filter = FilterChannelPost() 429 | _handler = MessageHandler(channel_post_filter, channel_post_msg) 430 | -------------------------------------------------------------------------------- /modules/clean_cmd.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ Channel Helper Bot """ 5 | """ clean_cmd.py """ 6 | """ Copyright 2018, Jogle Lew """ 7 | import json 8 | import datetime 9 | import helper_const 10 | import helper_global 11 | import helper_database 12 | from telegram.ext import CommandHandler 13 | from telegram.error import TimedOut, NetworkError 14 | 15 | def get_invalid_channel_access(bot): 16 | configs = helper_database.get_all_channel_config() 17 | invalid_list = [] 18 | for config in configs: 19 | channel_id = int(config[0]) 20 | admin_id = int(config[5]) 21 | try: 22 | chat_members = bot.get_chat_administrators(chat_id=channel_id).result() 23 | except TimedOut: 24 | pass 25 | except NetworkError: 26 | pass 27 | except: 28 | invalid_list.append(config) 29 | return invalid_list 30 | 31 | 32 | def check_channel_access(bot, job): 33 | invalid_list = get_invalid_channel_access(bot) 34 | for owner_id in helper_const.BOT_OWNER: 35 | bot.send_message(chat_id=owner_id, text=str(invalid_list)) 36 | 37 | 38 | def clean(bot, update, args, job_queue): 39 | from_id = update.message.from_user.id 40 | if not from_id in helper_const.BOT_OWNER: 41 | return 42 | if len(args) == 1 and args[0] == "check": 43 | invalid_list = get_invalid_channel_access(bot) 44 | bot.send_message(chat_id=from_id, text=helper_global.value("clean_cmd_start", "")) 45 | bot.send_message(chat_id=from_id, text=str(invalid_list)) 46 | if len(args) == 2 and args[0] == "touch": 47 | channel_id = int(args[1]) 48 | chat_members = bot.get_chat_administrators(chat_id=channel_id).result() 49 | for member in chat_members: 50 | if member.user.username and member.user.username == helper_global.value('bot_username', ''): 51 | bot.send_message(chat_id=from_id, text='%s %s %s' % (member.can_post_messages, member.can_edit_messages, member.can_delete_messages)) 52 | if len(args) == 2 and args[0] == "delete": 53 | channel_id = int(args[1]) 54 | helper_database.delete_channel_config(channel_id) 55 | bot.send_message(chat_id=from_id, text=helper_global.value("clean_cmd_deleted", "")) 56 | if len(args) == 2 and args[0] == "auto": 57 | job = helper_global.value("check_daily_job", None) 58 | if job is None: 59 | job = job_queue.run_daily(check_channel_access, datetime.time(0, 0)) 60 | if args[1] == "on": 61 | job.enabled = True 62 | elif args[1] == "off": 63 | job.enabled = False 64 | helper_global.assign("check_daily_job", job) 65 | bot.send_message(chat_id=from_id, text=helper_global.value("clean_cmd_set", "")) 66 | 67 | 68 | _handler = CommandHandler('clean', clean, pass_args=True, pass_job_queue=True) 69 | -------------------------------------------------------------------------------- /modules/help_cmd.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ Channel Helper Bot """ 5 | """ help_cmd.py """ 6 | """ Copyright 2018, Jogle Lew """ 7 | import helper_const 8 | import helper_global 9 | from telegram.ext import CommandHandler 10 | from ninesix import Logger 11 | 12 | def help(bot, update): 13 | logger = Logger.logger 14 | chat_id = update.message.chat_id 15 | logger.msg({ 16 | "user_id": chat_id 17 | }, tag="help", log_level=80) 18 | helper_global.send_intro_template(bot, chat_id, helper_const.DEFAULT_LANG, "help", "help_cmd_text") 19 | 20 | 21 | _handler = CommandHandler('help', help) 22 | -------------------------------------------------------------------------------- /modules/inline_query.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ Channel Helper Bot """ 5 | """ inline_query.py """ 6 | """ Copyright 2020, Jogle Lew """ 7 | import re 8 | import helper_const 9 | import helper_global 10 | import helper_database 11 | from telegram import InlineKeyboardButton, InlineKeyboardMarkup 12 | from telegram import InlineQueryResultArticle, InputTextMessageContent 13 | from telegram.ext import InlineQueryHandler 14 | from ninesix import Logger 15 | 16 | def inline_caps(bot, update): 17 | user_id = update.inline_query.from_user.id 18 | args = helper_global.value(str(user_id) + "_status", "0,0") 19 | params = args.split(",") 20 | channel_id = int(params[0]) 21 | msg_id = int(params[1]) 22 | 23 | if channel_id == 0: 24 | bot.answer_inline_query(update.inline_query.id, []) 25 | return 26 | 27 | config = helper_database.get_channel_config(channel_id) 28 | if config is None: 29 | bot.answer_inline_query(update.inline_query.id, []) 30 | return 31 | channel_lang = config[1] 32 | recent = config[3] 33 | 34 | query = update.inline_query.query 35 | if len(query.strip()) == 0: 36 | bot.answer_inline_query( 37 | update.inline_query.id, [], 38 | switch_pm_text=helper_global.value("reply_prompt", "comment here first", lang=channel_lang), 39 | switch_pm_parameter="0", 40 | cache_time=0, 41 | is_personal=True 42 | ) 43 | return 44 | 45 | records = helper_database.get_recent_records(channel_id, msg_id, recent, 0) 46 | results = [] 47 | for idx, record in enumerate(records): 48 | name = record[3] 49 | content = record[5] 50 | msg_user_id = record[8] 51 | row_id = int(record[10]) 52 | results.append( 53 | InlineQueryResultArticle( 54 | id=idx, 55 | title=name, 56 | description=re.sub("<.*?>", "", content).replace('<', '<').replace('>', '>'), 57 | input_message_content=InputTextMessageContent( 58 | message_text= query.replace('<', '<').replace('>', '>'), 59 | parse_mode='HTML' 60 | ), 61 | reply_markup=InlineKeyboardMarkup([[ 62 | InlineKeyboardButton( 63 | helper_global.value("reply_to", "Reply to: ", lang=channel_lang) + name, 64 | callback_data="notify,%d,%d,%d" % (channel_id, msg_id, row_id) 65 | ) 66 | ]]) 67 | ) 68 | ) 69 | bot.answer_inline_query( 70 | update.inline_query.id, results, 71 | switch_pm_text=helper_global.value("reply_prompt", "comment here first", lang=channel_lang), 72 | switch_pm_parameter="0", 73 | cache_time=0, 74 | is_personal=True 75 | ) 76 | 77 | _handler = InlineQueryHandler(inline_caps) 78 | 79 | -------------------------------------------------------------------------------- /modules/option_cmd.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ Channel Helper Bot """ 5 | """ option_cmd.py """ 6 | """ Copyright 2018, Jogle Lew """ 7 | import helper_const 8 | import helper_global 9 | import helper_database 10 | import telegram 11 | from telegram import InlineKeyboardButton, InlineKeyboardMarkup 12 | from telegram.ext import CommandHandler 13 | from ninesix import Logger 14 | 15 | def option(bot, update, args): 16 | logger = Logger.logger 17 | if args is None or len(args) == 0: 18 | lang = helper_const.DEFAULT_LANG 19 | else: 20 | lang = args[0] 21 | chat_id = update.message.chat_id 22 | logger.msg({ 23 | "user_id": chat_id 24 | }, tag="option", log_level=80) 25 | records = helper_database.get_channel_info_by_user(chat_id) 26 | if records is None or len(records) == 0: 27 | helper_global.send_intro_template(bot, chat_id, helper_const.DEFAULT_LANG, "option_no_channel", "option_no_channel") 28 | return 29 | 30 | #Prepare keyboard 31 | lang_list = helper_const.LANG_LIST 32 | width = helper_const.LANG_WIDTH 33 | current_lang = lang 34 | key = "option" 35 | motd_keyboard = [[ 36 | InlineKeyboardButton( 37 | "@" + record[1] if record[1] else "id: " + str(record[0]), 38 | callback_data="option|%s,%s" % (lang, record[0]) 39 | ) 40 | ] for record in records] + [[ 41 | InlineKeyboardButton( 42 | helper_global.value("option_finish", "", lang), 43 | callback_data="option_finish|%s" % lang 44 | ) 45 | ]] + [[ 46 | InlineKeyboardButton( 47 | lang_list[width * idx + delta] + (" (*)" if lang_list[width * idx + delta] == current_lang else ""), 48 | callback_data="%s|%s" % (key, lang_list[width * idx + delta]) 49 | ) for delta in range(width) 50 | ] for idx in range(len(lang_list) // width)] + [[ 51 | InlineKeyboardButton( 52 | lang_list[idx] + (" (*)" if lang_list[idx] == current_lang else ""), 53 | callback_data="%s|%s" % (key, lang_list[idx]) 54 | ) 55 | for idx in range(width * (len(lang_list) // width), len(lang_list))]] 56 | 57 | motd_markup = InlineKeyboardMarkup(motd_keyboard) 58 | bot.send_message( 59 | chat_id=chat_id, 60 | text=helper_global.value("option_choose_channel", "", lang=lang), 61 | reply_markup=motd_markup 62 | ) 63 | 64 | 65 | _handler = CommandHandler('option', option, pass_args=True) 66 | -------------------------------------------------------------------------------- /modules/private_msg.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ Channel Helper Bot """ 5 | """ private_msg.py """ 6 | """ Copyright 2018, Jogle Lew """ 7 | import helper_const 8 | import helper_global 9 | import helper_database 10 | import telegram 11 | import threading 12 | from telegram import InlineKeyboardButton, InlineKeyboardMarkup 13 | from telegram.ext import MessageHandler, Filters 14 | from ninesix import Logger 15 | 16 | def add_record(bot, channel_id, msg_id, message): 17 | logger = Logger.logger 18 | ori_msg_id = message.message_id 19 | user = message.from_user 20 | username = user.username 21 | user_id = user.id 22 | name = user.first_name 23 | if user.last_name: 24 | name += " " + user.last_name 25 | date = message.date.strftime("%Y-%m-%d %H:%M:%S") 26 | 27 | msg_type = "text" 28 | msg_content = "" 29 | media_id = "" 30 | if message.text: 31 | msg_type = "text" 32 | msg_content = message.text 33 | elif message.sticker: 34 | msg_type = 'sticker' 35 | media_id = message.sticker.file_id 36 | if message.sticker.emoji: 37 | msg_content = message.sticker.emoji 38 | elif message.photo: 39 | msg_type = 'photo' 40 | media_id = message.photo[-1].file_id 41 | if message.caption: 42 | msg_content = message.caption 43 | elif message.video: 44 | msg_type = 'video' 45 | media_id = message.video.file_id 46 | if message.caption: 47 | msg_content = message.caption 48 | elif message.document: 49 | msg_type = 'document' 50 | media_id = message.document.file_id 51 | if message.document.file_name: 52 | msg_content = message.document.file_name 53 | elif message.audio: 54 | msg_type = 'audio' 55 | media_id = message.audio.file_id 56 | if message.audio.title: 57 | msg_content = message.audio.title 58 | elif message.voice: 59 | msg_type = 'voice' 60 | media_id = message.voice.file_id 61 | 62 | msg_content = helper_global.parse_entity(msg_content, message.entities) 63 | 64 | if message.reply_markup and message.reply_markup.inline_keyboard: 65 | keyboard = message.reply_markup.inline_keyboard 66 | if len(keyboard) > 0 and len(keyboard[0]) > 0: 67 | query = keyboard[0][0] 68 | if query.callback_data: 69 | args = query.callback_data.split(",") 70 | if len(args) == 4 and args[0] == "notify": 71 | target_channel_id = int(args[1]) 72 | target_msg_id = int(args[2]) 73 | target_row_id = args[3] 74 | record = helper_database.get_record_by_rowid(target_row_id) 75 | if len(record) > 0 and target_channel_id == int(record[0][0]) and target_msg_id == int(record[0][1]): 76 | target_name = record[0][3] 77 | target_user_id = record[0][8] 78 | config = helper_database.get_channel_config(channel_id) 79 | if config is None: 80 | return 81 | channel_lang, channel_username = config[1], config[4] 82 | msg_content = "(➤%s) " % target_name.replace('<', '<').replace('>', '>') + msg_content 83 | if channel_username is not None: 84 | logger.msg({ 85 | "channel_id": channel_id, 86 | "msg_id": msg_id, 87 | "target_user": target_user_id, 88 | "action": "notify reply" 89 | }, tag="private", log_level=80) 90 | bot.send_message( 91 | chat_id=target_user_id, 92 | text=helper_global.value("new_reply_message", "You receive a reply message.", lang=channel_lang) + "\n" + helper_global.value("target_message", "", lang=channel_lang) + "https://t.me/%s/%d" % (channel_username, target_msg_id) 93 | ) 94 | else: 95 | link_id = abs(channel_id) % 10000000000 96 | bot.send_message( 97 | chat_id=target_user_id, 98 | text=helper_global.value("new_reply_message", "You receive a reply message.", lang=channel_lang) + "\n" + helper_global.value("target_message", "", lang=channel_lang) + "https://t.me/c/%d/%d" % (link_id, target_msg_id) 99 | ) 100 | 101 | return helper_database.add_record(channel_id, msg_id, username, name, msg_type, msg_content, media_id, date, user_id, ori_msg_id) 102 | 103 | 104 | def update_comments(bot, channel_id, msg_id, update_mode): 105 | logger = Logger.logger 106 | config = helper_database.get_channel_config(channel_id) 107 | if config is None: 108 | return 109 | channel_lang = config[1] 110 | mode = config[2] 111 | recent = config[3] 112 | logger.msg({ 113 | "channel_id": channel_id, 114 | "msg_id": msg_id, 115 | "update_mode": update_mode 116 | }, tag="private", log_level=80) 117 | 118 | # For mode 3 119 | if mode == 3 and update_mode == 2: 120 | buttons = helper_database.get_button_options(channel_id, msg_id) 121 | stat = helper_database.get_reaction_stat(channel_id, msg_id) 122 | # Prepare Keyboard 123 | motd_keyboard = [[ 124 | InlineKeyboardButton( 125 | value + (" (%d)" % stat[idx] if idx in stat else ""), 126 | callback_data="like,%s,%s,%d" % (channel_id, msg_id, idx) 127 | ) 128 | for idx, value in enumerate(buttons)]] + [[ 129 | InlineKeyboardButton( 130 | helper_global.value("add_comment", "Add Comment", lang=channel_lang), 131 | url="http://telegram.me/%s?start=add_%d_%d" % (helper_global.value('bot_username', ''), channel_id, msg_id) 132 | ), 133 | InlineKeyboardButton( 134 | helper_global.value("show_all_comments", "Show All", lang=channel_lang), 135 | url="http://telegram.me/%s?start=show_%s_%d" % (helper_global.value('bot_username', ''), channel_id, msg_id) 136 | ) 137 | ]] 138 | motd_markup = InlineKeyboardMarkup(motd_keyboard) 139 | 140 | records = helper_database.get_recent_records(channel_id, msg_id, recent) 141 | origin_post = helper_database.get_origin_post(channel_id, msg_id) 142 | 143 | try: 144 | bot.edit_message_caption( 145 | caption=origin_post + "\n\n" + helper_global.records_to_str(records, channel_lang), 146 | chat_id=channel_id, 147 | message_id=msg_id, 148 | parse_mode=telegram.ParseMode.HTML, 149 | reply_markup=motd_markup 150 | ) 151 | except: 152 | bot.edit_message_text( 153 | text=origin_post + "\n\n" + helper_global.records_to_str(records, channel_lang), 154 | chat_id=channel_id, 155 | message_id=msg_id, 156 | parse_mode=telegram.ParseMode.HTML, 157 | reply_markup=motd_markup 158 | ) 159 | return 160 | 161 | # update comments in channel 162 | comment_id = helper_database.get_comment_id(channel_id, msg_id) 163 | if comment_id is None: 164 | # If no comment message, just update Like buttons 165 | buttons = helper_database.get_button_options(channel_id, msg_id) 166 | stat = helper_database.get_reaction_stat(channel_id, msg_id) 167 | # Prepare Keyboard 168 | motd_keyboard = [[ 169 | InlineKeyboardButton( 170 | value + (" (%d)" % stat[idx] if idx in stat else ""), 171 | callback_data="like,%s,%s,%d" % (channel_id, msg_id, idx) 172 | ) 173 | for idx, value in enumerate(buttons)]] + [[ 174 | InlineKeyboardButton( 175 | helper_global.value("add_comment", "Add Comment", lang=channel_lang), 176 | url="http://telegram.me/%s?start=add_%d_%d" % (helper_global.value('bot_username', ''), channel_id, msg_id) 177 | ), 178 | InlineKeyboardButton( 179 | helper_global.value("show_all_comments", "Show All", lang=channel_lang), 180 | url="http://telegram.me/%s?start=show_%s_%d" % (helper_global.value('bot_username', ''), channel_id, msg_id) 181 | ) 182 | ]] 183 | motd_markup = InlineKeyboardMarkup(motd_keyboard) 184 | bot.edit_message_reply_markup( 185 | chat_id=channel_id, 186 | message_id=msg_id, 187 | reply_markup=motd_markup 188 | ) 189 | return 190 | 191 | # Otherwise 192 | # Update Like buttons 193 | if update_mode == 0: 194 | buttons = helper_database.get_button_options(channel_id, msg_id) 195 | stat = helper_database.get_reaction_stat(channel_id, msg_id) 196 | # Prepare Keyboard 197 | motd_keyboard = [[ 198 | InlineKeyboardButton( 199 | value + (" (%d)" % stat[idx] if idx in stat else ""), 200 | callback_data="like,%s,%s,%d" % (channel_id, msg_id, idx) 201 | ) 202 | for idx, value in enumerate(buttons)]] 203 | if comment_id - msg_id > 1: 204 | link_id = abs(channel_id) % 10000000000 205 | motd_keyboard += [[ 206 | InlineKeyboardButton( 207 | helper_global.value("jump_to_comment", "Jump to Comment", lang=channel_lang), 208 | url="https://t.me/c/%d/%d" % (link_id, comment_id) 209 | ) 210 | ]] 211 | motd_markup = InlineKeyboardMarkup(motd_keyboard) 212 | bot.edit_message_reply_markup( 213 | chat_id=channel_id, 214 | message_id=msg_id, 215 | reply_markup=motd_markup 216 | ) 217 | return 218 | 219 | # Update comment message 220 | records = helper_database.get_recent_records(channel_id, msg_id, recent) 221 | 222 | # Prepare Keyboard 223 | motd_keyboard = [[ 224 | InlineKeyboardButton( 225 | helper_global.value("add_comment", "Add Comment", lang=channel_lang), 226 | url="http://telegram.me/%s?start=add_%d_%d" % (helper_global.value('bot_username', ''), channel_id, msg_id) 227 | ), 228 | InlineKeyboardButton( 229 | helper_global.value("show_all_comments", "Show All", lang=channel_lang), 230 | url="http://telegram.me/%s?start=show_%s_%d" % (helper_global.value('bot_username', ''), channel_id, msg_id) 231 | ) 232 | ]] 233 | motd_markup = InlineKeyboardMarkup(motd_keyboard) 234 | 235 | bot.edit_message_text( 236 | text=helper_global.records_to_str(records, channel_lang), 237 | chat_id=channel_id, 238 | message_id=comment_id, 239 | parse_mode=telegram.ParseMode.HTML, 240 | reply_markup=motd_markup 241 | ) 242 | 243 | 244 | def update_dirty_list(): 245 | lock.acquire() 246 | dirty_list = helper_global.value("dirty_list", []) 247 | bot = helper_global.value("bot", None) 248 | for item in dirty_list: 249 | channel_id, msg_id, update_mode = item 250 | threading.Thread( 251 | target=update_comments, 252 | args=(bot, channel_id, msg_id, update_mode) 253 | ).start() 254 | helper_global.assign("dirty_list", []) 255 | lock.release() 256 | 257 | 258 | def check_channel_message(bot, message): 259 | logger = Logger.logger 260 | chat_id = message.chat_id 261 | if not message.forward_from_chat: 262 | helper_global.send_intro_template(bot, chat_id, helper_const.DEFAULT_LANG, "register_invalid", "register_cmd_invalid") 263 | return 264 | chat_type = message.forward_from_chat.type 265 | if not chat_type == "channel": 266 | helper_global.send_intro_template(bot, chat_id, helper_const.DEFAULT_LANG, "register_invalid", "register_cmd_invalid") 267 | return 268 | channel_username = message.forward_from_chat.username 269 | channel_id = message.forward_from_chat.id 270 | user_id = message.from_user.id 271 | logger.msg({ 272 | "user_id": chat_id, 273 | "channel_id": channel_id, 274 | "action": "check channel" 275 | }, tag="private", log_level=90) 276 | bot_id = int(helper_const.BOT_TOKEN.split(":")[0]) 277 | try: 278 | chat_members = bot.get_chat_administrators(chat_id=channel_id).result() 279 | chat_member_ids = [member.user.id for member in chat_members] 280 | if not user_id in chat_member_ids: 281 | helper_global.send_intro_template(bot, chat_id, helper_const.DEFAULT_LANG, "register_not_admin", "register_cmd_not_admin") 282 | return 283 | for member in chat_members: 284 | if member.user.id == bot_id: 285 | post_permission = member.can_post_messages if member.can_post_messages else False 286 | edit_permission = member.can_edit_messages if member.can_edit_messages else False 287 | delete_permission = member.can_delete_messages if member.can_delete_messages else False 288 | if not post_permission or not edit_permission or not delete_permission: 289 | helper_global.send_intro_template(bot, chat_id, helper_const.DEFAULT_LANG, "register_no_permission", "register_cmd_no_permission") 290 | return 291 | break 292 | except: 293 | helper_global.send_intro_template(bot, chat_id, helper_const.DEFAULT_LANG, "register_no_info", "register_cmd_no_info") 294 | return 295 | try: 296 | helper_database.add_channel_config(channel_id, helper_const.DEFAULT_LANG, 1, 10, channel_username, chat_id, 1, 1) 297 | except: 298 | helper_global.assign(str(chat_id) + "_status", "0,0") 299 | helper_global.send_intro_template(bot, chat_id, helper_const.DEFAULT_LANG, "register_failed", "register_cmd_failed") 300 | return 301 | 302 | helper_global.assign(str(chat_id) + "_status", "0,0") 303 | helper_global.send_intro_template(bot, chat_id, helper_const.DEFAULT_LANG, "register_success", "register_cmd_success") 304 | 305 | 306 | def private_msg(bot, update): 307 | logger = Logger.logger 308 | message = update.edited_message if update.edited_message else update.message 309 | chat_id = message.chat_id 310 | args = helper_global.value(str(chat_id) + "_status", "0,0") 311 | logger.msg({ 312 | "user_id": chat_id, 313 | "status": args 314 | }, tag="private", log_level=90) 315 | 316 | params = args.split(",") 317 | channel_id = int(params[0]) 318 | msg_id = int(params[1]) 319 | if channel_id == 0: 320 | if msg_id == 1: 321 | check_channel_message(bot, message) 322 | return 323 | 324 | # Check comment message 325 | comment_exist = helper_database.check_reflect(channel_id, msg_id) 326 | config = helper_database.get_channel_config(channel_id) 327 | if config is None: 328 | return 329 | channel_lang = config[1] 330 | mode, recent, username, admin_id, notify = config[2], config[3], config[4], config[5], config[6] 331 | logger.msg({ 332 | "user_id": chat_id, 333 | "channel_id": channel_id, 334 | "msg_id": msg_id, 335 | "action": "add comment" 336 | }, tag="private", log_level=90) 337 | 338 | # For Auto Mode = 2 339 | if not comment_exist: 340 | logger.msg({ 341 | "user_id": chat_id, 342 | "channel_id": channel_id, 343 | "msg_id": msg_id, 344 | "action": "add comment area" 345 | }, tag="private", log_level=80) 346 | comment_message = bot.send_message( 347 | chat_id=channel_id, 348 | text=helper_global.value("comment_refreshing", "Refreshing...", lang=channel_lang), 349 | reply_to_message_id=msg_id, 350 | parse_mode=telegram.ParseMode.HTML 351 | ).result() 352 | helper_database.add_reflect(channel_id, msg_id, comment_message.message_id) 353 | #bot.edit_message_reply_markup( 354 | # chat_id=channel_id, 355 | # message_id=msg_id, 356 | # reply_markup=None 357 | #) 358 | update_dirty_msg(channel_id, msg_id, update_mode=0) 359 | 360 | result = add_record(bot, channel_id, msg_id, message) 361 | 362 | # Update Dirty List 363 | update_dirty_msg(channel_id, msg_id, update_mode=(2 if mode == 3 else 1)) 364 | if notify == 1 and not int(chat_id) == int(admin_id): 365 | logger.msg({ 366 | "user_id": chat_id, 367 | "channel_id": channel_id, 368 | "msg_id": msg_id, 369 | "admin_id": admin_id, 370 | "action": "notify channel owner" 371 | }, tag="private", log_level=80) 372 | if username is not None: 373 | bot.send_message( 374 | chat_id=admin_id, 375 | text=helper_global.value("new_comment_message", "You have a new comment message.", lang=channel_lang) + "\n" + helper_global.value("target_message", "", lang=channel_lang) + "https://t.me/%s/%d" % (username, msg_id) 376 | ) 377 | else: 378 | link_id = abs(channel_id) % 10000000000 379 | bot.send_message( 380 | chat_id=admin_id, 381 | text=helper_global.value("new_comment_message", "You have a new comment message.", lang=channel_lang) + "\n" + helper_global.value("target_message", "", lang=channel_lang) + "https://t.me/c/%d/%d" % (link_id, msg_id) 382 | ) 383 | 384 | if result == 0: 385 | bot.send_message(chat_id=chat_id, text=helper_global.value("comment_success", "Success!", lang=channel_lang)) 386 | elif result == 1: 387 | bot.send_message(chat_id=chat_id, text=helper_global.value("comment_edit_success", "Success!", lang=channel_lang)) 388 | 389 | 390 | def update_dirty_msg(channel_id, msg_id, update_mode=1): 391 | lock.acquire() 392 | dirty_list = helper_global.value("dirty_list", []) 393 | if not (channel_id, msg_id, update_mode) in dirty_list: 394 | dirty_list.append((channel_id, msg_id, update_mode)) 395 | helper_global.assign("dirty_list", dirty_list) 396 | lock.release() 397 | 398 | 399 | def set_interval(func, sec): 400 | def func_wrapper(): 401 | set_interval(func, sec) 402 | func() 403 | t = threading.Timer(sec, func_wrapper) 404 | t.start() 405 | return t 406 | 407 | 408 | refresh_status = helper_global.value("refresh_status", False) 409 | if not refresh_status: 410 | set_interval(update_dirty_list, helper_const.MIN_REFRESH_INTERVAL) 411 | helper_global.assign("refresh_status", True) 412 | lock = threading.Lock() 413 | _handler = MessageHandler(Filters.private, private_msg, edited_updates=True) 414 | -------------------------------------------------------------------------------- /modules/register_cmd.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ Channel Helper Bot """ 5 | """ register_cmd.py """ 6 | """ Copyright 2018, Jogle Lew """ 7 | import helper_const 8 | import helper_global 9 | import helper_database 10 | from telegram.ext import CommandHandler 11 | from telegram import InlineKeyboardButton, InlineKeyboardMarkup 12 | from ninesix import Logger 13 | 14 | def register(bot, update): 15 | logger = Logger.logger 16 | from_id = update.message.from_user.id 17 | chat_id = update.message.chat_id 18 | logger.msg({"user_id": from_id}, tag="register", log_level=80) 19 | helper_global.assign(str(from_id) + "_status", "0,1") 20 | helper_global.send_intro_template(bot, chat_id, helper_const.DEFAULT_LANG, "register", "register_cmd_text") 21 | 22 | 23 | _handler = CommandHandler('register', register) 24 | -------------------------------------------------------------------------------- /modules/sql_cmd.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ Channel Helper Bot """ 5 | """ sql_cmd.py """ 6 | """ Copyright 2018, Jogle Lew """ 7 | import helper_const 8 | import helper_global 9 | import helper_database 10 | from telegram.ext import CommandHandler 11 | 12 | def sql(bot, update, args): 13 | from_id = update.message.from_user.id 14 | if not from_id in helper_const.BOT_OWNER: 15 | return 16 | script = " ".join(args) 17 | text = "" 18 | try: 19 | result = helper_database.execute(script, ()) 20 | text = "执行成功,结果:\n" + str(list(result)) 21 | except Exception as e: 22 | text = "执行失败 " + str(e) 23 | bot.send_message(chat_id=update.message.chat_id, text=text) 24 | 25 | 26 | _handler = CommandHandler('sql', sql, pass_args=True) 27 | -------------------------------------------------------------------------------- /modules/start_cmd.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ Channel Helper Bot """ 5 | """ start_cmd.py """ 6 | """ Copyright 2018, Jogle Lew """ 7 | import helper_const 8 | import helper_global 9 | import helper_database 10 | import telegram 11 | from telegram import InlineKeyboardButton, InlineKeyboardMarkup 12 | from telegram.ext import CommandHandler 13 | from ninesix import Logger 14 | 15 | def start(bot, update, args): 16 | logger = Logger.logger 17 | if args is None or len(args) == 0: 18 | chat_id = update.message.chat_id 19 | logger.msg({"user_id": chat_id}, tag="start", log_level=80) 20 | helper_global.send_intro_template(bot, chat_id, helper_const.DEFAULT_LANG, "start", "start_cmd_text") 21 | return 22 | 23 | params = args[0].split("_") 24 | channel_id = int(params[1]) 25 | msg_id = int(params[2]) 26 | chat_id = update.message.chat_id 27 | logger.msg({"user_id": chat_id, "args": args}, tag="start", log_level=90) 28 | if chat_id < 0: 29 | return 30 | 31 | config = helper_database.get_channel_config(channel_id) 32 | if config is None: 33 | return 34 | channel_lang = config[1] 35 | recent, username = config[3], config[4] 36 | 37 | if helper_database.check_ban(channel_id, chat_id): 38 | helper_global.assign(str(chat_id) + "_status", "0,0") 39 | bot.send_message(chat_id=update.message.chat_id, text=helper_global.value("banned_prompt", "You are banned.", lang=channel_lang)) 40 | return 41 | 42 | if params[0] == "add": 43 | helper_global.assign(str(chat_id) + "_status", params[1] + "," + params[2]) 44 | motd_keyboard = [[ 45 | InlineKeyboardButton( 46 | helper_global.value("reply_to", "Reply", lang=channel_lang) + "...", 47 | switch_inline_query_current_chat=" " 48 | ) 49 | ]] 50 | motd_markup = InlineKeyboardMarkup(motd_keyboard) 51 | if username is not None: 52 | bot.send_message( 53 | chat_id=update.message.chat_id, 54 | text=helper_global.value("start_comment_mode", "", lang=channel_lang) + "\n" + helper_global.value("target_message", "", lang=channel_lang) + "https://t.me/%s/%d" % (username, msg_id), 55 | reply_markup=motd_markup 56 | ) 57 | else: 58 | link_id = abs(channel_id) % 10000000000 59 | bot.send_message( 60 | chat_id=update.message.chat_id, 61 | text=helper_global.value("start_comment_mode", "", lang=channel_lang) + "\n" + helper_global.value("target_message", "", lang=channel_lang) + "https://t.me/c/%d/%d" % (link_id, msg_id), 62 | reply_markup=motd_markup 63 | ) 64 | elif params[0] == "show": 65 | offset = 0 66 | channel_username = config[4] 67 | 68 | records = helper_database.get_recent_records(channel_id, msg_id, recent, offset) 69 | 70 | # Prepare Keyboard 71 | msg_buttons = helper_global.records_to_buttons(records, channel_id, msg_id) 72 | motd_keyboard = msg_buttons + [[ 73 | InlineKeyboardButton( 74 | helper_global.value("prev_page", "Prev Page", lang=channel_lang), 75 | callback_data="msg,%d,%d,%d,%d,%d" % (channel_id, msg_id, recent, offset + 1, chat_id) 76 | ), 77 | InlineKeyboardButton( 78 | helper_global.value("next_page", "Next Page", lang=channel_lang), 79 | callback_data="msg,%d,%d,%d,%d,%d" % (channel_id, msg_id, recent, offset - 1, chat_id) 80 | ) 81 | ]] 82 | motd_markup = InlineKeyboardMarkup(motd_keyboard) 83 | 84 | prompt_text = helper_global.value("comment_header", "", lang=channel_lang) 85 | if channel_username is not None and len(channel_username) > 0: 86 | prompt_text = "https://t.me/%s/%a\n" % (channel_username, msg_id) + prompt_text 87 | bot.send_message( 88 | chat_id=update.message.chat_id, 89 | text=prompt_text, 90 | parse_mode=telegram.ParseMode.HTML, 91 | reply_markup=motd_markup 92 | ) 93 | 94 | 95 | _handler = CommandHandler('start', start, pass_args=True) 96 | --------------------------------------------------------------------------------