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