Repository: JogleLew/channel-helper-bot Branch: master Commit: c48f03caf663 Files: 23 Total size: 157.2 KB Directory structure: gitextract_zu_6bqod/ ├── .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 ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ # Created by .ignore support plugin (hsz.mobi) ### Python template # Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python env/ build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ *.egg-info/ .installed.cfg *.egg # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *,cover .hypothesis/ # Translations *.mo *.pot # Django stuff: *.log local_settings.py # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder target/ # Jupyter Notebook .ipynb_checkpoints # pyenv .python-version # celery beat schedule file celerybeat-schedule # SageMath parsed files *.sage.py # dotenv .env # virtualenv .venv venv/ ENV/ # Spyder project settings .spyderproject # Rope project settings .ropeproject # ignore DB file *.db helper_const.py nohup.out ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: README.md ================================================ # Channel Helper Bot Channel Helper Bot 是一个 Telegram Bot,用于给频道添加简单的评论功能。Channel Helper Bot 的功能包括:在频道中创建评论区、收集用户评论和显示最近评论等。使用 Channel Helper Bot 能够为频道提供一个评论的平台,实现轻度的社交功能,有助于促进频道主与关注者、关注者和关注者之间直接的交流和沟通。 ## 特性 ### 简单的评论管理 在频道主发布了新的消息后,仅需要通过简单的操作即可呼出评论区。当频道消息对应的评论区出现在频道中时,关注者即可进行评论操作。 在自动模式下,频道主发布完消息后,无需任何操作,评论区会自动出现。 在手动模式下,频道主发布完消息后,仅需要以 `/command` 指令回复发布的消息,就可出现评论区。 ### 方便的评论过程 每一个评论区都有两个按钮,“添加评论”和“显示所有评论”。点击按钮即自动跳转到 Channel Helper Bot 页面,按照提示进行操作即可完成评论和浏览。 在点击“添加评论”之后,即进入评论模式,向 bot 写下想说的话即可发布评论。如需退出评论模式,请使用 `/cancel` 命令。 在点击“显示所有评论”之后,bot 会在私聊页面显示一个可翻页的评论区,用户能够查看所有之前的评论信息(支持查看贴纸、图片、视频、文件等),管理员可以在这里进行删除消息、封禁用户的操作。 ### 轻松的配置流程 配置过程十分简单,频道主只需几个步骤即可轻松完成 Channel Helper Bot 的配置。 1. 将 bot 添加为频道的管理员,同时 bot 需要足够的权限进行消息的发送和编辑。 2. 向 bot 私聊发送 `/register` 命令,按照 bot 的指示从频道中转发一条消息,用以记录频道的相关信息。 3. 发布一条消息看看吧!如果自动呼出评论区了则说明配置成功。(注:默认情况下 bot 为自动模式) 4. 如果您需要修改配置(模式、最近消息条数等),请向 bot 发送 `/option`命令,按照提示进行配置。 ### 智慧的一物多用 Channel Helper Bot 并不满足于只服务一个频道。任何人都可以通过配置来添加和使用 Channel Helper Bot。同时 bot 本身也是开源的,您可以根据自己的需要另行部署。[@jogle_channel_bot](https://t.me/jogle_channel_bot) 是作者进行部署的最新版 Bot,欢迎使用。 ## 部署 为了能运行 Channel Helper Bot,需要准备一个 Python 3 的环境,并需要使用 pip安装相应的依赖。 ### 安装依赖 `pip3 install python-telegram-bot` ### 配置文件 请将 `helper_const.py.sample` 重命名为 `helper_const.py`,并填写其中的配置项目。 | 配置项目 | 类型 | 含义 |----------------------|---------------|-------------------------------------------------- | BOT_TOKEN | (str) | Telegram Bot 的 token | BOT_OWNER | (list of int) | bot 管理员的 userID | MIN_REFRESH_INTERVAL | (int) | 最小刷新时间间隔,单位为秒 | MODULE_NAME | (list of str) | 启用的模块名称(如无特殊需求,则不需要更改这项) | DATABASE_DIR | (str) | 数据库存放位置 ------------------------------------------------------------------------------------------ ### 运行 bot `python3 helper_main.py` ## 致谢 Channel Helper Bot 使用了 [python-telegram-bot](https://github.com/python-telegram-bot/python-telegram-bot) 的 Bot API。 ================================================ FILE: helper_const.py.sample ================================================ #!/usr/bin/env python # -*- coding: utf-8 -*- """ Channel Helper Bot """ """ helper_const.py """ """ Copyright 2018, Jogle Lew """ BOT_TOKEN = 'Bot Token Here' BOT_OWNER = [Bot Owner 1 UserID, Bot Owner 2 UserID] MIN_REFRESH_INTERVAL = 3 MODULE_NAME = ['start_cmd', 'help_cmd', 'cancel_cmd', 'sql_cmd', 'clean_cmd', 'register_cmd', 'option_cmd', 'channel_msg', 'private_msg', 'callback_query', 'inline_query'] DATABASE_DIR = "." DEFAULT_LANG = "zh-CN" LANG_LIST = ["zh-CN", "pt-BR", "en-US"] LANG_WIDTH = 3 DEFAULT_BUTTONS = ["👍", "👎"] ================================================ FILE: helper_database.py ================================================ #!/usr/bin/env python # -*- coding: utf-8 -*- """ Channel Helper Bot """ """ helper_database.py """ """ Copyright 2018, Jogle Lew """ import os import sqlite3 import helper_const import helper_global from threading import Lock def init_database(filepath): conn = sqlite3.connect(filepath, check_same_thread=False) helper_global.assign("database", conn) cursor = conn.cursor() cursor.execute( """ CREATE TABLE config ( chat_id text PRIMARY KEY, lang text, mode int, recent int, username text, admin_id text, notify int, button int ); """ ) cursor.execute( """ CREATE TABLE reflect ( chat_id text, msg_id text, comment_id text, PRIMARY KEY (chat_id, msg_id) ); """ ) cursor.execute( """ CREATE TABLE button ( chat_id text, msg_id text, options text, PRIMARY KEY (chat_id, msg_id) ); """ ) cursor.execute( """ CREATE TABLE record ( chat_id text, msg_id text, username text, name text, type text, content text, media_id text, date text, user_id text, ori_msg_id text ); """ ) cursor.execute( """ CREATE TABLE blacklist ( chat_id text, user_id text, name text, PRIMARY KEY (chat_id, user_id) ); """ ) cursor.execute( """ CREATE TABLE reaction ( chat_id text, msg_id text, user_id text, option int, PRIMARY KEY (chat_id, msg_id, user_id) ); """ ) cursor.execute("CREATE INDEX record_chat_id_msg_id on record (chat_id, msg_id);") cursor.execute("CREATE INDEX record_user_id_ori_msg_id on record (user_id, ori_msg_id);") conn.commit() def execute(sql, params): lock.acquire() try: conn = helper_global.value("database", None) if conn is None: return cursor = conn.cursor() result = cursor.execute(sql, params) conn.commit() except Exception as e: lock.release() raise e lock.release() return result def get_channel_config(chat_id): script = "SELECT * FROM config WHERE chat_id = ?" params = [str(chat_id)] result = list(execute(script, params)) if len(result) == 0: return None return result[0] def delete_channel_config(chat_id): script = "DELETE FROM config WHERE chat_id = ?" params = [str(chat_id)] result = list(execute(script, params)) return result def get_all_channel_config(): script = "SELECT * FROM config" params = [] result = list(execute(script, params)) return result def add_channel_config(channel_id, lang, mode, recent, channel_username, admin_id, notify, button): script = "INSERT INTO config VALUES (?, ?, ?, ?, ?, ?, ?, ?)" params = [str(channel_id), lang, mode, recent, channel_username, str(admin_id), notify, button] execute(script, params) def update_config_by_channel(channel_id, item, value): script = "UPDATE config SET %s = ? WHERE chat_id = ?" % item params = [value, str(channel_id)] execute(script, params) def add_button_options(chat_id, msg_id, options): script = "DELETE FROM button WHERE chat_id = ? AND msg_id = ?" params = [str(chat_id), str(msg_id)] execute(script, params) script = "INSERT INTO button VALUES (?, ?, ?)" params = [str(chat_id), str(msg_id), " ".join(options)] execute(script, params) def get_button_options(chat_id, msg_id): script = "SELECT options FROM button WHERE chat_id = ? AND msg_id = ?" params = [str(chat_id), str(msg_id)] result = list(execute(script, params)) if len(result) > 0: return result[0][0].split() script = "SELECT options FROM button WHERE chat_id = ? AND msg_id = ?" params = [str(chat_id), str(0)] result = list(execute(script, params)) if len(result) > 0: return result[0][0].split() return helper_const.DEFAULT_BUTTONS def get_default_button_options(chat_id): script = "SELECT options FROM button WHERE chat_id = ? AND msg_id = ?" params = [str(chat_id), str(0)] result = list(execute(script, params)) if len(result) == 0: return helper_const.DEFAULT_BUTTONS return result[0][0].split() def add_reflect(chat_id, msg_id, comment_id): script = "DELETE FROM reflect WHERE chat_id = ? AND msg_id = ?" params = [str(chat_id), str(msg_id)] execute(script, params) script = "INSERT INTO reflect VALUES (?, ?, ?)" params = [str(chat_id), str(msg_id), str(comment_id)] execute(script, params) def check_reflect(chat_id, msg_id): script = "SELECT * FROM reflect WHERE chat_id = ? AND msg_id = ?" params = [str(chat_id), str(msg_id)] result = list(execute(script, params)) if len(result) == 0: return False return True def get_reflect_by_msg_id(chat_id, msg_id_or_comment_id): script = "SELECT * FROM reflect WHERE chat_id = ? AND (msg_id = ? OR comment_id = ?)" params = [str(chat_id), str(msg_id_or_comment_id), str(msg_id_or_comment_id)] result = list(execute(script, params)) if len(result) == 0: return None return result[0] def delete_reflect(chat_id, msg_id): script = "DELETE FROM reflect WHERE chat_id = ? AND msg_id = ?" params = [str(chat_id), str(msg_id)] execute(script, params) def add_record(channel_id, msg_id, username, name, msg_type, msg_content, media_id, date, user_id, ori_msg_id): if len(name) > 15: name = name[:15] + "..." script = "SELECT * FROM record WHERE user_id = ? AND ori_msg_id = ?" params = [str(user_id), str(ori_msg_id)] result = list(execute(script, params)) if len(result) == 0: script = "INSERT INTO record VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" params = [str(channel_id), str(msg_id), username, name, msg_type, msg_content, media_id, date, str(user_id), str(ori_msg_id)] execute(script, params) return 0 else: script = "UPDATE record SET type = ?, content = ?, media_id = ? WHERE user_id = ? AND ori_msg_id = ?" params = [msg_type, msg_content, media_id, str(user_id), str(ori_msg_id)] execute(script, params) return 1 def get_comment_id(channel_id, msg_id): script = "SELECT comment_id FROM reflect WHERE chat_id = ? and msg_id = ?" params = [str(channel_id), str(msg_id)] result = list(execute(script, params)) if len(result) == 0: return None comment_id = int(result[0][0]) return comment_id def get_origin_post(channel_id, msg_id): script = "SELECT comment_id FROM reflect WHERE chat_id = ? and msg_id = ?" params = [str(channel_id), str(msg_id)] result = list(execute(script, params)) if len(result) == 0: return None comment_id = result[0][0] return comment_id def get_recent_records(channel_id, msg_id, recent, offset=0): script = "SELECT *, ROWID FROM record WHERE chat_id = ? and msg_id = ? ORDER BY date DESC LIMIT ? OFFSET ?" params = [str(channel_id), str(msg_id), recent, offset * recent] result = list(execute(script, params)) return result def get_record_by_rowid(row_id): script = "SELECT * FROM record WHERE ROWID = ?" params = [row_id] result = list(execute(script, params)) return result def delete_record_by_rowid(row_id): script = "DELETE FROM record WHERE ROWID = ?" params = [row_id] result = list(execute(script, params)) return result def get_base_offset_by_rowid(channel_id, msg_id, row_id): script = "SELECT count(*) FROM record WHERE chat_id = ? AND msg_id = ? AND ROWID >= ?" params = [str(channel_id), str(msg_id), row_id] result = list(execute(script, params)) return result[0][0] def get_prev_rowid(channel_id, msg_id, row_id): script = "SELECT ROWID FROM record WHERE chat_id = ? AND msg_id = ? AND ROWID > ? ORDER BY ROWID ASC LIMIT 1" params = [str(channel_id), str(msg_id), row_id] result = list(execute(script, params)) if result is not None and len(result) == 1: return result[0][0] return -1 def get_next_rowid(channel_id, msg_id, row_id): script = "SELECT ROWID FROM record WHERE chat_id = ? AND msg_id = ? AND ROWID < ? ORDER BY ROWID DESC LIMIT 1" params = [str(channel_id), str(msg_id), row_id] result = list(execute(script, params)) if result is not None and len(result) == 1: return result[0][0] return -1 def get_channel_info_by_user(user_id): script = "SELECT chat_id, username FROM config WHERE admin_id = ?" params = [str(user_id)] result = list(execute(script, params)) return result def ban_user(channel_id, user_id, name): script = "INSERT INTO blacklist VALUES (?, ?, ?)" params = [str(channel_id), str(user_id), name] result = list(execute(script, params)) return result def unban_user(channel_id, user_id, name): script = "DELETE FROM blacklist WHERE chat_id = ? AND user_id = ?" params = [str(channel_id), str(user_id)] result = list(execute(script, params)) return result def check_ban(channel_id, user_id): script = "SELECT * FROM blacklist WHERE chat_id = ? AND user_id = ?" params = [str(channel_id), str(user_id)] result = list(execute(script, params)) return len(result) > 0 def add_reaction(channel_id, msg_id, user_id, like_id): script = "SELECT count(*) FROM reaction WHERE chat_id = ? AND msg_id = ? AND user_id = ?" params = [str(channel_id), str(msg_id), str(user_id)] result = list(execute(script, params))[0][0] if result == 0: script = "INSERT INTO reaction VALUES(?, ?, ?, ?)" params = [str(channel_id), str(msg_id), str(user_id), like_id] else: script = "UPDATE reaction SET option = ? WHERE chat_id = ? AND msg_id = ? AND user_id = ?" params = [like_id, str(channel_id), str(msg_id), str(user_id)] execute(script, params) def get_reaction_stat(channel_id, msg_id): script = "SELECT option, count(*) FROM reaction WHERE chat_id = ? AND msg_id = ? GROUP BY option" params = [str(channel_id), str(msg_id)] result = list(execute(script, params)) r = {} for like_id, count in result: r[like_id] = count return r def clear_reaction(channel_id, msg_id): script = "DELETE FROM reaction WHERE chat_id = ? AND msg_id = ?" params = [str(channel_id), str(msg_id)] result = list(execute(script, params)) return result lock = Lock() filepath = os.path.join(helper_const.DATABASE_DIR, "data.db") if not os.path.exists(filepath): init_database(filepath) else: conn = sqlite3.connect(filepath, check_same_thread=False) helper_global.assign("database", conn) ================================================ FILE: helper_global.py ================================================ #!/usr/bin/env python # -*- coding: utf-8 -*- """ Channel Helper Bot """ """ helper_global.py """ """ Copyright 2018, Jogle Lew """ import helper_const from threading import Lock from telegram import InlineKeyboardButton, InlineKeyboardMarkup lock = Lock() class GlobalVar: var_set = {} def assign(var_name, var_value, lang=helper_const.DEFAULT_LANG): lock.acquire() if not lang in GlobalVar.var_set: GlobalVar.var_set[lang] = {} GlobalVar.var_set[lang][var_name] = var_value lock.release() def value(var_name, default_value, lang=helper_const.DEFAULT_LANG): if lang == "all": result = "" for lang_item in helper_const.LANG_LIST: result += value(var_name, default_value, lang=lang_item) + "\n\n" return result if not lang in GlobalVar.var_set: lang = helper_const.DEFAULT_LANG lock.acquire() if not var_name in GlobalVar.var_set[lang]: GlobalVar.var_set[lang][var_name] = default_value result = GlobalVar.var_set[lang][var_name] lock.release() return result def get_sender_name(message): real_sender = message.from_user if message.forward_from: real_sender = message.forward_from username = real_sender.first_name if real_sender.last_name: username = username + " " + real_sender.last_name if message.forward_from_chat: username = message.forward_from_chat.title return username def records_to_str(records, lang): s = value("comment_header", "", lang=lang) + "\n" if records is None or len(records) == 0: s += value("comment_empty", "", lang=lang) return s records = records[::-1] for record in records: username = record[2] name = record[3].replace('<', '<').replace('>', '>') msg_type = record[4] msg_content = record[5] s += ("%s: " % name) if not msg_type == "text": s += ("[%s] " % msg_type) s += msg_content + "\n" return s def records_to_buttons(records, channel_id, msg_id): b = [] if records is None or len(records) == 0: return b records = records[::-1] for idx, record in enumerate(records): username = record[2] name = record[3] msg_type = record[4] msg_content = record[5] row_id = record[10] s = ("%s: " % name) if not msg_type == "text": s += ("[%s] " % msg_type) s += msg_content button = [[ InlineKeyboardButton( s, callback_data="msg_detail,%d,%d,%d" % (channel_id, msg_id, row_id) ) ]] b += button return b def parse_entity(src, entity_list): if entity_list is None or len(entity_list) == 0: return src.replace('<', '<').replace('>', '>') head = 0 p_str = "" for entity in entity_list: begin_str = '' end_str = '' if entity.type == 'bold': begin_str = '' end_str = '' elif entity.type == 'code': begin_str = '' end_str = '' elif entity.type == 'italic': begin_str = '' end_str = '' elif entity.type == 'strikethrough': begin_str = '' end_str = '' elif entity.type == 'pre': begin_str = '
'
            end_str = '
