diff --git a/.github/workflows/pythonapp.yml b/.github/workflows/pythonapp.yml
new file mode 100644
index 0000000..2b319b6
--- /dev/null
+++ b/.github/workflows/pythonapp.yml
@@ -0,0 +1,37 @@
+# This workflow will install Python dependencies, run tests and lint with a single version of Python
+# For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions
+
+name: shanibot tester
+
+on:
+ push:
+ branches: [ master ]
+ pull_request:
+ branches: [ master ]
+
+jobs:
+ build:
+
+ runs-on: windows-latest
+
+ steps:
+ - uses: actions/checkout@v2
+ - name: Set up Python 3.8
+ uses: actions/setup-python@v1
+ with:
+ python-version: 3.8
+ - name: Install dependencies
+ run: |
+ python -W ignore -m pip install --upgrade pip
+ pip install flake8 pytest
+ pip install cython
+ pip install -r requirements.txt
+ - name: Lint with flake8
+ run: |
+ # stop the build if there are Python syntax errors or undefined names
+ flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
+ # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide
+ flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
+ - name: Test with pytest
+ run: |
+ pytest
diff --git a/.gitignore b/.gitignore
index 04bcfee..928bd50 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,5 +1,7 @@
*.pyc
token.txt
+creds/github_token.txt
sentence_tokenizer.pickle
db.sqlite3-shm
db.sqlite3-wal
+*idea
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..f288702
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ Copyright (C)
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
diff --git a/README.md b/README.md
index 5e8c8f8..a494503 100644
--- a/README.md
+++ b/README.md
@@ -9,17 +9,22 @@ The following commands are currently available to use:
1. `/start` - Start the bot! (Highly recommended :P)
2. `/help` - General help and information about the bot.
3. `/facts` - Get a random fact from the internet.
-4. `/8ball` - Magic 8 ball on messages. Usage: reply to a message with /8ball, or just type /8ball and then type the question.
+4. `/8ball` - Magic 8 ball on messages. Usage: reply to a message with /8ball, or just type /8ball and
+ then type the question.
5. `/snake` - A roast
-6. `/tell` - Get more personal with the bot by providing a nickname and/or birthday, which it uses in regular conversations.
-7. `/settings` - Modify the behaviour of the bot in groups and private chat. You can toggle on/off morning messages, and choose the probability with which the bot reacts to profanity and media.
-8. More coming soon...
+6. `/tell` - Get more personal with the bot by providing a nickname and/or birthday, which it uses in regular
+ conversations.
+7. `/settings` - Modify the behaviour of the bot in groups and private chat. You can toggle on/off morning messages,
+ and choose the probability with which the bot reacts to profanity and media.
+8. `/quizizz` - The bot will send you one physics quiz (MCQ) from the internet.
+9. More coming soon...
### Behaviour in groups:
* If this bot is added to a group, it will try and behave like an actual user and reply to media sent (40% of the time by default) with some reactions.
* The bot will also check for profanity (20% of the time by default) and will suggest to stop using it.
* If any user replies to a message from the bot, it will reply to the user just like it would in private chat. The only difference is that here it does not learn from your replies.
+* The bot will not reply back to your reply if you prepend or append your message with `!r`.
* The bot will reply to the user if he is mentioned (@) in the message.
### Behaviour in private chat:
@@ -30,4 +35,4 @@ The following commands are currently available to use:
* It still reacts to media files just like in groups.
### Inline mode:
-This bot will give you clips from [Shanisirmodule](https://github.com/tmslads/Shanisirmodule), @ the bot and type a name of a clip and click on a result to send it to the target chat as a mp3 file.
+This bot will give you clips from [Shanisirmodule](https://github.com/tmslads/Shanisirmodule) (private repo sorry!), @ the bot and type a name of a clip and click on a result to send it to the target chat as a mp3 file.
diff --git a/bot_funcs/bday_wisher.py b/bot_funcs/bday_wisher.py
new file mode 100644
index 0000000..e3fafa5
--- /dev/null
+++ b/bot_funcs/bday_wisher.py
@@ -0,0 +1,45 @@
+from datetime import datetime, date
+
+from telegram.ext import CallbackContext
+
+from constants import group_ids
+from helpers.logger import logger
+from online import gcalendar
+
+
+def wish(context: CallbackContext) -> None:
+ """Gets the next birthday from Google Calendar and wishes you if today is your birthday."""
+
+ gcalendar.main()
+ days_remaining, name = gcalendar.get_next_bday()
+
+ bday_msgs = [f"Happy birthday {name}! !🎉 I don't know why like, but I know you despise me with the burning "
+ f"passion of a thousand suns. I don't give a flux, like you say. I implore you to let go of "
+ f"hate and embrace love. Spend the rest of your days with love in your heart and faith in your "
+ f"soul. Life's cyclotron may sometimes send you tumbling around, but remember that it is "
+ f"necessary to do so in order to hit the targit. Negative emotions act as charge for the "
+ f"velocity selector of life. Remove them from your being and you shall not stray from the "
+ f"straight path. I wish you the best. May your jockeys be unpressed and your apertures small. "
+ f"Enjoy your 18th. Forget about coronabitch. Godspeed.",
+
+ f"Happy birthday {name}! I wish you the best of luck for life. Remember: You matter. Until you "
+ f"multiply yourself times the speed of light squared. Then you energy, like you say!🎉 What "
+ f"your going to do today like?",
+
+ f"Happy birthday {name}! !🎉 What your going to do today like?"]
+
+ _12B = group_ids['12b']
+
+ # Wishes from Google Calendar-
+ if days_remaining == 0:
+ msg = context.bot.send_message(chat_id=_12B, text=bday_msgs[0])
+ context.bot.pin_chat_message(chat_id=_12B, message_id=msg.message_id, disable_notification=True)
+ logger(message=f"Happy birthday message to {name} was just sent.")
+
+ now = str(date.today())
+ today = datetime.strptime(now, "%Y-%m-%d") # Parses today's date (time object) into datetime object
+ new_date = today.replace(year=today.year + 1)
+
+ gcalendar.CalendarEventManager(name=name).update_event(new_date) # Updates bday to next year
+
+ # TODO: Wishes from /tell birthday input-
diff --git a/bot_funcs/conversation.py b/bot_funcs/conversation.py
new file mode 100644
index 0000000..23577b5
--- /dev/null
+++ b/bot_funcs/conversation.py
@@ -0,0 +1,231 @@
+import random as r
+import re
+
+import chatterbot
+import emoji
+from telegram import Update
+from telegram.ext import CallbackContext
+from textblob import TextBlob
+
+from chatbot import get_tags, shanisirbot
+from commands import prohibited
+from helpers.db_connector import connection
+from helpers.logger import logger
+from helpers.namer import get_nick, get_chat_name
+
+bot_response = None
+
+rebukes = ["This is not the expected behaviour", "I don't want you to talk like that", "Expand your vocabulary now",
+ "Bad language is not allowed okay", "See this is not my policy", "This is not a fruitful conversation",
+ "This language is embarrassingassing to me like basically"]
+
+responses1 = ["I am so sowry", "i don't want to talk like that", "it is embarrassing to me like basically",
+ "it's not to trouble you like you say", "go for the worksheet", "it's not that hard"]
+
+responses2 = ["it will be fruitful", "you will benefit", "that is the expected behaviour",
+ "now you are on the track like", "now class is in the flow like", "don't press the jockey",
+ "aim to hit the tarjit"]
+
+JJ_RB = ["like you say", "like you speak"] # For Adjectives or Adverbs
+
+
+def shanifier(update: Update, context: CallbackContext, is_group: bool = False, the_id=None) -> None:
+ user = update.message.from_user
+ full_name = user.full_name
+ bot_username = context.bot.name # Bot username with @
+ today = update.message.date
+ org_text = update.message.text
+ chat_id = update.effective_chat.id
+
+ flag = 0 # To check if a modal is present in the sentence
+ lydcount = 0 # Counts the number of times "like you do" has been added
+ JJ_RBcount = 0 # Counts the number of times a phrase from JJ_RB has been added
+ temp = 0
+
+ name = get_nick(update, context)
+
+ add_update_records(update, context)
+
+ context.bot.send_chat_action(chat_id=chat_id, action='typing') # Sends 'typing...' status for 6 sec
+
+ if bot_username in org_text: # Sends response if bot is @'ed in group
+ msg_text = re.sub(rf"(\s*){bot_username}(\s*)", ' ', org_text) # Remove mention from text so response is better
+ the_id = update.message.message_id
+ else:
+ msg_text = org_text
+
+ reply_to, bot_msg, user_msg = get_response(update, text=msg_text)
+
+ if not is_group:
+ shanisirbot.learn_response(user_msg, bot_response)
+ chat_type = "(PRIVATE)"
+
+ else:
+ chat_type = f"(GROUP: {update.effective_chat.title})"
+
+ punctuation = r"""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""
+ bot_msg = ''.join(c for c in bot_msg if c not in punctuation)
+ blob = TextBlob(bot_msg)
+ cleaned = blob.words # Returns list with no punctuation marks
+
+ if len(cleaned) < 20:
+ lydlim = 1 # to limit the number of times we add
+ JJ_RBlim = 1 # lyd and JJ_RB
+ else:
+ lydlim = len(cleaned) // 20
+ JJ_RBlim = len(cleaned) // 20
+
+ for word, tag in blob.tags: # returns list of tuples which tells the POS
+ index = cleaned.index(word)
+ if index - temp < 7: # Do not add lad things too close to each other
+ continue
+
+ if tag == 'MD' and not flag: # Modal
+ cleaned.insert(index + 1, "(if the laws of physics allow it)")
+ flag = 1
+
+ if tag in ['JJ', 'JJR', 'JJS', 'RB', 'RBR', 'RBS'] and JJ_RBcount < JJ_RBlim: # Adjective or Adverb
+ cleaned.insert(index + 1, r.choice(JJ_RB))
+ JJ_RBcount += 1
+ temp = index
+
+ elif tag in ['VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ'] and lydcount < lydlim: # Verb
+ cleaned.insert(index + 1, "like you do")
+ lydcount += 1
+ temp = index
+
+ if r.choice([0, 1]):
+ if r.choice([0, 1]):
+ cleaned.append(r.choice(responses1))
+ else:
+ cleaned.append(r.choice(responses2))
+ cleaned.insert(0, name)
+ else:
+ cleaned.append(name)
+
+ if len(cleaned) < 5: # Will run if input is too short
+ cleaned.append(r.choice(["*draws perfect circle*", "*scratches nose*"]))
+
+ if re.search('when|time', ' '.join(cleaned), flags=re.IGNORECASE):
+ cleaned.insert(-1, 'decide a date')
+
+ for word in update.message.text:
+ if word in emoji.UNICODE_EMOJI: # Checks if emoji is present in message
+ cleaned.append(r.choice(list(emoji.UNICODE_EMOJI))) # Adds a random emoji
+
+ shanitext = ' '.join(cleaned)
+ shanitext = shanitext[0].upper() + shanitext[1:]
+
+ inp = f"UTC+0 {today} {chat_type} {reply_to} {full_name} ({user.username}) SAID: {msg_text}\n"
+ out = shanitext
+
+ context.bot.send_message(chat_id=chat_id, text=out, reply_to_message_id=the_id) # Sends message
+ logger(message=f"\nThe input by {full_name} to the bot in {get_chat_name(update)} was:\n{msg_text}"
+ f"\n\n\nThe output by the bot was:\n{out}")
+
+ with open("files/interactions.txt", "a") as f1:
+ f1.write(emoji.demojize(inp))
+ f1.write(f"BOT REPLY: {emoji.demojize(out)}\n\n")
+
+
+def reply(update: Update, context: CallbackContext) -> None:
+ text = update.message.text
+ if update.message.reply_to_message.from_user.username == context.bot.username: # If the reply is to a bot:
+ if not (text.startswith('!r') or text.endswith('!r')): # Don't reply if this is prepended or appended.
+ logger(message=f"Bot received a reply from {update.effective_user.first_name} in "
+ f"{update.effective_chat.title}.")
+ shanifier(update, context, is_group=True, the_id=update.message.message_id)
+
+ elif context.bot.name in text:
+ shanifier(update, context, is_group=True, the_id=update.message.message_id)
+
+
+def group(update: Update, context: CallbackContext) -> None:
+ """Checks for profanity in messages and responds to that."""
+
+ chat_id = update.effective_chat.id
+ text = update.message.text
+
+ if any(bad_word in text.lower().split() for bad_word in prohibited):
+
+ query = f"SELECT PROFANE_PROB FROM CHAT_SETTINGS WHERE CHAT_ID={chat_id};"
+ true = connection(query, update)
+ logger(message=f"The query executed on the database was:\n{query}\nand the result was:\n{true=}")
+
+ false = 1 - true
+
+ if r.choices([0, 1], weights=[false, true])[0]: # Probabilities are 0.8 - False, 0.2 - True by default.
+ name = get_nick(update, context)
+
+ out = f"{r.choice(rebukes)} {name}"
+ context.bot.send_message(chat_id=chat_id, text=out,
+ reply_to_message_id=update.message.message_id) # Sends message
+ logger(message=f"{update.effective_user.first_name} used profane language in {get_chat_name(update)}."
+ f"\nThe rebuke by the bot was: '{out}'.")
+
+ elif context.bot.name in text:
+ shanifier(update, context, is_group=True, the_id=update.message.message_id)
+
+
+def get_response(update: Update, text: str) -> (str, str, str):
+ global bot_response
+
+ if bot_response is None:
+ search_in_response_text = None
+ else:
+ search_in_response_text = get_tags(bot_response.text)
+
+ user_msg = chatterbot.conversation.Statement(text=text, search_text=get_tags(text), in_response_to=bot_response,
+ search_in_response_to=search_in_response_text)
+
+ # If the user's message is a reply to a message
+ if update.message.reply_to_message is not None:
+ reply_text = update.message.reply_to_message.text
+ if reply_text is not None:
+ bot_response = chatterbot.conversation.Statement(text=reply_text, search_text=get_tags(reply_text))
+ user_msg = chatterbot.conversation.Statement(text=text, search_text=get_tags(text),
+ in_response_to=bot_response,
+ search_in_response_to=get_tags(reply_text))
+
+ reply_to = f"(REPLY TO [{user_msg.in_response_to}])"
+
+ bot_response = shanisirbot.get_response(user_msg.text)
+
+ if hasattr(bot_response, 'text'):
+ bot_msg = bot_response.text
+ else:
+ bot_msg = 'Hello'
+
+ return reply_to, bot_msg, user_msg
+
+
+def add_update_records(update: Update, context: CallbackContext) -> None:
+ chat_id = update.effective_chat.id
+ user = update.message.from_user
+ full_name = user.full_name
+ username = user.username
+
+ # Checks if your username or fullname or chat id is present in our records. If not, adds them.
+ if 'username' not in context.user_data:
+ context.user_data['username'] = [username]
+
+ elif username != context.user_data['username'][-1]:
+ context.user_data['username'].append(username)
+ logger(message=f"{full_name} changed their username to: {username}.")
+
+ if 'full_name' not in context.user_data:
+ context.user_data['full_name'] = [full_name]
+
+ elif full_name != context.user_data['full_name'][-1]:
+ context.user_data['full_name'].append(full_name)
+ logger(message=f"{username} changed their full name to: {full_name}.")
+
+ if "chat_ids" not in context.chat_data:
+ context.chat_data["chat_ids"] = [chat_id]
+ logger(message=f"{full_name} is talking to the bot for the first time.")
+
+ elif chat_id not in context.chat_data['chat_ids']: # Gets chat id of the user in which they have talked to the bot
+ context.chat_data['chat_ids'].append(chat_id)
+
+ context.dispatcher.persistence.update_user_data(user.id, context.user_data)
+ context.dispatcher.persistence.update_chat_data(chat_id, context.chat_data)
diff --git a/bot_funcs/delete_pin.py b/bot_funcs/delete_pin.py
new file mode 100644
index 0000000..52cc241
--- /dev/null
+++ b/bot_funcs/delete_pin.py
@@ -0,0 +1,11 @@
+from telegram import Update
+from telegram.ext import CallbackContext
+
+from helpers.logger import logger
+
+
+def de_pin(update: Update, context: CallbackContext) -> None:
+ """Deletes pinned message service status from the bot."""
+
+ context.bot.delete_message(chat_id=update.effective_chat.id, message_id=update.message.message_id)
+ logger(message=f"Bot deleted a pinned service message from {update.effective_chat.title}.")
diff --git a/bot_funcs/media_reactor.py b/bot_funcs/media_reactor.py
new file mode 100644
index 0000000..3bfa1b5
--- /dev/null
+++ b/bot_funcs/media_reactor.py
@@ -0,0 +1,94 @@
+from telegram import Update
+from telegram.ext import CallbackContext
+from time import sleep, time as cur_time
+from helpers.namer import get_nick
+from helpers.db_connector import connection
+import random as r
+from helpers.logger import logger
+
+last_reacted_at = 0
+
+
+def media(update: Update, context: CallbackContext) -> None:
+ """Sends a reaction to media messages (pictures, videos, documents, voice notes)"""
+
+ global last_reacted_at
+
+ now = cur_time()
+
+ if now - last_reacted_at < 60: # If a reaction was sent less than a minute ago
+ return # Don't send a reaction
+
+ last_reacted_at = cur_time()
+
+ chat_id = update.effective_chat.id
+ msg = update.message.message_id
+ name = get_nick(update, context)
+ query = f"SELECT MEDIA_PROB FROM CHAT_SETTINGS WHERE CHAT_ID={chat_id};"
+
+ true = connection(query, update)
+ logger(message=f"The query executed on the database was:\n{query}\nand the result was:\n{true=}")
+
+ false = 1 - true
+
+ prob = r.choices([0, 1], weights=[false, true])[0] # Probabilities are 0.7 - False, 0.3 - True by default
+
+ if not prob:
+ return
+
+ if hasattr(update.message.audio, 'performer'):
+ if update.message.audio.performer == 'Shani Sir': # Don't send reaction to its own inline clips.
+ return
+
+ try:
+ doc = update.message.document.file_name.split('.')[-1]
+ except Exception as e: # When there is no document sent (most likely AttributeError)
+ logger(message=f"File extension was not assigned. The warning is: \n{e}", warning=True)
+ doc = ''
+
+ img_reactions = ["😂", "🤣", "😐", f"Not funny {name} okay?", "This is not fine like you say", "*giggles*",
+ f"This is embarrassing to me {name}", "What your doing?! Go for the worksheet",
+ "I don't like this now", "This is beneficial to me like", f"I don't understand this {name}",
+ f"See {name}, I want you to delete this"]
+
+ vid_reactions = ["😂", "🤣", "😐", f"I've never seen anything like this {name}", "What is this",
+ f"Tell me the physics behind it {name}", "This is like you say boring", "Now I feel very bad like",
+ f"Are you fine {name}?", f"See {name}, I want you to delete this"]
+
+ voice_reactions = ["What is this", f"I can't hear you {name}", f"Are you fine {name}?",
+ "Now your on the track like", "Your voice is funny like you say",
+ f"See I can't tolerate this {name}", "What your saying??",
+ f"See {name}, I want you to delete this"]
+
+ app_reactions = ["Is this a virus", "I'm just suggesting like, don't open this", "We just don't mind that okay?"]
+
+ doc_reactions = [f"Did you read this {name}", "I'm not in agreement like", "I don't like this okay",
+ "This is very good like you say", "Now your on the track like", "Nice for reading okay",
+ "This is fake news delete this like", "This is like you say cut and paste from somewhere"]
+
+ context.bot.send_chat_action(chat_id=chat_id, action='typing')
+ sleep(2)
+
+ if update.message.photo or doc in ('jpg', 'jpeg', 'png'):
+ context.bot.send_message(chat_id=chat_id, text=r.choice(img_reactions), reply_to_message_id=msg)
+ logger(message=f"Bot sent a reaction to a photo to {name}.")
+
+ elif update.message.voice or update.message.audio:
+ context.bot.send_message(chat_id=chat_id, text=r.choice(voice_reactions), reply_to_message_id=msg)
+ logger(message=f"Bot sent a reaction to a voice message/audio to {name}.")
+
+ elif update.message.video or doc in ('mp4', 'gif'):
+ context.bot.send_message(chat_id=chat_id, text=r.choice(vid_reactions), reply_to_message_id=msg)
+ logger(message=f"Bot sent a reaction to a video to {name}.")
+
+ elif doc in ('apk', 'exe'):
+ context.bot.send_message(chat_id=chat_id, text=r.choice(app_reactions), reply_to_message_id=msg)
+ logger(message=f"Bot sent a reaction to a executable to {name}.")
+
+ elif doc in ('pdf', 'doc', 'docx', 'txt'):
+ context.bot.send_message(chat_id=chat_id, text=r.choice(doc_reactions), reply_to_message_id=msg)
+ logger(message=f"Bot sent a reaction to a text document to {name}.")
+
+ else:
+ logger(message=f"This shouldn't be happening, bot needs to respond to at least one of the media."
+ f"The file extension was {doc=}.", warning=True)
diff --git a/bot_funcs/morning_wisher.py b/bot_funcs/morning_wisher.py
new file mode 100644
index 0000000..a726b83
--- /dev/null
+++ b/bot_funcs/morning_wisher.py
@@ -0,0 +1,63 @@
+from datetime import datetime
+
+from telegram.ext import CallbackContext
+
+from helpers.db_connector import connection
+from helpers.logger import logger
+
+
+def morning_goodness(context: CallbackContext) -> None:
+ """
+ Send a "good morning" quote to the groups, along with a clip. This will only work if it has already been a
+ day since last good morning quote and is before 11am the next day.
+ """
+
+ right_now = datetime.now() # returns: Datetime obj
+ afternoon = datetime(right_now.year, right_now.month, right_now.day, 11) # 11am today
+
+ if 'last_sent' not in context.bot_data:
+ context.bot_data['last_sent'] = right_now
+
+ diff = right_now - context.bot_data['last_sent']
+
+ # Send only if it has been over a day and is before 11am next morning since last good morning message-
+ if diff.days < 1 and right_now >= afternoon:
+ return
+
+ with open("files/good_mourning.txt", "r") as greetings:
+ position = context.bot_data['seek']
+ if position == 13642: # If EOF was reached
+ position = 0 # Start from the beginning
+ greetings.seek(position)
+
+ greeting = greetings.readline()
+ logger(message=f"Today's morning quote is:\n{greeting}")
+ context.bot_data['seek'] = greetings.tell()
+
+ query = "SELECT CHAT_ID, CHAT_NAME FROM CHAT_SETTINGS WHERE MORNING_MSGS='✅';"
+ ids = connection(query, fetchall=True)
+ logger(message=f"The query executed on the database was:\n{query}\nand the result was:\n{ids=}")
+
+ # Open mp3 from desktop as github url doesn't support thumbnails-
+
+ clip_loc = r"C:/Users/Uncle Sam/Desktop/sthyaVERAT/4 FUN ya Practice/Shanisirmodule/Assets/clips/good mourning.mp3"
+
+ for chat_id, chat_name in ids:
+ try:
+ msg = context.bot.send_message(chat_id=chat_id, text=greeting)
+ logger(message=f"Today's morning quote was just sent to {chat_name}.")
+
+ context.bot.send_chat_action(chat_id=chat_id, action='upload_audio')
+
+ context.bot.send_audio(chat_id=chat_id, title="Good morning", performer="Shani sir",
+ audio=open(clip_loc, "rb"), thumb=open("files/shanisir.jpeg", 'rb'))
+ logger(message=f"Today's morning audio was just sent to {chat_name}.")
+
+ context.bot.pin_chat_message(chat_id=chat_id, message_id=msg.message_id, disable_notification=True)
+
+ except Exception as e: # When chat is private, no rights to pin message, or if bot was removed.
+ logger(message=f"There was an error for {chat_name} due to: {e}.")
+
+ context.bot_data['last_sent'] = datetime(right_now.year, right_now.month, right_now.day, 8) # Set it as 8AM today
+ context.dispatcher.persistence.update_bot_data(context.bot_data)
+ logger(message="The last_sent object was successfully updated to 8AM today.")
diff --git a/chatbot.py b/chatbot.py
index 4a59f19..d45a3d5 100644
--- a/chatbot.py
+++ b/chatbot.py
@@ -5,12 +5,15 @@
shanisirbot = chatterbot.ChatBot('The Shani Sir Bot',
storage_adapter='chatterbot.storage.SQLStorageAdapter',
logic_adapters=['chatterbot.logic.BestMatch'],
- response_selection_method=response_selection.get_first_response, # or get_random_response or get_most_frequent_response
+ response_selection_method=response_selection.get_first_response,
preprocessors=['chatterbot.preprocessors.clean_whitespace'],
- read_only=False) # Set to True to disable further learning from conversations the bot has
+ read_only=False) # Set to True to disable further learning from conversations the bot
+shanisirbot.initialize() # Does any work that needs to be done before the chatbot can process responses.
+get_tags = shanisirbot.storage.tagger.get_bigram_pair_string
-def train_with(corpus):
+
+def train_with(corpus: str) -> None:
"""
Trains the bot using the specified corpus
eng ---> chatterbot.corpus.english (standard English corpus from chatterbot_corpora)
@@ -22,7 +25,7 @@ def train_with(corpus):
import time
if corpus == 'ubu': # WARNING: TAKES A REALLY LONG TIME
- start = time.time() # (TOOK 114000 SECONDS = 31 HOURS TO EXTRACT AND TRAIN FOR UNCLE SAM, NOT INCLUDING DOWNLOAD TIME)
+ start = time.time() # (TOOK 114000 SECONDS = 31 HOURS TO EXTRACT & TRAIN FOR UNCLE SAM, NOT INCLUDING DL TIME)
corpus_trainer = UbuntuCorpusTrainer(shanisirbot)
corpus_trainer.train()
else:
diff --git a/commands.py b/commands.py
index 33b5583..61715fa 100644
--- a/commands.py
+++ b/commands.py
@@ -1,9 +1,12 @@
import itertools
import random as r
-from telegram import error, InlineKeyboardButton, InlineKeyboardMarkup
+from telegram import error, InlineKeyboardButton, InlineKeyboardMarkup, Poll, Update
+from telegram.ext import CallbackContext
-from online import util
+from helpers.logger import logger
+from helpers.namer import get_chat_name
+from online import util, quiz_scraper
with open(r"files/lad_words.txt", "r") as f:
prohibited = f.read().lower().split('\n')
@@ -12,10 +15,16 @@
snake_roast = f.read()
swear_advice = ["Don't use such words. Okay, fine?", "Such language fails to hit the tarjit.",
- "Vocabulary like this really presses my jokey.", "It's embarrassing vocabulary like basically.",
+
+ "Vocabulary like this really presses my jokey.",
+
+ "It's embarrassing vocabulary like basically.",
+
"Such language is not expected from 12th class students", "There's no meaning of soo sowry, okay?",
+
"You say shit like this then you go 'oh i'm so sowry sir it slipped' and expect me to forgive your"
" sorry ass. Pathetic. Get a grip, loser.",
+
"Some of you dumbasses talk as if your teachers are all deaf. Trust me; we hear a lot more than you'd"
" like us to."]
@@ -23,7 +32,7 @@
swear_advice = itertools.cycle(swear_advice)
-def ladcased(normal):
+def ladcased(normal: str) -> str:
"""Convert a string to 'ladcase' (Alternating uppercase and lowercase)"""
ladified = ''
@@ -33,8 +42,9 @@ def ladcased(normal):
return ladified
-def del_command(update):
+def del_command(update: Update) -> None:
"""Delete the command message sent by the user."""
+
try:
update.message.delete()
@@ -44,13 +54,25 @@ def del_command(update):
class BotCommands:
@staticmethod
- def start(update, context):
- context.bot.send_message(chat_id=update.effective_chat.id,
- text="You can use me anywhere, @ me in the chatbox and type to get an audio clip."
- " Or just talk to me here and get help from me directly. Type /help to know more")
+ def start(update: Update, context: CallbackContext) -> None:
+ """Starts the bot. Sends a short message detailing what the bot does."""
+
+ name = update.effective_user.first_name
+
+ msg = "You can use me anywhere, @ me in the chatbox and type to get an audio clip." \
+ " Or just talk to me here and get help from me directly. Type /help to know more."
+
+ if context.args:
+ msg = "See if you want to tell your nickname and birthday click this --> /tell"
+ logger(message=f"{name} just clicked the button to use /tell in private from {get_chat_name(update)}.")
+ else:
+ logger(update=update, message=f"/start", command=True)
+
+ context.bot.send_message(chat_id=update.effective_chat.id, text=msg)
@staticmethod
- def helper(update, context):
+ def helper(update: Update, context: CallbackContext) -> None:
+ """Sends a message to the user which explains how to use the bot."""
buttons = [[InlineKeyboardButton(text="Try out inline mode", switch_inline_query_current_chat="")],
[InlineKeyboardButton(text="Use inline mode in another chat", switch_inline_query="")]]
@@ -70,40 +92,74 @@ def helper(update, context):
"\n/facts \- Blesses you with an incredibly useful fact\."
"\n/8ball \- Answers yes/no questions in Shani Sir style\!"
"\n/settings \- Modify my behaviour with granular precision\."
+ "\n/quizizz \- Sends you a physics question\."
"\n\nHow to use /8ball:\n1\. Reply to a message with /8ball\n2\. Send /8ball in"
" chat and reply to the message the bot sends\.\n\n"
r"Inspired by the [Shani Sir Module](https://github.com/tmslads/Shanisirmodule)"
- r" and Telegram\.",
- parse_mode="MarkdownV2", disable_web_page_preview=True, reply_markup=markup
- )
+ r" and Telegram\!\.", parse_mode="MarkdownV2", disable_web_page_preview=True,
+ reply_markup=markup)
+ logger(update=update, message=f"/help", command=True)
@staticmethod
- def secret(update, context):
+ def secret(update: Update, context: CallbackContext) -> None:
context.bot.send_message(chat_id=update.effective_chat.id,
text="stop finding secret commands :P") # Secret command for later use
@staticmethod
- def swear(update, context):
+ def swear(update: Update, context: CallbackContext) -> None:
+ """Sends a couple of swear words to the user along with a message saying not to use them."""
+
del_command(update)
+
while True:
swears = r.choices(prohibited, k=4) # Returns a list of 4 elements
if len(set(swears)) == len(swears): # i.e. if there is a duplicate element
break
+
context.bot.send_message(chat_id=update.effective_chat.id,
text=ladcased(f"'{swears[0]}',\n'{swears[1]}',\n'{swears[2]}',\n'{swears[3]}'\n\n"
f"{next(swear_advice)}"))
+ logger(update=update, message=f"/swear", command=True)
@staticmethod
- def snake(update, context):
+ def snake(update: Update, context: CallbackContext) -> None:
+ """Sends a roast to the user."""
+
del_command(update)
context.bot.send_message(chat_id=update.effective_chat.id, text=snake_roast)
+ logger(update=update, message=f"/snake", command=True)
@staticmethod
- def facts(update, context):
+ def facts(update: Update, context: CallbackContext) -> None:
+ """Sends one random fact to the user."""
+
del_command(update)
fact = r.choice(util.facts())
context.bot.send_message(chat_id=update.effective_chat.id, text=fact)
+ logger(update=update, message=f"/facts", command=True)
+
+ @staticmethod
+ def quizizz(update: Update, context: CallbackContext) -> None:
+ """This is called when user calls /quizizz. This sends one physics quiz for the user from the internet."""
+
+ logger(update=update, message=f"/quizizz", command=True)
+
+ while True:
+ try:
+ questions, choices, answers = quiz_scraper.a_quiz()
+ break
+ except TypeError: # If we get None (due to error) back, retry.
+ logger(message="There was a problem getting the questions, trying again.", warning=True)
+
+ question = questions[0]
+ options = choices[0]
+ answer = answers[0]
+ context.bot.send_poll(chat_id=update.effective_chat.id, question=question, options=options, is_anonymous=False,
+ type=Poll.QUIZ, correct_option_id=answer)
@staticmethod
- def unknown(update, context):
+ def unknown(update: Update, context: CallbackContext) -> None:
+ """When user uses an invalid command."""
+
context.bot.send_message(chat_id=update.effective_chat.id, text="I didn't say wrong I don't know.")
+ logger(message=f"{update.effective_user.first_name} just used something weird in {get_chat_name(update)}.")
diff --git a/constants.py b/constants.py
index 95260ff..382c95e 100644
--- a/constants.py
+++ b/constants.py
@@ -11,16 +11,16 @@
CREATE TABLE IF NOT EXISTS CHAT_SETTINGS(
CHAT_ID INTEGER PRIMARY KEY,
CHAT_NAME TEXT,
- MORNING_MSGS BOOLEAN,
+ MORNING_MSGS TEXT,
MEDIA_PROB DECIMAL(2,1),
PROFANE_PROB DECIMAL(2,1)
);
"""
# Websites to scrape from-
-_DOWNLOAD = "https://raw.githubusercontent.com"
-_LINK = "https://github.com/tmslads/Shanisirmodule/tree/master/Assets/clips"
-URL = 'http://randomfactgenerator.net/' # To be scraped for facts()
+LINK = "https://api.github.com/repos/tmslads/shanisirmodule/contents/Assets/clips"
+FACT_URL = 'http://randomfactgenerator.net/' # To be scraped for facts()
+QUIZ_URL = "https://www.onlinegk.com/general-knowledge/gk-question-answers/physics"
# Bot usernames-
shanibot = "@shanisirbot"
diff --git a/convos/bday.py b/convos/bday.py
index 9249143..3fb17f2 100644
--- a/convos/bday.py
+++ b/convos/bday.py
@@ -1,50 +1,49 @@
# birthday function conversation-
-
import datetime
-from telegram import ForceReply
+from telegram import ForceReply, Update
from telegram import KeyboardButton
from telegram import ReplyKeyboardMarkup
+from telegram.ext import CallbackContext
+from helpers.logger import logger
+from helpers.namer import get_nick
from online.gcalendar import formatter
-from .namer import nicknamer
from .start import markup, CHOICE
INPUT, MODIFY = range(1, 3)
-def bday(update, context): # CHOICE
+def bday(update: Update, context: CallbackContext) -> int: # CHOICE
"""Asks user for their birthday if it is not known, else gives options on what to do with them."""
+ chat_id = update.effective_chat.id
+ msg_id = update.message.message_id
+
# Asks user for birthday if we don't have it stored.
if 'birthday' not in context.user_data:
- context.bot.send_message(chat_id=update.effective_chat.id,
+ context.bot.send_message(chat_id=chat_id,
text="I don't know your birthday like you say. When? \nEnter your DOB as: YYYY-MM-DD",
- reply_to_message_id=update.message.message_id,
- reply_markup=ForceReply(selective=True)
- )
+ reply_to_message_id=msg_id, reply_markup=ForceReply(selective=True))
return INPUT
else:
# Gives options for users by asking them what to do with their birthdays.
- bday_keyboard = [
- [KeyboardButton(text="Update my birthday sir"), KeyboardButton(text="Forget my birthday sir")],
- [KeyboardButton(text="No, thank you sir")]]
+ bday_keyboard = [[KeyboardButton(text="Update my birthday sir"), KeyboardButton(text="Forget my birthday sir")],
+ [KeyboardButton(text="No, thank you sir")]]
bday_markup = ReplyKeyboardMarkup(keyboard=bday_keyboard, one_time_keyboard=True, selective=True)
b_date = context.user_data['birthday']
- context.bot.send_message(chat_id=update.effective_chat.id,
- text=f"Your birthday is on"
- f" {formatter(b_date, format_style='DD/MM')} and"
- f" you are {age_cal(b_date)} years old. Would you like to update or remove it?",
- reply_to_message_id=update.message.message_id,
- reply_markup=bday_markup
- )
+ context.bot.send_message(chat_id=chat_id, text=f"Your birthday is on"
+ f" {formatter(b_date, format_style='DD/MM')} and"
+ f" you are {age_cal(b_date)} "
+ f"years old. Would you like to update or remove it?",
+ reply_to_message_id=msg_id, reply_markup=bday_markup)
return MODIFY
-def bday_add_or_update(update, context): # INPUT
+def bday_add_or_update(update: Update, context: CallbackContext) -> int: # INPUT
"""Changes or adds your birthday into our records."""
bday_date = update.message.text
@@ -53,46 +52,49 @@ def bday_add_or_update(update, context): # INPUT
dt_obj = datetime.datetime.strptime(bday_date, "%Y-%m-%d")
except Exception as e: # If user didn't enter birthday in the right format
- print(e)
+ logger(message=f"The traceback is: {e}", warning=True)
wrong(update, context) # Asks for a valid input
else:
- name = nicknamer(update, context)
+ name = get_nick(update, context)
context.user_data['birthday'] = dt_obj
context.bot.send_message(chat_id=update.effective_chat.id,
- text=f"Ok {name}, I'll remember your birthday like you say.",
- reply_markup=markup)
+ text=f"Ok {name}, I'll remember your birthday like you say.", reply_markup=markup)
+
+ logger(message=f"{update.effective_user.first_name} just changed their birthday to {bday_date}.")
+
return CHOICE
-def bday_mod(update, context): # MODIFY
+def bday_mod(update: Update, context: CallbackContext) -> int: # MODIFY
"""Asks user for input so we can update their birthday"""
- name = nicknamer(update, context)
+ name = get_nick(update, context)
context.bot.send_message(chat_id=update.effective_chat.id, text=f"{name}, I know your birthday yes? If it is"
f" wrong you can come and tell me the correct"
f" one okay?"
f"\nEnter your DOB as: YYYY-MM-DD",
- reply_to_message_id=update.message.message_id,
- reply_markup=ForceReply(selective=True))
+ reply_to_message_id=update.message.message_id, reply_markup=ForceReply(selective=True))
return INPUT
-def bday_del(update, context): # MODIFY
+def bday_del(update: Update, context: CallbackContext) -> int: # MODIFY
"""Deletes birthday from our records. Then goes back to main menu."""
- name = nicknamer(update, context)
+ name = get_nick(update, context)
context.bot.send_message(chat_id=update.effective_chat.id, text=f"Ok {name}, I forgot your birthday",
reply_to_message_id=update.message.message_id, reply_markup=markup)
+ logger(message=f"{update.effective_user.first_name} just deleted their birthday.")
+
del context.user_data['birthday']
return CHOICE
-def age_cal(date: datetime.datetime):
+def age_cal(date: datetime.datetime) -> int:
"""Returns your age based on your birth date."""
today = datetime.datetime.utcnow()
@@ -100,7 +102,7 @@ def age_cal(date: datetime.datetime):
return age.days // 365
-def reject(update, context): # fallback
+def reject(update: Update, context: CallbackContext) -> int: # fallback
"""When user cancels current operation. Goes back to main menu."""
context.bot.send_message(chat_id=update.effective_chat.id, text=f"Ok, what you want to do like?",
@@ -109,11 +111,10 @@ def reject(update, context): # fallback
return CHOICE
-def wrong(update, context): # INPUT
+def wrong(update: Update, context: CallbackContext) -> int: # INPUT
"""Asks user to enter his birthdate correctly."""
context.bot.send_message(chat_id=update.effective_chat.id,
text=f"This is not correct. Aim to hit the tarjit.\nEnter your DOB as: YYYY-MM-DD",
- reply_markup=ForceReply(selective=True),
- reply_to_message_id=update.message.message_id)
+ reply_markup=ForceReply(selective=True), reply_to_message_id=update.message.message_id)
return INPUT
diff --git a/convos/magic.py b/convos/magic.py
index 44d2413..13530e1 100644
--- a/convos/magic.py
+++ b/convos/magic.py
@@ -2,58 +2,65 @@
import random as r
from time import sleep
-from telegram import ForceReply
+from telegram import ForceReply, Update, ReplyKeyboardRemove
+from telegram.ext import CallbackContext
-from constants import shanibot
-from .namer import nicknamer
+from helpers.logger import logger
+from helpers.namer import get_nick, get_chat_name
-PROCESSING = range(1)
+PROCESSING = 0
-def magic8ball(update, context):
+def magic8ball(update: Update, context: CallbackContext) -> int:
"""Asks the user for the question."""
chat_id = update.effective_chat.id
- name = nicknamer(update, context)
+ name = get_nick(update, context)
initiate = ["If you have a doubt, just type it here",
f"{name}, are you confused? Ask me and I'll search for some sow...so..solutions"
- " okay?",
- "I can predict the future like you say . Just ask me. I'm just trying to find you option",
+ " okay?", "I can predict the future like you say . Just ask me. I'm just trying to find you option",
"Fast fast no time ask me!", "See tell me what's the confusion", f"Yes {name}?"]
context.bot.send_chat_action(chat_id=chat_id, action='typing')
sleep(1)
# Sends message with a force reply
- context.bot.send_message(chat_id=chat_id,
- text=f"{r.choice(initiate)}🔮\nOr, type /cancel so I won't mind that",
+ context.bot.send_message(chat_id=chat_id, text=f"{r.choice(initiate)}🔮\nOr, type /cancel so I won't mind that",
reply_markup=ForceReply(force_reply=True, selective=True),
reply_to_message_id=update.message.message_id)
+
+ logger(message=f"/8ball", command=True, update=update)
+
return PROCESSING # Will go into first (and only) state in convo handler in main.py
-def thinking(update, context):
+def thinking(update: Update, context: CallbackContext) -> int:
"""
First sends a message indicating his thinking process for 3 seconds, then on the 4th second he gives the answer
by editing his message.
"""
- name = nicknamer(update, context)
+
+ name = get_nick(update, context)
chat_id = update.effective_chat.id
- if update.message.reply_to_message.from_user.username != shanibot.replace('@', ''):
- actual_msg = update.message.reply_to_message.message_id
+ if update.message.reply_to_message.from_user.username != context.bot.name.replace('@', ''):
+
+ logger(message=f"{update.effective_user.first_name} used /8ball in {get_chat_name(update)}"
+ f" and on {update.message.reply_to_message.from_user.first_name}'s message.")
+
+ actual_msg = update.message.reply_to_message.message_id # Reply to the reply of the received message.
else:
actual_msg = update.message.message_id
- thoughts = ["See I'm spending time because your question normally comes mistake", "*scratching nose*",
- "Uhmmm", "Ok, there is one option", "*sniffs*", "What you say like"]
+ thoughts = ["See I'm spending time because your question normally comes mistake", "*scratching nose*", "Uhmmm",
+ "Ok, there is one option", "*sniffs*", "What you say like"]
answers = ["No no I'm sure not", "I don't want to tell you like you say", "I don't know like",
f"No {name}, I'm so sowry", "Obviously like you say", r"Yes\. No other option like",
"I didn't say wrong, I don't know", "See just do the worksheet no other importance of the situation",
- "This may be hard, but I think no okay?", "The laws of physics say yes 😄",
- f"Yes yes", "Maybe okay?", "Ah yea", "My feeling says no, now I feel very bad I told you like that",
+ "This may be hard, but I think no okay?", "The laws of physics say yes 😄", f"Yes yes", "Maybe okay?",
+ "Ah yea", "My feeling says no, now I feel very bad I told you like that",
"That's not my policy I'm not answering",
"See don't waste my time like you say with these easy questions okay, fine?",
f"The universe says yes {name}", "That's going to be broken now", "Sorry no idea"]
@@ -63,8 +70,7 @@ def thinking(update, context):
seconds = list(range(1, 5))
msg_sent = context.bot.send_message(chat_id=chat_id, text=f"`{thought}`", # Will be monospaced
- parse_mode='MarkdownV2', # Check Bot API 4.5 for MarkdownV2 docs
- reply_to_message_id=actual_msg)
+ parse_mode='MarkdownV2', reply_to_message_id=actual_msg)
# Editing message rapidly-
for second in seconds:
@@ -76,17 +82,32 @@ def thinking(update, context):
text = f"_{answer + edit_add}_" # Answer will be in italic
sleep(1) # So all of this doesn't happen instantly and is visible to user
- context.bot.edit_message_text(chat_id=chat_id, message_id=msg_sent.message_id,
- text=f"{text}", # Edits message sent by bot accordingly
- parse_mode='MarkdownV2')
+ context.bot.edit_message_text(chat_id=chat_id, message_id=msg_sent.message_id, text=f"{text}",
+ parse_mode='MarkdownV2') # Edits message sent by bot accordingly
return -1 # End of conversation
-def cancel(update, context):
+def cancel(update: Update, context: CallbackContext) -> int:
"""Called when user presses /cancel"""
+
context.bot.send_message(chat_id=update.effective_chat.id,
text="I just wanted to be in the right direction nothing else I mean okay?",
- reply_to_message_id=update.message.message_id)
+ reply_to_message_id=update.message.message_id,
+ reply_markup=ReplyKeyboardRemove(selective=True))
+
+ logger(message=f"{update.effective_user.first_name} just cancelled /8ball.")
return -1
+
+
+def timedout(update: Update, context: CallbackContext) -> None:
+ """Called when the user does not respond to /8ball after 35 seconds."""
+
+ context.bot.send_message(chat_id=update.effective_chat.id,
+ text=f"Ok, {get_nick(update, context)} don't tell me your problem. I have other things "
+ f"to do like",
+ reply_to_message_id=update.message.message_id,
+ reply_markup=ReplyKeyboardRemove(selective=True))
+
+ logger(message=f"{update.effective_user.first_name} just timed out using /8ball.")
diff --git a/convos/namer.py b/convos/namer.py
deleted file mode 100644
index 733942a..0000000
--- a/convos/namer.py
+++ /dev/null
@@ -1,13 +0,0 @@
-# Function to choose your nickname-
-
-
-def nicknamer(update, context):
- """Uses current nickname set by user."""
-
- try:
- name = context.user_data['nickname'][-1]
- except (KeyError, IndexError):
- context.user_data['nickname'] = []
- context.user_data['nickname'].append(update.message.from_user.first_name)
- finally:
- return context.user_data['nickname'][-1]
diff --git a/convos/nick.py b/convos/nick.py
index f28ed1b..9c80006 100644
--- a/convos/nick.py
+++ b/convos/nick.py
@@ -1,65 +1,65 @@
-from telegram import ForceReply
+from telegram import ForceReply, Update
from telegram import KeyboardButton
from telegram import ReplyKeyboardMarkup
+from telegram.ext import CallbackContext
from commands import prohibited
+from helpers.logger import logger
from .start import markup, CHOICE
SET_NICK, MODIFY_NICK = range(3, 5)
-def nick(update, context):
+def nick(update: Update, context: CallbackContext) -> int:
"""
Checks if nickname is set or not, if set, then gives options on what to do with them. Else will ask to set
a nickname.
"""
+
name = update.message.from_user.first_name
chat_id = update.effective_chat.id
msg_id = update.message.message_id
if 'nickname' not in context.user_data or context.user_data['nickname'][-1] == name:
- context.bot.send_message(chat_id=chat_id,
- text="What is your uhh.. what you say like... nickname?",
- reply_to_message_id=msg_id, reply_markup=ForceReply(selective=True))
+ context.bot.send_message(chat_id=chat_id, text="What is your uhh.. what you say like... nickname?",
+ reply_to_message_id=msg_id, reply_markup=ForceReply(selective=True))
return SET_NICK
else:
- nick_kb = [[KeyboardButton("Change nickname"), KeyboardButton("Remove nickname")],
- [KeyboardButton("Back")]]
+ nick_kb = [[KeyboardButton("Change nickname"), KeyboardButton("Remove nickname")], [KeyboardButton("Back")]]
nick_markup = ReplyKeyboardMarkup(nick_kb, one_time_keyboard=True, selective=True)
nick_name = context.user_data["nickname"][-1]
- context.bot.send_message(chat_id=chat_id,
- text=f"Hi {nick_name}, what you want to do like?", reply_markup=nick_markup,
- reply_to_message_id=msg_id)
+ context.bot.send_message(chat_id=chat_id, text=f"Hi {nick_name}, what you want to do like?",
+ reply_markup=nick_markup, reply_to_message_id=msg_id)
return MODIFY_NICK
-def del_nick(update, context): # MODIFY_NICK
+def del_nick(update: Update, context: CallbackContext) -> int: # MODIFY_NICK
"""Deletes nickname (i.e.) sets it to your first name."""
name = update.message.from_user.first_name
context.user_data['nickname'].append(name)
- context.bot.send_message(chat_id=update.effective_chat.id,
- text=f"I'm forgetting your nic.. {name}",
- reply_to_message_id=update.message.message_id,
- reply_markup=markup)
+ context.bot.send_message(chat_id=update.effective_chat.id, text=f"I'm forgetting your nic.. {name}",
+ reply_to_message_id=update.message.message_id, reply_markup=markup)
+
+ logger(message=f"{name} just deleted their nickname.")
+
return CHOICE
-def edit_nick(update, context): # MODIFY_NICK
+def edit_nick(update: Update, context: CallbackContext) -> int: # MODIFY_NICK
"""Asks for new nickname."""
- context.bot.send_message(chat_id=update.effective_chat.id,
- text="Tell me youre new nickname like you say",
+ context.bot.send_message(chat_id=update.effective_chat.id, text="Tell me your new nickname like you say",
reply_to_message_id=update.message.message_id, reply_markup=ForceReply(selective=True))
return SET_NICK
-def add_edit_nick(update, context): # SET_NICK
+def add_edit_nick(update: Update, context: CallbackContext) -> int: # SET_NICK
"""Adds or updates your nickname. Then goes back to main menu."""
chat_id = update.effective_chat.id
@@ -80,14 +80,15 @@ def add_edit_nick(update, context): # SET_NICK
context.bot.send_message(chat_id=chat_id, text=f"Hi {nicky} what you're doing like", reply_to_message_id=msg_id,
reply_markup=markup)
+
+ logger(message=f"{update.effective_user.first_name} just changed their nickname to {nicky}.")
+
return CHOICE
-def back(update, context): # MODIFY_NICK
+def back(update: Update, context: CallbackContext) -> int: # MODIFY_NICK
"""Goes back to main menu."""
- context.bot.send_message(chat_id=update.effective_chat.id,
- text=f"What you want?",
- reply_to_message_id=update.message.message_id,
- reply_markup=markup)
+ context.bot.send_message(chat_id=update.effective_chat.id, text=f"What you want?",
+ reply_to_message_id=update.message.message_id, reply_markup=markup)
return CHOICE
diff --git a/convos/settings_gui.py b/convos/settings_gui.py
index 30d32f5..aac84e0 100644
--- a/convos/settings_gui.py
+++ b/convos/settings_gui.py
@@ -1,10 +1,14 @@
import random as r
import sqlite3
+from typing import Union
-from telegram import (InlineKeyboardMarkup, InlineKeyboardButton)
+from telegram import (InlineKeyboardMarkup, InlineKeyboardButton, Update)
from telegram.error import BadRequest
+from telegram.ext import CallbackContext
from constants import samir, harshil, sql_table
+from helpers.logger import logger
+from helpers.namer import get_nick, get_chat_name
CURRENT_SETTINGS, UPDATED, PROBABILITY = range(3)
@@ -32,7 +36,7 @@
prob_markup = InlineKeyboardMarkup(prob_buttons)
-def start(update, context):
+def start(update: Update, context: CallbackContext) -> int:
"""
Called when user uses /settings. If it is the first time using it, it creates and uses default bot settings.
Can only be used in groups where user is admin, or in private chats.
@@ -58,9 +62,11 @@ def start(update, context):
reply_to_message_id=update.message.message_id)
return -1 # Stop convo since a regular user called /settings
+ logger(message=f"/settings", command=True, update=update)
+
conn = sqlite3.connect('./files/bot_settings.db')
c = conn.cursor()
- name = namer(update, context)
+ name = get_nick(update, context)
c.executescript(sql_table) # If table is not made
conn.commit()
@@ -78,22 +84,13 @@ def start(update, context):
# Sends the current settings applied-
if update.callback_query is None:
- context.bot.send_message(chat_id=chat_id, text=setting_msg(update),
- reply_markup=setting_markup, parse_mode="MarkdownV2")
+ context.bot.send_message(chat_id=chat_id, text=setting_msg(update), reply_markup=setting_markup,
+ parse_mode="MarkdownV2")
return UPDATED
-def namer(update, context) -> str:
- """Helper function to get name of private/group chat."""
-
- name = update.effective_chat.title
- if name is None:
- name = update.effective_chat.first_name
- return name
-
-
-def setting_msg(update, swap: bool = False):
+def setting_msg(update, swap: bool = False) -> str:
"""Helper function to modify or create the /settings menu message."""
global msg, media_prob, profane_prob, morn_setting
@@ -116,12 +113,12 @@ def setting_msg(update, swap: bool = False):
msg = "See is this the expected behaviour?\n\n" \
r"1\. _Media reactions:_ " + f"{media_pct}\n" \
- r"2\. _Profanity reactions:_ " + f"{profane_pct}\n" \
- r"3\. _Morning quotes:_ " + f"{morn_setting}\n"
+ r"2\. _Profanity reactions:_ " + f"{profane_pct}\n" \
+ r"3\. _Morning quotes:_ " + f"{morn_setting}\n"
return msg
-def prob_message(update, kind: str, column: str) -> [None, str]:
+def prob_message(update, kind: str, column: str) -> Union[None, str]:
"""Helper function to show current probability of corresponding setting."""
chat_id = update.effective_chat.id
@@ -137,7 +134,7 @@ def prob_message(update, kind: str, column: str) -> [None, str]:
return prob_msg
-def prob_updater(update, context): # PROBABILITY
+def prob_updater(update: Update, context: CallbackContext) -> int: # PROBABILITY
"""Updates probability when buttons are pressed. Also instantly saves those values in the database."""
global media_prob, profane_prob
@@ -190,7 +187,7 @@ def prob_updater(update, context): # PROBABILITY
return PROBABILITY
-def change_prob(update, context): # UPDATED
+def change_prob(update: Update, _: CallbackContext) -> int: # UPDATED
"""
This is run when the user clicks button to change the probability. It is common for both profanity and media
reactions.
@@ -199,7 +196,6 @@ def change_prob(update, context): # UPDATED
global _type, media_prob, profane_prob
data = update.callback_query.data
- chat_id = update.effective_chat.id
if data == "MEDIA_PROB":
_type = "media"
@@ -212,7 +208,7 @@ def change_prob(update, context): # UPDATED
return PROBABILITY
-def morn_swap(update, context): # UPDATED
+def morn_swap(update: Update, context: CallbackContext) -> int: # UPDATED
"""Used to swap states of morning quotes."""
global morn_setting
@@ -224,7 +220,7 @@ def morn_swap(update, context): # UPDATED
return UPDATED
-def go_back(update, context): # PROBABILITY
+def go_back(update: Update, _: CallbackContext) -> int: # PROBABILITY
"""Goes back to main menu."""
update.callback_query.edit_message_text(text=setting_msg(update), reply_markup=setting_markup,
@@ -233,7 +229,7 @@ def go_back(update, context): # PROBABILITY
return UPDATED
-def save(update, context): # UPDATED
+def save(update: Update, _: CallbackContext) -> int: # UPDATED
"""Called when user clicks save. Saves all applied settings into database."""
global morn_setting
@@ -250,13 +246,16 @@ def save(update, context): # UPDATED
update.callback_query.edit_message_text(text=r.choice(responses) + f"\n\n{r.choice(confirmations)}\n" + msg[36:],
parse_mode="MarkdownV2")
+ logger(message=f"{update.effective_user.first_name} just updated {get_chat_name(update)}'s settings to:\n"
+ f"Media={media_prob}, Profanity={profane_prob}, Morning quotes={morn_setting}.")
+
c.execute(f"UPDATE CHAT_SETTINGS SET MORNING_MSGS='{morn_setting}' WHERE CHAT_ID={chat_id};")
conn.commit()
# Checks if group name has changed, if it did, updates in db-
c.execute(f"SELECT CHAT_NAME FROM CHAT_SETTINGS WHERE CHAT_ID={chat_id};") # Gets name from db
result = c.fetchone()
- name = namer(update, context) # Gets name of chat
+ name = get_chat_name(update) # Gets name of chat
if name != result[0]: # If the name is not the same, update it in db
c.execute(f"UPDATE CHAT_SETTINGS SET CHAT_NAME='{name}' WHERE CHAT_ID={chat_id};")
diff --git a/convos/start.py b/convos/start.py
index 6fd3c6a..4350917 100644
--- a/convos/start.py
+++ b/convos/start.py
@@ -1,29 +1,54 @@
-from telegram import KeyboardButton, ReplyKeyboardMarkup, ReplyKeyboardRemove
+from telegram import (KeyboardButton, ReplyKeyboardMarkup, ReplyKeyboardRemove, InlineKeyboardMarkup,
+ InlineKeyboardButton, Update)
+from telegram.ext import CallbackContext
+from telegram.utils.helpers import create_deep_linked_url
-from .namer import nicknamer
+from helpers.logger import logger
+from helpers.namer import get_nick
# This is the main menu. Shown when /tell is invoked.
-keyboard = [
- [KeyboardButton(text="Birthday"), KeyboardButton(text="Nickname")],
- [KeyboardButton(text="Nothing")]
-]
+keyboard = [[KeyboardButton(text="Birthday"), KeyboardButton(text="Nickname")], [KeyboardButton(text="Nothing")]]
+
markup = ReplyKeyboardMarkup(keyboard=keyboard, one_time_keyboard=True, selective=True)
-CHOICE = range(1)
+CHOICE = 0
-def initiate(update, context): # Entry_point
- name = nicknamer(update, context)
+def initiate(update: Update, context: CallbackContext) -> int: # Entry_point
+ """This function is called when user uses /tell. It branches into 3- 'birthday', 'nickname' and 'nothing'."""
- context.bot.send_message(chat_id=update.effective_chat.id,
+ chat = update.effective_chat
+ first_name = update.effective_user.first_name
+
+ if chat.type != "private":
+ link = create_deep_linked_url(bot_username=context.bot.username, payload="tell")
+ button = [[InlineKeyboardButton(text="Let's go like you say!", url=link)]]
+ tell_markup = InlineKeyboardMarkup(button)
+
+ context.bot.send_message(chat_id=chat.id, text="Just come to another chat I want to talk to you like you say",
+ reply_markup=tell_markup)
+
+ logger(message=f"{first_name} just tried using /tell in a {chat.type}. "
+ f"A message telling them to use it private was sent.")
+
+ return -1
+
+ name = get_nick(update, context)
+
+ context.bot.send_message(chat_id=chat.id,
text=f'What do you want to tell me {name}? Type /cancel anytime to switch me off',
reply_to_message_id=update.message.message_id, reply_markup=markup)
+
+ logger(message=f"/tell", update=update, command=True)
+
return CHOICE
-def leave(update, context):
- name = nicknamer(update, context)
+def leave(update: Update, context: CallbackContext) -> int:
+ """This is called when user clicks 'Nothing'. Exits from the /tell conversation."""
+
+ name = get_nick(update, context)
context.bot.send_message(chat_id=update.effective_chat.id,
text=f'Bye {name}, sit and solve the past papers like you say, I want to put a test okay?',
@@ -33,8 +58,11 @@ def leave(update, context):
return -1
-def timedout(update, context):
- context.bot.send_message(chat_id=update.effective_chat.id,
- text="Ok I am fine being seenzoned",
+def timedout(update: Update, context: CallbackContext) -> None:
+ """This is called when a user has timed out while using /tell (after 35 seconds)."""
+
+ context.bot.send_message(chat_id=update.effective_chat.id, text="Ok I am fine being seenzoned",
reply_to_message_id=update.message.message_id,
reply_markup=ReplyKeyboardRemove(selective=True))
+
+ logger(message=f"{update.effective_user.first_name} just timed out while using /tell.")
diff --git a/creds/token.pickle b/creds/token.pickle
index 5f9c516..6e982ce 100644
Binary files a/creds/token.pickle and b/creds/token.pickle differ
diff --git a/files/bot_settings.db b/files/bot_settings.db
index 4402cf9..429b934 100644
Binary files a/files/bot_settings.db and b/files/bot_settings.db differ
diff --git a/files/cursor_test.py b/files/cursor_test.py
deleted file mode 100644
index 4c52983..0000000
--- a/files/cursor_test.py
+++ /dev/null
@@ -1,8 +0,0 @@
-# Prints the position of the cursor and then the line, for each line in the file
-
-
-def test():
- with open("good_mourning.txt", "r") as greetings:
- while True:
- print(greetings.tell())
- print(greetings.readline())
diff --git a/files/user_data b/files/user_data
index 0de8305..be1e867 100644
Binary files a/files/user_data and b/files/user_data differ
diff --git a/helpers/db_connector.py b/helpers/db_connector.py
new file mode 100644
index 0000000..e2c415d
--- /dev/null
+++ b/helpers/db_connector.py
@@ -0,0 +1,37 @@
+# Helper function to connect to database and get result.
+import sqlite3
+from typing import Union
+
+from telegram import Update
+
+from helpers.namer import get_chat_name
+
+
+def connection(query: str, update: Update = None, fetchall: bool = False) -> Union[list, int, float, str]:
+ """Connect to database and execute given query."""
+
+ conn = sqlite3.connect('./files/bot_settings.db')
+ c = conn.cursor()
+
+ if update is not None:
+ chat_id = update.effective_chat.id
+ c.execute(f"SELECT EXISTS(SELECT * FROM CHAT_SETTINGS WHERE chat_id = {chat_id});")
+ result = c.fetchone()
+
+ if not result[0]: # If /settings was never called
+ name = get_chat_name(update)
+
+ c.execute(f"INSERT INTO CHAT_SETTINGS VALUES({chat_id},'{name}','❌',0.3,0.2);") # First time use
+ conn.commit()
+
+ c.execute(query)
+
+ if fetchall:
+ result = c.fetchall()
+ else:
+ result = c.fetchone()
+ result = result[0]
+
+ conn.close()
+
+ return result
diff --git a/helpers/logger.py b/helpers/logger.py
new file mode 100644
index 0000000..6d469e5
--- /dev/null
+++ b/helpers/logger.py
@@ -0,0 +1,28 @@
+import logging
+
+from telegram import Update
+
+from .namer import get_chat_name
+
+# asctime - The time in human readable form
+# name - Name of the logger module
+# levelname - logging level for the message ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL')
+# lineno - Line number
+# message - The logged message
+
+logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(lineno)d - %(message)s', level=logging.INFO)
+
+
+def logger(message: str, update: Update = None, command: bool = False, warning: bool = False, debug: bool = False,
+ exception: bool = False) -> None:
+ if warning:
+ logging.warning(f"\n{message}\n\n")
+ elif exception:
+ logging.exception(f"\n{message}\n\n")
+ elif debug:
+ logging.debug(f"\n{message}\n\n")
+ else:
+ if command and update is not None:
+ logging.info(f"\n{update.effective_user.first_name} just used {message} in {get_chat_name(update)}.\n\n")
+ else:
+ logging.info(f"\n{message}\n\n")
diff --git a/helpers/namer.py b/helpers/namer.py
new file mode 100644
index 0000000..eddf36a
--- /dev/null
+++ b/helpers/namer.py
@@ -0,0 +1,23 @@
+# Functions to obtain nickname or chatname-
+from telegram import Update
+from telegram.ext import CallbackContext
+
+
+def get_nick(update: Update, context: CallbackContext) -> str:
+ """Uses current nickname set by user."""
+
+ try:
+ name = context.user_data['nickname'][-1]
+ except (KeyError, IndexError):
+ context.user_data['nickname'] = [update.message.from_user.first_name]
+ finally:
+ return context.user_data['nickname'][-1]
+
+
+def get_chat_name(update: Update) -> str:
+ """Helper function to get name of private/group chat."""
+
+ name = update.effective_chat.title
+ if name is None:
+ name = update.effective_chat.first_name
+ return name
diff --git a/inline.py b/inline.py
index dadb87d..ee44ad7 100644
--- a/inline.py
+++ b/inline.py
@@ -1,22 +1,32 @@
from difflib import get_close_matches
from uuid import uuid4
-from telegram import InlineQueryResultAudio
+from telegram import InlineQueryResultAudio, Update
+from telegram.ext import CallbackContext
from online import util
results = []
-links, names = util.clips()
+names = []
-# Adds all clips and names into one list
-for clip in zip(links, names):
- results.append(InlineQueryResultAudio(id=uuid4(), audio_url=clip[0], title=clip[1], performer="Shani Sir"))
+def get_clips(_: CallbackContext) -> None:
+ global results, names
-def inline_clips(update, context):
+ results.clear()
+ names.clear()
+ links, names = util.clips()
+
+ # Adds all clips and names into one list
+ for link, name in zip(links, names):
+ results.append(InlineQueryResultAudio(id=uuid4(), audio_url=link, title=name, performer="Shani Sir"))
+
+
+def inline_clips(update: Update, context: CallbackContext) -> None:
query = update.inline_query.query
if not query:
- context.bot.answer_inline_query(update.inline_query.id, results[:50]) # Show first 49 clips if nothing is typed
+ # Show first 49 clips if nothing is typed-
+ context.bot.answer_inline_query(update.inline_query.id, results[:50], cache_time=60)
else:
matches = get_close_matches(query, names, n=15, cutoff=0.3) # Searches for close matches
index = 0
diff --git a/leaderboard.png b/leaderboard.png
new file mode 100644
index 0000000..a24e54b
Binary files /dev/null and b/leaderboard.png differ
diff --git a/main.py b/main.py
index 4dfc075..06b0094 100644
--- a/main.py
+++ b/main.py
@@ -1,390 +1,29 @@
-import itertools
import logging
import pickle
import pprint
-import random as r
-import re
-import sqlite3
-from datetime import datetime, date
-from time import sleep, time as cur_time
-
-import chatterbot
-import emoji
+
from telegram.ext import (CommandHandler, ConversationHandler, InlineQueryHandler, MessageHandler, Filters,
- PicklePersistence, Updater, CallbackQueryHandler)
-from textblob import TextBlob
+ PicklePersistence, Updater, CallbackQueryHandler, PollAnswerHandler)
-import chatbot
import inline
-from commands import BotCommands as bc, prohibited
-from constants import group_ids, shanibot
-from convos import (bday, magic, nick, settings_gui, start)
-from convos.namer import nicknamer
-from online import gcalendar
-
-logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
+from bot_funcs import media_reactor, morning_wisher, bday_wisher, conversation, delete_pin
+from commands import BotCommands as bc
+from constants import shanibot
+from convos import bday, magic, nick, settings_gui, start
+from quiz import send_quiz, receive_answer
-chatbot.shanisirbot.initialize() # Does any work that needs to be done before the chatbot can process responses.
-get_tags = chatbot.shanisirbot.storage.tagger.get_bigram_pair_string
+logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(lineno)d - %(message)s', level=logging.INFO)
with open("files/token.txt", 'r') as file:
shanisir_token, test_token = file.read().split(',')
pp = PicklePersistence(filename='files/user_data')
-updater = Updater(token=f'{shanisir_token}', use_context=True, persistence=pp)
+updater = Updater(token=f'{test_token}', use_context=True, persistence=pp)
dp = updater.dispatcher
-shanisir_bot = updater.bot
-
-last_reacted_at = 0
-bot_response = None
-
-rebukes = ["this is not the expected behaviour", "i don't want you to talk like that",
- "this language is embarrassingassing to me like basically", "this is not a fruitful conversation"]
-
-r.shuffle(rebukes)
-rebukes = itertools.cycle(rebukes)
-
-
-def connection(query: str, update=None, fetchall=False):
- """Connect to database and execute given query."""
-
- conn = sqlite3.connect('./files/bot_settings.db')
- c = conn.cursor()
-
- if update is not None:
- chat_id = update.effective_chat.id
- c.execute(f"SELECT EXISTS(SELECT * FROM CHAT_SETTINGS WHERE chat_id = {chat_id});")
- result = c.fetchone()
-
- if not result[0]: # If /settings was never called
- name = update.effective_chat.title
- if name is None: # Will be None when it is a private chat
- name = update.effective_chat.first_name
-
- c.execute(f"INSERT INTO CHAT_SETTINGS VALUES({chat_id},'{name}','❌',0.3,0.2);") # First time use
- conn.commit()
-
- c.execute(query)
-
- if fetchall:
- result = c.fetchall()
- conn.close()
- return result
- else:
- result = c.fetchone()
- conn.close()
- return result[0]
-
-
-def media(update, context):
- """Sends a reaction to media messages (pictures, videos, documents, voice notes)"""
-
- global last_reacted_at
-
- now = cur_time()
-
- if now - last_reacted_at < 60: # If a reaction was sent less than a minute ago
- return # Don't send a reaction
-
- last_reacted_at = cur_time()
-
- chat_id = update.effective_chat.id
- msg = update.message.message_id
-
- true = connection(f"SELECT MEDIA_PROB FROM CHAT_SETTINGS WHERE CHAT_ID={chat_id};", update)
- false = 1 - true
-
- try:
- doc = update.message.document.file_name[-3:]
- except AttributeError: # When there is no document sent
- doc = ''
- name = nicknamer(update, context)
-
- img_reactions = ["😂", "🤣", "😐", f"Not funny {name} okay?", "This is not fine like you say", "*giggles*",
- f"This is embarrassing to me {name}", "What your doing?! Go for the worksheet"]
-
- vid_reactions = ["😂", "🤣", "😐", f"I've never seen anything like this {name}", "What is this",
- "Now I feel very bad like", f"Are you fine {name}?"]
-
- voice_reactions = ["What is this", f"I can't hear you {name}", f"Are you fine {name}?",
- "Now your on the track like", "Your voice is funny like you say",
- f"See I can't tolerate this {name}", "What your saying??"]
-
- app_reactions = ["Is this a virus", "I'm just suggesting like, don't open this", "We just don't mind that okay?"]
-
- prob = r.choices([0, 1], weights=[false, true])[0] # Probabilities are 0.7 - False, 0.3 - True by default
- if prob:
- shanisir_bot.send_chat_action(chat_id=chat_id, action='typing')
- sleep(2)
-
- if update.message.photo:
- print("Img")
- shanisir_bot.send_message(chat_id=chat_id, text=r.choice(img_reactions), reply_to_message_id=msg)
-
- elif update.message.voice:
- print("voiceee")
- shanisir_bot.send_message(chat_id=chat_id, text=r.choice(voice_reactions), reply_to_message_id=msg)
-
- elif update.message.video or doc == 'mp4' or doc == 'gif':
- print("vid")
- shanisir_bot.send_message(chat_id=chat_id, text=r.choice(vid_reactions), reply_to_message_id=msg)
-
- elif doc == 'apk' or doc == 'exe':
- print("app")
- shanisir_bot.send_message(chat_id=chat_id, text=r.choice(app_reactions), reply_to_message_id=msg)
-
-
-def del_pin(update, context):
- """Deletes pinned message service status from the bot."""
- shanisir_bot.delete_message(chat_id=update.effective_chat.id, message_id=update.message.message_id)
-
-
-def reply(update, context):
- if update.message.reply_to_message.from_user.username == shanibot.replace('@', ''): # If the reply is from a bot:
- private(update, context, grp=True, the_id=update.message.message_id) # send a response like in private chat
-
-
-def group(update, context):
- """Checks for profanity in messages and responds to that."""
-
- chat_id = update.effective_chat.id
- if any(bad_word in update.message.text.lower().split() for bad_word in prohibited):
- true = connection(f"SELECT PROFANE_PROB FROM CHAT_SETTINGS WHERE CHAT_ID={chat_id};", update)
- false = 1 - true
-
- if r.choices([0, 1], weights=[false, true])[0]: # Probabilities are 0.8 - False, 0.2 - True by default.
- name = nicknamer(update, context)
-
- out = f"{next(rebukes)} {name}"
- shanisir_bot.send_message(chat_id=chat_id, text=out,
- reply_to_message_id=update.message.message_id) # Sends message
- print(f"Rebuke: {out}")
-
-
-def private(update, context, grp=False, the_id=None, isgrp="(PRIVATE)"):
- global bot_response
-
- user = update.message.from_user
- msg_text = update.message.text
- chat_id = update.effective_chat.id
-
- JJ_RB = ["like you say", "like you speak"] # For Adjectives or Adverbs
-
- # Checks if your username or fullname or chat id is present in our records. If not, adds them.
- if 'username' not in context.user_data:
- context.user_data['username'] = [user.username]
-
- elif user.username != context.user_data['username'][-1]:
- context.user_data['username'].append(user.username)
-
- if 'full_name' not in context.user_data:
- context.user_data['full_name'] = [user.full_name]
-
- elif user.full_name != context.user_data['full_name'][-1]:
- context.user_data['full_name'].append(user.full_name)
-
- if "chat_ids" not in context.chat_data:
- context.chat_data["chat_ids"] = []
-
- elif chat_id not in context.chat_data['chat_ids']: # Gets chat id of the user in which they have talked to the bot
- context.chat_data['chat_ids'].append(chat_id)
-
- # Attempted fix-
- pp.update_user_data(update.effective_user.id, context.user_data)
- pp.update_chat_data(chat_id, context.chat_data)
-
- if shanibot in msg_text: # Sends response if bot is @'ed in group
- msg_text = re.sub(r"(\s*)@shanisirbot(\s*)", ' ', msg_text) # Remove mention from text so response is better
- the_id = update.message.message_id
- grp = True
-
- if bot_response is None:
- search_in_response_text = None
- else:
- search_in_response_text = get_tags(bot_response.text)
- # If the user's message is a reply to a message
- if update.message.reply_to_message is not None:
- reply_text = update.message.reply_to_message.text
- bot_response = chatterbot.conversation.Statement(text=reply_text, search_text=get_tags(reply_text))
- user_msg = chatterbot.conversation.Statement(text=msg_text,
- search_text=get_tags(msg_text),
- in_response_to=bot_response,
- search_in_response_to=get_tags(reply_text))
- else:
- user_msg = chatterbot.conversation.Statement(text=msg_text,
- search_text=get_tags(msg_text),
- in_response_to=bot_response,
- search_in_response_to=search_in_response_text)
-
- reply = f"(REPLY TO [{user_msg.in_response_to}])"
-
- if grp:
- isgrp = f"(GROUP: {update.effective_chat.title})"
- else: # Learn user's latest message (user_msg) as response to bot's last message (bot_response)
- chatbot.shanisirbot.learn_response(user_msg, bot_response)
-
- bot_response = chatbot.shanisirbot.get_response(user_msg.text)
- try:
- bot_msg = bot_response.text
- except AttributeError:
- bot_msg = 'Hello'
-
- punctuation = r"""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""
- bot_msg = ''.join(c for c in bot_msg if c not in punctuation)
- blob = TextBlob(bot_msg)
- cleaned = blob.words # Returns list with no punctuation marks
-
- flag = 0 # To check if a modal is present in the sentence
- lydcount = 0 # Counts the number of times "like you do" has been added
- JJ_RBcount = 0 # Counts the number of times a phrase from JJ_RB has been added
-
- if len(cleaned) < 20:
- lydlim = 1 # to limit the number of times we add
- JJ_RBlim = 1 # lyd and JJ_RB
- else:
- lydlim = len(cleaned) // 20
- JJ_RBlim = len(cleaned) // 20
-
- temp = 0
-
- for word, tag in blob.tags: # returns list of tuples which tells the POS
- index = cleaned.index(word)
- if index - temp < 7: # Do not add lad things too close to each other
- continue
-
- if tag == 'MD' and not flag: # Modal
- cleaned.insert(index + 1, "(if the laws of physics allow it)")
- flag = 1
-
- if tag in ['JJ', 'JJR', 'JJS', 'RB', 'RBR', 'RBS'] and JJ_RBcount < JJ_RBlim: # Adjective or Adverb
- cleaned.insert(index + 1, r.choice(JJ_RB))
- JJ_RBcount += 1
- temp = index
-
- elif tag in ['VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ'] and lydcount < lydlim: # Verb
- cleaned.insert(index + 1, "like you do")
- lydcount += 1
- temp = index
-
- name = nicknamer(update, context)
-
- if r.choice([0, 1]):
- if r.choice([0, 1]):
- cleaned.append(r.choice(["I am so sowry", "i don't want to talk like that",
- "it is embarrassing to me like basically", "it's not to trouble you like you say",
- "go for the worksheet", "it's not that hard"]))
- else:
- cleaned.append(r.choice(["it will be fruitful", "you will benefit", "that is the expected behaviour",
- "now you are on the track like", "now class is in the flow like",
- "aim to hit the tarjit", "don't press the jockey"]))
- cleaned.insert(0, name)
- else:
- cleaned.append(name)
-
- if len(cleaned) < 5: # Will run if input is too short
- cleaned.append(r.choice(["*draws perfect circle*", "*scratches nose*"]))
-
- if re.search('when|time', ' '.join(cleaned), flags=re.IGNORECASE):
- cleaned.insert(-1, 'decide a date')
-
- for word in update.message.text:
- if word in emoji.UNICODE_EMOJI: # Checks if emoji is present in message
- cleaned.append(r.choice(list(emoji.UNICODE_EMOJI))) # Adds a random emoji
-
- shanitext = ' '.join(cleaned).capitalize()
-
- with open("files/interactions.txt", "a") as f1:
- inp = f"UTC+0 {update.message.date} {isgrp} {reply} {update.message.from_user.full_name}" \
- f" ({update.message.from_user.username}) SAID: {update.message.text}\n"
- out = shanitext
-
- print(f"{inp}\n{out}")
-
- f1.write(emoji.demojize(inp))
- f1.write(f"BOT REPLY: {emoji.demojize(out)}\n\n")
-
- shanisir_bot.send_chat_action(chat_id=chat_id, action='typing') # Sends 'typing...' status for 6 sec
- # Assuming 25 WPM typing speed on a phone
- time_taken = (25 / 60) * len(out.split())
- sleep(time_taken) if time_taken < 6 else sleep(6) # Sends status for 6 seconds if message is too long to type
- shanisir_bot.send_message(chat_id=chat_id, text=out, reply_to_message_id=the_id) # Sends message
-
-
-def morning_goodness(context):
- """Send a "good morning" quote to the groups, along with a clip"""
-
- right_now = datetime.now() # returns: Datetime obj
-
- if 'last_sent' not in context.bot_data:
- context.bot_data['last_sent'] = right_now
-
- diff = right_now - context.bot_data['last_sent']
-
- # Send only if it has been over a day since last good morning message-
- if diff.days < 1:
- return
-
- with open("files/good_mourning.txt", "r") as greetings:
- position = context.bot_data['seek']
- if position == 13642: # If EOF was reached
- position = 0 # Start from the beginning
- greetings.seek(position)
-
- greeting = greetings.readline()
- print(greeting)
- context.bot_data['seek'] = greetings.tell()
-
- ids = connection("SELECT CHAT_ID FROM CHAT_SETTINGS WHERE MORNING_MSGS='✅';", fetchall=True)
-
- # Bug with ptb where performer,title,thumb might be ignored when a url is supplied in 'audio' param in 'send_audio'.
- # Workaround for now is to just open mp3 from desktop-
-
- clip_loc = r"C:/Users/Uncle Sam/Desktop/sthyaVERAT/4 FUN ya Practice/Shanisirmodule/Assets/clips/good mourning.mp3"
-
- for chat_id in ids:
- try:
- msg = shanisir_bot.send_message(chat_id=chat_id[0], text=greeting)
- shanisir_bot.pin_chat_message(chat_id=chat_id[0], message_id=msg.message_id, disable_notification=True)
- shanisir_bot.send_chat_action(chat_id=chat_id[0], action='upload_audio')
- shanisir_bot.send_audio(chat_id=chat_id[0], title="Good morning", performer="Shani sir",
- audio=open(clip_loc, "rb"), thumb=open("files/shanisir.jpeg", 'rb'))
-
- except Exception as e: # When chat is private, no rights to pin message, or if bot was removed.
- print(e)
-
- context.bot_data['last_sent'] = datetime(right_now.year, right_now.month, right_now.day, 8) # Set it as 8AM today
- pp.update_bot_data(context.bot_data) # Have to update this manually as ptb 12.5 has new bug
-
-
-def bday_wish(context):
- """Wishes you on your birthday."""
-
- gcalendar.main()
- days_remaining, name = gcalendar.get_next_bday()
-
- happy_birthday = f"Happy birthday {name}! !🎉 I don't know why like, but I know you despise me with the burning passion of a thousand suns. I don't give a flux, like you say. I implore you to let go of hate and embrace love. Spend the rest of your days with love in your heart and faith in your soul. Life's cyclotron may sometimes send you tumbling around, but remember that it is necessary to do so in order to hit the targit. Negative emotions act as charge for the velocity selector of life. Remove them from your being and you shall not stray from the straight path. I wish you the best. May your jockeys be unpressed and your apertures small. Enjoy your 18th. Forget about coronabitch. Godspeed."
- happy_birthday1 = f"Happy birthday {name}! I wish you the best of luck for life. Remember: You matter. Until you multiply yourself times the speed of light squared. Then you energy, like you say!🎉 What your going to do today like?"
- happy_birthday2 = f"Happy birthday {name}! !🎉 What your going to do today like?"
-
- # Wishes from Google Calendar-
- if days_remaining == 0:
- msg = context.bot.send_message(chat_id=group_ids['12b'],
- text=happy_birthday)
- shanisir_bot.pin_chat_message(chat_id=group_ids['12b'], message_id=msg.message_id, disable_notification=True)
-
- now = str(date.today())
- today = datetime.strptime(now, "%Y-%m-%d") # Parses today's date (time object) into datetime object
- new_date = today.replace(year=today.year + 1)
-
- gcalendar.CalendarEventManager(name=name).update_event(new_date) # Updates bday to next year
-
- # TODO: Wishes from /tell birthday input-
-
-
-def prettyprintview():
+def data_view() -> None:
with open('files/user_data', 'rb') as f:
pprint.PrettyPrinter(indent=2).pprint(pickle.load(f))
@@ -396,59 +35,51 @@ def prettyprintview():
dp.add_handler(CommandHandler(command='swear', callback=bc.swear))
dp.add_handler(CommandHandler(command='snake', callback=bc.snake))
dp.add_handler(CommandHandler(command='facts', callback=bc.facts))
+dp.add_handler(CommandHandler(command='quizizz', callback=bc.quizizz))
+dp.add_handler(PollAnswerHandler(callback=receive_answer))
# /8ball conversation-
magicball_handler = ConversationHandler(
- entry_points=[
- CommandHandler(command="8ball", callback=magic.magic8ball, filters=~Filters.reply),
- MessageHandler(filters=Filters.command(False) & Filters.regex("8ball") & Filters.reply,
- callback=magic.thinking)
- ],
+ entry_points=[CommandHandler(command="8ball", callback=magic.magic8ball, filters=~Filters.reply),
+ MessageHandler(filters=Filters.command(False) & Filters.regex("8ball") & Filters.reply,
+ callback=magic.thinking)],
states={
- magic.PROCESSING: [MessageHandler(filters=Filters.reply & Filters.text, callback=magic.thinking)]
- },
+ magic.PROCESSING: [MessageHandler(filters=Filters.reply & Filters.text, callback=magic.thinking)],
+
+ ConversationHandler.TIMEOUT: [MessageHandler(filters=Filters.all, callback=magic.timedout)]},
- fallbacks=[CommandHandler(command='cancel', callback=magic.cancel)
- ],
- conversation_timeout=20
-)
+ fallbacks=[CommandHandler(command='cancel', callback=magic.cancel)], conversation_timeout=35)
dp.add_handler(magicball_handler)
-# /tell conversation
+# /tell conversation-
tell_handler = ConversationHandler(
- entry_points=[CommandHandler('tell', start.initiate, filters=Filters.private)],
+ entry_points=[CommandHandler('tell', start.initiate)],
states={
start.CHOICE: [MessageHandler(filters=Filters.regex("^Birthday$"), callback=bday.bday),
MessageHandler(filters=Filters.regex("^Nickname$"), callback=nick.nick),
- MessageHandler(filters=Filters.regex("^Nothing$"), callback=start.leave)
- ],
+ MessageHandler(filters=Filters.regex("^Nothing$"), callback=start.leave)],
+
bday.INPUT: [MessageHandler(filters=Filters.regex("^([1-9][0-9]{3}-[0-9]{2}-[0-9]{2})$"), # Valid date check
callback=bday.bday_add_or_update),
- MessageHandler(filters=Filters.text, callback=bday.wrong) # If it is not a date
- ],
+ MessageHandler(filters=Filters.text, callback=bday.wrong)], # If it is not a date
bday.MODIFY: [MessageHandler(filters=Filters.regex("^Forget my birthday sir$"), callback=bday.bday_del),
-
- MessageHandler(filters=Filters.regex("^Update my birthday sir$"), callback=bday.bday_mod)
- ],
+ MessageHandler(filters=Filters.regex("^Update my birthday sir$"), callback=bday.bday_mod)],
nick.SET_NICK: [MessageHandler(filters=Filters.text & Filters.reply, callback=nick.add_edit_nick)],
nick.MODIFY_NICK: [MessageHandler(filters=Filters.regex("^Change nickname$"), callback=nick.edit_nick),
MessageHandler(filters=Filters.regex("^Remove nickname$"), callback=nick.del_nick),
- MessageHandler(filters=Filters.regex("^Back$"), callback=nick.back)
- ],
+ MessageHandler(filters=Filters.regex("^Back$"), callback=nick.back)],
+
+ ConversationHandler.TIMEOUT: [MessageHandler(filters=Filters.all, callback=start.timedout)]},
- ConversationHandler.TIMEOUT: [MessageHandler(filters=Filters.all, callback=start.timedout)]
- },
fallbacks=[MessageHandler(Filters.regex("^No, thank you sir$"), callback=bday.reject),
- CommandHandler("cancel", start.leave)
- ],
+ CommandHandler("cancel", start.leave)],
- name="/tell convo", persistent=True, allow_reentry=True, conversation_timeout=20
-)
+ name="/tell convo", persistent=True, allow_reentry=True, conversation_timeout=35)
dp.add_handler(tell_handler)
settings_gui_handler = ConversationHandler(
@@ -457,32 +88,32 @@ def prettyprintview():
states={
settings_gui.UPDATED: [CallbackQueryHandler(settings_gui.change_prob, pattern="MEDIA_PROB|PROFANE_PROB"),
CallbackQueryHandler(settings_gui.morn_swap, pattern="Morning"),
- CallbackQueryHandler(settings_gui.save, pattern="SAVE")
- ],
-
- settings_gui.PROBABILITY:
- [CallbackQueryHandler(settings_gui.prob_updater, pattern="0.0|-0.1|-0.05|0.05|0.1|1.0"),
- CallbackQueryHandler(settings_gui.go_back, pattern="Back")
- ]
- },
- fallbacks=[CommandHandler('cancel', settings_gui.save)]
-)
+ CallbackQueryHandler(settings_gui.save, pattern="SAVE")],
+
+ settings_gui.PROBABILITY: [
+ CallbackQueryHandler(settings_gui.prob_updater, pattern="0.0|-0.1|-0.05|0.05|0.1|1.0"),
+ CallbackQueryHandler(settings_gui.go_back, pattern="Back")]},
+
+ fallbacks=[CommandHandler('cancel', settings_gui.save)])
dp.add_handler(settings_gui_handler)
-media_filters = (Filters.document | Filters.photo | Filters.video | Filters.voice)
+media_filters = (Filters.document | Filters.photo | Filters.video | Filters.voice | Filters.audio)
edit_filter = Filters.update.edited_message
+pin_filter = Filters.status_update.pinned_message
-dp.add_handler(MessageHandler(media_filters, media))
-dp.add_handler(MessageHandler(Filters.status_update.pinned_message & Filters.user(username=shanibot), del_pin))
-dp.add_handler(MessageHandler(Filters.reply & Filters.group & ~ edit_filter, reply))
-dp.add_handler(MessageHandler(Filters.regex(shanibot) & Filters.group & ~ edit_filter & ~ Filters.command, private))
-dp.add_handler(MessageHandler(Filters.group & Filters.text & ~ edit_filter, group))
-dp.add_handler(MessageHandler(Filters.private & Filters.text & ~ edit_filter, private))
+dp.add_handler(MessageHandler(media_filters, media_reactor.media))
+dp.add_handler(MessageHandler(pin_filter & Filters.user(username=shanibot), delete_pin.de_pin))
+dp.add_handler(MessageHandler(Filters.reply & Filters.group & ~ edit_filter, conversation.reply))
+dp.add_handler(MessageHandler(Filters.group & Filters.text & ~ edit_filter, conversation.group))
+dp.add_handler(MessageHandler(Filters.private & Filters.text & ~ edit_filter, conversation.shanifier))
dp.add_handler(MessageHandler(Filters.command, bc.unknown))
-updater.job_queue.run_repeating(bday_wish, 86400, first=1) # Will run every time script is started, and once a day.
-updater.job_queue.run_repeating(morning_goodness, 86400, first=1)
+updater.job_queue.run_repeating(bday_wisher.wish, 86400, first=1) # Runs every time script is started, and once a day.
+updater.job_queue.run_repeating(morning_wisher.morning_goodness, 86400, first=1)
+updater.job_queue.run_repeating(inline.get_clips, 60, first=1) # Have to re-fetch clips since links expire
+updater.job_queue.run_repeating(send_quiz, 604800, first=1) # Send quiz to 12B weekly
+
+# data_view()
updater.start_polling()
updater.idle()
-# prettyprintview()
diff --git a/online/gcalendar.py b/online/gcalendar.py
index f5fc388..e7798d5 100644
--- a/online/gcalendar.py
+++ b/online/gcalendar.py
@@ -1,31 +1,33 @@
# Connection to 12B class calendar, using Google Calendar API
-
import datetime
import os.path
import pickle
from datetime import date
from datetime import timedelta
+from typing import Tuple, Union
from google.auth.transport.requests import Request
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
+from helpers.logger import logger
+
+
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/calendar']
-service = None
class CalendarEventManager(object):
- def __init__(self, name: str, date: datetime.date = None) -> None:
+ def __init__(self, name: str, _date: datetime.date = None) -> None:
"""
:param name: Name of the person's whose birthday it is
- :param date: Date of that person's birthday
+ :param _date: Date of that person's birthday
"""
self.name = name
- self.date = date
+ self.date = _date
# self.formatted = formatter(self.date)
self.event = {
@@ -56,7 +58,7 @@ def add_event(self) -> None:
raise ValueError("Date must be specified!")
event = service.events().insert(calendarId='primary', body=self.event).execute()
- print("Inserted")
+ logger(message=f"{self.event['summary']} was added.")
def update_event(self, new_date: datetime.datetime):
"""
@@ -64,9 +66,6 @@ def update_event(self, new_date: datetime.datetime):
class instance.
"""
# Get event id of the event to be modified
- print(new_date)
- print(self.name)
-
events = service.events().list(calendarId='primary').execute()
for event in events['items']:
@@ -75,17 +74,17 @@ class instance.
self.event['start']['date'] = f"{formatter(new_date)}"
self.event['end']['date'] = f"{formatter(new_date + timedelta(days=1))}"
- print("Updated dates in the event.")
updated_event = service.events().update(calendarId='primary', eventId=event['id'],
body=self.event).execute()
- print(f"Successfully updated {self.name}'s birthday: {updated_event['start']['date']}")
+ logger(f"Successfully updated {self.name}'s birthday: {updated_event['start']['date']}.")
+
break
else:
raise ValueError("Event not found")
-def formatter(date: datetime.date, days: int = 0, format_style=""):
+def formatter(today: datetime.date, days: int = 0, format_style: str = "") -> Union[str, None]:
"""
Formats the date and returns it in the form used in the Google Calendar API. Adds 'days' no. of days to the date
if 'days' parameter is specified.
@@ -93,22 +92,22 @@ def formatter(date: datetime.date, days: int = 0, format_style=""):
Args:
:param format_style: If specified, type 'DD/MM' to format it in that way.
:param days: Number of days to add to the date.
- :param date: A datetime object
+ :param today: A datetime object
"""
- if isinstance(date, datetime.datetime):
+ if isinstance(today, datetime.datetime):
if days != 0:
- date += timedelta(days=days)
+ today += timedelta(days=days)
if format_style == "DD/MM":
- return date.strftime("%d/%m")
+ return today.strftime("%d/%m")
- return date.strftime("%Y-%m-%d")
+ return today.strftime("%Y-%m-%d")
return
-def get_next_bday():
+def get_next_bday() -> Tuple[int, str]:
"""
Fetches a birthday from google calendar (12B only) and returns the number of days till the next birthday of a
person along with their name.
@@ -141,7 +140,7 @@ def get_next_bday():
return next_bday # Returns lowest (i.e. next bday) in the calendar
-def main():
+def main() -> None:
"""
Sets up the Google Calendar API for easy use.
"""
@@ -169,9 +168,6 @@ def main():
service = build('calendar', 'v3', credentials=creds)
- # Call the Calendar API
- now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
-
if __name__ == '__main__':
main()
diff --git a/online/quiz_scraper.py b/online/quiz_scraper.py
new file mode 100644
index 0000000..a45fb90
--- /dev/null
+++ b/online/quiz_scraper.py
@@ -0,0 +1,72 @@
+import random as r
+import re
+from typing import List, Union
+
+import requests
+from bs4 import BeautifulSoup
+
+from constants import QUIZ_URL
+from helpers.logger import logger
+
+
+# TODO: Improve the entire thing-
+
+
+def a_quiz() -> Union[(list, List[List[str]], List[int]), None]:
+ page = r.randint(1, 76)
+ logger(message=f"Quiz obtained from {page=}.", debug=True)
+ quiz_url = f"{QUIZ_URL}/{page}"
+ content = requests.get(quiz_url).content
+
+ soup = BeautifulSoup(content, 'html.parser')
+ results = soup.find_all(class_=r.choice(['even', 'odd']))
+ all_questions = []
+ all_choices = [] # Type: List[List[str(choice)]]
+ all_answers = []
+
+ for result in results:
+ question_choices = []
+
+ question = result.find('b') # Get question
+ question = question.text.strip()
+ question = question[3:] # Removes the 'Q. ' part
+
+ if len(question) > 255: # If we've reached max question character limit for ptb
+ return
+
+ all_questions.append(question)
+
+ options = result.find_all('br') # Get options as a list
+
+ if len(options) > 5: # If there are notes or something weird (cheap way out, but practicality >>)
+ options = options[:5]
+
+ for option in options: # Get string between
tags by printing next sibling
+ choice = option.nextSibling
+
+ if choice is None: # Edge case when there's that stupid note
+ text = option.text.strip()
+ spliced = re.sub('([0-4][)])*', '', text).split()
+ question_choices.extend(spliced)
+ break
+
+ to_str = str(choice).strip()
+ stripped = re.sub('([0-4][)])*', '', to_str).strip()
+
+ if len(stripped) > 100: # Telegram doesn't allow a choice to have more than 100 characters
+ return
+
+ question_choices.append(stripped)
+
+ question_choices.pop() # Remove last empty string
+
+ if len(question_choices) > 10: # Telegram doesn't allow more than 10 choices
+ return
+
+ all_choices.append(question_choices)
+
+ answer = result.find('span', class_='ans') # Returns answer number
+ right_answer = int(answer.text.strip().replace('ANS: ', ''))
+ all_answers.append(right_answer - 1)
+
+ return all_questions, all_choices, all_answers
diff --git a/online/util.py b/online/util.py
index e548998..0d57b94 100644
--- a/online/util.py
+++ b/online/util.py
@@ -1,32 +1,37 @@
-import re
-
import requests
-from bs4 import BeautifulSoup
+from bs4 import BeautifulSoup, SoupStrainer
+from typing import Tuple
+
+from constants import LINK, FACT_URL
+
+with open('creds/github_token.txt', 'r') as f:
+ token = f.read()
-from constants import _LINK, _DOWNLOAD, URL
+header = {'Authorization': f'token {token}', 'token_type': 'bearer'}
-dl_links = []
-names = []
-getting = requests.get(_LINK)
-scraped = BeautifulSoup(getting.content, 'html.parser')
-results = scraped.find_all(href=re.compile('/tmslads/Shanisirmodule/blob/master/Assets/clips/'))
+def clips() -> Tuple[list, list]:
+ """Extracts the download links and names from the Shanisirmodule using the Github API."""
+ dl_links = []
+ names = []
+ getting = requests.get(LINK, headers=header).json()
+
+ for result in getting:
+ url = result['download_url']
+ name = result['name'][:-4]
+ if url is not None:
+ dl_links.append(url)
+ names.append(name)
-def clips():
- for index, result in enumerate(results):
- url = f"{_DOWNLOAD}{result['href'].replace('blob/', '')}"
- name = result['title'][:-4]
- dl_links.append(url)
- names.append(name)
return dl_links, names
-def facts():
+def facts() -> list:
"""Return list of three facts"""
- page = requests.get(URL)
- soup = BeautifulSoup(page.content, 'html.parser')
- result = soup.find_all(id='z') # Finds HTML elements with ID 'z'
- facts_list = [result[0].getText()[:-6], result[1].getText()[:-6],
- result[2].getText()[:-6]]
+
+ page = requests.get(FACT_URL)
+ results = BeautifulSoup(page.content, 'html.parser', parse_only=SoupStrainer(id='z')) # Get only z tags
+ facts_list = [str(results.contents[index].contents[0]) for index in range(len(results))]
+
return facts_list
diff --git a/profile_pics/nobody.png b/profile_pics/nobody.png
new file mode 100644
index 0000000..589afb5
Binary files /dev/null and b/profile_pics/nobody.png differ
diff --git a/profile_pics/trophy.png b/profile_pics/trophy.png
new file mode 100644
index 0000000..c75e810
Binary files /dev/null and b/profile_pics/trophy.png differ
diff --git a/quiz.py b/quiz.py
new file mode 100644
index 0000000..fbaac88
--- /dev/null
+++ b/quiz.py
@@ -0,0 +1,344 @@
+import os
+import random as r
+from datetime import datetime
+from time import sleep
+
+import matplotlib
+import numpy as np
+from PIL import Image, ImageDraw
+from matplotlib import patheffects
+from matplotlib import pyplot as plt
+from matplotlib.cbook import get_sample_data
+from matplotlib.offsetbox import (OffsetImage, AnnotationBbox)
+from telegram import Poll, ParseMode, Update
+from telegram.ext import CallbackContext
+from telegram.utils.helpers import mention_html
+
+from constants import group_ids
+from helpers.logger import logger
+from helpers.namer import get_nick
+from online import quiz_scraper
+
+quizzes = []
+cwd = os.getcwd()
+
+
+def send_quiz(context: CallbackContext) -> None:
+ """Sends 5 quizzes to target chat (12B for now). Also sets a timer for 24 hours for quiz expiry (using jobs)."""
+
+ global quizzes
+
+ right_now = datetime.now() # returns: Datetime obj
+ if 'last_quiz' not in context.bot_data:
+ context.bot_data['last_quiz'] = right_now
+
+ diff = right_now - context.bot_data['last_quiz']
+ print(diff)
+ if diff.days < 5:
+ print("Not enough days for next quiz!")
+ return
+
+ starts = ["See I'm keeping one quizizz now okay. You have one day to finish. For boards ok. I want everyone to do "
+ "it that's it.", "I have kept one quizizz now. I expect something okay.",
+ "Because of the bad like you say situation I have kept this online quizizz now. Do fast okay.",
+ "I'm sending these 5 questions now like. I want it to be done by tomorrow okay? Fast fast"]
+
+ context.bot.send_message(chat_id=group_ids['12b'], text=r.choice(starts))
+
+ # Get our questions, choices and answers from the web-
+ while True:
+ try:
+ questions, choices, answers = quiz_scraper.a_quiz()
+ break
+ except TypeError: # If we get None (due to error), retry.
+ pass
+
+ # Support sending quiz to 12B only for now-
+ # TODO: Change this back to 12B
+ for question, choice, answer in zip(questions, choices, answers):
+ quiz = context.bot.send_poll(chat_id=group_ids['12b'], question=question, options=choice, is_anonymous=False,
+ type=Poll.QUIZ, correct_option_id=answer, is_closed=False)
+ quizzes.append(quiz)
+
+ logger(message=f"The 5 quizzes were just sent to 12B successfully.")
+
+ context.job_queue.run_once(callback=timedout, when=60 * 60 * 10, context=[quizzes])
+ context.bot_data['last_quiz'] = right_now # Save new time for last quiz
+ context.dispatcher.persistence.flush()
+
+
+def timedout(context: CallbackContext) -> None:
+ """Closes quiz when the time limit is over. Also scolds people if they got 3 or more answers wrong in the quiz."""
+
+ to_scold = []
+ scolds = ["See if this is troubling you, you can come and get help from me directly okay?",
+ "Now I didn't expect thaaat level. See this is counted for the term exam okay",
+ "This is for you okay? This is for you to see your level. Aim to hit the tarjit",
+ "It's not that hard I expected something but I didn't know this level",
+ "You have to write retest no other option like you say",
+ "I'm just trying to find you option keep in mind you have any other option keep in mind like",
+ "This is like you say embarrassing to me. You have to put effort and work towards the boards now",
+ "That's it. I am telling mudassir sir now. Just tell me what's the confusion.",
+ "Are you fine? Physics is easy what's the problem like",
+ "You are troubling me. See I just wanted to be in the right direction nothing else I mean okay?"]
+
+ scold_names = ""
+
+ # Assign additional argument passed from job to variables
+ array = context.job.context[0]
+
+ for index, quiz in enumerate(array): # Stop all quizzes
+ context.bot.stop_poll(chat_id=group_ids['12b'], message_id=quiz.message_id)
+
+ context.bot.send_chat_action(chat_id=group_ids['12b'], action='upload_photo')
+ pp(context)
+ leaderboard(context) # Make the leaderboard
+
+ context.bot.send_photo(chat_id=group_ids['12b'], photo=open('leaderboard.png', 'rb'),
+ caption="This is where you stand like you say") # Send latest leaderboard
+
+ logger(message=f"The leaderboard was just sent on the group.")
+
+ # Get user mentions of people who got 3 or more answers wrong and scold them-
+ for user_id, value in context.bot_data['quizizz'].items():
+ if value['answers_wrong'] >= 3:
+ name = value['name']
+ to_scold.append((user_id, name)) # Add to list of people to scold
+ value['answers_wrong'] = 0 # Reset answers_wrong for every quiz
+
+ for _id, name in to_scold:
+ mention = mention_html(user_id=_id, name=name) # Get their mention in html
+ scold_names += mention + " " # Add a whitespace after every name
+
+ if to_scold: # Send only if there is someone to scold!
+ context.bot.send_chat_action(chat_id=group_ids['12b'], action='typing')
+ sleep(2)
+ context.bot.send_message(chat_id=group_ids['12b'], text=scold_names + r.choice(scolds),
+ parse_mode=ParseMode.HTML)
+
+ context.dispatcher.persistence.flush()
+
+
+def receive_answer(update: Update, context: CallbackContext) -> None:
+ """
+ Saves quiz related user data. Runs everytime a user answers a quiz. This data is used later in generating the
+ leaderboard.
+ """
+
+ user = update.poll_answer.user
+ chosen_answer = update.poll_answer.option_ids
+
+ # Get quiz id and correct option id-
+ for quiz in quizzes:
+ if quiz.poll.id == update.poll_answer.poll_id:
+ correct_answer = quiz.poll.correct_option_id
+ break
+ else: # Only happens when /quizizz quiz was answered.
+ return
+
+ assert correct_answer is not None
+
+ # Storing quiz related user data-
+ if 'quizizz' not in context.bot_data:
+ context.bot_data['quizizz'] = {}
+
+ if user.id not in context.bot_data['quizizz']:
+ # Note: `answers_wrong` below is only for one quiz. For the next quiz, they are reset.
+ context.bot_data['quizizz'][user.id] = {'answers_right': 0, 'questions_answered': 0, 'answers_wrong': 0}
+
+ # Update/add entries if changed-
+ guy = context.bot_data['quizizz'][user.id]
+
+ guy['name'] = get_nick(update, context)
+ guy['profile_pic'] = f"profile_pics/{get_nick(update, context)}.jpg"
+ guy['questions_answered'] += 1
+
+ if correct_answer != chosen_answer[0]: # If guy got it wrong
+ guy['answers_wrong'] += 1
+ else:
+ guy['answers_right'] += 1
+
+ context.dispatcher.persistence.flush()
+
+
+def pp(context: CallbackContext) -> None:
+ """Helper function to get a user's profile pic. This will be then used in the bar graph."""
+
+ for user_id, value in context.bot_data['quizizz'].items():
+ pic = context.bot.get_user_profile_photos(user_id=user_id, offset=0, limit=1)
+ if not pic: # If user doesn't have a pp
+ value['profile_pic'] = "profile_pics/nobody.jpg"
+
+ first_pic = pic.photos[0][0]
+ file_id = first_pic.file_id
+
+ file = context.bot.get_file(file_id=file_id)
+ file.download(custom_path=value['profile_pic']) # Dl's as jpg
+
+ context.dispatcher.persistence.flush()
+
+
+def round_pic() -> None:
+ """
+ Helper function to crop all the images in `profile_pics` into circular ones since it looks better.
+ Receives files in .jpg format and saves it in .png format.
+ """
+
+ # Open the input image as numpy array, convert to RGB
+ for name in os.listdir(f"{cwd}/profile_pics"):
+
+ if name in ("nobody.png", "trophy.png"): # We don't want to touch these, they're already round
+ continue
+
+ img = Image.open(f"profile_pics/{name}").convert("RGB")
+ npImage = np.array(img)
+ h, w = img.size
+
+ # Create same size alpha layer with circle
+ alpha = Image.new('L', img.size, 0)
+ draw = ImageDraw.Draw(alpha)
+ draw.pieslice([0, 0, h, w], 0, 360, fill=255)
+
+ # Convert alpha Image to numpy array
+ npAlpha = np.array(alpha)
+
+ # Add alpha layer to RGB
+ npImage = np.dstack((npImage, npAlpha))
+
+ png_name = name.replace('jpg', 'png')
+ jpg_name_path = f"{cwd}/profile_pics/{name}"
+
+ # Save with alpha
+ Image.fromarray(npImage).save(f"profile_pics/{png_name}") # Only saves in .png
+ os.remove(jpg_name_path) # Remove jpg file
+
+
+def add_image(name: str, x: float or int, y: int, offset: float, zoom: float = 0.20) -> AnnotationBbox:
+ """
+ Adds the given image to the bar graph, with the given specifications.
+
+ Args:
+ name - Should be a string representing name of the file to open (without file extension)
+ x - x-coordinate
+ y - y-coordinate
+ offset - By how much to the left or right should the image be placed. Is applied only to x coordinate.
+ zoom - Controls how big the image is.
+ """
+ # Open image as numpy array-
+ with get_sample_data(f"{cwd}/profile_pics/{name}.png") as file:
+ arr_img = plt.imread(file, format='jpg')
+
+ image_box = OffsetImage(arr_img, zoom=zoom) # zoom changes the size of the image
+
+ # Adds image to the provided coordinates-
+ return AnnotationBbox(image_box, (x + offset, y), frameon=False, annotation_clip=False)
+
+
+def leaderboard(context) -> None:
+ """
+ Makes a horizontal bar graph using data from the quiz. The list is sorted in ascending order. Thus, the person
+ with the highest marks is displayed at the top. The leaderboard is then saved in the current working directory.
+ """
+ round_pic() # Make sure all pics are round before starting
+
+ names, vals = [], []
+
+ for stuff in context.bot_data['quizizz'].values():
+ names.append(stuff['name'])
+ vals.append(stuff['answers_right'])
+
+ if not names:
+ return
+
+ mean = sum(vals) / len(vals) # Gets average for color sorting later
+ vals, names = zip(*sorted(zip(vals, names))) # Sorts both lists correspondingly in ascending order. Returns tuples
+ matplotlib.use('Agg')
+ canvas, ax = plt.subplots(1, 1, figsize=(10, 8)) # That fig size is perfect for 1920x1080 (Don't change this!)
+ plt.grid() # Shows grid lines
+
+ ax.set_axisbelow(True) # Makes grid lines go behind bars
+ canvas.patch.set_facecolor("#20124d") # Purple color as background
+ ax.patch.set_facecolor("#20124d") # and for the graph too!
+
+ barlist = ax.barh(y=list(names), width=list(vals), height=0.4,
+ path_effects=[patheffects.SimpleLineShadow(shadow_color='#331C7C', alpha=0.8),
+ patheffects.Normal()]) # Makes bar graph with shadows
+
+ # for loop to adjust bar color and add arrows, correct answers and profile pics next to the bar-
+ for (index, bar), name in zip(enumerate(barlist), names):
+
+ marks = bar.get_width() # Get no. of correct answers of that guy
+
+ if index == len(barlist) - 1: # Make text bolder, add trophy for the guy who is #1
+ size = 16
+ alpha = 1 # alpha controls transparency
+ trophy_scale = 0.16 * max(vals) # Value obtained by experimenting
+ effects = [patheffects.SimpleLineShadow(shadow_color='black', alpha=0.95), patheffects.Normal()]
+
+ ab = add_image("trophy", marks, index, offset=trophy_scale, zoom=0.034)
+ ax.add_artist(ab) # Draws annotation
+
+ else:
+ size = 13
+ alpha = 0.7
+ effects = None
+
+ if marks > mean:
+ color = '#00FA3F' # Set bar color to green if guy got above avg marks
+ elif marks <= mean - 5:
+ color = '#FA1D07' # Set bar color to red if guy got really bad marks
+ else:
+ color = '#F8ED0F' # Set bar color to yellow if guy got below avg marks
+
+ barlist[index].set_color(color) # Sets bar color
+
+ if marks != 0: # Don't draw arrow and marks if he got a big fat ZERO.
+ text_scale = 0.026 * max(vals) # Another experimental value
+ plt.text(marks - text_scale, index, str(marks), color="#000000", va='center', ha='center', alpha=alpha,
+ fontdict={'weight': 'bold', 'size': size, 'fontfamily': 'DejaVu Sans'},
+ path_effects=effects) # Puts marks on the bars near the end
+
+ arrow_scale = max(vals) * 0.016
+ ax.annotate("", xy=(marks + arrow_scale, index), xytext=(marks + 0.001 + arrow_scale, index), xycoords='data',
+ arrowprops={'color': '#02D4F5'}, annotation_clip=False)
+
+ # Add profile pic next to arrows-
+ image_scale = max(vals) * 0.08375 # Yet another experimental value
+ ab = add_image(name, marks, index, offset=image_scale)
+ ax.add_artist(ab)
+
+ # Set x ticks which are only integers, and make it aesthetically pleasing.
+ plt.xticks([tick for tick in ax.get_xticks() if tick % 1 == 0], fontweight='demi', fontfamily='DejaVu Sans')
+ plt.yticks(range(len(names)), names, fontweight='demi', fontstretch='condensed', fontfamily='DejaVu Sans',
+ fontvariant='small-caps', fontsize=13) # Changes look of names
+
+ plt.ylim(top=len(vals) - 0.6) # Slightly cut off y-axis at the top for aesthetic purposes.
+
+ # Remove the 'box' like look of graph-
+ ax.spines['top'].set_visible(False)
+ ax.spines['right'].set_visible(False)
+ ax.spines['bottom'].set_linewidth(False)
+ ax.spines['left'].set_visible(0.9)
+
+ # Set color to white for aesthetic purposes-
+ ax.spines['left'].set_color("#FFFFFF")
+ ax.spines['bottom'].set_color("#FFFFFF")
+
+ # Change grid line properties for both x and y axis for aesthetic purposes-
+ ax.tick_params(axis='x', grid_alpha=1, colors='#dcd5f4', direction='inout', grid_color='#382a65',
+ grid_linewidth=1.7)
+ ax.tick_params(axis='y', colors='#dcd5f4', grid_alpha=0.0)
+
+ # Set title and add properties to make it a beaut
+ plt.title(label="LADDERBOARD",
+ fontdict={'fontname': 'Gill Sans MT', 'size': 23, 'weight': 'bold', 'color': '#f3c977'}, loc='left',
+ pad=20, path_effects=[patheffects.Stroke(linewidth=0.1, foreground="#F4C05B"), patheffects.Normal()])
+
+ # Add only x axis label and then adjust it to look good.
+ plt.xlabel(xlabel="Correct answers", fontdict={'size': 14, 'color': '#d6d0ec', 'weight': 'semibold'}, labelpad=18)
+
+ plt.savefig("leaderboard.png", facecolor="#20124d") # Save figure with same 'purple' fig color
+
+ for name in os.listdir(f"{cwd}/profile_pics"):
+ if name not in ("nobody.png", "trophy.png"): # These should always be there
+ os.remove(f"{cwd}/profile_pics/{name}")
diff --git a/requirements.txt b/requirements.txt
index dfe19a7..7db2759 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,9 +1,15 @@
-python-telegram-bot~=12.5.1
+python-telegram-bot~=12.7
textblob~=0.15.3
emoji~=0.5.4
Chatterbot~=1.0.5
-google-api-python-client~=1.7.11
-google-auth~=1.11.0
+google-api-python-client~=1.8.2
+google-auth~=1.14.1
google-auth-httplib2~=0.0.3
google-auth-oauthlib~=0.4.1
-httplib2~=0.17.0
+httplib2~=0.17.3
+
+requests~=2.23.0
+beautifulsoup4~=4.9.0
+numpy~=1.18.3
+Pillow~=7.1.2
+matplotlib~=3.2.1
diff --git a/updatedb.py b/updatedb.py
deleted file mode 100644
index 8da42a1..0000000
--- a/updatedb.py
+++ /dev/null
@@ -1,34 +0,0 @@
-import os
-import sqlite3
-
-import main
-
-os.chdir(r"C:\Users\Uncle Sam\Desktop\sthyaVERAT\4 FUN ya Practice\Shani-Sir-Telegram-Bot")
-connection = sqlite3.connect('dbtest.sqlite3')
-c = connection.cursor()
-
-get_tags = main.chatbot.shanisirbot.storage.tagger.get_bigram_pair_string
-
-c.execute("SELECT id FROM statement;")
-results = c.fetchall()
-
-ids = [result[0] for result in results]
-
-for ID in ids:
- c.execute("SELECT * FROM statement WHERE id = ?", (ID,))
- record = c.fetchall()[0] # record format: (id, text, search_text, conversation, created_at, in_response_to, search_in_response_to, persona)
-
- text = record[1]
- in_response_to = record[5]
-
- search_text = get_tags(text)
- if in_response_to is not None:
- search_in_response_to = get_tags(in_response_to)
- else:
- search_in_response_to = "NULL"
- print(search_text, search_in_response_to)
- c.execute("UPDATE statement SET search_text = ? WHERE id = ?", (search_text, ID))
- c.execute("UPDATE statement SET search_in_response_to = ? WHERE id = ?", (search_in_response_to, ID))
-
-connection.commit()
-print('Completed.')
\ No newline at end of file