' elif entity.type == 'text_link': begin_str = '' % entity.url end_str = '' p_str += src[head:entity.offset].replace('<', '<').replace('>', '>') p_str += begin_str p_str += src[entity.offset:(entity.offset + entity.length)].replace('<', '<').replace('>', '>') p_str += end_str head = entity.offset + entity.length p_str += src[head:] return p_str def send_intro_template(bot, chat_id, lang, key, text_key): # Prepare Keyboard lang_list = helper_const.LANG_LIST width = helper_const.LANG_WIDTH current_lang = lang motd_keyboard = [[ InlineKeyboardButton( lang_list[width * idx + delta] + (" (*)" if lang_list[width * idx + delta] == current_lang else ""), callback_data="%s|%s" % (key, lang_list[width * idx + delta]) ) for delta in range(width) ] for idx in range(len(lang_list) // width)] + [[ InlineKeyboardButton( lang_list[idx] + (" (*)" if lang_list[idx] == current_lang else ""), callback_data="%s|%s" % (key, lang_list[idx]) ) for idx in range(width * (len(lang_list) // width), len(lang_list))]] motd_markup = InlineKeyboardMarkup(motd_keyboard) bot.send_message( chat_id=chat_id, text=value(text_key, "", lang=current_lang), reply_markup=motd_markup ) ================================================ FILE: helper_main.py ================================================ #!/usr/bin/env python # -*- coding: utf-8 -*- """ Channel Helper Bot """ """ helper_main.py """ """ Copyright 2018, Jogle Lew """ import json import logging import traceback import importlib import datetime import helper_global import helper_database import telegram import telegram.bot import messagequeue as mq from telegram.ext import Updater, CommandHandler from telegram.utils.request import Request from ninesix import Logger # config logger logger = Logger("channel_helper", log_level=0, preserve=True) # import constant, strings, database helper_const = importlib.import_module('helper_const') helper_string = importlib.import_module('helper_string') helper_database = importlib.import_module('helper_database') # load admin list helper_global.assign('admin_list', []) def reload_admin_list(): global admin_list admin_list = helper_const.BOT_OWNER helper_global.assign('admin_list', admin_list) reload_admin_list() logger.msg("Admin List: " + str(helper_global.value('admin_list', [])), "main", log_level=100) # config bot class MQBot(telegram.bot.Bot): '''A subclass of Bot which delegates send method handling to MQ''' def __init__(self, *args, is_queued_def=True, mqueue=None, **kwargs): super(MQBot, self).__init__(*args, **kwargs) # below 2 attributes should be provided for decorator usage self._is_messages_queued_default = is_queued_def self._msg_queue = mqueue or mq.MessageQueue() def __del__(self): try: self._msg_queue.stop() except: pass super(MQBot, self).__del__() @mq.queuedmessage def send_message(self, *args, **kwargs): '''Wrapped method would accept new `queued` and `isgroup` OPTIONAL arguments''' return super(MQBot, self).send_message(*args, **kwargs) @mq.queuedmessage def send_audio(self, *args, **kwargs): '''Wrapped method would accept new `queued` and `isgroup` OPTIONAL arguments''' return super(MQBot, self).send_audio(*args, **kwargs) @mq.queuedmessage def send_document(self, *args, **kwargs): '''Wrapped method would accept new `queued` and `isgroup` OPTIONAL arguments''' return super(MQBot, self).send_document(*args, **kwargs) @mq.queuedmessage def send_photo(self, *args, **kwargs): '''Wrapped method would accept new `queued` and `isgroup` OPTIONAL arguments''' return super(MQBot, self).send_photo(*args, **kwargs) @mq.queuedmessage def send_sticker(self, *args, **kwargs): '''Wrapped method would accept new `queued` and `isgroup` OPTIONAL arguments''' return super(MQBot, self).send_sticker(*args, **kwargs) @mq.queuedmessage def send_video(self, *args, **kwargs): '''Wrapped method would accept new `queued` and `isgroup` OPTIONAL arguments''' return super(MQBot, self).send_video(*args, **kwargs) @mq.queuedmessage def send_voice(self, *args, **kwargs): '''Wrapped method would accept new `queued` and `isgroup` OPTIONAL arguments''' return super(MQBot, self).send_voice(*args, **kwargs) @mq.queuedmessage def edit_message_text(self, *args, **kwargs): '''Wrapped method would accept new `queued` and `isgroup` OPTIONAL arguments''' return super(MQBot, self).edit_message_text(*args, **kwargs) @mq.queuedmessage def edit_message_reply_markup(self, *args, **kwargs): '''Wrapped method would accept new `queued` and `isgroup` OPTIONAL arguments''' return super(MQBot, self).edit_message_reply_markup(*args, **kwargs) @mq.queuedmessage def get_chat_administrators(self, *args, **kwargs): '''Wrapped method would accept new `queued` and `isgroup` OPTIONAL arguments''' return super(MQBot, self).get_chat_administrators(*args, **kwargs) q = mq.MessageQueue(all_burst_limit=3, all_time_limit_ms=3000) request = Request(con_pool_size=8) bot = MQBot(token=helper_const.BOT_TOKEN, request=request, mqueue=q) logger.msg(bot.get_me(), tag="main", log_level=100) bot_username = bot.get_me().username helper_global.value('bot', bot) helper_global.value('bot_username', bot_username) updater = Updater(bot=bot, request_kwargs={'read_timeout': 6, 'connect_timeout': 7}, use_context=False) dispatcher = updater.dispatcher job_queue = updater.job_queue def check_admin(check_id): admin_list = helper_global.value('admin_list', []) if check_id in admin_list: return True return False # initial reload command def bot_reload(bot, update): global helper_const global helper_string global helper_database global command_module if not check_admin(update.message.from_user.id): permission_denied = helper_global.value("permission_denied_text", "") bot.send_message(chat_id=update.message.chat_id, text=permission_denied) return ## update constant helper_const = importlib.reload(helper_const) helper_string = importlib.reload(helper_string) helper_database = importlib.reload(helper_database) reload_admin_list() ## remove old handlers for current_module in command_module: dispatcher.remove_handler(current_module._handler) ## reload modules and update handlers try: command_module = [] for module_name in helper_const.MODULE_NAME: logger.msg("Reloading module \"%s\"..." % module_name, tag="main", log_level=100) current_module = importlib.import_module("modules." + module_name) current_module = importlib.reload(current_module) command_module.append(current_module) dispatcher.add_handler(current_module._handler) success_text = helper_global.value("reload_cmd_success", "") bot.send_message(chat_id=update.message.chat_id, text=success_text) except Exception as e: failed_text = helper_global.value("reload_cmd_failed", "") bot.send_message(chat_id=update.message.chat_id, text=failed_text) bot.send_message(chat_id=update.message.chat_id, text=traceback.print_exc()) reload_handler = CommandHandler('reload', bot_reload) dispatcher.add_handler(reload_handler) # initial other commands command_module = [] for module_name in helper_const.MODULE_NAME: logger.msg("Loading module \"%s\"..." % module_name, tag="main", log_level=100) current_module = importlib.import_module("modules." + module_name) command_module.append(current_module) dispatcher.add_handler(current_module._handler) def error(bot, update, error): logger.msg("Update: %s, Error: %s" % (update, error), tag="error", log_level=100) dispatcher.add_error_handler(error) updater.start_polling() ================================================ FILE: helper_string.py ================================================ #!/usr/bin/env python # -*- coding: utf-8 -*- """ Channel Helper Bot """ """ helper_string.py """ """ Copyright 2018, Jogle Lew """ import json import helper_const import helper_global lang_config = helper_const.LANG_LIST for lang_code in lang_config: with open("i18n/%s.json" % lang_code, "r") as f: lang_dict = json.load(f) for item, value in lang_dict.items(): helper_global.assign(item, value, lang=lang_code) ================================================ FILE: i18n/en-US.json ================================================ { "development_text": "This feature is under development...", "permission_denied_text": "No Permission", "reload_cmd_success": "Reloaded. Good luck.", "reload_cmd_failed": "Problem occurred when reloading.", "start_cmd_text": "This is Jogle Lew's Channel Helper Bot. Use /help command for more information.", "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", "add_comment": "Add Comment", "show_all_comments": "Show All Comments", "comment_header": "===== Comments =====", "comment_empty": "", "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", "stop_comment_mode": "[Quit Comment Mode]", "comment_success": "[Comment Successfully]", "comment_edit_success": "[Edit Successfully]", "prev_page": "Prev Page", "next_page": "Next Page", "no_prev_page": "No previous page", "no_next_page": "No next page", "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.", "register_cmd_invalid": "This message contains no channel info. Please forward me an original message from your channel.", "register_cmd_not_admin": "You are not the channel admin, so you're not allowed to register.", "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.", "register_cmd_no_info": "This bot cannot access your channel. Please check whether the bot is an admin of your channel.", "register_cmd_failed": "Registration Failed. Maybe you've already registered. Please contact the developer @JogleLew for further assistance.", "register_cmd_success": "Registered Successfully. Default config is applied to your channel. Use /option command to modify your config.", "option_no_channel": "No registration info found. Please use /register command first.", "option_delete": "Delete registration", "option_record_deleted": "Registration record is deleted. Thanks for your using!", "option_back": "Go back", "option_finish": "Finish", "option_finished": "Config updated.", "option_choose_channel": "Please choose a channel to config.", "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", "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: ", "option_choose_recent_value": "In a comment message, only the most recent comments appear. Please choose the number of shown comments:", "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.", "option_choose_lang_value": "Choose the language of comment buttons and text in your channel. Take effect when the next message is coming", "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\"", "option_update_success": "Config updated", "option_update_failed": "Failed to update config", "clean_cmd_start": "Now checking, Please wait...", "clean_cmd_deleted": "Registration record deleted", "clean_cmd_set": "Auto schedule set", "fwd_source": "From: ", "prev_msg": "Prev Comment", "next_msg": "Next Comment", "no_message_detail": "No comment detail found", "back_to_msg_list": "Back to comment list", "msg_from": "From: ", "delete_msg": "Delete Comment", "delete_success": "Comment deleted.", "ban_user": "Ban User", "unban_user": "Unban User", "user_banned": "User banned.", "user_banned_failed": "Failed to ban this user. This user might have been banned.", "user_unbanned": "User unbanned.", "banned_prompt": "You are not allowed to leave comments in this channel.", "new_comment_message": "New comment received.", "new_reply_message": "New reply received.", "target_message": "Target message: ", "like_recorded": "You %s it.", "comment_refreshing": "Refreshing...", "reply_to": "Reply to ", "reply_prompt": "Write comment first, then choose a comment to reply.", "jump_to_comment": "Go to Comments" } ================================================ FILE: i18n/pt-BR.json ================================================ { "development_text": "Esta função ainda está em desenvolvimento...", "permission_denied_text": "Sem permissão", "reload_cmd_success": "Recarregado. Boa sorte.", "reload_cmd_failed": "Ocorreu um problema ao recarregar.", "start_cmd_text": "Este é o bot Channel Helper de Jogle Lew. Use o comando /help para obter mais informações.", "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", "add_comment": "Comentar", "show_all_comments": "Todos os comentários", "comment_header": "===== Comentários =====", "comment_empty": "", "start_comment_mode": "[Modo de comentário] Deixe um comentário enviando uma mensagem. Envie /cancel para sair deste modo.", "stop_comment_mode": "[Saiu do Modo de comentário]", "comment_success": "[Comentário enviado]", "comment_edit_success": "[Editado com sucesso]", "prev_page": "Página anterior", "next_page": "Próxima página", "no_prev_page": "Nenhuma página anterior", "no_next_page": "Nenhuma página seguinte", "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.", "register_cmd_invalid": "Esta mensagem não contém informações do canal. Envie-me uma mensagem original do seu canal.", "register_cmd_not_admin": "Você não é o administrador do canal, portanto não tem permissão para se registrar.", "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.", "register_cmd_no_info": "Este bot não pode acessar seu canal. Verifique se o bot é um administrador do seu canal. ", "register_cmd_failed": "Falha no registro. Entre em contato com o desenvolvedor @JogleLew para obter ajuda.", "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.", "option_no_channel": "Nenhuma informação de registro encontrada. Por favor, use o comando /register antes.", "option_delete": "Excluir registro", "option_record_deleted": "O registro foi excluído. Obrigado pela sua utilização!", "option_back": "Voltar", "option_finish": "Concluir", "option_finished": "Configuração atualizada.", "option_choose_channel": "Por favor, escolha um canal para configurar.", "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", "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: ", "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:", "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.", "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", "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ê\"", "option_update_success": "Configuração atualizada", "option_update_failed": "Falha ao atualizar a configuração", "clean_cmd_start": "Verificando. Por favor, aguarde...", "clean_cmd_deleted": "Registro excluído", "clean_cmd_set": "Agendamento automático definido", "fwd_source": "De: ", "prev_msg": "Comentário anterior", "next_msg": "Próximo comentário", "no_message_detail": "Nenhum comentário encontrado", "back_to_msg_list": "Voltar à lista de comentários", "msg_from": "De: ", "delete_msg": "Excluir comentário", "delete_success": "Comentário excluído.", "ban_user": "Banir usuário", "unban_user": "Desbanir usuário", "user_banned": "Usuário banido.", "user_banned_failed": "Falha ao banir este usuário. Este usuário pode já ter sido banido.", "user_unbanned": "Usuário desbanido.", "banned_prompt": "Você não tem permissão para comentar neste canal.", "new_comment_message": "Novo comentário recebido.", "new_reply_message": "Nova resposta recebida.", "target_message": "Mensagem de destino: ", "like_recorded": "Você enviou %s.", "comment_refreshing": "Atualizando...", "reply_to": "Responder para ", "jump_to_comment": "Go to Comments" } ================================================ FILE: i18n/zh-CN.json ================================================ { "development_text": "该功能正在开发中...", "permission_denied_text": "你怕不是假的 jogle", "reload_cmd_success": "重启好了,很棒棒哦!", "reload_cmd_failed": "嗯,好像出现了一些问题呢…", "start_cmd_text": "这是由 JogleLew 开发的频道回复助手 Bot 。你可以使用 /help 命令查看详细使用说明。", "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 命令。", "add_comment": "添加评论", "show_all_comments": "显示所有评论", "comment_header": "===== 评论区 =====", "comment_empty": "", "start_comment_mode": "[进入评论模式] 向我发送消息即可进行评论。使用 Inline Query 可以回复一条评论。使用 /cancel 命令可以中止评论模式。", "stop_comment_mode": "[退出评论模式]", "comment_success": "[评论成功]", "comment_edit_success": "[编辑评论成功]", "prev_page": "上一页", "next_page": "下一页", "no_prev_page": "没有上一页了", "no_next_page": "没有下一页了", "register_cmd_text": "请先将本 bot 添加为频道的管理员(注:只需要在频道设置中添加管理员,搜索本 bot 的 username,点击添加即可),并授予 bot 发送、编辑、删除消息的权限。然后从您的频道中转发一条消息(这条消息不能是转发的别处的消息)给我,以便我获取频道的 ID。", "register_cmd_invalid": "这条消息中似乎不包含频道信息呢...请从您的频道中转发一条消息给我", "register_cmd_not_admin": "您看起来不是频道的管理员呢,本 bot 无法为您进行登记", "register_cmd_no_permission": "检测到您没有给本 bot 提供发送、编辑、删除消息的权限。修改完权限后,请重新执行登记操作。", "register_cmd_no_info": "本 bot 无法获取您的频道信息,请检查是否已经将本 bot 添加为频道管理员。", "register_cmd_failed": "频道信息记录失败,您可能已经注册过。如有问题请联系管理员 @JogleLew", "register_cmd_success": "您的频道信息已成功记录,并启用了默认的评论设置。如需修改配置,请使用 /option 命令。", "option_no_channel": "您还没有登记过频道信息,请先使用 /register 命令完成登记。", "option_delete": "删除频道记录", "option_record_deleted": "频道记录已删除,感谢您的使用!", "option_back": "返回", "option_finish": "完成配置", "option_finished": "配置已完成", "option_choose_channel": "请选择一个频道以进行配置", "option_choose_item": "请选择一个项目以进行配置\nmode: bot 的工作模式\nrecent: 在频道中显示的评论数量\nnotify: 新评论提醒\nlang: 评论功能使用的语言\nbutton: 点赞按钮显示方式", "option_choose_mode_value": "本 bot 有三种工作模式\n模式 0: 手动模式。当频道中新增消息时,bot 不会自动创建评论消息。当频道管理员使用 /comment 回复需要评论的原始消息时,bot 才会创建评论消息。\n模式 1: 自动模式。当频道中新增消息时,bot 自动创建评论消息。该模式能保持原始频道消息不被修改。\n模式 2: 自动模式(beta)。当频道中新增消息时,bot 会尝试编辑原消息,显示添加评论按钮。如果编辑失败则直接创建评论消息。该模式能尽可能减少频道里的评论区数量。\n请选择您所需要的工作模式:", "option_choose_recent_value": "在频道中仅显示最近的若干条评论内容。请选择频道显示评论的最近条目数量:", "option_choose_notify_value": "您可以选择当频道收到新评论时是否开启提醒功能。0代表关闭,1代表开启。将在从下一条消息开始生效。", "option_choose_lang_value": "请选择频道中评论功能采用的语言。", "option_choose_button_value": "请选择评论区点赞按钮显示的方式。\n0代表永不显示\n1代表自动显示,默认为%s。在您的频道内发送 /defaultbuttons + 用空格分隔的内容可以修改默认按钮。\n2代表手动模式,可以自行设定显示内容\n当处于模式1或模式2时,在频道内使用 /comment + 用空格分隔的内容,即可在频道内添加或更换点赞按钮。(如使用 /comment 我 ❤️ 你,则相应的消息会出现\"我\"、\"❤️\"、\"你\"的三个点赞按钮)", "option_update_success": "配置更新成功", "option_update_failed": "配置更新失败", "clean_cmd_start": "正在进行检查,请稍候...", "clean_cmd_deleted": "删除记录成功", "clean_cmd_set": "设置成功", "fwd_source": "消息来源: ", "prev_msg": "上一条消息", "next_msg": "下一条消息", "no_message_detail": "未找到消息", "back_to_msg_list": "返回消息列表", "msg_from": "消息来源:", "delete_msg": "删除消息", "delete_success": "消息删除成功", "ban_user": "封禁用户", "unban_user": "解封用户", "user_banned": "已封禁该用户", "user_banned_failed": "封禁失败,该用户可能已被封禁", "user_unbanned": "用户已解封", "banned_prompt": "频道管理员不允许你进行评论操作", "new_comment_message": "您收到了新的评论", "new_reply_message": "您收到了一条评论回复", "target_message": "目标消息:", "like_recorded": "您觉得这很 %s", "comment_refreshing": "评论区刷新中...", "reply_to": "回复 ", "reply_prompt": "先填写回复信息,再选择需要回复的评论", "jump_to_comment": "跳转到评论区" } ================================================ FILE: messagequeue.py ================================================ #!/usr/bin/env python # # Module author: # Tymofii A. Khodniev (thodnev) # # A library that provides a Python interface to the Telegram Bot API # Copyright (C) 2015-2020 # Leandro Toledo de Souza # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser Public License for more details. # # You should have received a copy of the GNU Lesser Public License # along with this program. If not, see [http://www.gnu.org/licenses/] """ Channel Helper Bot """ """ helper_main.py """ """ Copyright 2020, Jogle Lew """ """A throughput-limiting message processor for Telegram bots.""" from telegram.utils import promise import functools import time import threading import queue as q import uuid from datetime import datetime from ninesix import Logger class DelayPriorityQueueError(RuntimeError): """Indicates processing errors.""" pass class DelayPriorityQueue(threading.Thread): """ Processes callbacks from queue with specified throughput limits. Creates a separate thread to process callbacks with delays. Attributes: burst_limit (:obj:`int`): Number of maximum callbacks to process per time-window. time_limit (:obj:`int`): Defines width of time-window used when each processing limit is calculated. exc_route (:obj:`callable`): A callable, accepting 1 positional argument; used to route exceptions from processor thread to main thread; name (:obj:`str`): Thread's name. Args: queue (:obj:`Queue`, optional): Used to pass callbacks to thread. Creates ``Queue`` implicitly if not provided. burst_limit (:obj:`int`, optional): Number of maximum callbacks to process per time-window defined by :attr:`time_limit_ms`. Defaults to 30. time_limit_ms (:obj:`int`, optional): Defines width of time-window used when each processing limit is calculated. Defaults to 1000. exc_route (:obj:`callable`, optional): A callable, accepting 1 positional argument; used to route exceptions from processor thread to main thread; is called on `Exception` subclass exceptions. If not provided, exceptions are routed through dummy handler, which re-raises them. autostart (:obj:`bool`, optional): If :obj:`True`, processor is started immediately after object's creation; if :obj:`False`, should be started manually by `start` method. Defaults to :obj:`True`. name (:obj:`str`, optional): Thread's name. Defaults to ``'DelayPriorityQueue-N'``, where N is sequential number of object created. """ _instcnt = 0 # instance counter def __init__(self, queue=None, burst_limit=30, time_limit_ms=1000, exc_route=None, autostart=True, name=None): self._queue = queue if queue is not None else q.PriorityQueue() self.prior_dict = {} self.prior_date = datetime.today().strftime("%Y-%m-%d") self.lock = threading.Lock() self.burst_limit = burst_limit self.time_limit = time_limit_ms / 1000 self.exc_route = (exc_route if exc_route is not None else self._default_exception_handler) self.__exit_req = False # flag to gently exit thread self.__class__._instcnt += 1 if name is None: name = '{}-{}'.format(self.__class__.__name__, self.__class__._instcnt) super().__init__(name=name) self.daemon = False if autostart: # immediately start processing super().start() def run(self): """ Do not use the method except for unthreaded testing purposes, the method normally is automatically called by autostart argument. """ times = [] # used to store each callable processing time while True: item = self._queue.get() if self.__exit_req: return # shutdown thread # delay routine now = time.perf_counter() t_delta = now - self.time_limit # calculate early to improve perf. if times and t_delta > times[-1]: # if last call was before the limit time-window # used to impr. perf. in long-interval calls case times = [now] else: # collect last in current limit time-window times = [t for t in times if t >= t_delta] times.append(now) if len(times) >= self.burst_limit: # if throughput limit was hit time.sleep(times[1] - t_delta) # finally process one try: priority, uuid, func, args, kwargs = item func(*args, **kwargs) except Exception as exc: # re-route any exceptions self.exc_route(exc) # to prevent thread exit def stop(self, timeout=None): """Used to gently stop processor and shutdown its thread. Args: timeout (:obj:`float`): Indicates maximum time to wait for processor to stop and its thread to exit. If timeout exceeds and processor has not stopped, method silently returns. :attr:`is_alive` could be used afterwards to check the actual status. ``timeout`` set to :obj:`None`, blocks until processor is shut down. Defaults to :obj:`None`. """ self.__exit_req = True # gently request self._queue.put(None) # put something to unfreeze if frozen super().join(timeout=timeout) @staticmethod def _default_exception_handler(exc): """ Dummy exception handler which re-raises exception in thread. Could be possibly overwritten by subclasses. """ raise exc def __call__(self, func, *args, **kwargs): """Used to process callbacks in throughput-limiting thread through queue. Args: func (:obj:`callable`): The actual function (or any callable) that is processed through queue. *args (:obj:`list`): Variable-length `func` arguments. **kwargs (:obj:`dict`): Arbitrary keyword-arguments to `func`. """ if not self.is_alive() or self.__exit_req: raise DelayPriorityQueueError('Could not process callback in stopped thread') current_date = datetime.today().strftime("%Y-%m-%d") if current_date != self.prior_date: self.prior_date = current_date self.lock.acquire() self.prior_dict = {} self.lock.release() 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) channel_id = str(channel_id) self.lock.acquire() if not channel_id in self.prior_dict: self.prior_dict[channel_id] = 0 self.prior_dict[channel_id] += 1 priority = self.prior_dict[channel_id] self.lock.release() logger = Logger.logger logger.msg({ "channel_id": channel_id, "priority": priority }, tag="queue", log_level=20) self._queue.put((priority, uuid.uuid1(), func, args, kwargs)) # The most straightforward way to implement this is to use 2 sequential delay # queues, like on classic delay chain schematics in electronics. # So, message path is: # msg --> group delay if group msg, else no delay --> normal msg delay --> out # This way OS threading scheduler cares of timings accuracy. # (see time.time, time.clock, time.perf_counter, time.sleep @ docs.python.org) class MessageQueue: """ Implements callback processing with proper delays to avoid hitting Telegram's message limits. Contains two ``DelayPriorityQueue``, for group and for all messages, interconnected in delay chain. Callables are processed through *group* ``DelayPriorityQueue``, then through *all* ``DelayPriorityQueue`` for group-type messages. For non-group messages, only the *all* ``DelayPriorityQueue`` is used. Args: all_burst_limit (:obj:`int`, optional): Number of maximum *all-type* callbacks to process per time-window defined by :attr:`all_time_limit_ms`. Defaults to 30. all_time_limit_ms (:obj:`int`, optional): Defines width of *all-type* time-window used when each processing limit is calculated. Defaults to 1000 ms. group_burst_limit (:obj:`int`, optional): Number of maximum *group-type* callbacks to process per time-window defined by :attr:`group_time_limit_ms`. Defaults to 20. group_time_limit_ms (:obj:`int`, optional): Defines width of *group-type* time-window used when each processing limit is calculated. Defaults to 60000 ms. exc_route (:obj:`callable`, optional): A callable, accepting one positional argument; used to route exceptions from processor threads to main thread; is called on ``Exception`` subclass exceptions. If not provided, exceptions are routed through dummy handler, which re-raises them. autostart (:obj:`bool`, optional): If :obj:`True`, processors are started immediately after object's creation; if :obj:`False`, should be started manually by :attr:`start` method. Defaults to :obj:`True`. """ def __init__(self, all_burst_limit=30, all_time_limit_ms=1000, group_burst_limit=20, group_time_limit_ms=60000, exc_route=None, autostart=True): # create according delay queues, use composition self._all_delayq = DelayPriorityQueue( burst_limit=all_burst_limit, time_limit_ms=all_time_limit_ms, exc_route=exc_route, autostart=autostart) self._group_delayq = DelayPriorityQueue( burst_limit=group_burst_limit, time_limit_ms=group_time_limit_ms, exc_route=exc_route, autostart=autostart) def start(self): """Method is used to manually start the ``MessageQueue`` processing.""" self._all_delayq.start() self._group_delayq.start() def stop(self, timeout=None): self._group_delayq.stop(timeout=timeout) self._all_delayq.stop(timeout=timeout) stop.__doc__ = DelayPriorityQueue.stop.__doc__ or '' # reuse docstring if any def __call__(self, promise, is_group_msg=False): """ Processes callables in throughput-limiting queues to avoid hitting limits (specified with :attr:`burst_limit` and :attr:`time_limit`. Args: promise (:obj:`callable`): Mainly the ``telegram.utils.promise.Promise`` (see Notes for other callables), that is processed in delay queues. is_group_msg (:obj:`bool`, optional): Defines whether ``promise`` would be processed in group*+*all* ``DelayPriorityQueue``s (if set to :obj:`True`), or only through *all* ``DelayPriorityQueue`` (if set to :obj:`False`), resulting in needed delays to avoid hitting specified limits. Defaults to :obj:`False`. Note: Method is designed to accept ``telegram.utils.promise.Promise`` as ``promise`` argument, but other callables could be used too. For example, lambdas or simple functions could be used to wrap original func to be called with needed args. In that case, be sure that either wrapper func does not raise outside exceptions or the proper :attr:`exc_route` handler is provided. Returns: :obj:`callable`: Used as ``promise`` argument. """ if not is_group_msg: # ignore middle group delay self._all_delayq(promise) else: # use middle group delay self._group_delayq(self._all_delayq, promise) return promise def queuedmessage(method): """A decorator to be used with :attr:`telegram.Bot` send* methods. Note: As it probably wouldn't be a good idea to make this decorator a property, it has been coded as decorator function, so it implies that first positional argument to wrapped MUST be self. The next object attributes are used by decorator: Attributes: self._is_messages_queued_default (:obj:`bool`): Value to provide class-defaults to ``queued`` kwarg if not provided during wrapped method call. self._msg_queue (:class:`telegram.ext.messagequeue.MessageQueue`): The actual ``MessageQueue`` used to delay outbound messages according to specified time-limits. Wrapped method starts accepting the next kwargs: Args: queued (:obj:`bool`, optional): If set to :obj:`True`, the ``MessageQueue`` is used to process output messages. Defaults to `self._is_queued_out`. isgroup (:obj:`bool`, optional): If set to :obj:`True`, the message is meant to be group-type(as there's no obvious way to determine its type in other way at the moment). Group-type messages could have additional processing delay according to limits set in `self._out_queue`. Defaults to :obj:`False`. Returns: ``telegram.utils.promise.Promise``: In case call is queued or original method's return value if it's not. """ @functools.wraps(method) def wrapped(self, *args, **kwargs): queued = kwargs.pop('queued', self._is_messages_queued_default) isgroup = kwargs.pop('isgroup', False) if queued: prom = promise.Promise(method, (self, ) + args, kwargs) return self._msg_queue(prom, isgroup) return method(self, *args, **kwargs) return wrapped ================================================ FILE: modules/callback_query.py ================================================ #!/usr/bin/env python # -*- coding: utf-8 -*- """ Channel Helper Bot """ """ callback_query.py """ """ Copyright 2018, Jogle Lew """ import helper_const import helper_global import helper_database import modules.option_cmd as option_cmd import modules.private_msg as private_msg import telegram from telegram import InlineKeyboardButton, InlineKeyboardMarkup, \ InputMediaAudio, InputMediaDocument, InputMediaPhoto, InputMediaVideo from telegram.ext import CallbackQueryHandler from ninesix import Logger def show_msg(bot, update, origin_message_id, chat_id, args): channel_id = int(args[1]) msg_id = int(args[2]) recent = int(args[3]) offset = int(args[4]) ori_chat_id = int(args[5]) config = helper_database.get_channel_config(channel_id) if config is None: return channel_lang = config[1] channel_username = config[4] if offset < 0: bot.answer_callback_query( callback_query_id=update.callback_query.id, text=helper_global.value("no_next_page", "", lang=channel_lang) ) return records = helper_database.get_recent_records(channel_id, msg_id, recent, offset) # Prepare Keyboard msg_buttons = helper_global.records_to_buttons(records, channel_id, msg_id) motd_keyboard = msg_buttons + [[ InlineKeyboardButton( helper_global.value("prev_page", "Prev Page", lang=channel_lang), callback_data="msg,%d,%d,%d,%d,%d" % (channel_id, msg_id, recent, offset + 1, ori_chat_id) ), InlineKeyboardButton( helper_global.value("next_page", "Next Page", lang=channel_lang), callback_data="msg,%d,%d,%d,%d,%d" % (channel_id, msg_id, recent, offset - 1, ori_chat_id) ) ]] motd_markup = InlineKeyboardMarkup(motd_keyboard) if offset > 0 and len(records) == 0: bot.answer_callback_query( callback_query_id=update.callback_query.id, text=helper_global.value("no_prev_page", "", lang=channel_lang) ) return prompt_text = helper_global.value("comment_header", "", lang=channel_lang) if channel_username is not None and len(channel_username) > 0: prompt_text = "https://t.me/%s/%a\n" % (channel_username, msg_id) + prompt_text bot.send_message( chat_id=ori_chat_id, text=prompt_text, parse_mode=telegram.ParseMode.HTML, reply_markup=motd_markup ) bot.delete_message( chat_id=chat_id, message_id=origin_message_id ) def msg_detail(bot, update, chat_id, origin_message_id, args): channel_id = int(args[1]) msg_id = int(args[2]) row_id = int(args[3]) config = helper_database.get_channel_config(channel_id) if config is None: return channel_lang = config[1] recent = config[3] admin_id = config[5] if row_id < 0: bot.answer_callback_query( callback_query_id=update.callback_query.id, text=helper_global.value("no_message_detail", "No Message", lang=channel_lang) ) return records = helper_database.get_record_by_rowid(row_id) if records is None or len(records) == 0: bot.answer_callback_query( callback_query_id=update.callback_query.id, text=helper_global.value("no_message_detail", "No Message", lang=channel_lang) ) return record = records[0] username = record[2] name = record[3] msg_type = record[4] msg_content = record[5] media_id= record[6] user_id = int(record[8]) base_offset = helper_database.get_base_offset_by_rowid(channel_id, msg_id, row_id) offset = base_offset // recent msg_from_button = [ [ InlineKeyboardButton( helper_global.value("msg_from", "Message From: ", lang=channel_lang) + name, callback_data="blank" ) ] ] admin_operation_button = [ [ InlineKeyboardButton( helper_global.value("delete_msg", "Delete Message", lang=channel_lang), callback_data="msg_delete,%d,%d,%d,%d,%d,%d" % (row_id, channel_id, msg_id, recent, offset, chat_id) ), InlineKeyboardButton( helper_global.value("unban_user", "Unban User", lang=channel_lang), callback_data="user_unban,%d,%d,%s,%d,%d" % (channel_id, user_id, "", msg_id, row_id) ) if helper_database.check_ban(channel_id, user_id) else \ InlineKeyboardButton( helper_global.value("ban_user", "Ban User", lang=channel_lang), callback_data="user_ban,%d,%d,%s,%d,%d" % (channel_id, user_id, "", msg_id, row_id) ) ] ] if str(chat_id) == str(admin_id) else [] motd_keyboard = msg_from_button + admin_operation_button + [ [ InlineKeyboardButton( helper_global.value("prev_msg", "Prev Message", lang=channel_lang), callback_data="msg_detail,%d,%d,%d" % (channel_id, msg_id, helper_database.get_next_rowid(channel_id, msg_id, row_id)) ), InlineKeyboardButton( helper_global.value("next_msg", "Next Message", lang=channel_lang), callback_data="msg_detail,%d,%d,%d" % (channel_id, msg_id, helper_database.get_prev_rowid(channel_id, msg_id, row_id)) ) ], [ InlineKeyboardButton( helper_global.value("back_to_msg_list", "Back to message list", lang=channel_lang), callback_data="msg,%d,%d,%d,%d,%d" % (channel_id, msg_id, recent, offset, chat_id) ) ] ] motd_markup = InlineKeyboardMarkup(motd_keyboard) if msg_type == "text": bot.send_message( chat_id=chat_id, text=msg_content, parse_mode='HTML', reply_markup=motd_markup ) bot.delete_message( chat_id=chat_id, message_id=origin_message_id ) elif msg_type == "audio" or msg_type == "document" or msg_type == "photo" or msg_type == "video" or msg_type == "sticker" or msg_type == "voice": send_func = { "audio": bot.send_audio, "document": bot.send_document, "photo": bot.send_photo, "video": bot.send_video, "sticker": bot.send_sticker, "voice": bot.send_voice } send_func[msg_type]( chat_id, media_id, caption=msg_content, parse_mode='HTML', reply_markup=motd_markup ) bot.delete_message( chat_id=chat_id, message_id=origin_message_id ) else: bot.send_message( chat_id=chat_id, text="[%s] %s" % (msg_type, msg_content), parse_mode='HTML', reply_markup=motd_markup ) bot.delete_message( chat_id=chat_id, message_id=origin_message_id ) def option_finish(bot, lang, chat_id, origin_message_id): bot.edit_message_text( chat_id=chat_id, message_id=origin_message_id, text=helper_global.value("option_finished", "", lang=lang) ) def option_item(bot, update, lang, chat_id, origin_message_id, args): # Prepare Keyboard motd_keyboard = [[ InlineKeyboardButton( "mode", callback_data="option|%s,%s,mode" % (lang, args[1]) ), InlineKeyboardButton( "recent", callback_data="option|%s,%s,recent" % (lang, args[1]) ), InlineKeyboardButton( "notify", callback_data="option|%s,%s,notify" % (lang, args[1]) ) ]] + [[ InlineKeyboardButton( "lang", callback_data="option|%s,%s,lang" % (lang, args[1]) ), InlineKeyboardButton( "button", callback_data="option|%s,%s,button" % (lang, args[1]) ) ]] + [[ InlineKeyboardButton( helper_global.value("option_delete", "", lang=lang), callback_data="option_delete|%s,%s" % (lang, args[1]) ) ]] + [[ InlineKeyboardButton( helper_global.value("option_finish", "", lang=lang), callback_data="option_finish|%s" % lang ) ]] motd_markup = InlineKeyboardMarkup(motd_keyboard) bot.answer_callback_query( callback_query_id=update.callback_query.id ) bot.edit_message_text( chat_id=chat_id, message_id=origin_message_id, text=helper_global.value("option_choose_item", "", lang=lang), reply_markup=motd_markup ) def option_key(bot, update, key, values, lang, chat_id, origin_message_id, args): config = helper_database.get_channel_config(args[1]) if config is None or len(config) == 0: return key2idx = { "lang": 1, "mode": 2, "recent": 3, "notify": 6, "button": 7 } # Prepare Keyboard width = helper_const.LANG_WIDTH motd_keyboard = [[ InlineKeyboardButton( values[idx * width + delta] + (" (*)" if str(values[idx * width + delta]) == str(config[key2idx[key]]) else ""), callback_data="option|%s,%s,%s,%s" % (lang, args[1], key, values[idx * width + delta]) ) for delta in range(width) ] for idx in range(len(values) // width)] + [[ InlineKeyboardButton( values[idx] + (" (*)" if str(values[idx]) == str(config[key2idx[key]]) else ""), callback_data="option|%s,%s,%s,%s" % (lang, args[1], key, values[idx]) ) for idx in range(width * (len(values) // width), len(values))]] + [[ InlineKeyboardButton( helper_global.value("option_back", "", lang=lang), callback_data="option|%s,%s" % (lang, args[1]) ) ]] motd_markup = InlineKeyboardMarkup(motd_keyboard) text = helper_global.value("option_choose_%s_value" % key, "", lang=lang) if key == "button": text = text % (", ".join(helper_database.get_default_button_options(args[1]))) bot.answer_callback_query( callback_query_id=update.callback_query.id ) bot.edit_message_text( chat_id=chat_id, message_id=origin_message_id, text=text, reply_markup=motd_markup ) def option_delete(bot, lang, chat_id, origin_message_id, args): channel_id = args[1] helper_database.delete_channel_config(channel_id) bot.edit_message_text( chat_id=chat_id, message_id=origin_message_id, text=helper_global.value("option_record_deleted", "", lang=lang) ) def option_update(bot, update, lang, chat_id, origin_message_id, args): try: helper_database.update_config_by_channel(args[1], args[2], args[3]) bot.answer_callback_query( callback_query_id=update.callback_query.id, text=helper_global.value("option_update_success", "", lang=lang) ) except: bot.answer_callback_query( callback_query_id=update.callback_query.id, text=helper_global.value("option_update_failed", "", lang=lang) ) option_item(bot, update, lang, chat_id, origin_message_id, args) def option_index(bot, update, lang, chat_id, origin_message_id, args): records = helper_database.get_channel_info_by_user(chat_id) if records is None or len(records) == 0: bot.send_message( chat_id=chat_id, text=helper_global.value("option_no_channel", "", lang=lang) ) return #Prepare keyboard lang_list = helper_const.LANG_LIST width = helper_const.LANG_WIDTH current_lang = lang key = "option" motd_keyboard = [[ InlineKeyboardButton( "@" + record[1] if record[1] else "id: " + str(record[0]), callback_data="option|%s,%s" % (lang, record[0]) ) ] for record in records] + [[ InlineKeyboardButton( helper_global.value("option_finish", "", lang), callback_data="option_finish|%s" % lang ) ]] + [[ InlineKeyboardButton( lang_list[width * idx + delta] + (" (*)" if lang_list[width * idx + delta] == current_lang else ""), callback_data="%s|%s" % (key, lang_list[width * idx + delta]) ) for delta in range(width) ] for idx in range(len(lang_list) // width)] + [[ InlineKeyboardButton( lang_list[idx] + (" (*)" if lang_list[idx] == current_lang else ""), callback_data="%s|%s" % (key, lang_list[idx]) ) for idx in range(width * (len(lang_list) // width), len(lang_list))]] motd_markup = InlineKeyboardMarkup(motd_keyboard) bot.answer_callback_query( callback_query_id=update.callback_query.id ) bot.edit_message_text( chat_id=chat_id, message_id=origin_message_id, text=helper_global.value("option_choose_channel", "", lang=lang), reply_markup=motd_markup ) def msg_delete(bot, update, chat_id, origin_message_id, args): row_id = int(args[1]) channel_id = int(args[2]) msg_id = int(args[3]) msg_args = ["msg"] + args[2:] config = helper_database.get_channel_config(channel_id) if config is None: return channel_lang = config[1] helper_database.delete_record_by_rowid(row_id) bot.answer_callback_query( callback_query_id=update.callback_query.id, text=helper_global.value("delete_success", "", lang=channel_lang) ) private_msg.update_dirty_msg(channel_id, msg_id) show_msg(bot, update, origin_message_id, chat_id, msg_args) def user_ban(bot, update, chat_id, origin_message_id, args): channel_id = int(args[1]) user_id = int(args[2]) name = args[3] msg_id = int(args[4]) row_id = int(args[5]) config = helper_database.get_channel_config(channel_id) if config is None: return channel_lang = config[1] try: helper_database.ban_user(channel_id, user_id, name) except: bot.answer_callback_query( callback_query_id=update.callback_query.id, text=helper_global.value("user_banned_failed", "", lang=channel_lang) ) bot.answer_callback_query( callback_query_id=update.callback_query.id, text=helper_global.value("user_banned", "", lang=channel_lang) ) msg_detail(bot, update, chat_id, origin_message_id, ["msg_detail", channel_id, msg_id, row_id]) def user_unban(bot, update, chat_id, origin_message_id, args): channel_id = int(args[1]) user_id = int(args[2]) name = args[3] msg_id = int(args[4]) row_id = int(args[5]) config = helper_database.get_channel_config(channel_id) if config is None: return channel_lang = config[1] helper_database.unban_user(channel_id, user_id, name) bot.answer_callback_query( callback_query_id=update.callback_query.id, text=helper_global.value("user_unbanned", "", lang=channel_lang) ) msg_detail(bot, update, chat_id, origin_message_id, ["msg_detail", channel_id, msg_id, row_id]) def reaction(bot, update, chat_id, origin_message_id, user_id, args): channel_id = int(args[1]) msg_id = int(args[2]) like_id = int(args[3]) config = helper_database.get_channel_config(channel_id) if config is None: return channel_lang, mode = config[1], config[2] buttons = helper_database.get_button_options(channel_id, msg_id) helper_database.add_reaction(channel_id, msg_id, user_id, like_id) private_msg.update_dirty_msg(channel_id, msg_id, update_mode=(2 if mode == 3 else 0)) bot.answer_callback_query( callback_query_id=update.callback_query.id, text=helper_global.value("like_recorded", "", lang=channel_lang) % buttons[like_id] ) def intro_template(bot, update, lang, chat_id, origin_message_id, key, text_key): lang_list = helper_const.LANG_LIST width = helper_const.LANG_WIDTH current_lang = lang motd_keyboard = [[ InlineKeyboardButton( lang_list[width * idx + delta] + (" (*)" if lang_list[width * idx + delta] == current_lang else ""), callback_data="%s|%s" % (key, lang_list[width * idx + delta]) ) for delta in range(width) ] for idx in range(len(lang_list) // width)] + [[ InlineKeyboardButton( lang_list[idx] + (" (*)" if lang_list[idx] == current_lang else ""), callback_data="%s|%s" % (key, lang_list[idx]) ) for idx in range(width * (len(lang_list) // width), len(lang_list))]] motd_markup = InlineKeyboardMarkup(motd_keyboard) bot.answer_callback_query( callback_query_id=update.callback_query.id ) bot.edit_message_text( chat_id=chat_id, message_id=origin_message_id, text=helper_global.value(text_key, "", lang=current_lang), reply_markup=motd_markup ) def callback_query(bot, update): logger = Logger.logger callback_data = update.callback_query.data if update.callback_query.message is None: bot.answer_callback_query( callback_query_id=update.callback_query.id ) return origin_message_id = update.callback_query.message.message_id chat_id = update.callback_query.message.chat_id user_id = update.callback_query.from_user.id args = callback_data.split(',') logger.msg({ "channel_id": chat_id, "msg_id": origin_message_id, "user_id": user_id, "callback": callback_data }, tag="callback", log_level=90) if "|" in args[0]: lang = args[0].split("|")[1] if args[0] == 'msg': show_msg(bot, update, origin_message_id, chat_id, args) elif args[0] == 'msg_detail': msg_detail(bot, update, chat_id, origin_message_id, args) elif args[0] == 'msg_delete': msg_delete(bot, update, chat_id, origin_message_id, args) elif args[0] == 'user_ban': user_ban(bot, update, chat_id, origin_message_id, args) elif args[0] == 'user_unban': user_unban(bot, update, chat_id, origin_message_id, args) elif args[0] == 'like': reaction(bot, update, chat_id, origin_message_id, user_id, args) elif args[0].startswith('register'): item = args[0].split("|")[0] item_config = { "register": "register_cmd_text", "register_invalid": "register_cmd_invalid", "register_not_admin": "register_cmd_not_admin", "register_no_permission": "register_cmd_no_permission", "register_no_info": "register_cmd_no_info", "register_failed": "register_cmd_failed", "register_success": "register_cmd_success", } intro_template(bot, update, lang, chat_id, origin_message_id, item, item_config[item]) elif args[0].startswith('start'): intro_template(bot, update, lang, chat_id, origin_message_id, "start", "start_cmd_text") elif args[0].startswith('help'): intro_template(bot, update, lang, chat_id, origin_message_id, "help", "help_cmd_text") elif args[0].startswith('option_no_channel'): intro_template(bot, update, lang, chat_id, origin_message_id, "option_no_channel", "option_no_channel") elif args[0].startswith('option_delete'): option_delete(bot, lang, chat_id, origin_message_id, args) elif args[0].startswith('option_finish'): option_finish(bot, lang, chat_id, origin_message_id) elif args[0].startswith('option'): if len(args) == 1: option_index(bot, update, lang, chat_id, origin_message_id, args) if len(args) == 2: option_item(bot, update, lang, chat_id, origin_message_id, args) elif len(args) == 3: item_config = { "mode": ["0", "1", "2"], "recent": ["5", "10", "15", "20"], "notify": ["0", "1"], "lang": helper_const.LANG_LIST, "button": ["0", "1", "2"] } key = args[2] values = item_config[key] option_key(bot, update, key, values, lang, chat_id, origin_message_id, args) elif len(args) == 4: option_update(bot, update, lang, chat_id, origin_message_id, args) else: bot.answer_callback_query( callback_query_id=update.callback_query.id ) _handler = CallbackQueryHandler(callback_query) ================================================ FILE: modules/cancel_cmd.py ================================================ #!/usr/bin/env python # -*- coding: utf-8 -*- """ Channel Helper Bot """ """ cancel_cmd.py """ """ Copyright 2018, Jogle Lew """ import helper_global import helper_database from telegram.ext import CommandHandler from ninesix import Logger def cancel(bot, update): logger = Logger.logger chat_id = update.message.chat_id channel_id = helper_global.value(str(chat_id) + "_status", "0,0").split(",")[0] logger.msg({ "channel_id": channel_id, "user_id": chat_id }, tag="cancel", log_level=80) config = helper_database.get_channel_config(channel_id) if config is None: lang = "all" else: lang = config[1] helper_global.assign(str(chat_id) + "_status", "0,0") help_text = helper_global.value("stop_comment_mode", "", lang=lang) bot.send_message(chat_id=chat_id, text=help_text) _handler = CommandHandler('cancel', cancel) ================================================ FILE: modules/channel_msg.py ================================================ #!/usr/bin/env python # -*- coding: utf-8 -*- """ Channel Helper Bot """ """ channel_msg.py """ """ Copyright 2018, Jogle Lew """ import helper_const import helper_global import helper_database import telegram from telegram.utils.helpers import effective_message_type from telegram.ext import MessageHandler, Filters if telegram.__version__ < '13.0': from telegram.ext import BaseFilter else: from telegram.ext import MessageFilter as BaseFilter from telegram import InlineKeyboardButton, InlineKeyboardMarkup from ninesix import Logger parse_entity = helper_global.parse_entity def add_comment(bot, chat_id, config, message_id, media_group_id=None): logger = Logger.logger logger.msg({ "channel_id": chat_id, "msg_id": message_id, "action": "normal comment" }, tag="channel", log_level=80) channel_lang = config[1] recent = config[3] if helper_database.check_reflect(chat_id, message_id): return # Avoid duplicated comment for media group if media_group_id: last_media_group = helper_global.value(str(chat_id) + '_last_media_group', '0') # print(last_media_group) if last_media_group == media_group_id: return helper_global.assign(str(chat_id) + '_last_media_group', media_group_id) # Prepare Keyboard motd_keyboard = [[ InlineKeyboardButton( helper_global.value("add_comment", "Add Comment", lang=channel_lang), url="http://telegram.me/%s?start=add_%d_%d" % (helper_global.value('bot_username', ''), chat_id, message_id) ), InlineKeyboardButton( helper_global.value("show_all_comments", "Show All", lang=channel_lang), url="http://telegram.me/%s?start=show_%s_%d" % (helper_global.value('bot_username', ''), chat_id, message_id) ) ]] motd_markup = InlineKeyboardMarkup(motd_keyboard) records = helper_database.get_recent_records(chat_id, message_id, recent) comment_message = bot.send_message( chat_id=chat_id, text=helper_global.records_to_str(records, channel_lang), reply_to_message_id=message_id, reply_markup=motd_markup, parse_mode=telegram.ParseMode.HTML ).result() helper_database.add_reflect(chat_id, message_id, comment_message.message_id) def add_compact_comment(bot, chat_id, config, message_id, message): logger = Logger.logger logger.msg({ "channel_id": chat_id, "msg_id": message_id, "action": "compact comment" }, tag="channel", log_level=80) channel_lang = config[1] # Fallback media group message if message.media_group_id: add_comment(bot, chat_id, config, message_id, media_group_id=message.media_group_id) return if message.forward_from or message.forward_from_chat: new_message = deforward(bot, message, channel_lang) message_id = new_message.message_id message = new_message # Prepare Keyboard motd_keyboard = [[ InlineKeyboardButton( helper_global.value("add_comment", "Add Comment", lang=channel_lang), url="http://telegram.me/%s?start=add_%d_%d" % (helper_global.value('bot_username', ''), chat_id, message_id) ), InlineKeyboardButton( helper_global.value("show_all_comments", "Show All", lang=channel_lang), url="http://telegram.me/%s?start=show_%s_%d" % (helper_global.value('bot_username', ''), chat_id, message_id) ) ]] motd_markup = InlineKeyboardMarkup(motd_keyboard) try: bot.edit_message_reply_markup( chat_id=chat_id, message_id=message_id, reply_markup=motd_markup ).result() except telegram.error.BadRequest: logger.msg({ "channel_id": chat_id, "msg_id": message_id, "action": "compact -> normal" }, tag="channel", log_level=80) add_comment(bot, chat_id, config, message_id) except: pass def add_inplace_comment(bot, chat_id, config, message_id, message, buttons): logger = Logger.logger logger.msg({ "channel_id": chat_id, "msg_id": message_id, "action": "inplace comment" }, tag="channel", log_level=80) channel_lang = config[1] # Fallback media group message if message.media_group_id: return if message.forward_from or message.forward_from_chat: new_message = deforward(bot, message, channel_lang) message_id = new_message.message_id message = new_message # Prepare Keyboard if buttons and len(buttons) > 0: helper_database.add_button_options(chat_id, message_id, buttons) helper_database.clear_reaction(chat_id, message_id) motd_keyboard = [[ InlineKeyboardButton( value, callback_data="like,%s,%s,%d" % (chat_id, message_id, idx) ) for idx, value in enumerate(buttons)]] + ([[ InlineKeyboardButton( helper_global.value("add_comment", "Add Comment", lang=channel_lang), url="http://telegram.me/%s?start=add_%d_%d" % (helper_global.value('bot_username', ''), chat_id, message_id) ), InlineKeyboardButton( helper_global.value("show_all_comments", "Show All", lang=channel_lang), url="http://telegram.me/%s?start=show_%s_%d" % (helper_global.value('bot_username', ''), chat_id, message_id) ) ]]) motd_markup = InlineKeyboardMarkup(motd_keyboard) try: bot.edit_message_reply_markup( chat_id=chat_id, message_id=message_id, reply_markup=motd_markup ).result() except: return helper_database.add_reflect(chat_id, message_id, avoidNone(message.caption if message.caption else message.text)) def avoidNone(s): if s: return str(s) return '' def deforward(bot, msg, lang): logger = Logger.logger chat_id = msg.chat_id message_id = msg.message_id logger.msg({ "channel_id": chat_id, "msg_id": message_id, "action": "messaage deforward" }, tag="channel", log_level=80) # Generate forward info has_msg_link = False if msg.forward_from: # Check username existence if msg.forward_from.username: forward_info = helper_global.value('fwd_source', 'Forwarded from:', lang=lang) + '@%s' % msg.forward_from.username else: forward_info = helper_global.value('fwd_source', 'Forwarded from:', lang=lang) + '%s' % ( msg.forward_from.id, msg.forward_from.first_name + " " + avoidNone(msg.forward_from.last_name) ) elif msg.forward_from_chat: # Check channel public/private if msg.forward_from_chat.username: forward_info = helper_global.value('fwd_source', 'Forwarded from:', lang=lang) + 'https://t.me/%s/%s' % ( msg.forward_from_chat.username, msg.forward_from_message_id ) has_msg_link = True else: forward_info = helper_global.value('fwd_source', 'Forwarded from:', lang=lang) + msg.forward_from_chat.title message_type = effective_message_type(msg) new_msg = None # Ignore media group if msg.media_group_id: return msg # Handle by message type if message_type == 'text': has_content_link = False for entity in msg.entities: if entity.type == 'url' or entity.type == 'text_link': has_content_link = True break new_msg = bot.send_message( chat_id=chat_id, text=parse_entity(avoidNone(msg.text), msg.entities) + '\n\n' + forward_info, parse_mode='HTML', disable_notification=True, disable_web_page_preview=(not has_content_link and has_msg_link) ).result() elif message_type == 'audio': new_msg = bot.send_audio( chat_id=chat_id, audio=msg.audio.file_id, caption=parse_entity(avoidNone(msg.caption), msg.caption_entities) + '\n\n' + forward_info, parse_mode='HTML', disable_notification=True ).result() elif message_type == 'document': new_msg = bot.send_document( chat_id=chat_id, document=msg.document.file_id, caption=parse_entity(avoidNone(msg.caption), msg.caption_entities) + '\n\n' + forward_info, parse_mode='HTML', disable_notification=True ).result() elif message_type == 'photo': new_msg = bot.send_photo( chat_id=chat_id, photo=msg.photo[-1].file_id, caption=parse_entity(avoidNone(msg.caption), msg.caption_entities) + '\n\n' + forward_info, parse_mode='HTML', disable_notification=True ).result() elif message_type == 'sticker': new_msg = bot.send_sticker( chat_id=chat_id, sticker=msg.sticker.file_id, disable_notification=True ).result() elif message_type == 'video': new_msg = bot.send_video( chat_id=chat_id, video=msg.video.file_id, caption=parse_entity(avoidNone(msg.caption), msg.caption_entities) + '\n\n' + forward_info, parse_mode='HTML', disable_notification=True ).result() elif message_type == 'voice': new_msg = bot.send_voice( chat_id=chat_id, voice=msg.voice.file_id, caption=parse_entity(avoidNone(msg.caption), msg.caption_entities) + '\n\n' + forward_info, parse_mode='HTML', disable_notification=True ).result() if new_msg: bot.delete_message(chat_id=chat_id, message_id=message_id) return new_msg return msg def add_like_buttons(bot, channel_lang, config, chat_id, message_id, message, buttons): logger = Logger.logger logger.msg({ "channel_id": chat_id, "msg_id": message_id, "action": "add like buttons" }, tag="channel", log_level=80) flag = 1 ref = helper_database.get_reflect_by_msg_id(chat_id, message_id) if ref is not None: flag = 0 message_id = ref[1] # Fallback media group message if message.media_group_id: add_comment(bot, chat_id, config, message_id, media_group_id=message.media_group_id) return if message.forward_from or message.forward_from_chat: new_message = deforward(bot, message, channel_lang) message_id = new_message.message_id message = new_message # Prepare Keyboard helper_database.add_button_options(chat_id, message_id, buttons) helper_database.clear_reaction(chat_id, message_id) motd_keyboard = [[ InlineKeyboardButton( value, callback_data="like,%s,%s,%d" % (chat_id, message_id, idx) ) for idx, value in enumerate(buttons)]] + ([[ InlineKeyboardButton( helper_global.value("add_comment", "Add Comment", lang=channel_lang), url="http://telegram.me/%s?start=add_%d_%d" % (helper_global.value('bot_username', ''), chat_id, message_id) ), InlineKeyboardButton( helper_global.value("show_all_comments", "Show All", lang=channel_lang), url="http://telegram.me/%s?start=show_%s_%d" % (helper_global.value('bot_username', ''), chat_id, message_id) ) ]] if flag == 1 else [[]]) motd_markup = InlineKeyboardMarkup(motd_keyboard) bot.edit_message_reply_markup( chat_id=chat_id, message_id=message_id, reply_markup=motd_markup ) def channel_post_msg(bot, update): logger = Logger.logger message = update.channel_post if message is None: return chat_id = message.chat_id message_id = message.message_id config = helper_database.get_channel_config(chat_id) if config is None: return lang, mode, recent, button_mode = config[1], config[2], config[3], config[7] # Manual Mode if message.reply_to_message is not None and message.text.startswith("/comment"): logger.msg({ "channel_id": chat_id, "msg_id": message_id, "mode": mode, "button": button_mode, "action": "/comment" }, tag="channel", log_level=90) message_id = message.reply_to_message.message_id bot.delete_message(chat_id=chat_id, message_id=message.message_id) if not helper_database.check_reflect(chat_id, message_id) and message.reply_to_message.reply_markup is None: add_compact_comment(bot, chat_id, config, message_id, message.reply_to_message) if not button_mode == 0: buttons = message.text.split()[1:] if button_mode == 1 and len(buttons) == 0: buttons = helper_database.get_default_button_options(chat_id) add_like_buttons(bot, lang, config, chat_id, message_id, message, buttons) # Force Comment for Special Cases elif message.reply_to_message is not None and message.text == "/forcecomment": logger.msg({ "channel_id": chat_id, "msg_id": message_id, "mode": mode, "button": button_mode, "action": "/forcecomment" }, tag="channel", log_level=90) message_id = message.reply_to_message.message_id bot.delete_message(chat_id=chat_id, message_id=message.message_id) helper_database.delete_reflect(chat_id, message_id) add_compact_comment(bot, chat_id, config, message_id, message.reply_to_message) # Set default buttons elif message.text is not None and message.text.startswith("/defaultbuttons"): logger.msg({ "channel_id": chat_id, "msg_id": message_id, "mode": mode, "button": button_mode, "action": "/defaultbuttons" }, tag="channel", log_level=90) buttons = message.text.split()[1:] bot.delete_message(chat_id=chat_id, message_id=message.message_id) helper_database.add_button_options(chat_id, 0, buttons) # Auto Comment Mode elif mode == 1: logger.msg({ "channel_id": chat_id, "msg_id": message_id, "mode": mode, "button": button_mode, "action": "new channel post" }, tag="channel", log_level=90) add_comment(bot, chat_id, config, message_id, media_group_id=message.media_group_id) if button_mode == 1: add_like_buttons(bot, lang, config, chat_id, message_id, message, helper_database.get_default_button_options(chat_id)) elif mode == 2: logger.msg({ "channel_id": chat_id, "msg_id": message_id, "mode": mode, "button": button_mode, "action": "new channel post" }, tag="channel", log_level=90) if button_mode == 1: add_like_buttons(bot, lang, config, chat_id, message_id, message, helper_database.get_default_button_options(chat_id)) else: add_compact_comment(bot, chat_id, config, message_id, message) elif mode == 3: logger.msg({ "channel_id": chat_id, "msg_id": message_id, "mode": mode, "button": button_mode, "action": "new channel post" }, tag="channel", log_level=90) add_inplace_comment(bot, chat_id, config, message_id, message, (helper_database.get_default_button_options(chat_id) if button_mode == 1 else [])) class FilterChannelPost(BaseFilter): def filter(self, message): return message.chat.type == "channel" channel_post_filter = FilterChannelPost() _handler = MessageHandler(channel_post_filter, channel_post_msg) ================================================ FILE: modules/clean_cmd.py ================================================ #!/usr/bin/env python # -*- coding: utf-8 -*- """ Channel Helper Bot """ """ clean_cmd.py """ """ Copyright 2018, Jogle Lew """ import json import datetime import helper_const import helper_global import helper_database from telegram.ext import CommandHandler from telegram.error import TimedOut, NetworkError def get_invalid_channel_access(bot): configs = helper_database.get_all_channel_config() invalid_list = [] for config in configs: channel_id = int(config[0]) admin_id = int(config[5]) try: chat_members = bot.get_chat_administrators(chat_id=channel_id).result() except TimedOut: pass except NetworkError: pass except: invalid_list.append(config) return invalid_list def check_channel_access(bot, job): invalid_list = get_invalid_channel_access(bot) for owner_id in helper_const.BOT_OWNER: bot.send_message(chat_id=owner_id, text=str(invalid_list)) def clean(bot, update, args, job_queue): from_id = update.message.from_user.id if not from_id in helper_const.BOT_OWNER: return if len(args) == 1 and args[0] == "check": invalid_list = get_invalid_channel_access(bot) bot.send_message(chat_id=from_id, text=helper_global.value("clean_cmd_start", "")) bot.send_message(chat_id=from_id, text=str(invalid_list)) if len(args) == 2 and args[0] == "touch": channel_id = int(args[1]) chat_members = bot.get_chat_administrators(chat_id=channel_id).result() for member in chat_members: if member.user.username and member.user.username == helper_global.value('bot_username', ''): bot.send_message(chat_id=from_id, text='%s %s %s' % (member.can_post_messages, member.can_edit_messages, member.can_delete_messages)) if len(args) == 2 and args[0] == "delete": channel_id = int(args[1]) helper_database.delete_channel_config(channel_id) bot.send_message(chat_id=from_id, text=helper_global.value("clean_cmd_deleted", "")) if len(args) == 2 and args[0] == "auto": job = helper_global.value("check_daily_job", None) if job is None: job = job_queue.run_daily(check_channel_access, datetime.time(0, 0)) if args[1] == "on": job.enabled = True elif args[1] == "off": job.enabled = False helper_global.assign("check_daily_job", job) bot.send_message(chat_id=from_id, text=helper_global.value("clean_cmd_set", "")) _handler = CommandHandler('clean', clean, pass_args=True, pass_job_queue=True) ================================================ FILE: modules/help_cmd.py ================================================ #!/usr/bin/env python # -*- coding: utf-8 -*- """ Channel Helper Bot """ """ help_cmd.py """ """ Copyright 2018, Jogle Lew """ import helper_const import helper_global from telegram.ext import CommandHandler from ninesix import Logger def help(bot, update): logger = Logger.logger chat_id = update.message.chat_id logger.msg({ "user_id": chat_id }, tag="help", log_level=80) helper_global.send_intro_template(bot, chat_id, helper_const.DEFAULT_LANG, "help", "help_cmd_text") _handler = CommandHandler('help', help) ================================================ FILE: modules/inline_query.py ================================================ #!/usr/bin/env python # -*- coding: utf-8 -*- """ Channel Helper Bot """ """ inline_query.py """ """ Copyright 2020, Jogle Lew """ import re import helper_const import helper_global import helper_database from telegram import InlineKeyboardButton, InlineKeyboardMarkup from telegram import InlineQueryResultArticle, InputTextMessageContent from telegram.ext import InlineQueryHandler from ninesix import Logger def inline_caps(bot, update): user_id = update.inline_query.from_user.id args = helper_global.value(str(user_id) + "_status", "0,0") params = args.split(",") channel_id = int(params[0]) msg_id = int(params[1]) if channel_id == 0: bot.answer_inline_query(update.inline_query.id, []) return config = helper_database.get_channel_config(channel_id) if config is None: bot.answer_inline_query(update.inline_query.id, []) return channel_lang = config[1] recent = config[3] query = update.inline_query.query if len(query.strip()) == 0: bot.answer_inline_query( update.inline_query.id, [], switch_pm_text=helper_global.value("reply_prompt", "comment here first", lang=channel_lang), switch_pm_parameter="0", cache_time=0, is_personal=True ) return records = helper_database.get_recent_records(channel_id, msg_id, recent, 0) results = [] for idx, record in enumerate(records): name = record[3] content = record[5] msg_user_id = record[8] row_id = int(record[10]) results.append( InlineQueryResultArticle( id=idx, title=name, description=re.sub("<.*?>", "", content).replace('<', '<').replace('>', '>'), input_message_content=InputTextMessageContent( message_text= query.replace('<', '<').replace('>', '>'), parse_mode='HTML' ), reply_markup=InlineKeyboardMarkup([[ InlineKeyboardButton( helper_global.value("reply_to", "Reply to: ", lang=channel_lang) + name, callback_data="notify,%d,%d,%d" % (channel_id, msg_id, row_id) ) ]]) ) ) bot.answer_inline_query( update.inline_query.id, results, switch_pm_text=helper_global.value("reply_prompt", "comment here first", lang=channel_lang), switch_pm_parameter="0", cache_time=0, is_personal=True ) _handler = InlineQueryHandler(inline_caps) ================================================ FILE: modules/option_cmd.py ================================================ #!/usr/bin/env python # -*- coding: utf-8 -*- """ Channel Helper Bot """ """ option_cmd.py """ """ Copyright 2018, Jogle Lew """ import helper_const import helper_global import helper_database import telegram from telegram import InlineKeyboardButton, InlineKeyboardMarkup from telegram.ext import CommandHandler from ninesix import Logger def option(bot, update, args): logger = Logger.logger if args is None or len(args) == 0: lang = helper_const.DEFAULT_LANG else: lang = args[0] chat_id = update.message.chat_id logger.msg({ "user_id": chat_id }, tag="option", log_level=80) records = helper_database.get_channel_info_by_user(chat_id) if records is None or len(records) == 0: helper_global.send_intro_template(bot, chat_id, helper_const.DEFAULT_LANG, "option_no_channel", "option_no_channel") return #Prepare keyboard lang_list = helper_const.LANG_LIST width = helper_const.LANG_WIDTH current_lang = lang key = "option" motd_keyboard = [[ InlineKeyboardButton( "@" + record[1] if record[1] else "id: " + str(record[0]), callback_data="option|%s,%s" % (lang, record[0]) ) ] for record in records] + [[ InlineKeyboardButton( helper_global.value("option_finish", "", lang), callback_data="option_finish|%s" % lang ) ]] + [[ InlineKeyboardButton( lang_list[width * idx + delta] + (" (*)" if lang_list[width * idx + delta] == current_lang else ""), callback_data="%s|%s" % (key, lang_list[width * idx + delta]) ) for delta in range(width) ] for idx in range(len(lang_list) // width)] + [[ InlineKeyboardButton( lang_list[idx] + (" (*)" if lang_list[idx] == current_lang else ""), callback_data="%s|%s" % (key, lang_list[idx]) ) for idx in range(width * (len(lang_list) // width), len(lang_list))]] motd_markup = InlineKeyboardMarkup(motd_keyboard) bot.send_message( chat_id=chat_id, text=helper_global.value("option_choose_channel", "", lang=lang), reply_markup=motd_markup ) _handler = CommandHandler('option', option, pass_args=True) ================================================ FILE: modules/private_msg.py ================================================ #!/usr/bin/env python # -*- coding: utf-8 -*- """ Channel Helper Bot """ """ private_msg.py """ """ Copyright 2018, Jogle Lew """ import helper_const import helper_global import helper_database import telegram import threading from telegram import InlineKeyboardButton, InlineKeyboardMarkup from telegram.ext import MessageHandler, Filters from ninesix import Logger def add_record(bot, channel_id, msg_id, message): logger = Logger.logger ori_msg_id = message.message_id user = message.from_user username = user.username user_id = user.id name = user.first_name if user.last_name: name += " " + user.last_name date = message.date.strftime("%Y-%m-%d %H:%M:%S") msg_type = "text" msg_content = "" media_id = "" if message.text: msg_type = "text" msg_content = message.text elif message.sticker: msg_type = 'sticker' media_id = message.sticker.file_id if message.sticker.emoji: msg_content = message.sticker.emoji elif message.photo: msg_type = 'photo' media_id = message.photo[-1].file_id if message.caption: msg_content = message.caption elif message.video: msg_type = 'video' media_id = message.video.file_id if message.caption: msg_content = message.caption elif message.document: msg_type = 'document' media_id = message.document.file_id if message.document.file_name: msg_content = message.document.file_name elif message.audio: msg_type = 'audio' media_id = message.audio.file_id if message.audio.title: msg_content = message.audio.title elif message.voice: msg_type = 'voice' media_id = message.voice.file_id msg_content = helper_global.parse_entity(msg_content, message.entities) if message.reply_markup and message.reply_markup.inline_keyboard: keyboard = message.reply_markup.inline_keyboard if len(keyboard) > 0 and len(keyboard[0]) > 0: query = keyboard[0][0] if query.callback_data: args = query.callback_data.split(",") if len(args) == 4 and args[0] == "notify": target_channel_id = int(args[1]) target_msg_id = int(args[2]) target_row_id = args[3] record = helper_database.get_record_by_rowid(target_row_id) if len(record) > 0 and target_channel_id == int(record[0][0]) and target_msg_id == int(record[0][1]): target_name = record[0][3] target_user_id = record[0][8] config = helper_database.get_channel_config(channel_id) if config is None: return channel_lang, channel_username = config[1], config[4] msg_content = "(➤%s) " % target_name.replace('<', '<').replace('>', '>') + msg_content if channel_username is not None: logger.msg({ "channel_id": channel_id, "msg_id": msg_id, "target_user": target_user_id, "action": "notify reply" }, tag="private", log_level=80) bot.send_message( chat_id=target_user_id, 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) ) else: link_id = abs(channel_id) % 10000000000 bot.send_message( chat_id=target_user_id, 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) ) return helper_database.add_record(channel_id, msg_id, username, name, msg_type, msg_content, media_id, date, user_id, ori_msg_id) def update_comments(bot, channel_id, msg_id, update_mode): logger = Logger.logger config = helper_database.get_channel_config(channel_id) if config is None: return channel_lang = config[1] mode = config[2] recent = config[3] logger.msg({ "channel_id": channel_id, "msg_id": msg_id, "update_mode": update_mode }, tag="private", log_level=80) # For mode 3 if mode == 3 and update_mode == 2: buttons = helper_database.get_button_options(channel_id, msg_id) stat = helper_database.get_reaction_stat(channel_id, msg_id) # Prepare Keyboard motd_keyboard = [[ InlineKeyboardButton( value + (" (%d)" % stat[idx] if idx in stat else ""), callback_data="like,%s,%s,%d" % (channel_id, msg_id, idx) ) for idx, value in enumerate(buttons)]] + [[ InlineKeyboardButton( helper_global.value("add_comment", "Add Comment", lang=channel_lang), url="http://telegram.me/%s?start=add_%d_%d" % (helper_global.value('bot_username', ''), channel_id, msg_id) ), InlineKeyboardButton( helper_global.value("show_all_comments", "Show All", lang=channel_lang), url="http://telegram.me/%s?start=show_%s_%d" % (helper_global.value('bot_username', ''), channel_id, msg_id) ) ]] motd_markup = InlineKeyboardMarkup(motd_keyboard) records = helper_database.get_recent_records(channel_id, msg_id, recent) origin_post = helper_database.get_origin_post(channel_id, msg_id) try: bot.edit_message_caption( caption=origin_post + "\n\n" + helper_global.records_to_str(records, channel_lang), chat_id=channel_id, message_id=msg_id, parse_mode=telegram.ParseMode.HTML, reply_markup=motd_markup ) except: bot.edit_message_text( text=origin_post + "\n\n" + helper_global.records_to_str(records, channel_lang), chat_id=channel_id, message_id=msg_id, parse_mode=telegram.ParseMode.HTML, reply_markup=motd_markup ) return # update comments in channel comment_id = helper_database.get_comment_id(channel_id, msg_id) if comment_id is None: # If no comment message, just update Like buttons buttons = helper_database.get_button_options(channel_id, msg_id) stat = helper_database.get_reaction_stat(channel_id, msg_id) # Prepare Keyboard motd_keyboard = [[ InlineKeyboardButton( value + (" (%d)" % stat[idx] if idx in stat else ""), callback_data="like,%s,%s,%d" % (channel_id, msg_id, idx) ) for idx, value in enumerate(buttons)]] + [[ InlineKeyboardButton( helper_global.value("add_comment", "Add Comment", lang=channel_lang), url="http://telegram.me/%s?start=add_%d_%d" % (helper_global.value('bot_username', ''), channel_id, msg_id) ), InlineKeyboardButton( helper_global.value("show_all_comments", "Show All", lang=channel_lang), url="http://telegram.me/%s?start=show_%s_%d" % (helper_global.value('bot_username', ''), channel_id, msg_id) ) ]] motd_markup = InlineKeyboardMarkup(motd_keyboard) bot.edit_message_reply_markup( chat_id=channel_id, message_id=msg_id, reply_markup=motd_markup ) return # Otherwise # Update Like buttons if update_mode == 0: buttons = helper_database.get_button_options(channel_id, msg_id) stat = helper_database.get_reaction_stat(channel_id, msg_id) # Prepare Keyboard motd_keyboard = [[ InlineKeyboardButton( value + (" (%d)" % stat[idx] if idx in stat else ""), callback_data="like,%s,%s,%d" % (channel_id, msg_id, idx) ) for idx, value in enumerate(buttons)]] if comment_id - msg_id > 1: link_id = abs(channel_id) % 10000000000 motd_keyboard += [[ InlineKeyboardButton( helper_global.value("jump_to_comment", "Jump to Comment", lang=channel_lang), url="https://t.me/c/%d/%d" % (link_id, comment_id) ) ]] motd_markup = InlineKeyboardMarkup(motd_keyboard) bot.edit_message_reply_markup( chat_id=channel_id, message_id=msg_id, reply_markup=motd_markup ) return # Update comment message records = helper_database.get_recent_records(channel_id, msg_id, recent) # Prepare Keyboard motd_keyboard = [[ InlineKeyboardButton( helper_global.value("add_comment", "Add Comment", lang=channel_lang), url="http://telegram.me/%s?start=add_%d_%d" % (helper_global.value('bot_username', ''), channel_id, msg_id) ), InlineKeyboardButton( helper_global.value("show_all_comments", "Show All", lang=channel_lang), url="http://telegram.me/%s?start=show_%s_%d" % (helper_global.value('bot_username', ''), channel_id, msg_id) ) ]] motd_markup = InlineKeyboardMarkup(motd_keyboard) bot.edit_message_text( text=helper_global.records_to_str(records, channel_lang), chat_id=channel_id, message_id=comment_id, parse_mode=telegram.ParseMode.HTML, reply_markup=motd_markup ) def update_dirty_list(): lock.acquire() dirty_list = helper_global.value("dirty_list", []) bot = helper_global.value("bot", None) for item in dirty_list: channel_id, msg_id, update_mode = item threading.Thread( target=update_comments, args=(bot, channel_id, msg_id, update_mode) ).start() helper_global.assign("dirty_list", []) lock.release() def check_channel_message(bot, message): logger = Logger.logger chat_id = message.chat_id if not message.forward_from_chat: helper_global.send_intro_template(bot, chat_id, helper_const.DEFAULT_LANG, "register_invalid", "register_cmd_invalid") return chat_type = message.forward_from_chat.type if not chat_type == "channel": helper_global.send_intro_template(bot, chat_id, helper_const.DEFAULT_LANG, "register_invalid", "register_cmd_invalid") return channel_username = message.forward_from_chat.username channel_id = message.forward_from_chat.id user_id = message.from_user.id logger.msg({ "user_id": chat_id, "channel_id": channel_id, "action": "check channel" }, tag="private", log_level=90) bot_id = int(helper_const.BOT_TOKEN.split(":")[0]) try: chat_members = bot.get_chat_administrators(chat_id=channel_id).result() chat_member_ids = [member.user.id for member in chat_members] if not user_id in chat_member_ids: helper_global.send_intro_template(bot, chat_id, helper_const.DEFAULT_LANG, "register_not_admin", "register_cmd_not_admin") return for member in chat_members: if member.user.id == bot_id: post_permission = member.can_post_messages if member.can_post_messages else False edit_permission = member.can_edit_messages if member.can_edit_messages else False delete_permission = member.can_delete_messages if member.can_delete_messages else False if not post_permission or not edit_permission or not delete_permission: helper_global.send_intro_template(bot, chat_id, helper_const.DEFAULT_LANG, "register_no_permission", "register_cmd_no_permission") return break except: helper_global.send_intro_template(bot, chat_id, helper_const.DEFAULT_LANG, "register_no_info", "register_cmd_no_info") return try: helper_database.add_channel_config(channel_id, helper_const.DEFAULT_LANG, 1, 10, channel_username, chat_id, 1, 1) except: helper_global.assign(str(chat_id) + "_status", "0,0") helper_global.send_intro_template(bot, chat_id, helper_const.DEFAULT_LANG, "register_failed", "register_cmd_failed") return helper_global.assign(str(chat_id) + "_status", "0,0") helper_global.send_intro_template(bot, chat_id, helper_const.DEFAULT_LANG, "register_success", "register_cmd_success") def private_msg(bot, update): logger = Logger.logger message = update.edited_message if update.edited_message else update.message chat_id = message.chat_id args = helper_global.value(str(chat_id) + "_status", "0,0") logger.msg({ "user_id": chat_id, "status": args }, tag="private", log_level=90) params = args.split(",") channel_id = int(params[0]) msg_id = int(params[1]) if channel_id == 0: if msg_id == 1: check_channel_message(bot, message) return # Check comment message comment_exist = helper_database.check_reflect(channel_id, msg_id) config = helper_database.get_channel_config(channel_id) if config is None: return channel_lang = config[1] mode, recent, username, admin_id, notify = config[2], config[3], config[4], config[5], config[6] logger.msg({ "user_id": chat_id, "channel_id": channel_id, "msg_id": msg_id, "action": "add comment" }, tag="private", log_level=90) # For Auto Mode = 2 if not comment_exist: logger.msg({ "user_id": chat_id, "channel_id": channel_id, "msg_id": msg_id, "action": "add comment area" }, tag="private", log_level=80) comment_message = bot.send_message( chat_id=channel_id, text=helper_global.value("comment_refreshing", "Refreshing...", lang=channel_lang), reply_to_message_id=msg_id, parse_mode=telegram.ParseMode.HTML ).result() helper_database.add_reflect(channel_id, msg_id, comment_message.message_id) #bot.edit_message_reply_markup( # chat_id=channel_id, # message_id=msg_id, # reply_markup=None #) update_dirty_msg(channel_id, msg_id, update_mode=0) result = add_record(bot, channel_id, msg_id, message) # Update Dirty List update_dirty_msg(channel_id, msg_id, update_mode=(2 if mode == 3 else 1)) if notify == 1 and not int(chat_id) == int(admin_id): logger.msg({ "user_id": chat_id, "channel_id": channel_id, "msg_id": msg_id, "admin_id": admin_id, "action": "notify channel owner" }, tag="private", log_level=80) if username is not None: bot.send_message( chat_id=admin_id, 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) ) else: link_id = abs(channel_id) % 10000000000 bot.send_message( chat_id=admin_id, 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) ) if result == 0: bot.send_message(chat_id=chat_id, text=helper_global.value("comment_success", "Success!", lang=channel_lang)) elif result == 1: bot.send_message(chat_id=chat_id, text=helper_global.value("comment_edit_success", "Success!", lang=channel_lang)) def update_dirty_msg(channel_id, msg_id, update_mode=1): lock.acquire() dirty_list = helper_global.value("dirty_list", []) if not (channel_id, msg_id, update_mode) in dirty_list: dirty_list.append((channel_id, msg_id, update_mode)) helper_global.assign("dirty_list", dirty_list) lock.release() def set_interval(func, sec): def func_wrapper(): set_interval(func, sec) func() t = threading.Timer(sec, func_wrapper) t.start() return t refresh_status = helper_global.value("refresh_status", False) if not refresh_status: set_interval(update_dirty_list, helper_const.MIN_REFRESH_INTERVAL) helper_global.assign("refresh_status", True) lock = threading.Lock() _handler = MessageHandler(Filters.private, private_msg, edited_updates=True) ================================================ FILE: modules/register_cmd.py ================================================ #!/usr/bin/env python # -*- coding: utf-8 -*- """ Channel Helper Bot """ """ register_cmd.py """ """ Copyright 2018, Jogle Lew """ import helper_const import helper_global import helper_database from telegram.ext import CommandHandler from telegram import InlineKeyboardButton, InlineKeyboardMarkup from ninesix import Logger def register(bot, update): logger = Logger.logger from_id = update.message.from_user.id chat_id = update.message.chat_id logger.msg({"user_id": from_id}, tag="register", log_level=80) helper_global.assign(str(from_id) + "_status", "0,1") helper_global.send_intro_template(bot, chat_id, helper_const.DEFAULT_LANG, "register", "register_cmd_text") _handler = CommandHandler('register', register) ================================================ FILE: modules/sql_cmd.py ================================================ #!/usr/bin/env python # -*- coding: utf-8 -*- """ Channel Helper Bot """ """ sql_cmd.py """ """ Copyright 2018, Jogle Lew """ import helper_const import helper_global import helper_database from telegram.ext import CommandHandler def sql(bot, update, args): from_id = update.message.from_user.id if not from_id in helper_const.BOT_OWNER: return script = " ".join(args) text = "" try: result = helper_database.execute(script, ()) text = "执行成功,结果:\n" + str(list(result)) except Exception as e: text = "执行失败 " + str(e) bot.send_message(chat_id=update.message.chat_id, text=text) _handler = CommandHandler('sql', sql, pass_args=True) ================================================ FILE: modules/start_cmd.py ================================================ #!/usr/bin/env python # -*- coding: utf-8 -*- """ Channel Helper Bot """ """ start_cmd.py """ """ Copyright 2018, Jogle Lew """ import helper_const import helper_global import helper_database import telegram from telegram import InlineKeyboardButton, InlineKeyboardMarkup from telegram.ext import CommandHandler from ninesix import Logger def start(bot, update, args): logger = Logger.logger if args is None or len(args) == 0: chat_id = update.message.chat_id logger.msg({"user_id": chat_id}, tag="start", log_level=80) helper_global.send_intro_template(bot, chat_id, helper_const.DEFAULT_LANG, "start", "start_cmd_text") return params = args[0].split("_") channel_id = int(params[1]) msg_id = int(params[2]) chat_id = update.message.chat_id logger.msg({"user_id": chat_id, "args": args}, tag="start", log_level=90) if chat_id < 0: return config = helper_database.get_channel_config(channel_id) if config is None: return channel_lang = config[1] recent, username = config[3], config[4] if helper_database.check_ban(channel_id, chat_id): helper_global.assign(str(chat_id) + "_status", "0,0") bot.send_message(chat_id=update.message.chat_id, text=helper_global.value("banned_prompt", "You are banned.", lang=channel_lang)) return if params[0] == "add": helper_global.assign(str(chat_id) + "_status", params[1] + "," + params[2]) motd_keyboard = [[ InlineKeyboardButton( helper_global.value("reply_to", "Reply", lang=channel_lang) + "...", switch_inline_query_current_chat=" " ) ]] motd_markup = InlineKeyboardMarkup(motd_keyboard) if username is not None: bot.send_message( chat_id=update.message.chat_id, 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), reply_markup=motd_markup ) else: link_id = abs(channel_id) % 10000000000 bot.send_message( chat_id=update.message.chat_id, 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), reply_markup=motd_markup ) elif params[0] == "show": offset = 0 channel_username = config[4] records = helper_database.get_recent_records(channel_id, msg_id, recent, offset) # Prepare Keyboard msg_buttons = helper_global.records_to_buttons(records, channel_id, msg_id) motd_keyboard = msg_buttons + [[ InlineKeyboardButton( helper_global.value("prev_page", "Prev Page", lang=channel_lang), callback_data="msg,%d,%d,%d,%d,%d" % (channel_id, msg_id, recent, offset + 1, chat_id) ), InlineKeyboardButton( helper_global.value("next_page", "Next Page", lang=channel_lang), callback_data="msg,%d,%d,%d,%d,%d" % (channel_id, msg_id, recent, offset - 1, chat_id) ) ]] motd_markup = InlineKeyboardMarkup(motd_keyboard) prompt_text = helper_global.value("comment_header", "", lang=channel_lang) if channel_username is not None and len(channel_username) > 0: prompt_text = "https://t.me/%s/%a\n" % (channel_username, msg_id) + prompt_text bot.send_message( chat_id=update.message.chat_id, text=prompt_text, parse_mode=telegram.ParseMode.HTML, reply_markup=motd_markup ) _handler = CommandHandler('start', start, pass_args=True)