diff --git a/.gitignore b/.gitignore index a8b048e5d..93aea828e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,35 +1,38 @@ -# Env file -.env - -# SonarQube scan config -.scannerwork/ - -# VSCode config -.vscode/ - -# Downloaded cards -cards.json - -# Sync config -.sync_config - -# Some assets -assets/hugs/* -# Still allow an "official" hug for development -!assets/hugs/0.jpg -assets/cards/* -# Still allow the placeholder cards for development -!assets/cards/PLACEHOLDER*.png - -# API log -/api.log - -#python stuff -**/__pycache__ - -# Rust build -**/target - -**/env - +# Env file +.env + +# SonarQube scan config +.scannerwork/ + +# VSCode config +.vscode/ + +# Downloaded cards +cards.json + +# Sync config +.sync_config + +# Configuration files with sensitive information +**/config.json + +# Some assets +assets/hugs/* +# Still allow an "official" hug for development +!assets/hugs/0.jpg +assets/cards/* +# Still allow the placeholder cards for development +!assets/cards/PLACEHOLDER*.png + +# API log +/api.log + +#python stuff +**/__pycache__ + +# Rust build +**/target + +**/env + **/.DS_Store \ No newline at end of file diff --git a/tests/.github/FUNDING.yml b/tests/.github/FUNDING.yml new file mode 100644 index 000000000..f85836dc6 --- /dev/null +++ b/tests/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] +patreon: KileAlkuri +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/tests/.github/ISSSUE_TEMPLATE/bug.yaml b/tests/.github/ISSSUE_TEMPLATE/bug.yaml new file mode 100644 index 000000000..74d306a5f --- /dev/null +++ b/tests/.github/ISSSUE_TEMPLATE/bug.yaml @@ -0,0 +1,64 @@ +name: Bug Report +description: File a bug report +title: "[Bug]: " +labels: [bug, triage] +assignees: + - Kile +body: + - type: markdown + attributes: + value: | + Thanks for taking the time to fill out this bug report! + - type: input + id: contact + attributes: + label: Contact Details + description: How can we get in touch with you if we need more info? + placeholder: ex. Kile#0606 + validations: + required: false + - type: textarea + id: what-happened + attributes: + label: What happened? + description: Describe briefly what issue you had + placeholder: Tell us what you see! + value: "A bug happened!" + validations: + required: true + - type: textarea + id: repro + attributes: + label: How can we reproduce this issue? + description: Give us some steps to consistently reproduce this issue + placeholder: What did you do? + value: "I pressed the red button" + validations: + required: true + - type: textarea + id: expected + attributes: + label: What was the expected response? + description: What did you expect to happen after following the steps described above? + placeholder: What should have happened + value: "I should have gotten cookies" + validations: + required: true + - type: textarea + id: reality + attributes: + label: What did happen? + description: What actually happened after doing these steps? + placeholder: What was the result + value: "I got vegetables :c" + validations: + required: true + - type: textarea + id: additional-info + attributes: + label: Provide additional info + description: Provide additional info here such as screenshots, ids or other comments you want to add + placeholder: What else do you want to say? + value: "The vegetables did taste pretty good though" + validations: + required: false diff --git a/tests/.github/ISSSUE_TEMPLATE/config.yaml b/tests/.github/ISSSUE_TEMPLATE/config.yaml new file mode 100644 index 000000000..3ba13e0ce --- /dev/null +++ b/tests/.github/ISSSUE_TEMPLATE/config.yaml @@ -0,0 +1 @@ +blank_issues_enabled: false diff --git a/tests/.github/ISSSUE_TEMPLATE/feature-request.yaml b/tests/.github/ISSSUE_TEMPLATE/feature-request.yaml new file mode 100644 index 000000000..e4b25fe70 --- /dev/null +++ b/tests/.github/ISSSUE_TEMPLATE/feature-request.yaml @@ -0,0 +1,28 @@ +name: Feature request +description: Make a feature request +title: "[FEATURE REQUEST]: " +labels: [feature-request] +assignees: + - Kile +body: + - type: markdown + attributes: + value: | + Thanks for giving feedback by making a feature request! + - type: input + id: contact + attributes: + label: Contact Details + description: How can we get in touch with you if we need more info? + placeholder: ex. Kile#0606 + validations: + required: false + - type: textarea + id: request + attributes: + label: What is your request + description: Please describe your feature request as detailed as possible + placeholder: Descibe your wish! + value: "I want... cats! And dogs! And- and I want a really really big loli!" + validations: + required: true diff --git a/tests/.github/pull_request_template.md b/tests/.github/pull_request_template.md new file mode 100644 index 000000000..1e78604ca --- /dev/null +++ b/tests/.github/pull_request_template.md @@ -0,0 +1,19 @@ +Thanks for contributing to this repository! + +### What is the pull request for? +Please describe what this pull request add + + +### Please check the boxes if appropriate + +- [ ] I have tested these changes +- [ ] This PR fixes an open issue +- [ ] This PR adds a new feature + + +### What issues are fixed by this PR? + If this PR closes any open issues, please add them here + + +### How can we get in touch with you if we need more info? +Please provide a discord id or tag diff --git a/tests/.github/workflows/codeql-analysis.yml b/tests/.github/workflows/codeql-analysis.yml new file mode 100644 index 000000000..fa6e77e1c --- /dev/null +++ b/tests/.github/workflows/codeql-analysis.yml @@ -0,0 +1,72 @@ +# For most projects, this workflow file will not need changing; you simply need +# to commit it to your repository. +# +# You may wish to alter this file to override the set of languages analyzed, +# or to provide custom queries or build logic. +# +# ******** NOTE ******** +# We have attempted to detect the languages in your repository. Please check +# the `language` matrix defined below to confirm you have the correct set of +# supported CodeQL languages. +# +name: "CodeQL" + +on: + push: + branches: [ "main" ] + pull_request: + # The branches below must be a subset of the branches above + branches: [ "main" ] + schedule: + - cron: '26 8 * * 6' + +jobs: + analyze: + name: Analyze + runs-on: ubuntu-latest + permissions: + actions: read + contents: read + security-events: write + + strategy: + fail-fast: false + matrix: + language: [ 'python' ] + # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ] + # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support + + steps: + - name: Checkout repository + uses: actions/checkout@v3 + + # Initializes the CodeQL tools for scanning. + - name: Initialize CodeQL + uses: github/codeql-action/init@v2 + with: + languages: ${{ matrix.language }} + # If you wish to specify custom queries, you can do so here or in a config file. + # By default, queries listed here will override any specified in a config file. + # Prefix the list here with "+" to use these queries and those in the config file. + + # Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs + # queries: security-extended,security-and-quality + + + # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). + # If this step fails, then you should remove it and run the build manually (see below) + - name: Autobuild + uses: github/codeql-action/autobuild@v2 + + # â„šī¸ Command-line programs to run using the OS shell. + # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun + + # If the Autobuild fails above, remove it and uncomment the following three lines. + # modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance. + + # - run: | + # echo "Run, Build Application using script" + # ./location_of_script_within_repo/buildscript.sh + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v2 diff --git a/tests/.gitignore b/tests/.gitignore new file mode 100644 index 000000000..4e825e18a --- /dev/null +++ b/tests/.gitignore @@ -0,0 +1,12 @@ +# Configuration +/config.json + +# Downloaded cards +/cards.json + +#python stuff +**/__pycache__ + +**/env + +**/.DS_Store \ No newline at end of file diff --git a/tests/LICENSE.txt b/tests/LICENSE.txt new file mode 100644 index 000000000..f288702d2 --- /dev/null +++ b/tests/LICENSE.txt @@ -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/tests/README.md b/tests/README.md new file mode 100644 index 000000000..57baa9340 --- /dev/null +++ b/tests/README.md @@ -0,0 +1,145 @@ +## Killua Discord Bot +

+ + + +

+

+ + Killua + +

+

Games, Moderation, todo lists and much more.

+ +

+ + Discord Server + + + Lines + + + + + + discord.py + + + + + + + + + + + + Support Killua on Patreon! + + Language grade: Python + +

+ +## What is Killua? + +I started Killua as a way to learn python and different programming concepts. It definitely was not the easiest way to do it, but it got me to a good level of python knowledge plus having a cool bot! As a result, I greatly appreciate issues, PRs and contributions enhancing my code. + +## Links + +* [Website](https://killua.dev) +* [Support server](https://discord.gg/Jkd29QvhBP) +* [Invite link](https://discord.com/oauth2/authorize?client_id=756206646396452975&scope=bot&permissions=268723414&applications.commands) +* [Patreon](https://patreon.com/kilealkuri) + +## Programming concepts list + +As explained previously, I use Killua as a tool to learn more about python and programming. Here is a list of programming concepts Killua uses and which ones it is planned to use at some point in the future. + +* [x] OOP (Object Oriented Programming) +* [x] Web scraping +* [x] IPC (Inter Process Communication) +* [x] Providing and requesting REST-APIs +* [x] Image manipulation +* [x] Asyncronous Programming +* [x] logging +* [x] NonSQL databases +* [x] Python `typing` library +* [x] GitHub PRs, branches, issues, todo-lists, CLI +* [x] caching +* [ ] Website with backend +* [ ] CSS +* [ ] Threading +* [ ] Github workflows + +## Contributors + +I would like to give a big thank you to everyone who has helped me on this journey, each in their different way. + +* [WhoAmI](https://github.com/WhoAmI1000) + +> Who has been with the project since the start, creating the website and supporting it through Patreon. + +* [MNW](https://linktr.ee/Michaelnw_mnw) + +> An incredibly talented artist who made many artworks which make Killua look and feel so much better for little to no price. + +* [ClashCrafter](https://github.com/FlorianStrobl) + +> Contributed initial parts of the web scraping code. + +* [danii](https://github.com/danii) + +> Helped to change the incredibly bad mess of everything in one file into an organised, dynamic system and helped out with git commands. + +* [DerUSBStick](https://github.com/DerUSBstick) + +> He contributed a lot to one of the best looking commands, `book` which uses image generation to make your collection book filled with cards! + +* [Scarf](https://odaibako.net/u/ano_furi) + +> Helped write some of the action texts, topics, 8ball responses and would you rather questions. + +* [Scientia](https://github.com/ScientiaEtVeritas) + +> Gave me the original idea for this bot and helped me in the early stages, enduring lots of pings and stupid questions. + +## Running Killua locally + +First, set up a virtual environment. Do so with `python3 -m venv env; source env/bin/activate`. To leave the virtual environment after you are done, simply run `deactivate` + +`requirements.txt` contains the libraries you'll need. To install them use `pip3 install -r requirements.txt` + +You will need a Mongodb account. Why do I use mongodb and not SQL? In my opinion, mongo is easier to use and you can manually add and remove data. + +You will have to create a mongodb account [here](https://www.mongodb.com), then follow the instructions in [`setup.py`](https://github/Kile/Killua/blob/main/setup.py) and then run `python3 setup.py` or choose the "setup database" option in the menu to get the database set up + +You will also need a file named `config.json` having the layout like this: + +```plaintext +{ + "token": "token", + + "mongodb": "your-mongodb-token", + "pxlapi": "pxlapi-token", + "patreon": "patreon-api-token", + "dbl_token": "dbl-token", + "topgg_token": "topgg-token", + "password": "vote-pages-password", + "port": 8000, + "ipc": "ipc-token" +} +``` + +You can finally run the bot in development or production environment in a menu by running `./run.sh` + +**If you add any commands, please make sure to also add tests for it. A document explaining how tests for Killua work can be found** [**here**](https://github.com/Kile/Killua/blob/main/killua/tests/README.md) + +If you don't like me using one of your images for the hug command, please contact me on discord `Kile#0606` or on `kile@killua.dev` + +If you have any further questions, join my discord server or dm me! + +

+ + + +

diff --git a/tests/data.json b/tests/data.json new file mode 100644 index 000000000..2e411cfd6 --- /dev/null +++ b/tests/data.json @@ -0,0 +1,692 @@ +[ + { + "id": "756206646396452975", + "timestamp": "1624715214", + "guild": 1520 + }, + { + "id": "756206646396452975", + "timestamp": "1624745771", + "guild": 1530 + }, + { + "id": "756206646396452975", + "timestamp": "1625276911", + "guild": 1540 + }, + { + "id": "756206646396452975", + "timestamp": "1625362813", + "guild": 1550 + }, + { + "id": "756206646396452975", + "timestamp": "1625542307", + "guild": 1540 + }, + { + "id": "756206646396452975", + "timestamp": "1625720636", + "guild": 1550 + }, + { + "id": "756206646396452975", + "timestamp": "1625895552", + "guild": 1560 + }, + { + "id": "756206646396452975", + "timestamp": "1626251729", + "guild": 1570 + }, + { + "id": "756206646396452975", + "timestamp": "1626729226", + "guild": 1590 + }, + { + "id": "756206646396452975", + "timestamp": "1627058472", + "guild": 1600 + }, + { + "id": "756206646396452975", + "timestamp": "1627784468", + "guild": 1630 + }, + { + "id": "756206646396452975", + "timestamp": "1627872385", + "guild": 1640 + }, + { + "id": "756206646396452975", + "timestamp": "1628308645", + "guild": 1650 + }, + { + "id": "756206646396452975", + "timestamp": "1628661194", + "guild": 1660 + }, + { + "id": "756206646396452975", + "timestamp": "1628750299", + "guild": 1650 + }, + { + "id": "756206646396452975", + "timestamp": "1628838191", + "guild": 1660 + }, + { + "id": "756206646396452975", + "timestamp": "1629102618", + "guild": 1670 + }, + { + "id": "756206646396452975", + "timestamp": "1629368729", + "guild": 1680 + }, + { + "id": "756206646396452975", + "timestamp": "1629632911", + "guild": 1690 + }, + { + "id": "756206646396452975", + "timestamp": "1629722696", + "guild": 1700 + }, + { + "id": "756206646396452975", + "timestamp": "1629814434", + "guild": 1710 + }, + { + "id": "756206646396452975", + "timestamp": "1629997438", + "guild": 1720 + }, + { + "id": "756206646396452975", + "timestamp": "1630086523", + "guild": 1730 + }, + { + "id": "756206646396452975", + "timestamp": "1630264531", + "guild": 1740 + }, + { + "id": "756206646396452975", + "timestamp": "1630790237", + "guild": 1750 + }, + { + "id": "756206646396452975", + "timestamp": "1631058457", + "guild": 1760 + }, + { + "id": "756206646396452975", + "timestamp": "1631236055", + "guild": 1770 + }, + { + "id": "756206646396452975", + "timestamp": "1631409168", + "guild": 1780 + }, + { + "id": "756206646396452975", + "timestamp": "1631504813", + "guild": 1770 + }, + { + "id": "756206646396452975", + "timestamp": "1631585904", + "guild": 1780 + }, + { + "id": "756206646396452975", + "timestamp": "1631674899", + "guild": 1770 + }, + { + "id": "756206646396452975", + "timestamp": "1631762422", + "guild": 1780 + }, + { + "id": "756206646396452975", + "timestamp": "1632029166", + "guild": 1790 + }, + { + "id": "756206646396452975", + "timestamp": "1632117307", + "guild": 1800 + }, + { + "id": "756206646396452975", + "timestamp": "1632381716", + "guild": 1820 + }, + { + "id": "756206646396452975", + "timestamp": "1632554734", + "guild": 1830 + }, + { + "id": "756206646396452975", + "timestamp": "1635639148", + "guild": 1880 + }, + { + "id": "756206646396452975", + "timestamp": "1635824044", + "guild": 1890 + }, + { + "id": "756206646396452975", + "timestamp": "1635911747", + "guild": 1900 + }, + { + "id": "756206646396452975", + "timestamp": "1636090604", + "guild": 1910 + }, + { + "id": "756206646396452975", + "timestamp": "1636188518", + "guild": 1920 + }, + { + "id": "756206646396452975", + "timestamp": "1638167658", + "guild": 1960 + }, + { + "id": "756206646396452975", + "timestamp": "1638255124", + "guild": 1950 + }, + { + "id": "756206646396452975", + "timestamp": "1632997836", + "guild": 1840 + }, + { + "id": "756206646396452975", + "timestamp": "1633177338", + "guild": 1840 + }, + { + "id": "756206646396452975", + "timestamp": "1633446552", + "guild": 1850 + }, + { + "id": "756206646396452975", + "timestamp": "1633284352", + "guild": 1830 + }, + { + "id": "756206646396452975", + "timestamp": "1633357791", + "guild": 1840 + }, + { + "id": "756206646396452975", + "timestamp": "1633089025", + "guild": 1830 + }, + { + "id": "756206646396452975", + "timestamp": "1633537987", + "guild": 1840 + }, + { + "id": "756206646396452975", + "timestamp": "1633818640", + "guild": 1850 + }, + { + "id": "756206646396452975", + "timestamp": "1634183980", + "guild": 1860 + }, + { + "id": "756206646396452975", + "timestamp": "1636631501", + "guild": 1930 + }, + { + "id": "756206646396452975", + "timestamp": "1636901996", + "guild": 1940 + }, + { + "id": "756206646396452975", + "timestamp": "1636991007", + "guild": 1950 + }, + { + "id": "756206646396452975", + "timestamp": "1635084049", + "guild": 1860 + }, + { + "id": "756206646396452975", + "timestamp": "1634806768", + "guild": 1850 + }, + { + "id": "756206646396452975", + "timestamp": "1638615243", + "guild": 1960 + }, + { + "id": "756206646396452975", + "timestamp": "1638983187", + "guild": 1950 + }, + { + "id": "756206646396452975", + "timestamp": "1639075738", + "guild": 1960 + }, + { + "id": "756206646396452975", + "timestamp": "1639353279", + "guild": 1950 + }, + { + "id": "756206646396452975", + "timestamp": "1639433787", + "guild": 1960 + }, + { + "id": "756206646396452975", + "timestamp": "1642436535", + "guild": 1990 + }, + { + "id": "756206646396452975", + "timestamp": "1641524591", + "guild": 1970 + }, + { + "id": "756206646396452975", + "timestamp": "1641696988", + "guild": 1980 + }, + { + "id": "756206646396452975", + "timestamp": "1642613010", + "guild": 2000 + }, + { + "id": "756206646396452975", + "timestamp": "1642799893", + "guild": 2010 + }, + { + "id": "756206646396452975", + "timestamp": "1644643479", + "guild": 2070 + }, + { + "id": "756206646396452975", + "timestamp": "1644729342", + "guild": 2080 + }, + { + "id": "756206646396452975", + "timestamp": "1644896167", + "guild": 2070 + }, + { + "id": "756206646396452975", + "timestamp": "1645017364", + "guild": 2080 + }, + { + "id": "756206646396452975", + "timestamp": "1645274669", + "guild": 2090 + }, + { + "id": "756206646396452975", + "timestamp": "1643073548", + "guild": 2020 + }, + { + "id": "756206646396452975", + "timestamp": "1643264089", + "guild": 2040 + }, + { + "id": "756206646396452975", + "timestamp": "1643614641", + "guild": 2050 + }, + { + "id": "756206646396452975", + "timestamp": "1643195085", + "guild": 2030 + }, + { + "id": "756206646396452975", + "timestamp": "1644531659", + "guild": 2080 + }, + { + "id": "756206646396452975", + "timestamp": "1644072514", + "guild": 2060 + }, + { + "id": "756206646396452975", + "timestamp": "1644345918", + "guild": 2070 + }, + { + "id": "756206646396452975", + "timestamp": "1644167119", + "guild": 2050 + }, + { + "id": "756206646396452975", + "timestamp": "1644263439", + "guild": 2060 + }, + { + "id": "756206646396452975", + "timestamp": "1645942871", + "guild": 2100 + }, + { + "id": "756206646396452975", + "timestamp": "1646809800", + "guild": 2100 + }, + { + "id": "756206646396452975", + "timestamp": "1646886860", + "guild": 2130 + }, + { + "id": "756206646396452975", + "timestamp": "1646986262", + "guild": 2140 + }, + { + "id": "756206646396452975", + "timestamp": "1646455070", + "guild": 2110 + }, + { + "id": "756206646396452975", + "timestamp": "1647152844", + "guild": 2150 + }, + { + "id": "756206646396452975", + "timestamp": "1647233001", + "guild": 2160 + }, + { + "id": "756206646396452975", + "timestamp": "1648850986", + "guild": 2220 + }, + { + "id": "756206646396452975", + "timestamp": "1648945943", + "guild": 2210 + }, + { + "id": "756206646396452975", + "timestamp": "1648682839", + "guild": 2210 + }, + { + "id": "756206646396452975", + "timestamp": "1647412237", + "guild": 2160 + }, + { + "id": "756206646396452975", + "timestamp": "1647492517", + "guild": 2170 + }, + { + "id": "756206646396452975", + "timestamp": "1648132103", + "guild": 2220 + }, + { + "id": "756206646396452975", + "timestamp": "1647331072", + "guild": 2170 + }, + { + "id": "756206646396452975", + "timestamp": "1647679614", + "guild": 2180 + }, + { + "id": "756206646396452975", + "timestamp": "1648043200", + "guild": 2190 + }, + { + "id": "756206646396452975", + "timestamp": "1650405212", + "guild": 2230 + }, + { + "id": "756206646396452975", + "timestamp": "1650657665", + "guild": 2240 + }, + { + "id": "756206646396452975", + "timestamp": "1651369346", + "guild": 2250 + }, + { + "id": "756206646396452975", + "timestamp": "1649668339", + "guild": 2200 + }, + { + "id": "756206646396452975", + "timestamp": "1649847122", + "guild": 2210 + }, + { + "id": "756206646396452975", + "timestamp": "1650031344", + "guild": 2220 + }, + { + "id": "756206646396452975", + "timestamp": "1651550296", + "guild": 2260 + }, + { + "id": "756206646396452975", + "timestamp": "1652101561", + "guild": 2270 + }, + { + "id": "756206646396452975", + "timestamp": "1652198976", + "guild": 2260 + }, + { + "id": "756206646396452975", + "timestamp": "1655676502", + "guild": 2360 + }, + { + "id": "756206646396452975", + "timestamp": "1655766417", + "guild": 2370 + }, + { + "id": "756206646396452975", + "timestamp": "1655494373", + "guild": 2370 + }, + { + "id": "756206646396452975", + "timestamp": "1656227986", + "guild": 2380 + }, + { + "id": "756206646396452975", + "timestamp": "1654132170", + "guild": 2270 + }, + { + "id": "756206646396452975", + "timestamp": "1654302786", + "guild": 2300 + }, + { + "id": "756206646396452975", + "timestamp": "1654677820", + "guild": 2330 + }, + { + "id": "756206646396452975", + "timestamp": "1654763503", + "guild": 2360 + }, + { + "id": "756206646396452975", + "timestamp": "1654495290", + "guild": 2310 + }, + { + "id": "756206646396452975", + "timestamp": "1654211411", + "guild": 2290 + }, + { + "id": "756206646396452975", + "timestamp": "1658557921", + "guild": 2390 + }, + { + "id": "756206646396452975", + "timestamp": "1657919148", + "guild": 2400 + }, + { + "id": "756206646396452975", + "timestamp": "1658003916", + "guild": 2390 + }, + { + "id": "756206646396452975", + "timestamp": "1658285695", + "guild": 2390 + }, + { + "id": "756206646396452975", + "timestamp": "1658186491", + "guild": 2400 + }, + { + "id": "756206646396452975", + "timestamp": "1657729947", + "guild": 2390 + }, + { + "id": "756206646396452975", + "timestamp": "1658373766", + "guild": 2400 + }, + { + "id": "756206646396452975", + "timestamp": "1658641222", + "guild": 2400 + }, + { + "id": "756206646396452975", + "timestamp": "1660494552", + "guild": 2400 + }, + { + "id": "756206646396452975", + "timestamp": "1660782790", + "guild": 2410 + }, + { + "id": "756206646396452975", + "timestamp": "1659849589", + "guild": 2410 + }, + { + "id": "756206646396452975", + "timestamp": "1659949403", + "guild": 2400 + }, + { + "id": "756206646396452975", + "timestamp": "1660332759", + "guild": 2410 + }, + { + "id": "756206646396452975", + "timestamp": "1661752406", + "guild": 2400 + }, + { + "id": "756206646396452975", + "timestamp": "1661848409", + "guild": 2410 + }, + { + "id": "756206646396452975", + "timestamp": "1662606937", + "guild": 2400 + }, + { + "id": "756206646396452975", + "timestamp": "1663064709", + "guild": 2410 + }, + { + "id": "756206646396452975", + "timestamp": "1663879129", + "guild": 2420 + }, + { + "id": "756206646396452975", + "timestamp": "1665674782", + "guild": 2440 + }, + { + "id": "756206646396452975", + "timestamp": "1665772697", + "guild": 2430 + }, + { + "id": "756206646396452975", + "timestamp": "1664641423", + "guild": 2430 + }, + { + "id": "756206646396452975", + "timestamp": "1667191901", + "guild": 2440 + } +] \ No newline at end of file diff --git a/tests/killua/__init__.py b/tests/killua/__init__.py new file mode 100644 index 000000000..83f58ad1d --- /dev/null +++ b/tests/killua/__init__.py @@ -0,0 +1,109 @@ +from . import cogs +import discord +import aiohttp +import asyncio +import logging + +from .tests import run_tests +from .migrate import migrate +from .download import download +from .bot import BaseBot as Bot, get_prefix +# This needs to be in a seperate file from the __init__ file to +# avoid relative import errors when subclassing it in the testing module +from .webhook.api import app +from .static.constants import TOKEN, PORT + +import killua.args as args_file + +async def main(): + start_time = time.time() + args_file.Args.get_args() + args = args_file.Args + + # Set up logger from command line arguments + log_level = getattr(logging, args.log.upper()) + logging.basicConfig( + level=log_level, + datefmt='%I:%M:%S', + format="[%(asctime)s] %(levelname)s: %(message)s" + ) + logger = logging.getLogger('killua') + logger.info(f"Starting Killua bot with log level: {args.log.upper()}") + + # Check if MongoDB is running before proceeding + try: + logger.info("Checking MongoDB connection...") + # Set a shorter timeout for faster startup + DB.const.database.client.server_info() + logger.info("MongoDB connection successful") + except Exception as e: + logger.critical(f"MongoDB connection failed: {e}") + logger.critical("Please make sure MongoDB is running and the connection string is correct in config.json") + logger.critical("Bot cannot start without a database connection. Exiting...") + return 1 + + if args.migrate: + logger.info("Running database migration") + return migrate() + + if args.test is not None: + logger.info(f"Running tests: {args.test}") + return await run_tests(args.test) + + if args.download: + logger.info("Running download operation") + return await download() + + logger.info("Initializing HTTP session") + async with aiohttp.ClientSession() as session: + logger.info("Setting up Discord intents") + intents = discord.Intents( + guilds=True, + members=True, + emojis_and_stickers=True, + messages=True, + message_content=True + ) + + # Create the bot instance + logger.info("Creating bot instance") + bot = Bot( + command_prefix=get_prefix, + description="The discord bot Killua", + case_insensitive=True, + intents=intents, + session=session + ) + bot.session = session + + # Set development mode + bot.is_dev = args.development + logger.info(f"Development mode: {bot.is_dev}") + + # Setup cogs + logger.info(f"Loading {len(cogs.all_cogs)} cogs...") + cog_load_start = time.time() + for i, cog_module in enumerate(cogs.all_cogs): + try: + logger.debug(f"Loading cog {i+1}/{len(cogs.all_cogs)}: {cog_module.__name__}") + await bot.add_cog(cog_module.Cog(bot)) + except Exception as e: + logger.error(f"Failed to load cog {cog_module.__name__}: {e}") + logger.info(f"Loaded all cogs in {time.time() - cog_load_start:.2f} seconds") + + # Calculate startup time + logger.info(f"Bot initialization completed in {time.time() - start_time:.2f} seconds") + + if bot.is_dev: # runs the api locally if the bot is in dev mode + logger.info(f"Starting development server on port {PORT}") + # Use asyncio.create_task instead of deprecated get_event_loop + tasks = [bot.start(TOKEN), app.run_task(host="0.0.0.0", port=PORT)] + logger.info("Bot is now running in development mode") + done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED) + # Cancel any pending tasks + for task in pending: + task.cancel() + else: + # Start the bot in production mode + logger.info("Starting bot in production mode") + await bot.start(TOKEN) \ No newline at end of file diff --git a/tests/killua/__main__.py b/tests/killua/__main__.py new file mode 100644 index 000000000..50947b055 --- /dev/null +++ b/tests/killua/__main__.py @@ -0,0 +1,5 @@ +from . import main +from asyncio import run + +if __name__ == "__main__": + run(main()) \ No newline at end of file diff --git a/tests/killua/args.py b/tests/killua/args.py new file mode 100644 index 000000000..978e91e08 --- /dev/null +++ b/tests/killua/args.py @@ -0,0 +1,32 @@ +import argparse + +from typing import Optional + +class _Args: + + development: Optional[bool] = None + migrate: Optional[bool] = None + test: Optional[bool] = None + log: Optional[str] = None + + @classmethod + def get_args(cls) -> None: + + parser = argparse.ArgumentParser(description="CLI arguments for the bot") + parser.add_argument("-d", "--development", help="Run the bot in development mode", action="store_const", const=True) + parser.add_argument("-m", "--migrate", help="Migrates the database setup from a previous version to the current one", action="store_const", const=True) + parser.add_argument("-t", "--test", help="Run the tests", nargs="*", default=None, metavar=("cog", "command")) + parser.add_argument("-l", "--log", help="Set the logging level", default="INFO", choices=["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"], metavar="level") + parser.add_argument("-dl", "--download", help="Download all cards into a file for offline testing", action="store_const", const=True) + + parsed = parser.parse_args() + + cls.development = parsed.development + cls.migrate = parsed.migrate + cls.test = parsed.test + cls.log = parsed.log + cls.download = parsed.download + +def init(): + global Args + Args = _Args \ No newline at end of file diff --git a/tests/killua/bot.py b/tests/killua/bot.py new file mode 100644 index 000000000..d0b6ec952 --- /dev/null +++ b/tests/killua/bot.py @@ -0,0 +1,347 @@ +import logging +import math +import asyncio +import discord +import jishaku +import time +import sys + +from typing import Dict, Union, List, Tuple, Coroutine, Any, Optional +from datetime import date, datetime +from random import randint, choice +from discord.ext import commands +from aiohttp import ClientSession + +from killua.static.constants import * +from killua.static.tips import TIPS +from killua.utils.db import DB +from killua.utils.enums import Category +from killua.utils.functions import get_prefix +from killua.utils.ui import Modal +from killua.utils.migrate import migrate_requiring_bot + +# Configure root logger +logging.basicConfig(level=logging.INFO, + format='[%(asctime)s] %(levelname)s [%(name)s.%(funcName)s:%(lineno)d] %(message)s', + datefmt='%Y-%m-%d %H:%M:%S') + +# Create a logger for this module +logger = logging.getLogger('killua.bot') + +def get_prefix(bot, message): + if bot.is_dev: + return commands.when_mentioned_or('kil!', 'kil.')(bot, message) + try: + from .utils.classes import Guild + + g = Guild(message.guild.id) + if g is None: + return commands.when_mentioned_or('k!')(bot, message) + return commands.when_mentioned_or(g.prefix)(bot, message) + except Exception: + # in case message.guild is `None` or something went wrong getting the prefix the bot still NEEDS to react to mentions and k! + return commands.when_mentioned_or('k!')(bot, message) + +class BaseBot(commands.AutoShardedBot): + def __init__(self, *args, **kwargs): + logger.info("Initializing Killua bot...") + self.startup_time = time.time() + + # Extract session from kwargs if provided + self.session = kwargs.pop('session', None) + logger.debug(f"Session provided: {self.session is not None}") + + # Set modern defaults for Discord.py 2.5+ + kwargs.setdefault('chunk_guilds_at_startup', False) + kwargs.setdefault('max_messages', 10000) # Increase message cache for better performance + kwargs.setdefault('enable_debug_events', False) + kwargs.setdefault('assume_unsync_clock', True) # Better for distributed systems + + logger.info("Calling parent constructor with optimized settings") + super().__init__(*args, **kwargs) + + # Bot configuration + self.support_server_invite = "https://discord.gg/MKyWA5M" + self.invite = "https://discord.com/oauth2/authorize?client_id=756206646396452975&scope=bot%20applications.commands&permissions=268723414" + self.is_dev = False + logger.info(f"Development mode: {self.is_dev}") + + # Performance optimizations + self._command_cache = {} + self._formatted_commands_cache = None + logger.info("Bot initialization complete") + + async def setup_hook(self): + logger.info("Setting up bot hooks and extensions...") + + # Check MongoDB connection first + try: + logger.info("Testing MongoDB connection...") + db_info = DB.const.database.client.server_info() + logger.info(f"Connected to MongoDB version: {db_info.get('version', 'unknown')}") + except Exception as e: + logger.critical(f"MongoDB connection failed: {e}") + logger.critical("Please make sure MongoDB is running and the connection string is correct in config.json") + logger.critical("Bot cannot start without a database connection. Exiting...") + sys.exit(1) + + # Load extensions + try: + logger.info("Loading jishaku extension...") + await self.load_extension("jishaku") + logger.info("Successfully loaded jishaku extension") + except Exception as e: + logger.error(f"Failed to load jishaku: {e}") + + # Sync application commands + try: + logger.info("Syncing application commands...") + await self.tree.sync() + logger.info("Successfully synced application commands") + except Exception as e: + logger.error(f"Failed to sync application commands: {e}") + + # Check for migration + try: + logger.info("Checking for pending database migrations...") + migrate_doc = DB.const.find_one({"_id": "migrate"}) + if migrate_doc and migrate_doc.get("value", False): + logger.info("Running database migration...") + migrate_requiring_bot(self) + logger.info("Database migration completed successfully") + else: + logger.info("No pending migrations found") + except Exception as e: + logger.error(f"Failed to check/run migration: {e}") + + logger.info("Bot setup completed successfully") + + async def close(self): + # Clean up resources before closing + logger.info("Bot is shutting down, cleaning up resources...") + + # Calculate uptime + uptime = time.time() - self.startup_time + logger.info(f"Bot was running for {uptime:.2f} seconds") + + # Clear caches + logger.debug("Clearing command caches") + self._command_cache.clear() + self._formatted_commands_cache = None + + # Only close the session if it was created by this instance and not passed in + if hasattr(self, 'session') and self.session is not None and not self.session.closed: + try: + logger.info("Closing HTTP session") + await self.session.close() + logger.debug("HTTP session closed successfully") + except Exception as e: + logger.error(f"Error closing session: {e}") + + # Call parent close method + logger.info("Calling parent close method") + await super().close() + logger.info("Bot shutdown complete") + + def __format_command(self, res: Dict[str, list], cmd: commands.Command) -> dict: + """Adds a command to a dict of formatted commands""" + if cmd.name in ["jishaku", "help"] or cmd.hidden: + return res + + res[cmd.extras["category"].value["name"]]["commands"].append(cmd) + + return res + + def get_formatted_commands(self) -> dict: + """Gets a dictionary of formatted commands with caching for better performance""" + # Return cached result if available + if self._formatted_commands_cache is not None: + return self._formatted_commands_cache + + # Initialize result dictionary + res = {c.value["name"]: {"description": c.value["description"], "emoji": c.value["emoji"], "commands": []} for c in Category} + + # Process commands + for cmd in self.commands: + if isinstance(cmd, commands.Group) and cmd.name != "jishaku": + for c in cmd.commands: + res = self.__format_command(res, c) + continue + res = self.__format_command(res, cmd) + + # Cache the result + self._formatted_commands_cache = res + return res + + async def find_user(self, ctx: commands.Context, user: str) -> Union[discord.Member, discord.User, None]: + """Attempts to create a member or user object from the passed string + Optimized for Python 3.11 with better error handling""" + # Check if input is empty + if not user: + return None + + # Try to convert to member first (most common case) + try: + return await commands.MemberConverter().convert(ctx, user) + except commands.MemberNotFound: + pass + + # If not a digit ID, return None + if not user.isdigit(): + return None + + # Try to get from cache first (faster) + user_id = int(user) + res = self.get_user(user_id) + if res: + return res + + # Fetch from API as last resort + try: + return await self.fetch_user(user_id) + except (discord.NotFound, discord.HTTPException): + return None + + def get_lootbox_from_name(self, name: str) -> Union[int, None]: + """Gets a lootbox id from its name""" + for k, v in LOOTBOXES.items(): + if name.lower() == v["name"].lower(): + return k + + def callback_from_command(self, command: Coroutine, message: bool, *args, **kwargs) -> Coroutine[discord.Interaction, Union[discord.Member, discord.Message], None]: + """Turn a command function into a context menu callback""" + if message: + async def callback(interaction: discord.Interaction, message: discord.Message): + ctx = await commands.Context.from_interaction(interaction) + ctx.message = message + ctx.invoked_by_context_menu = True # This is added so we can check inside of the command if it was invoked from a modal + await ctx.invoke(command, text=message.content, *args, **kwargs) + else: + async def callback(interaction: discord.Interaction, member: discord.Member): + ctx = await commands.Context.from_interaction(interaction) + ctx.invoked_by_context_menu = True + await ctx.invoke(command, str(member.id), *args, **kwargs) + return callback + + async def get_text_response( + self, + ctx: commands.Context, + text: str, + timeout: int = None, + timeout_message: str = None, + interaction: discord.Interaction = None, + *args, + **kwargs + ) -> Union[str, None]: + """Gets a reponse from either a textinput UI or by waiting for a response""" + + if (ctx.interaction and not ctx.interaction.response.is_done()) or interaction: + modal = Modal(title="Anser the question(s) and click submit", timeout=timeout) + textinput = discord.ui.TextInput(label=text, *args, **kwargs) + modal.add_item(textinput) + + if interaction: + await interaction.response.send_modal(modal) + else: + await ctx.interaction.response.send_modal(modal) + + await modal.wait() + if modal.timed_out: + if timeout_message: + await ctx.send(timeout_message, delete_after=5) + return + await modal.interaction.response.defer() + + return textinput.value + + else: + def check(m: discord.Message): + return m.author.id == ctx.author.id + + msg = await ctx.send(text) + try: + confirmmsg: discord.Message = await self.wait_for('message', check=check, timeout=timeout) + except asyncio.TimeoutError: + if timeout_message: + await ctx.send(timeout_message, delete_after=5) + res = None + else: + res = confirmmsg.content + + await msg.delete() + try: + await confirmmsg.delete() + except commands.Forbidden: + pass + + return res + + async def update_presence(self): + """Update the bot's presence with improved error handling and caching""" + logger.debug("Updating bot presence...") + try: + # Try to get custom presence from database + logger.debug("Fetching presence data from database") + status = DB.const.find_one({"_id": "presence"}) + if status and status.get('text'): + logger.info(f"Using custom presence: {status['text']}") + # Set defaults if missing + activity_type = status.get('activity', 'playing') + presence_status = status.get('presence', 'online') + + # Create activity object + activity = discord.Activity( + name=status['text'], + type=getattr(discord.ActivityType, activity_type) + ) + + # Update presence + logger.debug(f"Setting presence: {activity.name} ({activity.type.name})") + await self.change_presence( + activity=activity, + status=getattr(discord.Status, presence_status) + ) + return + + # Calculate bot age + today = date.today() + bot_birthday = date(2020, 9, 17) # The day Killua was born!! + days_running = (today - bot_birthday).days + + # Create default activity + logger.info(f"Using default presence for {len(self.guilds)} guilds") + playing = discord.Activity( + name=f'over {len(self.guilds)} guilds | k! | day {days_running}', + type=discord.ActivityType.watching + ) + + # Update presence + logger.debug(f"Setting default presence: {playing.name}") + await self.change_presence(status=discord.Status.online, activity=playing) + logger.info("Presence updated successfully") + except Exception as e: + logger.error(f"Failed to update presence: {e}") + + async def send_message(self, messageable: discord.abc.Messageable, *args, **kwargs) -> discord.Message: + """A helper function sending messages and adding a tip with the probability of 5%""" + msg = await messageable.send(*args, **kwargs) + if randint(1, 100) < 6: # 5% probability to send a tip afterwards + await messageable.send(f"**Tip:** {choice(TIPS).replace('', get_prefix(self, messageable.message)[2]) if hasattr(messageable, 'message') else ('k!' if not self.is_dev else 'kil!')}", ephemeral=True) + return msg + + def convert_to_timestamp(self, id: int, args: str = "f") -> str: + """Turns a discord snowflake into a discord timestamp string""" + return f"> 22) / 1000) + 1420070400}:{args}>" + + def _encrypt(self, n: int, b: int = 10000, smallest: bool = True) -> str: + """Changes an integer into base 10000 but with my own characters resembling numbers. It only returns the last 2 characters as they are the most unique""" + chars = "".join([chr(i) for i in range(b+1)][::-1]) + chars = chars.replace(":", "").replace(";", "").replace("-", "").replace(",", "") # These characters are indicators used in the ids so they should be not be available as characters + + if n == 0: + return [0] + digits = [] + while n: + digits.append(int(n % b)) + n //= b + return "".join([chars[d] for d in digits[::-1]])[-2:] if smallest else "".join([chars[d] for d in digits[::-1]]) \ No newline at end of file diff --git a/tests/killua/cogs/__init__.py b/tests/killua/cogs/__init__.py new file mode 100644 index 000000000..429b5ae99 --- /dev/null +++ b/tests/killua/cogs/__init__.py @@ -0,0 +1,16 @@ +from importlib.abc import MetaPathFinder +import pkgutil + +# This module's submodules. +all_cogs = [] + +for loader, name, pkg in pkgutil.walk_packages(__path__): + # Load the module. + loader = loader.find_module(name, None) \ + if isinstance(loader, MetaPathFinder) else loader.find_module(name) + module = loader.load_module(name) + + # Make it a global. + globals()[name] = module + # Put it in the list. + all_cogs.append(module) diff --git a/tests/killua/cogs/actions.py b/tests/killua/cogs/actions.py new file mode 100644 index 000000000..57776bb9f --- /dev/null +++ b/tests/killua/cogs/actions.py @@ -0,0 +1,295 @@ +import discord +from discord.ext import commands +import random +import asyncio +from typing import List, Union + +from killua.bot import BaseBot +from killua.utils.checks import check +from killua.utils.classes import User +from killua.static.enums import Category +from killua.utils.interactions import View +from killua.static.constants import ACTIONS + +class SettingsSelect(discord.ui.Select): + """Creates a select menu to change action settings""" + def __init__(self, options, **kwargs): + super().__init__( + options=options, + **kwargs + ) + + async def callback(self, interaction: discord.Interaction): + self.view.values = interaction.data["values"] + for opt in self.options: + if opt.value in self.view.values: + opt.default = True + +class SettingsButton(discord.ui.Button): + + def __init__(self, **kwargs): + super().__init__(**kwargs) + + async def callback(self, interaction: discord.Interaction): + if not hasattr(self.view, "values"): + return await interaction.response.send_message("You have not changed any settings", ephemeral=True) + self.view.timed_out = False + self.view.stop() + +class Actions(commands.Cog): + + def __init__(self, client: BaseBot): + self.client = client + self.session = self.client.session + + async def request_action(self, endpoint: str) -> Union[dict, str]: + + r = await self.session.get(f"https://purrbot.site/api/img/sfw/{endpoint}/gif") + if r.status == 200: + res = await r.json() + + if res["error"]: + return res["message"] + + return res + else: + return await r.text() + + async def get_image(self, ctx) -> discord.Message: # for endpoints like /blush/gif where you don't want to mention a user + image = await self.request_action(ctx.command.name) + if isinstance(image, str): + return await ctx.send(f':x: {image}') + embed = discord.Embed.from_dict({ + "title": "", + "image": {"url": image["link"]}, + "color": 0x1400ff + }) + return await ctx.send(embed=embed) + + def generate_users(self, members: list, title: str) -> str: + if isinstance(members, str): + return members + memberlist = '' + for p, member in enumerate(members): + if len(memberlist + member.display_name + title.replace("(a)", "").replace("(u)", "")) > 231: # embed titles have a max lentgh of 256 characters. If the name list contains too many names, stuff breaks. This prevents that and displays the other people as "and x more" + memberlist = memberlist + f" *and {len(members)-(p+1)} more*" + break + if members[-1] == member and len(members) != 1: + memberlist = memberlist + f' and {member.display_name}' + else: + if members[0] == member: + memberlist = f'{member.display_name}' + else: + memberlist = memberlist + f', {member.display_name}' + return memberlist + + async def action_embed(self, endpoint: str, author: Union[str, discord.User], members: List[discord.Member], disabled: int = 0) -> discord.Embed: + if disabled == len(members): + return "All members targetted have disabled this action." + + if endpoint == 'hug': + image = {"link": random.choice(ACTIONS[endpoint]["images"])} # This might eventually be deprecated for copyright reasons + else: + image = await self.request_action(endpoint) + if isinstance(image, str): + return f':x: {image}' + + text = random.choice(ACTIONS[endpoint]["text"]) + text = text.replace("", "**" + (author if isinstance(author, str) else author.name) + "**").replace("", "**" + self.generate_users(members, text) + "**") + + embed = discord.Embed.from_dict({ + "title": text, + "image": {"url": image["link"]}, + "color": 0x1400ff + }) + + if disabled > 0: + embed.set_footer(text=f"{disabled} user{'s' if disabled > 1 else ''} disabled being targetted with this action") + return embed + + async def no_argument(self, ctx) -> Union[None, discord.Embed]: + await ctx.send(f'You provided no one to {ctx.command.name}.. Should- I {ctx.command.name} you?') + def check(m): + return m.content.lower() == 'yes' and m.author == ctx.author + try: + await self.client.wait_for('message', check=check, timeout=60) + except asyncio.TimeoutError: + pass + else: + return await self.action_embed(ctx.command.name, 'Killua', ctx.author.name) + + async def do_action(self, ctx, members: List[discord.Member] = None) -> Union[discord.Message, None]: + if not members: + embed = await self.no_argument(ctx) + if not embed: + return + elif ctx.author == members[0]: + return await ctx.send("Sorry... you can\'t use this command on yourself") + else: + first = User(members[0].id) + if len(members) == 1 and (ctx.command.name in first.action_settings) and not first.action_settings[ctx.command.name]: + return await ctx.send(f"**{members[0].display_name}** has disabled this action", allowed_mentions=discord.AllowedMentions.none()) + + allowed = [] + disabled = 0 + for member in members: + m = User(member.id) + if m.action_settings and ctx.command.name in m.action_settings and m.action_settings[ctx.command.name] is False: + disabled+=1 + else: + allowed.append(member) + embed = await self.action_embed(ctx.command.name, ctx.author, members, disabled) + + if isinstance(embed, str): + return await ctx.send(content=embed) + else: + return await ctx.bot.send_message(ctx, embed=embed) + + @commands.hybrid_group() + async def action(self, _: commands.Context) -> None: + """A collection of commands to express feeling through images and gifs""" + ... + + @check() + @action.command(extras={"category": Category.ACTIONS}, usage="hug ") + @discord.app_commands.describe(members="The people to hug") + async def hug(self, ctx: commands.Context, members: commands.Greedy[discord.Member] = None): + """Hug a user with this command""" + return await self.do_action(ctx, members) + + @check() + @action.command(extras={"category":Category.ACTIONS}, usage="pat ") + @discord.app_commands.describe(members="The people to pat") + async def pat(self, ctx: commands.Context, members: commands.Greedy[discord.Member] = None): + """Pat a user with this command""" + return await self.do_action(ctx, members) + + @check() + @action.command(extras={"category":Category.ACTIONS}, usage="poke ") + @discord.app_commands.describe(members="The people to poke") + async def poke(self, ctx: commands.Context, members: commands.Greedy[discord.Member] = None): + """Poke a user with this command""" + return await self.do_action(ctx, members) + + @check() + @action.command(extras={"category":Category.ACTIONS}, usage="tickle ") + @discord.app_commands.describe(members="The people to tickle") + async def tickle(self, ctx: commands.Context, members: commands.Greedy[discord.Member] = None): + """Tickle a user wi- ha- hahaha- stop- haha""" + return await self.do_action(ctx, members) + + @check() + @action.command(extras={"category":Category.ACTIONS}, usage="slap ") + @discord.app_commands.describe(members="The people to slap") + async def slap(self, ctx: commands.Context, members: commands.Greedy[discord.Member] = None): + """Slap a user with this command""" + return await self.do_action(ctx, members) + + @check() + @action.command(extras={"category": Category.ACTIONS}, usage="cuddle") + @discord.app_commands.describe(members="The people to cuddle with") + async def cuddle(self, ctx: commands.Context, members: commands.Greedy[discord.Member] = None): + """Snuggle up to a user and cuddle them with this command""" + return await self.do_action(ctx, members) + + @check() + @action.command(extras={"category": Category.ACTIONS}, usage="dance") + async def dance(self, ctx: commands.Context): + """Show off your dance moves!""" + return await self.get_image(ctx) + + @check() + @action.command(extras={"category": Category.ACTIONS}, usage="neko") + async def neko(self, ctx: commands.Context): + """uwu""" + return await self.get_image(ctx) + + @check() + @action.command(extras={"category": Category.ACTIONS}, usage="smile") + async def smile(self, ctx: commands.Context): + """Show a bright smile with this command""" + return await self.get_image(ctx) + + @check() + @action.command(extras={"category": Category.ACTIONS}, usage="blush") + async def blush(self, ctx: commands.Context): + """O-Oh! T-thank you for t-the compliment... You have beautiful fingernails too!""" + return await self.get_image(ctx) + + @check() + @action.command(extras={"category": Category.ACTIONS}, usage="tail") + async def tail(self, ctx: commands.Context): + """Wag your tail when you're happy!""" + return await self.get_image(ctx) + + def _get_view(self, id: int, current: dict) -> View: + options = [discord.SelectOption(label=k, value=k, default=v) for k, v in current.items()] + select = SettingsSelect(options, min_values=0, max_values=len(current), custom_id="select") + button = SettingsButton(label="Save", style=discord.ButtonStyle.green, emoji="\U0001f4be", custom_id="save") + view = View(user_id=id, timeout=100) + view.timed_out = True + + view.add_item(select) + view.add_item(button) + + return view + + @check() + @action.command(extras={"category": Category.ACTIONS}, usage="settings") + async def settings(self, ctx: commands.Context): + """Change the settings that control who can use what action on you""" + + embed = discord.Embed.from_dict({ + "title": "Settings", + "description": "By unticking a box users will no longer able to use that action on you", + "color": 0x1400ff + }) + + user = User(ctx.author.id) + current = user.action_settings + + for action in ACTIONS.keys(): + if action in current: + embed.add_field(name=action, value="✅" if current[action] else "❌", inline=False) + else: + embed.add_field(name=action, value="✅", inline=False) + current[action] = True + + view = self._get_view(ctx.author.id, current) + + msg = await ctx.send(embed=embed, view=view) + + await view.wait() + + if view.timed_out: + return await view.disable(msg) + + for val in view.values: + current[val] = True + + while True: + embed.clear_fields() + + for action in ACTIONS.keys(): + if action in view.values: + current[action] = True + embed.add_field(name=action, value="✅", inline=False) + else: + current[action] = False + embed.add_field(name=action, value="❌", inline=False) + + user.set_action_settings(current) + view = self._get_view(ctx.author.id, current) + + await msg.edit(embed=embed, view=view) + + await view.wait() + + if view.timed_out: + return await view.disable(msg) + + for val in view.values: + current[val] = True + + +Cog = Actions \ No newline at end of file diff --git a/tests/killua/cogs/api.py b/tests/killua/cogs/api.py new file mode 100644 index 000000000..2285d5012 --- /dev/null +++ b/tests/killua/cogs/api.py @@ -0,0 +1,118 @@ +import discord +from discord.ext import commands + +from asyncio import create_task +from zmq import REP, POLLIN, NOBLOCK +from zmq.asyncio import Context, Poller +from zmq.auth.asyncio import AsyncioAuthenticator + +from killua.bot import BaseBot +from killua.utils.classes import User, Guild, LootBox +from killua.static.constants import DB, LOOTBOXES, IPC_TOKEN + +from typing import List + +class IPCRoutes(commands.Cog): + + def __init__(self, client: BaseBot): + self.client = client + create_task(self.start()) + + async def start(self): + """Starts the zmq server asyncronously and handles incoming requests""" + context = Context() + + auth = AsyncioAuthenticator(context) + auth.start() + auth.configure_plain(domain="*", passwords={"killua": IPC_TOKEN}) + auth.allow("127.0.0.1") + + socket = context.socket(REP) + socket.plain_server = True + socket.bind("tcp://*:5555") + + poller = Poller() + poller.register(socket, POLLIN) + + while True: + socks = dict(await poller.poll()) + + if socket in socks and socks[socket] == POLLIN: + message = await socket.recv_json(NOBLOCK) + res = await getattr(self, message["route"])(message["data"]) + if res: + socket.send_json(res) + else: + socket.send_json({"status": "ok"}) + + def _get_reward(self, user: User, weekend: bool) -> int: + """A pretty simple algorithm that adjusts the reward for voting""" + if user.votes % 5 == 0: + return LootBox.get_random_lootbox() + if user.votes*2 > 100: + reward = int((user.votes*2)/100)*(150 if weekend else 100) + else: + reward = 100 + return reward + + async def handle_vote(self, data: dict) -> None: + user_id = data["user"] if "user" in data else data["id"] + + user = User(int(user_id)) + user.add_vote() + reward = self._get_reward(user, data["isWeekend"] if hasattr(data, "isWeekend") else False) + + if reward < 100: + user.add_lootbox(reward) + text = f"Thank you for voting for Killua! This time you get a :sparkles: special :sparkles: reward: the lootbox {LOOTBOXES[reward]['emoji']} {LOOTBOXES[reward]['name']}. Open it with `/economy open`" + else: + text = f"Thank you for voting for Killua! Here take {reward} Jenny as a sign of my gratitude. {5-user.votes%5} vote{'s' if 5-user.votes%5 > 1 else ''} away from a :sparkles: special :sparkles: reward" + user.add_jenny(reward) + + usr = self.client.get_user(user_id) or await self.client.fetch_user(user_id) + + try: + await usr.send(text) + except discord.HTTPException: + pass + + async def top(self, _) -> List[dict]: + """Returns a list of the top 50 users by the amount of jenny they have""" + members = DB.teams.find({'id': {'$in': [x.id for x in self.client.users]} }) + top = sorted(members, key=lambda x: x['points'], reverse=True)[:50] + res = [] + for t in top: + u = self.client.get_user(t["id"]) + res.append({"name": u.name, "tag": u.discriminator, "avatar": str(u.avatar.url), "jenny": t["points"]}) + return res + + async def commands(self, _) -> dict: + """Returns all commands with descriptions etc""" + return self.client.get_formatted_commands() + + async def save_user(self, data) -> None: + """This functions purpose is not that much getting user data but saving a user in the database""" + User(data["user"]) + + async def get_discord_user(self, data) -> dict: + """Getting additional info about a user with their id""" + res = self.client.get_user(data["user"]) + return {"name": res.name, "tag": res.discriminator, "avatar": str(res.avatar.url), "created_at": res.created_at.strftime('%Y-%m-%dT%H:%M:%SZ')} + + async def get_guild_data(self, data) -> dict: + """Getting some info about guild roles and channels for black and whitelisting""" + res = self.client.get_guild(int(data["guild"])) + return {"roles": [{"name": r.name, "id": str(r.id), "color": r.color.value} for r in res.roles], "channels": [{"name": c.name, "id": c.id} for c in res.channels if isinstance(c, discord.TextChannel)]} + + async def update_guild_cache(self, data) -> None: + """Makes sure the local cache is up to date with the db""" + guild = Guild(data.id) + guild.prefix = data["prefix"] + guild.commands = {v for _, v in data.commands.items()} + + async def vote(self, data) -> None: + """Registers a vote from either topgg or dbl""" + await self.handle_vote(data) + + +Cog = IPCRoutes \ No newline at end of file diff --git a/tests/killua/cogs/cards.py b/tests/killua/cogs/cards.py new file mode 100644 index 000000000..97c307215 --- /dev/null +++ b/tests/killua/cogs/cards.py @@ -0,0 +1,632 @@ +import discord +import math +import random +from discord.ext import commands +from datetime import datetime + +from typing import Union, List, Optional, Tuple, Optional, Dict + +from killua.bot import BaseBot +from killua.utils.checks import check +from killua.utils.paginator import Paginator +from killua.utils.classes import User, CardNotFound, CheckFailure, Book, NoMatches +from killua.static.enums import Category, HuntOptions, Items, SellOptions +from killua.utils.interactions import ConfirmButton +from killua.static.cards import Card +from killua.static.constants import ALLOWED_AMOUNT_MULTIPLE, FREE_SLOTS, DEF_SPELLS, VIEW_DEF_SPELLS, PRICES, BOOK_PAGES, LOOTBOXES, DB + + +class Cards(commands.Cog): + + def __init__(self, client: BaseBot): + self.client = client + self.cardname_cache = {} + self.reward_cache = { + "item": [x["_id"] for x in DB.items.find({"type": "normal", "rank": { "$in": ["A", "B", "C"]}})], + "spell": [x["_id"] for x in DB.items.find({"type": "spell", "rank": { "$in": ["B", "C"]}})], + "monster": { + "E": [x["_id"] for x in DB.items.find({"type": "monster", "rank": {"$in": ["E", "G", "H"]}})], + "D": [x["_id"] for x in DB.items.find({"type": "monster", "rank": {"$in": ["D", "E", "F"]}})], + "C": [x["_id"] for x in DB.items.find({"type": "monster", "rank": {"$in": ["C", "D", "E"]}})] + } + } + self._init_menus() + + def _init_menus(self) -> None: + menus = [] + menus.append(discord.app_commands.ContextMenu( + name='meet', + callback=self.client.callback_from_command(self.meet, message=False) + )) + + for menu in menus: + try: + self.client.tree.add_command(menu) + except discord.app_commands.errors.CommandAlreadyRegistered: + pass # Ignoring this + + async def all_cards_autocomplete( + self, + interaction: discord.Interaction, + current: str, + ) -> List[discord.app_commands.Choice[str]]: + """Autocomplete for all cards""" + if not self.cardname_cache: + for card in DB.items.find({}): + self.cardname_cache[card["_id"]] = card["name"], card["type"] + + name_cards = [(x[0], self.cardname_cache[x[0]][0]) for x in User(interaction.user.id).all_cards if self.cardname_cache[x[0]][0].lower().startswith(current.lower())] + id_cards = [(x[0], self.cardname_cache[x[0]][0]) for x in User(interaction.user.id).all_cards if str(x[0]).startswith(current)] + name_cards = list(dict.fromkeys(name_cards)) + id_cards = list(dict.fromkeys(id_cards)) # removing all duplicates from the list + + if current == "": # No ids AND names if the user hasn"t typed anything yet + return [discord.app_commands.Choice(name=x[1], value=str(x[0])) for x in name_cards] + return [*[discord.app_commands.Choice(name=n, value=str(i)) for i, n in name_cards], *[discord.app_commands.Choice(name=str(i), value=str(i)) for i, _ in id_cards]] + + def _get_single_reward(self, score:int) -> Tuple[int, int]: + if score == 1: + if random.randint(1, 10) < 5: + return 1, random.choice(self.reward_cache["item"]) + else: + return 1, random.choice(self.reward_cache["spell"]) + + if score < 3000/10000: + rarities = "E" + elif score < 7000/10000: + rarities = "D" + else: + rarities = "C" + + amount = random.randint(1, math.ceil(score*10)) + card = random.choice(self.reward_cache["monster"][rarities]) + return amount, card + + def _construct_rewards(self, score:int) -> List[Tuple[int, int]]: + # reward_score will be minutes/10080 which equals a week. Max rewards will get returned once a user has hunted for a week + rewards: List[Tuple[int, int]] = [] + + if score >= 1: + rewards.append(self._get_single_reward(1)) + score = 0.7 + + for _ in range(math.ceil(random.randint(1, math.ceil(score*10))/1.6)): + r = self._get_single_reward(score) + rewards.append(r) + + final_rewards: List[Tuple[int, int]] = [] + for reward in rewards: + # This avoid duplicates e.g. 4xPaladins Necklace, 2xPaladins Necklace => 6xPaladins Necklace + if reward[1] in (l:= [y for _, y in final_rewards]): + index = l.index(reward[1]) + final_rewards[index] = (final_rewards[index][0]+reward[0], final_rewards[index][1]) + else: + final_rewards.append(reward) + return final_rewards + + def _format_rewards(self, rewards:List[Tuple[int, int]], user:User) -> Tuple[List[list], List[str], bool]: + """Formats the generated rewards for further use""" + formatted_rewards: List[List[int, Dict[str, bool]]] = [] + formatted_text: List[str] = [] + + maxed = False + for pos, reward in enumerate(rewards): + for i in range(reward[0]): + if len([*user.fs_cards,*[x for x in rewards if x[1] > 99 and not user.has_rs_card(x[0])]]) >= 40 and (reward[1] > 99 or (not user.has_rs_card(reward[1]) and reward[1] < 100)): + # return formatted_rewards, formatted_text, True # if the free slots are full the process stops + maxed = (pos, i) # Returning the exact position where the cards are too much + else: + formatted_rewards.append([reward[1], {"fake": False, "clone": False}]) + card = Card(reward[1]) + if maxed: + if not maxed[1] == 0: # If there isn"t 0 of that card that will be added + formatted_text.append(f"{maxed[1]}x **{card.name}**{card.emoji}") + else: + formatted_text.append(f"{reward[0]}x **{card.name}**{card.emoji}") + + return formatted_rewards, formatted_text, maxed + + @commands.hybrid_group() + async def cards(self, _: commands.Context): + """Commands mimicing the greed island arc of hxh""" + ... + + @check(3) + @commands.bot_has_permissions(attach_files=True, embed_links=True) + @cards.command(extras={"category":Category.CARDS}, usage="book ") + @discord.app_commands.describe(page="The page of the book to see") + async def book(self, ctx: commands.Context, page: int = 1): + """Allows you to take a look at your cards""" + user = User(ctx.author.id) + + if len(user.all_cards) == 0: + return await ctx.send("You don't have any cards yet!") + + if page: + if page > 7+math.ceil(len(user.fs_cards)/18) or page < 1: + return await ctx.send(f"Please choose a page number between 1 and {6+math.ceil(len(user.fs_cards)/18)}") + + async def make_embed(page, *_) -> Tuple[discord.Embed, discord.File]: + return await Book(self.client.session).create(ctx.author, page) + return await Paginator(ctx, page=page, func=make_embed, max_pages=6+math.ceil(len(user.fs_cards)/18), has_file=True).start() + + @check(2) + @cards.command(extras={"category":Category.CARDS}, usage="sell ") + @discord.app_commands.describe( + card="The card to sell", + type="The type of card to bulk sell", + amount="The amount of the specified card to sell" + ) + @discord.app_commands.autocomplete(card=all_cards_autocomplete) + async def sell(self, ctx: commands.Context, card: str = None, type: SellOptions = None, amount: int = 1): + """Sell any amount of cards you own""" + + user = User(ctx.author.id) + + if not type and not card: + return await ctx.send("You need to specify what exactly to sell", ephemeral=True) + + if type: # always prefers if a type argument was given. However if both a type argument and card argument was given, + # both will be attempted to be executed. + if type.name == "all": + to_be_sold = [x for x in user.fs_cards if not x[1]["clone"] and not x[1]["fake"]] + elif type.name == "spells": + to_be_sold = [x for x in user.fs_cards if Card(x[0]).type == "spell" and not x[1]["clone"] and not x[1]["fake"]] + elif type.name == "monsters": + to_be_sold = [x for x in user.fs_cards if Card(x[0]).type == "monster"and not x[1]["clone"] and not x[1]["fake"]] + else: to_be_sold = [] + + to_be_gained = 0 + + for c, _ in to_be_sold: + j = int(PRICES[Card(c).rank]/10) + if user.is_entitled_to_double_jenny: + j *= 2 + to_be_gained += j + + if to_be_gained == 0: + return await ctx.send("You don't have any cards of that type to sell!", ephemeral=True) + + view = ConfirmButton(ctx.author.id, timeout=80) + msg = await ctx.send(f"You will receive {to_be_gained} Jenny for selling all {type.name if not type.name == 'all' else 'free slots'} cards, do you want to proceed?", view=view) + await view.wait() + await view.disable(msg) + + if not view.value: + if view.timed_out: + return await ctx.send(f"Timed out!") + else: + return await ctx.send(f"Successfully canceled!") + else: + user.bulk_remove(to_be_sold) + user.add_jenny(to_be_gained) + return await ctx.send(f"You sold all your {type.name if not type.name == 'all' else 'free slots cards'} for {to_be_gained} Jenny!") + if not card: + return + + if amount < 1: + amount = 1 + if len(user.all_cards) == 0: + return await ctx.send("You don't have any cards yet!") + try: + card = Card(card) + except CardNotFound: + return await ctx.send(f"A card with the id `{card}` does not exist", allowed_mentions=discord.AllowedMentions.none()) + + in_possesion = user.count_card(card.id, including_fakes=False) + + if in_possesion < amount: + return await ctx.send(f"Seems you don't own enough copies of this card. You own {in_possesion} cop{'y' if in_possesion == 1 else 'ies'} of this card") + + if card == 0: + return await ctx.send("You cannot sell this card!") + + jenny = int((PRICES[card.rank]*amount)/10) + if user.is_entitled_to_double_jenny: + jenny *= 2 + view = ConfirmButton(ctx.author.id, timeout=80) + msg = await ctx.send(f"You will receive {jenny} Jenny for selling {'this card' if amount == 1 else 'those cards'}, do you want to proceed?", view=view) + await view.wait() + await view.disable(msg) + + if not view.value: + if view.timed_out: + return await ctx.send(f"Timed out!") + else: + return await ctx.send(f"Successfully canceled!") + + for _ in range(amount): + user.remove_card(card.id, False) + user.add_jenny(jenny) + await ctx.send(f"Successfully sold {amount} cop{'y' if amount == 1 else 'ies'} of card {card.id} for {jenny} Jenny!") + + async def swap_cards_autocomplete( + self, + interaction: discord.Interaction, + current: str, + ) -> List[discord.app_commands.Choice[str]]: + """Autocomplete for the swap command""" + + if not self.cardname_cache: + for card in DB.items.find({}): + self.cardname_cache[card["_id"]] = card["name"], card["type"] + + user = User(interaction.user.id) + name_cards = [(x[0], self.cardname_cache[x[0]][0]) for x in user.all_cards if self.cardname_cache[x[0]][0].lower().startswith(current.lower())] + id_cards = [(x[0], self.cardname_cache[x[0]][0]) for x in user.all_cards if str(x[0]).startswith(current)] + + name_duplicates = [] + id_duplicates = [] + for id, name in name_cards: + if user.can_swap(id) and (id, name) not in name_duplicates: + name_duplicates.append((id, name)) + + for id, name in id_cards: + if user.can_swap(id) and (id, name) not in id_duplicates: + id_duplicates.append((id, name)) + + if current == "": # No ids AND names if the user hasn"t typed anything yet + return [discord.app_commands.Choice(name=x[1], value=str(x[0])) for x in name_duplicates] + return [*[discord.app_commands.Choice(name=n, value=str(i)) for i, n in name_duplicates], *[discord.app_commands.Choice(name=str(i), value=str(i)) for i, _ in id_duplicates]] + + @check(20) + @cards.command(extras={"category":Category.CARDS}, usage="swap ") + @discord.app_commands.describe(card="The card to swap out") + @discord.app_commands.autocomplete(card=swap_cards_autocomplete) + async def swap(self, ctx: commands.Context, card: str): + """Allows you to swap cards from your free slots with the restricted slots and the other way around""" + + user = User(ctx.author.id) + if len(user.all_cards) == 0: + return await ctx.send("You don't have any cards yet!") + try: + card = Card(card) + except CardNotFound: + return await ctx.send("Please use a valid card number!") + + if card.id == 0: + return await ctx.send("You cannot swap out card No. 0!") + + sw = user.swap(card.id) + + if sw is False: + return await ctx.send(f"You don't own a fake and real copy of card `{card.name}` you can swap out!") + + await ctx.send(f"Successfully swapped out card {card.name}") + + @check() + @cards.command(extras={"category":Category.CARDS}, usage="hunt ") + @discord.app_commands.describe(option="What to do with your hunt") + async def hunt(self, ctx: commands.Context, option: HuntOptions = HuntOptions.start): + """Go on a hunt! The longer you are on the hunt, the better the rewards!""" + option = option.name + + user = User(ctx.author.id) + has_effect, value = user.has_effect("hunting") + + if option == "time": + if not has_effect: + return await ctx.send("You are not on a hunt yet!") + + return await ctx.send(f"You've started hunting .") + + elif option == "end" and has_effect is True: + difference = datetime.now() - value + if int(difference.seconds/60/60+difference.days*24*60*60) < 12: # I don't think timedelta has an hours or minutes property :c + return await ctx.send("You must be at least hunting for twelve hours!") + + await ctx.interaction.response.defer() # The following part may take longer than 3 secons + + minutes = int(difference.seconds/60+difference.days*24*60) + score = minutes/10080 # There are 10080 minutes in a week if I'm not completely wrong + + rewards = self._construct_rewards(score) + formatted_rewards, formatted_text, hit_limit = self._format_rewards(rewards, user) + + jenny = 0 + if hit_limit: + c, n = hit_limit + for pos, card in enumerate(rewards): + if pos == c: + jenny += PRICES[Card(card[1]).rank] * (card[0]-n) + elif pos >= c: + jenny += PRICES[Card(card[1]).rank] * card[0] + + + text = f"You've started hunting . You brought back the following items from your hunt: \n\n" + + if hit_limit: + text += f":warning: Your free slot limit has been reached! Make sure you free it up before hunting again. The excess cards have been automatically sold bringing you `{jenny}` Jenny\n\n" + + embed = discord.Embed.from_dict({ + "title": "Hunt returned!", + "description": text + "\n".join(formatted_text), + "color": 0x1400ff + }) + user.remove_effect("hunting") + user.add_multi(*formatted_rewards) + user.add_jenny(jenny) + return await ctx.send(embed=embed) + + elif option == "end" and not has_effect: + return await ctx.send(f"You aren't on a hunt yet! Start one with `/cards hunt`", allowed_mentions=discord.AllowedMentions.none()) + + if has_effect: + return await ctx.send(f"You are already on a hunt! Get the results with `/cards hunt end`", allowed_mentions=discord.AllowedMentions.none()) + user.add_effect("hunting", datetime.now()) + await ctx.send("You went hunting! Make sure to claim your rewards at least twelve hours from now, but remember, the longer you hunt, the more you get") + + @check(120) + @discord.app_commands.describe(user="The user to meet. Must have sent a mesage recently.") + @cards.command(aliases=["approach"], extras={"category":Category.CARDS}, usage="meet ") + async def meet(self, ctx: commands.Context, user: discord.Member): + """Meet a user who has recently sent a message in this channel to enable certain effects""" + if hasattr(ctx, "invoked_by_context_menu"): + user = await self.client.find_user(ctx, user) + + author = User(ctx.author.id) + past_users = list() + if user.bot: + return await ctx.send("You can't interact with bots with this command", ephemeral=True) + async for message in ctx.channel.history(limit=20): + if message.author.id not in past_users: + past_users.append(message.author.id) + + if not user.id in past_users: + return await ctx.send("The user you tried to approach has not send a message in this channel recently", ephemeral=True) + + if user.id in author.met_user: + try: + await ctx.message.delete() + except discord.HTTPException: + pass + return await ctx.send(f"You already have `{user}` in the list of users you met, {ctx.author.name}", delete_after=2, allowed_mentions=discord.AllowedMentions.none(), ephemeral=True) + + author.add_met_user(user.id) + try: + await ctx.message.delete() + except discord.HTTPException: + pass + return await ctx.send(f"Done {ctx.author.mention}! Successfully added `{user}` to the list of people you've met", delete_after=5, allowed_mentions=discord.AllowedMentions.none(), ephemeral=hasattr(ctx, "invoked_by_context_menu")) + + @check() + @cards.command(extras={"category":Category.CARDS}, usage="discard ") + @discord.app_commands.describe(card="The card to discard") + @discord.app_commands.autocomplete(card=all_cards_autocomplete) + async def discard(self, ctx: commands.Context, card: str): + """Discard a card you want to get rid of with this command. Make sure it's in the free slots""" + + user = User(ctx.author.id) + try: + card = Card(card) + except CardNotFound: + return await ctx.send("This card does not exist!") + + if not user.has_any_card(card.id): + return await ctx.send("You are not in possesion of this card!") + + if card.id == 0: + return await ctx.send("You cannot discard this card!") + + view = ConfirmButton(ctx.author.id, timeout=20) + msg = await ctx.send(f"Do you really want to throw this card away? (if you want to throw a fake aware, make sure it's in the free slots (unless it's the only copy you own. You can switch cards between free and restricted slots with `{self.client.command_prefix(self.client, ctx.message)[2]}swap `)", view=view, allowed_mentions=discord.AllowedMentions.none()) + await view.wait() + await view.disable(msg) + + if not view.value: + if view.timed_out: + return await ctx.send(f"Timed out!") + else: + return await ctx.send(f"Successfully cancelled!") + + try: + user.remove_card(card.id, remove_fake=True, restricted_slot=False) + # essentially here it first looks for fakes in your free slots and tried to remove them. If it doesn't find any fakes in the free slots, it will remove the first match of the card it finds in free or restricted slots + except NoMatches: + user.remove_card(card.id) + await ctx.send(f"Successfully thrown away card No. `{card.id}`") + + @check() + @cards.command(aliases=["read"], extras={"category": Category.CARDS}, usage="cardinfo ") + @discord.app_commands.describe(card="The card to get infos about") + @discord.app_commands.autocomplete(card=all_cards_autocomplete) + async def cardinfo(self, ctx: commands.Context, card: str): + """Check card info out about any card you own""" + try: + c = Card(card) + except CardNotFound: + return await ctx.send("Invalid card") + + author = User(ctx.author.id) + if not author.has_any_card(c.id): + return await ctx.send("You don't own a copy of this card so you can't view its infos") + + embed = c._get_analysis_embed(c.id) + if c.type == "spell" and c.id not in [*DEF_SPELLS, *VIEW_DEF_SPELLS]: + card_class = [c for c in Card.__subclasses__() if c.__name__ == f"Card{card}"][0] + usage = f"`{self.client.command_prefix(self.client, ctx.message)[2]}use {card} " + " ".join([f"[{k}: {v.__name__}]" for k, v in card_class.exec.__annotations__.items() if not str(k) == "return"]) + "`" + embed.add_field(name="Usage", value=usage, inline=False) + + await ctx.send(embed=embed) + + @check() + @cards.command(name="check", extras={"category": Category.CARDS}, usage="check ") + @discord.app_commands.describe(card="The card to see how many fakes you own of it") + @discord.app_commands.autocomplete(card=all_cards_autocomplete) + async def _check(self, ctx: commands.Context, card: str): + """Lets you see how many copies of the specified card are fakes""" + try: + card_obj = Card(card) + except CardNotFound: + return await ctx.send("Invalid card") + + author = User(ctx.author.id) + + if not author.has_any_card(card_obj.id, only_allow_fakes=True): + return await ctx.send("You don't own any copies of this card which are fake") + + text = "" + + if len([x for x in author.rs_cards if x[1]["fake"] is True and x[0] == card_obj.id]) > 0: + text += f"The card in your restricted slots is fake" + + if (fs := len([x for x in author.fs_cards if x[1]["fake"] is True and x[0] == card_obj.id])) > 0: + text += (" and " if len(text) > 0 else "") + f"{fs} cop{'ies' if fs > 1 else 'y'} of this card in your free slots {'are' if fs > 1 else 'is'} fake" + + await ctx.send(text) + + async def _use_converter(self, ctx: commands.Context, args: str) -> Union[discord.Member, int, str]: + if (m := await self.client.find_user(ctx, args)) and not isinstance(m, discord.User): + return m + elif args.isdigit(): + return int(args) + else: + return args + + def _use_check(self, ctx: commands.Context, card: str, args: Optional[Union[discord.Member, int, str]], add_args: Optional[int]) -> None: + """Makes sure the inputs are valid if they exist""" + try: + card: Card = Card(card) + except CardNotFound: + raise CheckFailure("Invalid card id") + + if not card.id in [x[0] for x in User(ctx.author.id).fs_cards] and not card.id in [1036]: + raise CheckFailure("You are not in possesion of this card!") + + if card.type != "spell": + raise CheckFailure("You can only use spell cards!") + + if card.id in [*DEF_SPELLS, *VIEW_DEF_SPELLS]: + raise CheckFailure("You can only use this card in response to an attack!") + + if args: + if isinstance(args, discord.Member): + if args.id == ctx.author.id: + raise CheckFailure("You can't use spell cards on yourself") + elif args.bot: + raise CheckFailure("You can't use spell cards on bots") + + if isinstance(args, int): + if int(args) < 1: + raise CheckFailure("You can't use an integer less than 1") + + if add_args: + if add_args < 1: + raise CheckFailure("You can't use an integer less than 1") + + async def _use_core(self, ctx: commands.Context, item: int, *args) -> None: + """This passes the execution to the right class """ + card_class = [c for c in Card.__subclasses__() if c.__name__ == f"Card{item}"][0] + + l = [] + for p, (k, v) in enumerate([x for x in card_class.exec.__annotations__.items() if not str(x[0]) == "return"]): + if len(args) > p and isinstance(args[p], v): + l.append({k: args[p]}) + else: + l.append(None) + + if None in l: + return await ctx.send(f"Invalid arguments provided! Usage: `{self.client.command_prefix(self.client, ctx.message)[2]}use {item} " + " ".join([f"[{k}: {v.__name__}]" for k, v in card_class.exec.__annotations__.items() if not str(k) == "return"]) + "`", allowed_mentions=discord.AllowedMentions.none()) + kwargs = {k: v for d in l for k, v in d.items()} + try: + await card_class(ctx, name_or_id=item).exec(**kwargs) + except Exception as e: + await ctx.send(e.message, allowed_mentions=discord.AllowedMentions.none()) + + async def use_cards_autocomplete( + self, + interaction: discord.Interaction, + current: str, + ) -> List[discord.app_commands.Choice[str]]: + if not self.cardname_cache: + for card in DB.items.find({}): + self.cardname_cache[card["_id"]] = card["name"], card["type"] + + name_cards = [(x[0], self.cardname_cache[x[0]][0])for x in User(interaction.user.id).all_cards if self.cardname_cache[x[0]][0].lower().startswith(current.lower()) and self.cardname_cache[x[0]][1] == "spell"] + id_cards = [(x[0], self.cardname_cache[x[0]][0])for x in User(interaction.user.id).all_cards if str(x[0]).startswith(current) and self.cardname_cache[x[0]][1] == "spell"] + name_cards = list(dict.fromkeys(name_cards)) + id_cards = list(dict.fromkeys(id_cards)) # removing all duplicates from the list + + if current == "": # No ids AND names if the user hasn"t typed anything yet + res = [discord.app_commands.Choice(name=x[1], value=str(x[0])) for x in name_cards] + else: + res = [*[discord.app_commands.Choice(name=n, value=str(i)) for i, n in name_cards], *[discord.app_commands.Choice(name=str(i), value=str(i)) for i, _ in id_cards]] + if "booklet".startswith(current): + res.append(discord.app_commands.Choice(name="booklet", value="booklet")) + + return res + + @check() + @cards.command(extras={"category":Category.CARDS}, usage="use ") + @discord.app_commands.describe( + item="The card or item to use", + target="The target of the spell", + args="Additional required arguments by the card" + ) + @discord.app_commands.autocomplete(item=use_cards_autocomplete) + async def use(self, ctx: commands.Context, item: str, target: str = None, args: int = None): + """Use spell cards you own with this command! Check with cardinfo what arguments are required.""" + + if item.lower() == "booklet": + + def make_embed(page, embed, pages): + embed.title = "Introduction booklet" + embed.description = pages[page-1] + embed.set_image(url="https://cdn.discordapp.com/attachments/759863805567565925/834794115148546058/image0.jpg") + return embed + + return await Paginator(ctx, BOOK_PAGES, func=make_embed).start() + + try: + self._use_check(ctx, item, target, args) + except CheckFailure as e: + return await ctx.send(e.message) + + args = await self._use_converter(ctx, args) + args = [x for x in [target, args] if x] + + await self._use_core(ctx, item, *args) + + @commands.is_owner() + @cards.command(extras={"category":Category.CARDS}, usage="gain ", hidden=True) + @discord.app_commands.describe( + type="The type of item to gain", + item="The amount/id of the item to get" + ) + async def gain(self, ctx: commands.Context, type: Items, item: str): + """An owner restricted command allowing the user to obtain any card or amount of jenny or any lootbox""" + user = User(ctx.author.id) + type = type.name + + if type == "card": + try: + card = Card(item) + except CardNotFound: + return await ctx.send("Invalid card id") + if card.id == 0: + return await ctx.send("No") + if len(card.owners) >= card.limit * ALLOWED_AMOUNT_MULTIPLE: + return await ctx.send("Sorry! Global card limit reached!") + if len(user.fs_cards) >= FREE_SLOTS and (item > 99 or item in [x[0] for x in user.rs_cards]): + return await ctx.send("Seems like you have no space left in your free slots!") + user.add_card(card.id) + return await ctx.send(f"Added card '{card.name}' to your inventory") + + if type == "jenny": + if not item.isdigit(): + return await ctx.send("Please provide a valid amount of jenny!") + item = int(item) + if item < 1: + return await ctx.send("Please provide a valid amount of jenny!") + if item > 69420: + return await ctx.send("Be reasonable.") + user.add_jenny() + return await ctx.send(f"Added {item} Jenny to your account") + + if type == "lootbox": + if not item.isdigit() or not int(item) in list(LOOTBOXES.keys()): + return await ctx.send("Invalid lootbox!") + user.add_lootbox(int(item)) + return await ctx.send(f"Done! Added lootbox \"{LOOTBOXES[int(item)]['name']}\" to your inventory") + +Cog = Cards diff --git a/tests/killua/cogs/dev.py b/tests/killua/cogs/dev.py new file mode 100644 index 000000000..9599dccb7 --- /dev/null +++ b/tests/killua/cogs/dev.py @@ -0,0 +1,438 @@ +from discord.ext import commands +import discord + +import math +from typing import List, Tuple, Union +from io import BytesIO +from datetime import datetime, timedelta +from matplotlib import pyplot as plt +import numpy as np + +from killua.bot import BaseBot +from killua.utils.checks import check +from killua.utils.paginator import Paginator +from killua.utils.classes import User, Guild #lgtm [py/unused-import] +from killua.utils.interactions import View, Button, Modal +from killua.static.enums import Category, Activities, Presences, StatsOptions +from killua.static.cards import Card #lgtm [py/unused-import] +from killua.static.constants import DB, UPDATE_CHANNEL, GUILD_OBJECT, INFO + +class UsagePaginator(Paginator): + """A normal paginator with a button that returns to the original help command""" + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + self.view.add_item(Button(label="Back", style=discord.ButtonStyle.red, custom_id="1")) + + async def start(self): + view = await self._start() + + if view.ignore or view.timed_out: + return + + await self.view.message.delete() + await self.ctx.command.__call__(self.ctx, StatsOptions.usage) + +class Dev(commands.Cog): + + def __init__(self, client: BaseBot): + self.client = client + self.version_cache = [] + + async def version_autocomplete( + self, + _: discord.Interaction, + current: str, + ) -> List[discord.app_commands.Choice[str]]: + + if not self.version_cache: + self.version_cache = [x["version"] for x in DB.const.find_one({"_id": "updates"})["updates"]] + + return [ + discord.app_commands.Choice(name=v, value=v) + for v in self.version_cache if current.lower() in v.lower() + ] + + def _create_piechart(self, data: List[list], ) -> discord.File: + """Creates a piechart with the given data""" + labels = [x[0] for x in data] + values = [x[1] for x in data] + buffer = BytesIO() + plt.pie(values, labels=labels, autopct="%1.1f%%", shadow=True, textprops={'color':"w"}) + plt.axis("equal") + plt.tight_layout() + plt.savefig(buffer, format="png", transparent=True) + buffer.seek(0) + plt.close() + file = discord.File(buffer, filename="piechart.png") + return file + + def _create_graph(self, dates: List[datetime], y_points: List[int], label: str) -> BytesIO: + """Creates a graph with y over time supplied in the dates list""" + plt.style.use("seaborn") # After testing this is the best theme + # Plotting the main graph + plt.plot(dates, y_points, color="blue") + plt.xlabel("Time") + plt.ylabel(label) + + # Plot the trend using a linear regression + x = np.array([x.timestamp() for x in dates]) + y = np.array(y_points) + m, b = np.polyfit(x, y, 1) + plt.plot(dates, m*x + b, linestyle=":", color="grey") + + plt.tight_layout() # Making the actual graph a bit bigger + buf = BytesIO() + plt.savefig(buf, format='png') + buf.seek(0) + plt.close() + + return buf + + def _calc_predictions(self, values: List[int]) -> dict: + """Calculates various predictions for the given values""" + + #Calculates the average change between one value compared to the next one in the list + change = [values[i+1] - values[i] for i in range(len(values)-1)] + avg_change = round(sum(change)/len(values), 2) + # Calculates the standard deviation of the avergae change + std_change = round(math.sqrt(sum([(x - avg_change)**2 for x in change])/len(values)), 2) + + recent_avg = round(sum(values[-10:]) / 10, 2) + + return { + "recent_avg": recent_avg, + "min": min(values), + "max": max(values), + "avg_change": avg_change, + "std_change": std_change, + "median": sorted(values)[len(values) // 2], + "mode": max(set(values), key=values.count), + } + + def _get_stats_embed(self, data: List[dict], embed: discord.Embed, type: str) -> Tuple[discord.Embed, discord.File]: + """Creates an embed with the stats of the given type""" + dates = [x["date"] for x in data if type in x] + type_list = [x[type] for x in data if type in x] + + embed.title = f"Statistics about {self.client.user.name}'s " + type.replace("_", " ").title() + + if not dates: + embed.description = "No data available just yet" + return embed + + buffer = self._create_graph(dates, type_list, type.replace("_", " ").title()) + file = discord.File(buffer, filename=f"{type}.png") + add_data = self._calc_predictions(type_list) + + embed.set_image(url=f"attachment://{type}.png") + embed.add_field(name=f"Maximum {type} reached", value=add_data["max"]) # This is only really relevant for guilds and users as registered users cannot decrease + embed.add_field(name=f"Average {type} last 10 days", value=add_data["recent_avg"]) + embed.add_field(name=f"Average {type} gained per day", value=add_data["avg_change"]) + embed.add_field(name=f"\U000003c3 of the average daily {type} gain", value=add_data["std_change"]) + return embed, file + + async def all_top(self, ctx: commands.Context, top: List[tuple]) -> None: + """Shows a list of all top commands""" + def make_embed(page, embed, pages): + embed.title = "Top command usage" + + if len(pages)-page*10+10 > 10: + top = pages[page*10-10:-(len(pages)-page*10)] + elif len(pages)-page*10+10 <= 10: + top = pages[-(len(pages)-page*10+10):] + + embed.description = "```\n" + "\n".join(["#"+str(n+1)+" /"+k+" with "+str(v)+" uses" for n, (k, v) in enumerate(top, page*10-10)]) + "\n```" + return embed + + await UsagePaginator(ctx, top, func=make_embed, max_pages=math.ceil(len(top)/10)).start() + + async def group_top(self, ctx: commands.Context, top: List[tuple], interaction: discord.Interaction) -> None: + """Displays a pie chart of the top used commands in a group""" + # A list of all valid groups as strings + possible_groups = [g.name for g in self.client.commands if not g.parent and g.name != "help"] # The only time a command doesn't have a parent is when it's a group + group = await self.client.get_text_response(ctx, "Please enter a command group", interaction=interaction, style=discord.TextStyle.short, placeholder=(", ".join(possible_groups))[:97] + "...") + if not group: return + + if not group.lower() in possible_groups: + return await ctx.send("That is not a valid group", ephemeral=True) + else: + top = [(x[0].split(" ")[1], x[1]) for x in top if x[0].startswith(group.lower()) and len(x[0].split(" ")) > 1] + rest = 0 + for x in top[-9:]: + rest += x[1] + + if len(top) > 9: + real_top = [*top[:9], ("other", rest)] + else: + real_top = top[:9] + + file = self._create_piechart(real_top) + embed = discord.Embed(title=f"Top 10 used commands of group {group}", color=0x1400ff) + embed.set_image(url="attachment://piechart.png") + + view = View(ctx.author.id) + view.add_item(Button(label="Back", style=discord.ButtonStyle.red, custom_id="back")) + + msg = await ctx.send(embed=embed, file=file, view=view) + await view.wait() + + if view.timed_out: + await view.disable() + + if view.value: + if view.value == "back": + await msg.delete() + await self.initial_top(ctx) + + async def initial_top(self, ctx: commands.Context) -> None: + s = DB.const.find_one({"_id": "usage"})["command_usage"] + top = sorted(s.items(), key=lambda x: x[1], reverse=True) + rest = 0 + for x in top[-9:]: + rest += x[1] + + # creates a piechart in an embed with the top 10 commands using _create_piechart + file = self._create_piechart([*top[:9], ("other", rest)]) + embed = discord.Embed(title="Top 10 used commands", color=0x1400ff) + embed.set_image(url="attachment://piechart.png") + + view = View(ctx.author.id) + view.add_item(Button(label="See all", style=discord.ButtonStyle.primary, custom_id="all")) + view.add_item(Button(label="See for group", style=discord.ButtonStyle.primary, custom_id="group")) + + msg = await ctx.send(embed=embed, file=file, view=view) + + await view.wait() + + if view.timed_out: + await view.disable() + else: + await msg.delete() + if view.value == "all": + await self.all_top(ctx, top) + elif view.value == "group": + await self.group_top(ctx, top, view.interaction) + + + @commands.hybrid_group() + async def dev(self, _: commands.Context): + """A collection of commands regarding the development side of Killua""" + ... + + #Eval command, unnecessary with the jsk extension but useful for database stuff + @commands.is_owner() + @commands.command(aliases=["exec"], extras={"category":Category.OTHER}, usage="eval ", hidden=True, with_app_command=False) + @discord.app_commands.describe(code="The code to evaluate") # Since this is not an app command this won"t show up but is still added for consistency + async def eval(self, ctx: commands.Context, *, code: str): + """Standard eval command, owner restricted""" + try: + await ctx.send(f"```py\n{eval(code)}```") + except Exception as e: + await ctx.send(str(e)) + + @commands.is_owner() + @commands.command(extras={"category":Category.OTHER}, usage="say ", hidden=True, with_app_command=False) + @discord.app_commands.describe(content="What to say") # Same thing as for the eval command + async def say(self, ctx: commands.Context, *, content: str): + """Lets Killua say what is specified with this command. Possible abuse leads to this being restricted""" + + await ctx.message.delete() + await ctx.send(content, reference=ctx.message.reference) + + @commands.is_owner() + @dev.command(aliases=["publish-update", "pu"], extras={"category":Category.OTHER}, usage="publish_update ", hidden=True) + @discord.app_commands.guilds(GUILD_OBJECT) + async def publish_update(self, ctx: commands.Context): + """Allows me to publish Killua updates in a handy format""" + if not ctx.interaction: + return await ctx.send("This command can only be used with slash commands") + + modal = Modal(title="New update",timeout=None) + version = discord.ui.TextInput(label="Version", placeholder="v1.0") + image = discord.ui.TextInput(label="Image", default="https://cdn.discordapp.com/attachments/780554158154448916/788071254917120060/killua-banner-update.png", required=False) + description = discord.ui.TextInput(label="Description", placeholder="Killua is now open source!", max_length=4000, style=discord.TextStyle.long) + modal.add_item(version).add_item(image).add_item(description) + + await ctx.interaction.response.send_modal(modal) + + await modal.wait() + + old: list = DB.const.find_one({"_id": "updates"})["updates"] + old_version = old[-1]["version"] if old and "version" in old[-1] else "No version" + + if version.value in [x["version"] for x in old if "version" in x]: + return await ctx.send("This is an already existing version", ephemeral=True) + + embed = discord.Embed.from_dict({ + "title": f"Killua Update `{old_version}` -> `{version}`", + "description": description.value, + "color": 0x1400ff, + "footer": {"text": f"Update by {ctx.author}", "icon_url": str(ctx.author.avatar.url)}, + "image": {"url": image.value or "https://cdn.discordapp.com/attachments/780554158154448916/788071254917120060/killua-banner-update.png"} + }) + + data = {"version": version.value, "description": description.value, "published_on": datetime.now(), "published_by": ctx.author.id, "image": image.value} + DB.const.update_one({"_id": "updates"}, {"$push": {"updates": data}}) + self.version_cache.append(version.value) + + await modal.interaction.response.defer() + + if self.client.is_dev: # We do not want to accidentally publish a message when testing + return + channel = self.client.get_channel(UPDATE_CHANNEL) + msg = await channel.send(content= "<@&795422783261114398>", embed=embed) + await ctx.send("Published new update " + f"`{old_version}` -> `{version.value}`", ephemeral=True) + await msg.publish() + + @check() + @dev.command(extras={"category":Category.OTHER}, usage="update ") + @discord.app_commands.autocomplete(version=version_autocomplete) + @discord.app_commands.describe(version="The version to get information about") + async def update(self, ctx: commands.Context, version: str = None): + """Allows you to view current and past updates""" + if version is None: + data = DB.const.find_one({"_id": "updates"})["updates"][-1] + else: + d = [x for x in DB.const.find_one({"_id": "updates"})["updates"] if "version" in x and x["version"] == version] + if len(d) == 0: + return await ctx.send("Invalid version!") + data = d[0] + + author = self.client.get_user(data["published_by"]) + embed = discord.Embed.from_dict({ + "title": f"Infos about version `{data['version']}`", + "description": str(data["description"]), + "color": 0x1400ff, + "image": {"url": data["image"]}, + "footer": {"icon_url": str(author.avatar.url), "text": f"Published on {data['published_on'].strftime('%b %d %Y %H:%M:%S')}"} + }) + await ctx.send(embed=embed) + + @commands.is_owner() + @dev.command(extras={"category":Category.OTHER}, usage="blacklist ", hidden=True) + @discord.app_commands.guilds(GUILD_OBJECT) + @discord.app_commands.describe( + user="The user to blacklist", + reason="The reason for the blacklist" + ) + async def blacklist(self, ctx: commands.Context, user: str, *, reason = None): + """Blacklisting bad people like Hisoka. Owner restricted""" + discord_user: Union[discord.User, None] = await self.client.find_user(user) + if not discord_user: + return await ctx.send("Invalid user!", ephermal=True) + # Inserting the bad person into my database + DB.const.update_one({"_id": "blacklist"}, {"$push": {"blacklist": {"id": discord_user.id,"reason": reason or "No reason provided", "date": datetime.now()}}}) + await ctx.send(f"Blacklisted user `{user}` for reason: {reason}", ephermal=True) + + @commands.is_owner() + @dev.command(extras={"category":Category.OTHER}, usage="whitelist ", hidden=True) + @discord.app_commands.guilds(GUILD_OBJECT) + @discord.app_commands.describe( + user="The user to whitelist" + ) + async def whitelist(self, ctx: commands.Context, user: str): + """Whitelists a user. Owner restricted""" + user: Union[discord.User, None] = await self.client.find_user(user) + if not user: + return await ctx.send("Invalid user!", ephermal=True) + + to_pull = [d for d in DB.const.find_one({"_id": "blacklist"})["blacklist"] if d["id"] == user.id] + + if not to_pull: + return await ctx.send("User is not blacklisted!", ephermal=True) + + DB.const.update_one({"_id": "blacklist"}, {"$pull": {"blacklist": to_pull[0]}}) + await ctx.send(f"Successfully whitelisted `{user}`") + + @commands.is_owner() + @dev.command(aliases=["st", "pr", "status"], extras={"category":Category.OTHER}, usage="pr ", hidden=True) + @discord.app_commands.guilds(GUILD_OBJECT) + @discord.app_commands.describe( + text="The text displayed as the status", + activity="The activity Killua is doing", + presence="Killua's presence" + ) + async def presence(self, ctx: commands.Context, text: str, activity: Activities = None, presence: Presences = None): + """Changes the presence of Killua. Owner restricted""" + + if text == "-rm": + DB.const.update_many({"_id": "presence"}, {"$set": {"text": None, "activity": None, "presence": None}}) + await ctx.send("Done! reset Killua's presence", ephemeral=True) + return await self.client.update_presence() + + DB.const.update_many({"_id": "presence"}, {"$set": {"text": text, "presence": presence.name if presence else None, "activity": activity.name if activity else None}}) + await self.client.update_presence() + await ctx.send(f"Successfully changed Killua's status to `{text}`! (I hope people like it >-<)", ephemeral=True) + + @check() + @dev.command(extras={"category":Category.OTHER}, usage="stats ") + @discord.app_commands.describe(type="The type of stats you want to see") + async def stats(self, ctx: commands.Context, type: StatsOptions): + """Shows some statistics about the bot such as growth and command usage""" + if type == type.usage: + await self.initial_top(ctx) + elif type == StatsOptions.growth: + def make_embed(page, embed, _): + embed.clear_fields() + embed.description = "" + + data = DB.const.find_one({"_id": "growth"})["growth"] + + if page == 1: + # Guild growth + return self._get_stats_embed(data, embed, "guilds") + elif page == 2: + # User growth + return self._get_stats_embed(data, embed, "users") + elif page == 3: + # Registered user growth + return self._get_stats_embed(data, embed, "registered_users") + elif page == 4: + # Daily users + return self._get_stats_embed(data, embed, "daily_users") + + return await Paginator(ctx, func=make_embed, max_pages=4, has_file=True).start() + else: + n_of_commands = 0 + + for command in self.client.tree.walk_commands(): + if not isinstance(command, discord.app_commands.Group) and not command.qualified_name.startswith("jishaku"): + n_of_commands += 1 + + data = DB.const.find_one({"_id": "updates"})["updates"] + bot_version = "`Development`" if self.client.is_dev else (data[-1]["version"] if "version" in data[-1] else "`Unknown`") + + now = datetime.now() + diff: timedelta = now - self.client.startup_datetime + time = f"{diff.days} days, {int((diff.seconds/60)/60)} hours, {int(diff.seconds/60)-(int((diff.seconds/60)/60)*60)} minutes and {int(diff.seconds)-(int(diff.seconds/60)*60)} seconds" + + embed = discord.Embed.from_dict({ + "title": "General bot stats", + "fields": [ + {"name": "Bot uptime", "value": time, "inline": True}, + {"name": "Bot users", "value": str(len(self.client.users)), "inline": True}, + {"name": "Bot guilds", "value": str(len(self.client.guilds)), "inline": True}, + {"name": "Registered users", "value": str(DB.teams.count_documents({})), "inline": True}, + {"name": "Bot commands", "value": str(n_of_commands), "inline": True}, + {"name": "Owner id", "value": "606162661184372736", "inline": True}, + {"name": "Latency", "value": f"{int(self.client.latency*100)} ms", "inline": True}, + {"name": "Shard", "value": f"{self.client.shard_id or 0}/{self.client.shard_count}", "inline": True}, + {"name": "Bot version", "value": f"{bot_version}", "inline": True}, + ], + "color": 0x1400ff, + "timestamp": datetime.utcnow().isoformat() + }) + + await ctx.send(embed=embed) + + @check() + @dev.command(extras={"category":Category.OTHER}, usage="info") + async def info(self, ctx: commands.Context): + """Get some general information (lore) about the bot""" + embed = discord.Embed(title="Infos about the bot", description=INFO) + embed.color = 0x1400ff + return await ctx.send(embed=embed, ephemeral=True) + +Cog = Dev diff --git a/tests/killua/cogs/economy.py b/tests/killua/cogs/economy.py new file mode 100644 index 000000000..e2de8aa60 --- /dev/null +++ b/tests/killua/cogs/economy.py @@ -0,0 +1,300 @@ +import discord +from discord.ext import commands +from typing import Union, List, Tuple +from datetime import datetime +from random import randint + +from killua.bot import BaseBot +from killua.utils.checks import check +from killua.utils.interactions import View +from killua.utils.interactions import Select +from killua.utils.classes import User, Guild, LootBox +from killua.static.enums import Category +from killua.static.constants import USER_FLAGS, KILLUA_BADGES, GUILD_BADGES, LOOTBOXES, PREMIUM_ALIASES, DB + +class Economy(commands.Cog): + + def __init__(self, client: BaseBot): + self.client = client + self._init_menus() + + def _init_menus(self) -> None: + menus = [] + menus.append(discord.app_commands.ContextMenu( + name='profile', + callback=self.client.callback_from_command(self.profile, message=False), + # guild_ids=[...], + )) + menus.append(discord.app_commands.ContextMenu( + name='balance', + callback=self.client.callback_from_command(self.jenny, message=False), + )) + + for menu in menus: + self.client.tree.add_command(menu) + + + async def _get_user(self, user_id: int) -> Union[discord.User, None]: + u = self.client.get_user(user_id) + if not u: + u = await self.client.fetch_user(user_id) + return u + + def _fieldify_lootboxes(self, lootboxes: List[int]): + """Creates a list of fields from the lootboxes in the passed list""" + lbs: List[Tuple[int, int]] = [] # A list containing the a tuple with the amount and id of the lootboxes owned + res: List[dict] = [] # The fields to be returned + + for lb in lootboxes: + if not lb in (l:= [y for _, y in lbs]): + lbs.append((1, lb)) + else: + indx = l.index(lb) + lbs[indx] = (lbs[indx][0]+1, lb) + + for lb in lbs: + n, i = lb + data = LOOTBOXES[i] + res.append({"name": f"{n}x {data['emoji']} {data['name']} (id:{i})", "value": data["description"], "inline": False}) + + return res + + def _getmember(self, user: Union[discord.Member, discord.User]) -> discord.Embed: + """A function to handle getting infos about a user for less messy code """ + joined = self.client.convert_to_timestamp(user.id) + + info = User(user.id) + flags = [USER_FLAGS[x[0]] for x in user.public_flags if x[1]] + if (user.avatar and user.avatar.is_animated()) or len([x for x in self.client.guilds if user.id in [y.id for y in x.premium_subscribers]]) > 0: # A very simple nitro check that is not too accurate + flags.append(USER_FLAGS["nitro"]) + badges = [(KILLUA_BADGES[PREMIUM_ALIASES[x]] if x in PREMIUM_ALIASES.keys() else KILLUA_BADGES[x]) for x in info.badges] + + if str(datetime.now()) > str(info.daily_cooldown): + cooldown = "Ready to claim!" + else: + cooldown = f"" + + return discord.Embed.from_dict({ + "title": f"Information about {user}", + "description": f"{user.id}\n{' '.join(flags)}", + "fields": [ + {"name": "Killua Badges", "value": " ".join(badges) if len(badges) > 0 else "No badges", "inline": False}, + {"name": "Jenny", "value": str(info.jenny), "inline": False}, + {"name": "Account created at", "value": joined, "inline": False}, + {"name": "daily cooldown", "value": cooldown or "Never claimed `daily` before", "inline": False} + ], + "thumbnail": {"url": str(user.avatar.url) if user.avatar else None}, + "image": {"url": user.banner.url if user.banner else None}, + "color": 0x1400ff + }) + + def _lb(self, ctx: commands.Context, limit: int = 10) -> dict: + """Creates a list of the top members regarding jenny in a server""" + members = DB.teams.find({"id": {"$in": [x.id for x in ctx.guild.members]} }) + top = sorted(members, key=lambda x: x["points"], reverse=True) # Bringing it in a nice lederboard order + points = 0 + for m in top: + points += m["points"] # Working out total points in the server + + return { + "points": points, + "top": [{"name": ctx.guild.get_member(x["id"]), "points": x["points"]} for x in top][:(limit or len(top))] + } + + async def lootbox_autocomplete( + self, + _: discord.Interaction, + current:str + ) -> List[discord.app_commands.Choice[str]]: + """A function to autocomplete the lootbox name""" + options = [] + for id, lb in LOOTBOXES.items(): + if current in lb["name"]: + options.append(discord.app_commands.Choice(name=lb["name"], value=str(id))) + return options + + @commands.hybrid_group() + async def economy(self, _: commands.Context): + """' commands resolving around jenny, lootboxes and the general economy""" + ... + + @check() + @commands.guild_only() + @economy.command(aliases=["server"], extras={"category":Category.ECONOMY}, usage="guild") + async def guild(self, ctx: commands.Context): + """Displays infos about the current guild""" + top = self._lb(ctx, limit=1) + guild = Guild(ctx.guild.id) + badges = " ".join([GUILD_BADGES[b] for b in guild.badges]) + + embed = discord.Embed.from_dict({ + "title": f"Information about {ctx.guild.name}", + "fields": [ + {"name": "Owner", "value": str(ctx.guild.owner)}, + {"name": "Killua Badges", "value": (badges if len(badges) > 0 else "No badges")}, + {"name": "Combined Jenny", "value": top["points"]}, + {"name": "Richest Member", "value": f"{top['top'][0]['name']} with {top['top'][0]['points']} jenny"}, + {"name": "Server created at", "value": self.client.convert_to_timestamp(ctx.guild.id)}, + {"name": "Members", "value": ctx.guild.member_count} + ], + "description": str(ctx.guild.id), + "thumbnail": {"url": str(ctx.guild.icon.url)}, + "color": 0x1400ff + }) + await self.client.send_message(ctx, embed=embed) + + @check() + @commands.guild_only() + @economy.command(aliases=["lb", "top"], extras={"category":Category.ECONOMY}, usage="leaderboard") + async def leaderboard(self, ctx: commands.Context): + """Get a leaderboard of members with the most jenny""" + top = self._lb(ctx) + if top["points"] == 0: + return await ctx.send(f"Nobody here has any jenny! Be the first to claim some with `{self.client.command_prefix(self.client, ctx.message)[2]}daily`!", allowed_mentions=discord.AllowedMentions.none()) + embed = discord.Embed.from_dict({ + "title": f"Top users on guild {ctx.guild.name}", + "description": "\n".join([f"#{p+1} `{x['name']}` with `{x['points']}` jenny" for p, x in enumerate(top["top"])]), + "color": 0x1400ff, + "thumbnail": {"url": str(ctx.guild.icon.url)} + }) + await self.client.send_message(ctx, embed=embed) + + @check() + @economy.command(aliases=["whois", "p", "user"], extras={"category":Category.ECONOMY}, usage="profile ") + @discord.app_commands.describe(user="The user to get infos about") + async def profile(self, ctx, user: str = None): + """Get infos about a certain discord user with ID or mention""" + if user is None: + res = ctx.author + else: + res = await self.client.find_user(ctx, user) + + if not res: + return await ctx.send(f"Could not find user `{user}`", allowed_mentions=discord.AllowedMentions.none(), ephemeral=True) + + embed = self._getmember(res) + return await self.client.send_message(ctx, embed=embed, ephemeral=hasattr(ctx, "invoked_by_context_menu")) + + @check() + @economy.command(aliases=["bal", "balance", "points"], extras={"category":Category.ECONOMY}, usage="balance ") + @discord.app_commands.describe(user="The user to see the number of jenny of") + async def jenny(self, ctx: commands.Context, user: str = None): + """Gives you a users balance""" + + if not user: + res = ctx.author + else: + res = await self.client.find_user(ctx, user) + + if not res: + return await ctx.send("User not found", ephemeral=True) + + balance = User(res.id).jenny + return await ctx.send(f"{res}'s balance is {balance} Jenny", ephemeral=hasattr(ctx, "invoked_by_context_menu")) + + @check() + @economy.command(extras={"category":Category.ECONOMY}, usage="daily") + async def daily(self, ctx: commands.Context): + """Claim your daily Jenny with this command!""" + now = datetime.now() + user = User(ctx.author.id) + + if str(user.daily_cooldown) > str(now): # When the cooldown is still active + return await ctx.send(f"You can claim your daily Jenny the next time in ") + + min, max = 50, 100 + if user.is_premium: + min, max = min*2, max*2 # Sadly `min, max *= 2` does not work, this is the only way to fit it in one line + if ctx.guild and Guild(ctx.guild.id).is_premium: + min, max = min*2, max*2 + daily = randint(min, max) + if user.is_entitled_to_double_jenny: + daily *= 2 + + user.claim_daily() + user.add_jenny(daily) + await ctx.send(f"You claimed your {daily} daily Jenny and hold now on to {user.jenny}") + + @check() + @economy.command(extras={"category": Category.ECONOMY}, usage="open") + async def open(self, ctx: commands.Context): + """Open a lootbox with an interactive UI""" + if len((user:=User(ctx.author.id)).lootboxes) == 0: + return await ctx.send("Sadly you don't have any lootboxes!") + + lootboxes = self._fieldify_lootboxes(user.lootboxes) + embed = discord.Embed.from_dict({ + "title": "Choose a lootbox to open!", + "fields": lootboxes, + "color": 0x1400ff + }) + lbs = [] + for l in user.lootboxes: + if l not in lbs: + lbs.append(l) + + view = View(ctx.author.id) + select = Select(options=[discord.SelectOption(label=LOOTBOXES[lb]["name"], emoji=LOOTBOXES[lb]["emoji"], value=str(lb), description=d if len((d:=LOOTBOXES[lb]["description"])) < 47 else d[:47] + "...") for lb in lbs], placeholder="Select a box to open") + view.add_item(item=select) + + msg = await ctx.send(embed=embed, view=view) + await view.wait() + + await view.disable(msg) + if view.timed_out: + await ctx.send("Timed out!", ephemeral=True) + + user.remove_lootbox(view.value) + values = LootBox.generate_rewards(view.value) + box = LootBox(ctx, values) + return await box.open() + + @check() + @economy.command(aliases=["lootboxes", "inv"], extras={"category": Category.ECONOMY}, usage="inventory") + async def inventory(self, ctx: commands.Context): + """Displays the owned lootboxes""" + if len((user:=User(ctx.author.id)).lootboxes) == 0: + return await ctx.send("Sadly you don't have any lootboxes!") + + lootboxes = self._fieldify_lootboxes(user.lootboxes) + embed = discord.Embed.from_dict({ + "title": "Lootbox inventory", + "description": f"open a lootbox with `/economy open`", + "color": 0x1400ff, + "fields": lootboxes + }) + embed.timestamp = datetime.now() + await ctx.send(embed=embed) + + @check() + @economy.command(extras={"category": Category.ECONOMY}, usage="boxinfo ") + @discord.app_commands.autocomplete(box=lootbox_autocomplete) + @discord.app_commands.describe(box="The box to get infos about") + async def boxinfo(self, ctx: commands.Context, box: str): + """Get infos about any box you desire""" + if box.isdigit() and not int(box) in LOOTBOXES.keys(): + box = self.client.get_lootbox_from_name(box) + if not box: + return await ctx.send("Invalid box name or id", ephemeral=True) + + data = LOOTBOXES[int(box)] + + c_min, c_max = data["cards_total"] + j_min, j_max = data["rewards"]["jenny"] + contains = f"{data['rewards_total']} total rewards\n{f'{c_min}-{c_max}' if c_max != c_min else c_min} cards\n{j_min}-{j_max} jenny per field\n" + ('' if c_max == 0 else f"card rarities: {' or '.join(data['rewards']['cards']['rarities'])}\ncard types: {' or '.join(data['rewards']['cards']['types'])}") + embed = discord.Embed.from_dict({ + "title": f"Infos about lootbox {data['emoji']} {data['name']}", + "description": data["description"], + "fields": [ + {"name": "Contains", "value": contains, "inline": False}, + {"name": "Price", "value": data["price"], "inline": False}, + {"name": "Buyable", "value": "Yes" if data["available"] else "No"}, + ], + "color": 0x1400ff, + "image": {"url": data["image"]} + }) + await ctx.send(embed=embed) + + +Cog = Economy + diff --git a/tests/killua/cogs/events.py b/tests/killua/cogs/events.py new file mode 100644 index 000000000..a7c4b8d2b --- /dev/null +++ b/tests/killua/cogs/events.py @@ -0,0 +1,446 @@ +import io, re +import sys +import discord + +import logging +import traceback +from datetime import datetime +from discord.ext import commands, tasks +from PIL import Image +from typing import Dict, List, Tuple +from matplotlib import pyplot as plt + +from killua.bot import BaseBot +from killua.utils.classes import Guild, Book +from killua.static.enums import PrintColors +from killua.static.constants import TOPGG_TOKEN, DBL_TOKEN, PatreonBanner, DB, GUILD, MAX_VOTES_DISPLAYED + +class Events(commands.Cog): + + def __init__(self, client: BaseBot): + self.client = client + self.skipped_first = False + self.status_started = False + self.log_channel_id = 718818548524384310 + self.client.startup_datetime = datetime.now() + + @property + def old_commands(self) -> List[str]: + return self._get_old_commands() + + @property + def log_channel(self): + return self.client.get_guild(GUILD).get_channel(self.log_channel_id) + + def _get_old_commands(self) -> List[str]: + """Gets a list of all commands names without and their aliases""" + cmds = [] + for command in self.client.tree.walk_commands(): + if not isinstance(command, discord.app_commands.Group) and not command.name == "help" and\ + not command.qualified_name.startswith("jishaku") and \ + not command.qualified_name.startswith("todo") and \ + not command.qualified_name.startswith("tag"): + cmds.append(command.name) + return cmds + + async def _post_guild_count(self) -> None: + """Posts relevant stats to the botlists Killua is on""" + data = { # The data for discordbotlist + "guilds": len(self.client.guilds), + "users": len(self.client.users) + } + + await self.client.session.post(f"https://discordbotlist.com/api/v1/bots/756206646396452975/stats", headers={"Authorization": DBL_TOKEN}, data=data) + await self.client.session.post(f"https://top.gg/api/bots/756206646396452975/stats", headers={"Authorization": TOPGG_TOKEN}, data={"server_count": len(self.client.guilds)}) + + async def _load_cards_cache(self) -> None: + """Downloads all the card images so the image manipulation is fairly fast""" + cards = [x for x in DB.items.find()] + + if len(cards) == 0: + return logging.error(f"{PrintColors.WARNING}No cards in the database, could not load cache{PrintColors.ENDC}") + + logging.info(f"{PrintColors.WARNING}Loading cards cache....{PrintColors.ENDC}") + percentages = [25, 50, 75] + for p, item in enumerate(cards): + try: + if item["_id"] in Book.card_cache: + continue # in case the event fires multiple times this avoids using unnecessary cpu power + + async with self.client.session.get(item["Image"]) as res: + image_bytes = await res.read() + image_card = Image.open(io.BytesIO(image_bytes)).convert("RGBA") + image_card = image_card.resize((84, 115), Image.ANTIALIAS) + + Book.card_cache[str(item["_id"])] = image_card + if len(percentages) >= 1 and (p/len(cards))*100 > (percent:= percentages[0]): + logging.info(f"{PrintColors.WARNING}Cache loaded {percent}%...{PrintColors.ENDC}") + percentages.remove(percent) + except Exception as e: + logging.error(f"{PrintColors.FAIL}Failed to load card {item['_id']} with error: {e}{PrintColors.ENDC}") + + logging.info(f"{PrintColors.OKGREEN}All cards successfully cached{PrintColors.ENDC}") + + async def _set_patreon_banner(self) -> None: + """Loads the patron banner bytes so it can be quickly sent when needed""" + res = await self.client.session.get(PatreonBanner.URL) + image_bytes = await res.read() + PatreonBanner.VALUE = image_bytes + logging.info(f"{PrintColors.OKGREEN}Successfully loaded patreon banner{PrintColors.ENDC}") + + def print_dev_text(self) -> None: + logging.info(f"{PrintColors.OKGREEN}Running bot in dev enviroment...{PrintColors.ENDC}") + + async def cog_load(self): + #Changing Killua's status + await self._set_patreon_banner() + if self.client.is_dev: + self.print_dev_text() + else: + await self._post_guild_count() + await self._load_cards_cache() + + @commands.Cog.listener() + async def on_message(self, message: discord.Message) -> None: + prefix = "kil!" if self.client.is_dev else (Guild(message.guild.id).prefix if message.guild else "k!") + if message.content.startswith(prefix): + if message.content[len(prefix):].split(" ")[0] in self.old_commands: + return await message.reply("This command has been moved over to a command group, check `/help` to find the new command and `/dev update` to see what's changing with Killua.", allowed_mentions=discord.AllowedMentions.none()) + + @commands.Cog.listener() + async def on_ready(self): + self.save_guilds.start() + if not self.status_started: + self.status.start() + self.status_started = True + + logging.info(PrintColors.OKGREEN + "Logged in as: " + self.client.user.name + f" (ID: {self.client.user.id})" + PrintColors.ENDC) + + @tasks.loop(hours=12) + async def status(self): + await self.client.update_presence() # For some reason this does not work in cog_load because it always fires before the bot is connected and + # thus throws an error so I have to do it a bit more hacky in here + if not self.client.is_dev: + await self._post_guild_count() + + @status.before_loop + async def before_status(self): + await self.client.wait_until_ready() + + @tasks.loop(hours=24) + async def save_guilds(self): + from killua.static.constants import daily_users + + if not self.client.is_dev and self.skipped_first: + DB.const.update_one({"_id": "growth"}, {"$push": {"growth": {"date": datetime.now() ,"guilds": len(self.client.guilds), "users": len(self.client.users), "registered_users": DB.teams.count_documents({}), "daily_users": len(daily_users)}}}) + daily_users = [] # Resetting the daily users list lgtm [py/unused-local-variable] + elif not self.skipped_first: # We want to avoid saving data each time the bot restarts, start 24h after one + self.skipped_first = True + + @commands.Cog.listener() + async def on_guild_join(self, guild): + #Changing the status + await self.client.update_presence() + Guild.add_default(guild.id) + + @commands.Cog.listener() + async def on_guild_remove(self, guild): + #Changing Killua's status + await self.client.update_presence() + Guild(guild.id).delete() + await self._post_guild_count() + + @commands.Cog.listener() + async def on_member_join(self, member: discord.Member): + # Welcomes new member + if not self.client.is_dev and member.guild.id == GUILD: # In theory it would be cool if the dev bot welcomed you but it just isn't always online + embed = discord.Embed.from_dict({ + "title": "Welcome to the Killua support server a.k.a. Kile's dev!", + "description": "You joined. What now?\n\n**Where to go**\n" + \ + "┗ <#1019657047568035841> to recieve help or report bugs\n" + \ + "┗ <#787819439596896288> To get some ping roles\n" +\ + "┗ <#886546434663538728> Good place to check before asking questions\n" +\ + "┗ <#754063177553150002> To see newest announcements\n" +\ + "┗ <#757170264294424646> Read up on the newest Killua updates\n" +\ + "┗ <#716357592493981707> Use bots in here\n" +\ + "┗ <#811903366925516821> Check if there is any known outage/bug\n\n" +\ + "Thanks for joining and don't forget to vote for Killua! :)", + "color": 0x1400ff, + }) + embed.set_thumbnail(url=self.client.user.avatar.url if self.client.user else None) + embed.timestamp = datetime.now() + + await self.log_channel.send(content=member.mention, embed=embed) + # try: + # await member.send(embed=embed) + # except discord.Forbidden: + # pass + + def _create_piechart(self, data: List[list], title: str) -> discord.File: + """Creates a piechart with the given data""" + data = [l for l in data if l[1] > 0] # We want to avoid a 0% slice + + labels = [x[0] for x in data] + values = [x[1] for x in data] + colours = [x[2] for x in data] + buffer = io.BytesIO() + plt.pie(values, labels=labels, autopct="%1.1f%%", shadow=True, textprops={'color':"w"}, colors=colours) + plt.title(title, fontdict={"color": "w"}) + plt.axis("equal") + plt.tight_layout() + plt.savefig(buffer, format="png", transparent=True) + buffer.seek(0) + plt.close() + file = discord.File(buffer, filename="piechart.png") + return file + + def find_counter_start(self, title: str) -> int: + """Finds where the counter in a poll title starts""" + revers = title[::-1] + for i, char in enumerate(revers): + if char == "`" and revers[i-1] == "[": + return i+1 + + @commands.Cog.listener() + async def on_interaction(self, interaction: discord.Interaction): + if interaction.type == discord.InteractionType.component: + if interaction.data["custom_id"] and (interaction.data["custom_id"].startswith("poll:") or interaction.data["custom_id"].startswith("wyr:")): + # for component in interaction.message.components[0].children: + # print("Before: ", component.custom_id) + + if interaction.data["custom_id"].split(":")[2].isdigit(): # Backwards compatability + split = interaction.data["custom_id"].split(":") + _p = split[0] + action = split[1] + opt_votes = "" + else: + split = interaction.data["custom_id"].split(":") + _p = split[0] + action = split[1] + opt_votes = split[2] + + poll = _p == "poll" # As the logic for polls and wyr overlaps we can use the same code for both, just need to differentiate for a few small things + + guild = Guild(interaction.guild_id) + saved = guild.is_premium and poll + + if saved: + author = guild.polls[str(interaction.message.id)]["author"] + else: + author = interaction.message.components[0].children[-1].custom_id.split(":")[2] + + if action.startswith("opt"): + + if self.client._encrypt(interaction.user.id, smallest=False) == author or str(author).isdigit() and interaction.user.id == int(author): + return await interaction.response.send_message("You cannot vote in your own poll!", ephemeral=True) + + option = int(action.split("-")[1]) if poll else {"a": 1, "b": 2}[action.split("-")[1]] + + if not saved: # Determines votes etc from custom ids + votes: Dict[int, Tuple[list, list]] = {} + + old_close = interaction.message.components[0].children[-1].custom_id # as this value is modified in the loop the original value needs to be saved to check it + for pos, field in enumerate(interaction.message.embeds[0].fields): + child = interaction.message.components[0].children[pos] + votes[pos] = [int(v.replace("<@", "").replace(">", "")) for v in field.value.split("\n") if re.match(r"<@!?([0-9]+)>", v)], [v for v in child.custom_id.split(":")[2].split(",") if v != ""] if not child.custom_id.split(":")[2].isdigit() else [] + encrypted = self.client._encrypt(interaction.user.id) + + if (interaction.user.id in votes[pos][0] or encrypted in votes[pos][1] or re.findall(rf";{pos+1};[^;:]*{encrypted}(.*?)[;:]", old_close)) and pos == option-1: + return await interaction.response.send_message(f"You already {'voted for' if poll else 'chose'} this option!", ephemeral=True) + + if interaction.user.id in votes[pos][0]: + votes[pos][0].remove(interaction.user.id) + elif encrypted in votes[pos][1] or encrypted in interaction.message.components[0].children[-1].custom_id: + # find component and remove the vote + for component in interaction.message.components[0].children: + + if not (encrypted in component.custom_id): + continue + + component.custom_id = re.sub(rf"{encrypted},?", "", component.custom_id) + + if encrypted in votes[pos][1]: # Strange that I have to put this check in here again but it sometimes fails without it + votes[pos][1].remove(encrypted) + + if len(votes[option-1][0]) < MAX_VOTES_DISPLAYED: + votes[option-1][0].append(interaction.user.id) + elif len(interaction.data["custom_id"] + encrypted) <= 100: + votes[option-1][1].append(encrypted) + interaction.message.components[0].children[option-1].custom_id = _p + ":" + action + ":" + opt_votes + ("," if opt_votes else "") + encrypted + elif len(interaction.message.components[0].children[-1].custom_id) + len(encrypted) + (0 if str(option) in interaction.message.components[0].children[-1].custom_id else 2) <= 100 and poll: + # using regex it will find a free space after ;{option}; to put it in + # first finding the current thing after ;{option}; + found = re.findall(rf";{option};([^;:]*)", interaction.message.components[0].children[-1].custom_id) + if not found: # If the option has not been added yet + custom_id = interaction.message.components[0].children[-1].custom_id.split(":") + interaction.message.components[0].children[-1].custom_id = custom_id[0] + ":" + custom_id[1] + ":" + custom_id[2] + ":" + custom_id[3] + "" + f";{option};{encrypted}" + ":" + else: + if len(found[0]) > 0: # If other users have voted for this option + found_items = str(found[0]).split(",") + found_items.append(encrypted) + interaction.message.components[0].children[-1].custom_id = interaction.message.components[0].children[-1].custom_id.replace(str(found[0]), ",".join(found_items)) + else: # If the number exists but with no votes + interaction.message.components[0].children[-1].custom_id = interaction.message.components[0].children[-1].custom_id.replace(f";{option};",f";{option};{encrypted}") + else: + view = discord.ui.View() + view.add_item(discord.ui.Button(style=discord.ButtonStyle.link, label="Get Premium", url="https://patreon.com/kilealkuri")) + if poll: + return await interaction.response.send_message(f"The maximum votes on this {'poll' if poll else 'wyr'} has been reached! Make this a premium server to allow more votes! Please that votes started before becomind a premium server will still not be able to recieve more votes.", ephemeral=True, view=view) + else: + return await interaction.response.send_message(f"The maximum votes on this {'poll' if poll else 'wyr'} has been reached!", ephemeral=True) + else: + votes: Dict[int, list] = guild.polls[str(interaction.message.id)]["votes"] + + for pos, field in enumerate(interaction.message.embeds[0].fields): + if interaction.user.id in votes[str(pos)] and pos == option-1: + return await interaction.response.send_message(f"You already {'voted for' if poll else 'chose'} this option!", ephemeral=True) + + if interaction.user.id in votes[str(pos)]: + votes[str(pos)].remove(interaction.user.id) + + votes[str(option-1)].append(interaction.user.id) + + guild.update_poll_votes(interaction.message.id, votes) + + embed = interaction.message.embeds[0] + + new_embed = discord.Embed(title=embed.title, description=embed.description, color=embed.color) + new_embed.set_footer(text=embed.footer.text, icon_url=embed.footer.icon_url) + if embed.thumbnail: + new_embed.set_thumbnail(url=embed.thumbnail.url) + + for pos, field in enumerate(embed.fields): + if not saved: # Calculate poll votes if it is not saved + close_votes = re.findall(rf";{pos+1};(.*?)[;:]", interaction.message.components[0].children[-1].custom_id) + num_of_votes = len(votes[pos][0]) + len(votes[pos][1]) + (len([f for f in str(close_votes[0]).split(",") if f != ""]) if close_votes else 0) + new_name = field.name[:-self.find_counter_start(field.name)] + f"`[{num_of_votes} " + (f"vote{'s' if num_of_votes != 1 else ''}" if poll else f"{'people' if num_of_votes != 1 else 'person'}") + "]`" + if not votes[pos][1]: + value = "\n".join([f"<@{v}>" for v in votes[pos][0]]) if votes[pos][0] else ("No votes" if poll else "No takers") + else: + cancel_votes = re.findall(rf";{option};([^;:]*)", interaction.message.components[0].children[-1].custom_id) + additional_votes = len(votes[pos][1]) + (len(cancel_votes[0].split(",")) if cancel_votes else 0) + value = "\n".join([f"<@{v}>" for v in votes[pos][0]]) + f"\n*+ {additional_votes} more...*" + else: + num_of_votes = len(votes[str(pos)]) + new_name = field.name[:-self.find_counter_start(field.name)] + f"`[{num_of_votes} " + (f"vote{'s' if num_of_votes != 1 else ''}" if poll else f"{'people' if num_of_votes != 1 else 'person'}") + "]`" + if len(votes[str(pos)]) > MAX_VOTES_DISPLAYED: + value = "\n".join([f"<@{v}>" for v in votes[str(pos)][:MAX_VOTES_DISPLAYED]]) + f"\n*+ {len(votes[str(pos)])-MAX_VOTES_DISPLAYED} more...*" + else: + value = "\n".join([f"<@{v}>" for v in votes[str(pos)]]) if votes[str(pos)] else ("No votes" if poll else "No takers") + new_embed.add_field(name=new_name, value=value, inline=False) + + # for component in interaction.message.components[0].children: + # print("After: ", component.custom_id) + + new_view = discord.ui.View() + + for component in interaction.message.components[0].children: + d = component.to_dict() + del d["type"] + d["style"] = discord.ButtonStyle(d["style"]) + new_view.add_item(discord.ui.Button(**d)) + await interaction.response.edit_message(embed=new_embed, view=new_view) + + elif action == "close": + # poll_creator = interaction.message.components[0].children[-1].custom_id.split(":")[2] + if not (self.client._encrypt(interaction.user.id, smallest=False) == author or str(author).isdigit() and interaction.user.id == int(author)): + return await interaction.response.send_message("Only the polll author can close this poll!", ephemeral=True) + + # Create a piechart with the results + colours = ["#6aaae8", "#84ae62", "#a58fd0", "#e69639"] + if not saved: + data = [ + [ + f"Option {pos+1}", # Calculate the number of votes for each option + 0 if field.value == "No votes" else len(field.value.split("\n")) + \ + len(interaction.message.components[0].children[pos].custom_id.split(":")[2].split(",")) - \ + 1 if len(field.value.split("\n")) > MAX_VOTES_DISPLAYED else 0 + \ + + (len(str(close_votes[0]).split(",")) if (close_votes := re.findall(rf";{pos};[^;:]*", interaction.message.components[0].children[-1].custom_id)) else 0), + colours[pos] + ] + for pos, field in enumerate(interaction.message.embeds[0].fields) + ] + else: + votes: Dict[int, list] = guild.polls[str(interaction.message.id)]["votes"] + data = [ + [ + f"Option {pos+1}", + len(votes[str(pos)]), + colours[pos] + ] + for pos, _ in enumerate(interaction.message.embeds[0].fields) + ] + + if not data: + return await interaction.response.send_message("There are no votes for this poll!", ephemeral=True) + + piechart = self._create_piechart(data, interaction.message.embeds[0].description) + + new_embed = discord.Embed(title=interaction.message.embeds[0].title + " [closed]", description=interaction.message.embeds[0].description, color=interaction.message.embeds[0].color) + new_embed.set_image(url="attachment://piechart.png") + + colour_emotes = ["\U0001f535", "\U0001f7e2", "\U0001f7e3", "\U0001f7e0"] + for pos, field in enumerate(interaction.message.embeds[0].fields): + new_embed.add_field(name=field.name + f" {colour_emotes[pos]}", value=field.value, inline=False) + + new_view = discord.ui.View() + for button in interaction.message.components[0].children: + new_button = discord.ui.Button(label=button.label, style=button.style, disabled=True) + new_view.add_item(new_button) + + if saved: + guild.close_poll(str(interaction.message.id)) + + await interaction.message.delete() + await interaction.response.send_message(embed=new_embed, file=piechart, view=new_view) + + @commands.Cog.listener() + async def on_command_error(self, ctx: commands.Context, error): + + if ctx.channel.permissions_for(ctx.me).send_messages is False and not self.client.is_dev: # we don't want to raise an error inside the error handler when Killua ' send the error because that does not trigger `on_command_error` + return + + if ctx.command: + usage = f"`{self.client.command_prefix(self.client, ctx.message)[2]}{(ctx.command.parent.name + ' ') if ctx.command.parent else ''}{ctx.command.usage}`" + + if isinstance(error, commands.BotMissingPermissions): + return await ctx.send(f"I don't have the required permissions to use this command! (`{', '.join(error.missing_permissions)}`)") + + if isinstance(error, commands.MissingPermissions): + return await ctx.send(f"You don't have the required permissions to use this command! (`{', '.join(error.missing_permissions)}`)") + + if isinstance(error, commands.MissingRequiredArgument): + return await ctx.send(f"Seems like you missed a required argument for this command: `{str(error.param).split(':')[0]}`") + + if isinstance(error, commands.UserInputError): + return await ctx.send(f"Seems like you provided invalid arguments for this command. This is how you use it: {usage}", allowed_mentions=discord.AllowedMentions.none()) + + if isinstance(error, commands.NotOwner): + return await ctx.send("Sorry, but you need to be the bot owner to use this command") + + if isinstance(error, commands.BadArgument): + return await ctx.send(f"Could not process arguments. Here is the command should be used: {usage}", allowed_mentions=discord.AllowedMentions.none()) + + if isinstance(error, commands.NoPrivateMessage): + return await ctx.send("This command can only be used inside of a guild") + + if isinstance(error, commands.CommandNotFound) or isinstance(error, commands.CheckFailure): # I don't care if this happens + return + + view = discord.ui.View() + view.add_item(discord.ui.Button(label="Report bug", url=self.client.support_server_invite)) + await ctx.send(":x: an unexpected error occured. If this should keep happening, please report it by clicking on the button and using `/report` in the support server.", view=view) + + if self.client.is_dev: # prints the full traceback in dev enviroment + logging.error(PrintColors.FAIL + "Ignoring exception in command {}:".format(ctx.command)) + traceback.print_exception(type(error), error, error.__traceback__, file=sys.stderr) + return print(PrintColors.ENDC) + + else: + guild = ctx.guild.id if ctx.guild else "dm channel with "+ str(ctx.author.id) + command = ctx.command.name if ctx.command else "Error didn't occur during a command" + logging.error(f"{PrintColors.FAIL}------------------------------------------") + logging.error(f"An error occurred\nGuild id: {guild}\nCommand name: {command}\nError: {error}") + logging.error(f"------------------------------------------{PrintColors.ENDC}") + +Cog = Events \ No newline at end of file diff --git a/tests/killua/cogs/games.py b/tests/killua/cogs/games.py new file mode 100644 index 000000000..5410823cc --- /dev/null +++ b/tests/killua/cogs/games.py @@ -0,0 +1,694 @@ +import discord +from discord.ext import commands + +import re +import random +import asyncio +import math +from aiohttp import ClientSession +from urllib.parse import unquote +from typing import Union, List, Tuple, Literal + +from killua.bot import BaseBot +from killua.utils.paginator import View +from killua.utils.classes import CardLimitReached, User +from killua.utils.interactions import ConfirmButton +from killua.static.cards import Card +from killua.static.enums import Category, TriviaDifficulties, CountDifficulties, GameOptions +from killua.static.constants import ALLOWED_AMOUNT_MULTIPLE, DB +from killua.utils.checks import blcheck, check +from killua.utils.interactions import Select, Button + +leaderboard_options = [ + discord.app_commands.Choice(name="global", value="global"), + discord.app_commands.Choice(name="server", value="server") +] + +class PlayAgainButton(discord.ui.Button): + def __init__(self, **kwargs): + super().__init__(**kwargs) + self.label = "Play Again" + self.__clicked = None + self.custom_id = "play_again" + + async def callback(self, interaction: discord.Interaction): + + if not self.__clicked: + self.label = "[1/2] Play Again" + self.__clicked = interaction.user + await interaction.response.edit_message(view=self.view) + + else: + if self.__clicked == interaction.user: + self.label = "Play Again" + self.__clicked = None + await interaction.response.edit_message(view=self.view) + else: + self.label = "[2/2] Play Again" + self.view.value = True + await interaction.response.edit_message(view=self.view) + self.view.stop() + + +class RpsSelect(discord.ui.Select): + """Creates a select menu to confirm an rps choice""" + def __init__(self, options, **kwargs): + super().__init__( + min_values=1, + max_values=1, + options=options, + **kwargs + ) + + async def callback(self, interaction: discord.Interaction): + self.view.value = int(interaction.data["values"][0]) + for opt in self.options: + if opt.value == str(self.view.value): + opt.default = True + self.disabled = True + await interaction.response.edit_message(view=self.view) + self.view.stop() + +class Trivia: + """Handles a trivia game""" + + def __init__(self, ctx: commands.Context, difficulty: str, session: ClientSession): + self.url = f"https://opentdb.com/api.php?amount=1&difficulty={difficulty}&type=multiple" + self.difficulty = difficulty.lower() + self.session = session + self.ctx = ctx + self.timed_out = False + self.result = None + self.rewards = { + "easy": (5, 10), + "medium": (10, 20), + "hard": (20, 30) + } + + async def _get(self) -> dict: + """Requests the trivia url""" + res = await self.session.get(self.url) + self.res = await res.json() + self.failed = (self.res["response_code"] != 0) + + def _create_embed(self) -> discord.Embed: + """Creates the trivia embed""" + question = unquote(self.data["question"]) + question = re.sub("&.*?;", "", question) # Yes, apparently unqote is not enough to remove all html entities + self.embed = discord.Embed.from_dict({ + "title": f"Trivia of category {self.data['category']}", + "description": f"**difficulty:** {self.data['difficulty']}\n\n**Question:**\n{question}", + "color": 0x1400ff + }) + + def _create_view(self) -> None: + """Creates a select with the options needed""" + self.view = View(self.ctx.author.id) + self.data["incorrect_answers"].append(self.data["correct_answer"]) + self.options = random.sample(self.data["incorrect_answers"], k=4) + self.correct_index = self.options.index(self.data["correct_answer"]) + self.view.add_item(Select(options=[discord.SelectOption(label=x if len(x) < 50 else x[:47] + "...", value=str(i)) for i, x in enumerate(self.options)])) + + async def create(self) -> None: + """Creates all properties necessary""" + await self._get() + if not self.failed: + self.data = self.res["results"][0] + self._create_embed() + self._create_view() + + async def send(self) -> Union[discord.Message, None]: + """Sends the embed and view and awaits a response""" + if self.failed: + return await self.ctx.send(":x: There was an issue with the API. Please try again. If this should happen frequently, please report it") + self.msg = await self.ctx.bot.send_message(self.ctx, embed=self.embed, view=self.view) + await self.view.wait() + await self.view.disable(self.msg) + + if not hasattr(self.view, "value"): + self.timed_out = True + else: + self.result = self.view.value + + async def send_result(self) -> None: + """Sends the result of the trivia and hands out jenny as rewards""" + user = User(self.ctx.author.id) + + if self.failed: + return + + elif self.timed_out: + await self.ctx.send("Timed out!", reference=self.msg) + + elif self.result != self.correct_index: + user.add_trivia_stat("wrong", self.difficulty) + await self.ctx.send(f"Sadly not the right answer! The answer was {self.correct_index+1}) {self.options[self.correct_index]}") + + else: + rew = random.randint(*self.rewards[self.difficulty]) + if user.is_entitled_to_double_jenny: + rew *= 2 + user.add_jenny(rew) + user.add_trivia_stat("right", self.difficulty) + await self.ctx.send(f"Correct! Here are {rew} Jenny as a reward!") + + +class Rps: + """A class handling someone playing rps alone or with someone else""" + def __init__(self, ctx: commands.Context, points: int = None, other: discord.Member = None): + self.ctx = ctx + self.points = points + self.other = other + self.emotes = { + 0: ":page_facing_up:", + -1: ":moyai:", + 1: ":scissors:" + } + + async def _dmcheck(self, user: discord.User) -> bool: + """Checks if a users dms are open by sending them an empty message and either recieving an error for can't send an empty message or not allowed""" + try: + await user.send("") + except Exception as e: + if isinstance(e, discord.Forbidden): + return False + if isinstance(e, discord.HTTPException): + return True + return True + + def _get_options(self) -> List[discord.SelectOption]: + """Returns a new instance of the option list so itdoesn't get mixed up when editing""" + return [discord.SelectOption(label="rock", value="-1", emoji="\U0001f5ff"), discord.SelectOption(label="paper", value="0", emoji="\U0001f4c4"), discord.SelectOption(label="scissors", value="1", emoji="\U00002702")] + + def _result(self, p: int, q: int) -> int: + """Evaluates who won, by doing very smart math. -1 means player p won, 0 means it was a tie, 1 means player q won""" + return int(math.sin(math.pi/12*(q-p)*((q-p)**2+5))) + + async def _send_rps_embed(self) -> discord.Message: + """Sends a confirming embed""" + embed = discord.Embed.from_dict({ + "title": f"{self.ctx.author.display_name} against {self.other.display_name or self.ctx.me.display_name}: **Rock... Paper... Scissors!**", + "image": {"url": "https://media1.tenor.com/images/dc503adb8a708854089051c02112c465/tenor.gif?itemid=5264587"}, + "color": 0x1400ff + }) + + await self.ctx.bot.send_message(self.ctx, embed=embed) + + async def _timeout(self, players: list, data: List[Tuple[discord.Message, View]]) -> None: + """A way to handle a timeout of not responding to Killua in dms""" + for x in players: + if x.id in [v.user.id for _, v in data if v.value is not None]: + await x.send("Sadly the other player has not responded in time") + else: + await x.send("Too late, time to respond is up!") + + async def _wait_for_response(self, users: List[discord.Member]) -> Union[None, List[View]]: + data = [] + for u in users: + view = View(user_id=u.id, timeout=None) + select = RpsSelect(options=self._get_options()) + view.add_item(select) + view.user = u + msg = await u.send("You chose to play Rock Paper Scissors, what's your choice Hunter?", view=view) + data.append((msg, view)) + + done, pending = await asyncio.wait([v.wait() for _, v in data], return_when=asyncio.ALL_COMPLETED, timeout=100) + + for m, v in data: + await v.disable(m) + + if False in [x.done() == True for x in [*done, *pending]]: + # Handles the case that one or both players don't respond to the dm in time + return await self._timeout(users, data) + + return [v for _, v in data] + + async def check_for_achivement(self, player: discord.User) -> None: + """Checks wether someone has earend the "rps master" achivement""" + user = User(player.id) + if not "rps_master" in user.achievements and user.rps_stats["pve"]["won"] >= 25: + user.add_achievement(["rps_master"]) + card = Card(83) + try: + if len(card.owners) >= (card.limit * ALLOWED_AMOUNT_MULTIPLE): + user.add_jenny(1000) + await player.send(f"By defeating me 25 times you have earned the **RPS Master** achievemt! Sadly the normal reward, the card \"{card.name}\" {card.emoji}, is currently owned by too many people, so insead you get **1000 Jenny** as a reward!") + else: + user.add_card(83) + await player.send(f"By defeating me 25 times you have earned the **RPS Master** achievemt! As a reward you recieve the card \"{card.name}\" {card.emoji}") + except CardLimitReached: + user.add_jenny(1000) + await player.send(f"By defeating me 25 times you have earned the **RPS Master** achievemt! Sadly you have no space in your book for the normal reward, the card \"{card.name}\" {card.emoji}, so insead you get **1000 Jenny** as a reward!") + + async def _eval_outcome(self, winlose: int, choice1: int, choice2: int, player1:discord.Member, player2: discord.Member, view: View) -> discord.Message: + """Evaluates the outcome, informs the players and handles the points """ + p1 = User(player1.id) + p2 = User(player2.id) + if winlose == -1: + p1.add_rps_stat("won", player2 == self.ctx.me) + p2.add_rps_stat("lost", player1 == self.ctx.me) + await self.check_for_achivement(player1) + + if self.points: + p1.add_jenny(self.points) + if player2 != self.ctx.me: + p2.remove_jenny(self.points) + return await self.ctx.send(f"{self.emotes[choice1]} > {self.emotes[choice2]}: {player1.mention} won against {player2.mention} winning {self.points} Jenny which adds to a total of {p1.jenny}", view=view) + else: + return await self.ctx.send(f"{self.emotes[choice1]} > {self.emotes[choice2]}: {player1.mention} won against {player2.mention}", view=view) + + elif winlose == 0: + p1.add_rps_stat("tied", player2 == self.ctx.me) + if player2 != self.ctx.me: + p2.add_rps_stat("tied", player1 == self.ctx.me) + return await self.ctx.send(f"{self.emotes[choice1]} = {self.emotes[choice2]}: {player1.mention} tied against {player2.mention}", view=view) + + elif winlose == 1: + p1.add_rps_stat("lost", player2 == self.ctx.me) + p2.add_rps_stat("won", player1 == self.ctx.me) + await self.check_for_achivement(player2) + + if self.points: + p1.remove_jenny(self.points, player2 == self.ctx.me) + if player2 != self.ctx.me: + p2.add_jenny(self.points) + return await self.ctx.send(f"{self.emotes[choice1]} < {self.emotes[choice2]}: {player1.mention} lost against {player2.mention} losing {self.points} Jenny which leaves them a total of {p1.jenny}", view=view) + else: + return await self.ctx.send(f"{self.emotes[choice1]} < {self.emotes[choice2]}: {player1.mention} lost against {player2.mention}", view=view) + + def _play_again_view(self, players: List[discord.Member]) -> View: + """Creates a button that, if clicked by both players, automatically launches another game""" + view = View(user_id=[x.id for x in players]) + button = PlayAgainButton() + view.add_item(button) + return view + + async def singleplayer(self) -> Union[None, discord.Message]: + """Handles the case of the user playing against the bot""" + await self._send_rps_embed() + + resp = await self._wait_for_response([self.ctx.author]) + if not resp: + return + + c2 = random.randint(-1, 1) + winlose = self._result(resp[0].value, c2) + + view = View(user_id=self.ctx.author.id) + button = Button(label="Play again", style=discord.ButtonStyle.grey) + view.add_item(button) + + msg =await self._eval_outcome(winlose, resp[0].value, c2, self.ctx.author, self.ctx.me, view) + + await view.wait() + await view.disable(msg) + if not view.value or view.timed_out: + pass + else: + await self.singleplayer() + + async def multiplayer(self, replay: bool = False) -> Union[None, discord.Message]: + """Handles the case of the user playing against self.other user""" + if not replay: + if await self._dmcheck(self.ctx.author) is False: + return await self.ctx.send(f"You need to open your dm to Killua to play {self.ctx.author.mention}") + if await self._dmcheck(self.other) is False: + return await self.ctx.send(f"{self.other.name} needs to open their dms to Killua to play") + + if blcheck(self.other.id) is True: + return await self.ctx.send("You can't play against someone blacklisted") + + view = ConfirmButton(self.other.id, timeout=80) + msg = await self.ctx.send(f"{self.ctx.author.mention} challenged {self.other.mention} to a game of Rock Paper Scissors! Will **{self.other}** accept the challange?", view=view) + await view.wait() + await view.disable(msg) + + if not view.value: + if view.timed_out: + return await self.ctx.send(f"Sadly no response...") + else: + return await self.ctx.send(f"{self.other.display_name} doesn't want to play... maybe they do after a hug?") + + await self._send_rps_embed() + res = await self._wait_for_response([self.ctx.author, self.other]) + if not res: + return + winlose = self._result(res[0].value, res[1].value) + + view = self._play_again_view([self.ctx.author, self.other]) + msg = await self._eval_outcome(winlose, res[0].value, res[1].value, res[0].user, res[1].user, view) + await view.wait() + await view.disable(msg) + if not view.value or view.timed_out: + pass + else: + await self.multiplayer(replay=True) + + + async def start(self) -> None: + """The function starting the game""" + if self.other == self.ctx.me: + await self.singleplayer() + else: + await self.multiplayer() + +class CountButtons(discord.ui.Button): + """The code for every button used in the game""" + def __init__(self, solutions: dict, index: int, correct: bool = None, **kwargs): + self.index = index # the position the button is on. Starts with 1 + self.solutions = solutions # The solutions in the format {number: correct_button_index} + self.correct = correct # If the button is correct + super().__init__(style=discord.ButtonStyle.grey if correct is None else (discord.ButtonStyle.green if correct else discord.ButtonStyle.red), **kwargs) + + def _create_view(self, correct: bool) -> View: + """Creates a new view after the callback depending on if the result was correct or not""" + for c in self.view.children: + if correct: + c.correct=True if c.index == self.index else c.correct + c.disabled=True if c.index == self.index or self.view.stage-1 == len(self.solutions) else c.disabled + c.label=str(self.view.stage-1) if c.index == self.index else c.label + c.style=discord.ButtonStyle.success if c.index == self.index else c.style + else: + c.correct=False if c.index == self.index else c.correct + c.disabled=True + c.label=str(self.view.stage) if c.index == self.solutions[self.view.stage] else c.label + c.style=discord.ButtonStyle.red if c.index == self.index else c.style + + return self.view + + async def _respond(self, correct: bool, last: bool, view: View, interaction: discord.Interaction) -> discord.Message: + """Responds with the new view""" + if correct and last: + return await interaction.response.edit_message(content="Congrats, you move on to the next level!", view=view) + if not correct: + return await interaction.response.edit_message(content="Oh no! This was not the right order! Better luck next time", view=view) + if not last: + return await interaction.response.edit_message(content="Can you remember?", view=view) + + async def callback(self, interaction: discord.Interaction): + """Is called when a button is clicked and determines wether it was correct or not, then passes that on to other functions""" + self.view.correct = self.solutions[self.view.stage] == self.index # if the button was correct + last: bool = self.view.stage == len(self.solutions) # if this is the last stage + + if self.view.correct: + self.view.stage += 1 + + view = self._create_view(self.view.correct) + await self._respond(self.view.correct, last, view, interaction) + + if not self.view.correct or last: + self.view.stop() + +class CountGame: + """A game where you have to remember numbers and type them in the right order""" + def __init__(self, ctx: commands.Context, difficulty: str): + self.ctx = ctx + self.user = User(ctx.author.id) + self.difficulty = difficulty + self.level = 1 + + def _handle_reward(self) -> int: + """Creates a jenny reward based on the level and difficulty""" + return ((2 if self.user.is_entitled_to_double_jenny else 1) * int(random.randint(20, 30) * self.level * (0.5 if self.difficulty == "easy" else 1))) if self.level > 1 else 0 + + def _assign_until_unique(self, already_assigned: List[int]) -> int: + """Picks one random free spot to put the next number in""" + r = random.randint(1, 25) + if r in already_assigned: + return self._assign_until_unique(already_assigned) + else: + return r + + def _create_solutions(self, keep_used: bool) -> None: + """Creates the solution dictionary""" + res: dict = (self.solutions if hasattr(self, "solutions") else {}) if keep_used else {} + for i in range(1 if keep_used else self.level): + res[len(res)+1 if keep_used else i+1] = self._assign_until_unique(list(res.values())) + self.solutions = res + + async def _send_solutions(self, msg: discord.Message = None) -> discord.Message: + """Sends the solutions before hiding them""" + view = View(self.ctx.author.id) + view.stage = 1 + for i in range(25): + view.add_item(discord.ui.Button(label=str([k for k, v in self.solutions.items() if v-1 == i][0]) if i+1 in list(self.solutions.values()) else " ", disabled=True, style=discord.ButtonStyle.grey)) + if not msg: + msg = await self.ctx.bot.send_message(self.ctx, content="Press the buttons in the order displayed as soon as the time starts. Good luck!", view=view) + else: + await msg.edit(content="One more button to remember. Get ready!", view=view) + + await asyncio.sleep(3 if self.level == 1 else (self.level*2*(0.5 if self.difficulty == "easy" else 1))) + return msg + + async def _handle_game(self, msg: discord.Message) -> discord.Message: + """The core of the game, creates the buttons and waits until the buttons return a result and handles it""" + view = View(self.ctx.author.id, timeout=self.level*10*(0.5 if self.difficulty == "easy" else 1)) + view.stage = 1 + for i in range(25): + view.add_item(CountButtons(self.solutions, i+1, label=" ", custom_id=str(i+1))) + await msg.edit(content="Can you remember?", view=view) + await view.wait() + + if not hasattr(view, "correct") or not view.correct: # This happens when the user has lost the game or it timed out + reward = self._handle_reward() + resp = "Too slow!" if not hasattr(view, "correct") else "Wrong choice!" + for child in view.children: + child.disabled = True + await msg.edit(view=view) + self.user.add_jenny(reward) + + if self.level-1 > self.user.counting_highscore[self.difficulty]: + self.user.set_counting_highscore(self.difficulty, self.level-1) + return await self.ctx.send(resp + " But well done, you made it to level " + str(self.level) + ", your new **personal best**, which brings you a reward of " + str(reward) + " Jenny!") + else: + return await self.ctx.send(resp + " But well done, you made it to level " + str(self.level) + ", which brings you a reward of " + str(reward) + " Jenny!") + + + self.level += 1 + + if self.level == 26: + reward = self._handle_reward() + return await self.ctx.send("Well done, you completed the game! Your reward is " + str(reward) + " Jenny. Keep up the great work!") + + await asyncio.sleep(5) + self._create_solutions(self.difficulty == "easy") + new_msg = await self._send_solutions(msg) + await self._handle_game(new_msg) + + async def start(self): + """The function to call to start the game""" + self._create_solutions(self.difficulty == "easy") + msg = await self._send_solutions() + await self._handle_game(msg) + +class Games(commands.Cog): + + def __init__(self, client: BaseBot): + self.client = client + + @commands.hybrid_group() + async def games(self, _: commands.Context): + """A collection of games for Killua""" + ... + + @check(500) + @games.command(extras={"category": Category.GAMES}, usage="count ") + @discord.app_commands.describe(difficulty="The difficulty to play in") + async def count(self, ctx: commands.Context, difficulty: CountDifficulties = CountDifficulties.easy): + """See how many numbers you can remember with this count game!""" + game = CountGame(ctx, difficulty.name) + await game.start() + + @check(30) + @games.command(extras={"category":Category.GAMES}, usage="rps ") + @discord.app_commands.describe( + member="The person to challenge", + points="The points to play for" + ) + async def rps(self, ctx: commands.Context, member: discord.Member, points: int = None): + """Play Rock Paper Scissors with your friends! You can play investing Jenny or just for fun.""" + + if member.id == ctx.author.id: + return await ctx.send("Baka! You can't play against yourself") + + if not member.bot: + opponent = User(member.id) + elif member.bot and member != ctx.me: + return await ctx.send("Beep-boop, if you wanna play against a bot, play against me!") + + p2 = opponent.jenny if member != ctx.me else False + + user = User(ctx.author.id) + + p1 = user.jenny + + if points: + if points <= 0 or points > 100: + return await ctx.send(f"You can only play using 1-100 Jenny") + + if p1 < points: + return await ctx.send(f"You do not have enough Jenny for that. Your current balance is `{p1}`") + if not p2 is False and p2 < points: + return await ctx.send(f"Your opponent does not have enough Jenny for that. Their current balance is `{p2}`") + + game = Rps(ctx, points, member) + await game.start() + + @check(20) + @games.command(extras={"category": Category.GAMES}, usage="trivia ") + @discord.app_commands.describe(difficulty="The difficulty of the question") + async def trivia(self, ctx: commands.Context, difficulty: TriviaDifficulties = TriviaDifficulties.easy): + """Play trivia and earn some jenny if you get the answer right!""" + await ctx.defer() + game = Trivia(ctx, difficulty.name, self.client.session) + await game.create() + await game.send() + await game.send_result() + + @check() + @games.command(extras={"category": Category.GAMES}, usage="stats ") + @discord.app_commands.describe(member="The person to check the stats of") + async def stats(self, ctx: commands.Context, game_type: GameOptions, member: discord.Member = None): + """Check the game stats of yourself or another user""" + if not member: + member = ctx.author + + user = User(member.id) + + if game_type == GameOptions.rps: + pve_played = (user.rps_stats["pve"]["tied"] + user.rps_stats["pve"]["lost"] + user.rps_stats["pve"]["won"]) + pve_win_rate = int(100*(user.rps_stats["pve"]["won"]/pve_played)) if pve_played != 0 else 0 + + pvp_played = (user.rps_stats["pvp"]["tied"] + user.rps_stats["pvp"]["lost"] + user.rps_stats["pvp"]["won"]) + pvp_win_rate = int(100*(user.rps_stats["pvp"]["won"]/pvp_played)) if pvp_played != 0 else 0 + + await ctx.send(embed=discord.Embed( + title=f"{member.name}'s RPS stats", + description=f"**__PVE__**:\n:crown: Win rate: {pve_win_rate}%\n\n Wins: {user.rps_stats['pve']['won']}\nDraws: {user.rps_stats['pve']['tied']}\nLosses: {user.rps_stats['pve']['lost']}" + \ + f"\n\n**__PVP__**:\n:crown: Win rate: {pvp_win_rate}%\n\n Wins: {user.rps_stats['pvp']['won']}\nDraws: {user.rps_stats['pvp']['tied']}\nLosses: {user.rps_stats['pvp']['lost']}", + color=0x1400ff + )) + + elif game_type == GameOptions.trivia: + overall_right = user.trivia_stats["easy"]["right"] + user.trivia_stats["medium"]["right"] + user.trivia_stats["hard"]["right"] + overall_wrong = user.trivia_stats["easy"]["wrong"] + user.trivia_stats["medium"]["wrong"] + user.trivia_stats["hard"]["wrong"] + + win_rate_overall = int(100*(overall_right/(overall_right + user.trivia_stats["easy"]["wrong"] + user.trivia_stats["medium"]["wrong"] + user.trivia_stats["hard"]["wrong"]))) if overall_wrong != 0 else 0 + + easy_played = user.trivia_stats["easy"]["wrong"] + user.trivia_stats["easy"]["right"] + win_rate_easy = int(100*(user.trivia_stats["easy"]["right"]/easy_played)) if easy_played != 0 else 0 + + medium_played = user.trivia_stats["medium"]["wrong"] + user.trivia_stats["medium"]["right"] + win_rate_medium = int(100*(user.trivia_stats["medium"]["right"]/medium_played)) if medium_played != 0 else 0 + + hard_played = user.trivia_stats["hard"]["wrong"] + user.trivia_stats["hard"]["right"] + win_rate_hard = int(100*(user.trivia_stats["hard"]["right"]/hard_played)) if hard_played != 0 else 0 + + await ctx.send(embed=discord.Embed( + title=f"{member.name}'s Trivia stats", + description=f"__Overall correctness__: {win_rate_overall}%\n\n__Hard__:\nRight answers: {user.trivia_stats['hard']['right']}\nWrong answers: {user.trivia_stats['hard']['wrong']}\n{win_rate_hard}% correct\n\n__Medium__:\nRight answers: {user.trivia_stats['medium']['right']}\nWrong answers: {user.trivia_stats['medium']['wrong']}\n{win_rate_medium}% correct\n\n__Easy__:\nRight answers: {user.trivia_stats['easy']['right']}\nWrong answers: {user.trivia_stats['easy']['wrong']}\n{win_rate_easy}% correct", + color=0x1400ff + )) + + elif game_type == GameOptions.counting: + await ctx.send(embed=discord.Embed( + title=f"{member.name}'s Counting stats", + description=f"High score easy mode: {user.counting_highscore['easy']}\n\nHigh score hard mode: {user.counting_highscore['hard']}", + color=0x1400ff + )) + + @check() + @games.command(extras={"category": Category.GAMES}, usage="leaderboard ") + @discord.app_commands.describe(game="The game to check the leaderboard of", where="Whether to show the global or server leaderboard") + async def leaderboard(self, ctx: commands.Context, game: GameOptions, where: Literal["global", "server"] = "global"): + """Checks the top 10 players of a game, globally or on the server.""" + all: List[dict] = list(DB.teams.find({} if where == "global" else {"id": {"$in": [m.id for m in ctx.guild.members]}})) + + if game == GameOptions.rps: + top_5_pve: List[dict] = all + top_5_pve.sort(key=lambda x: dict(x).get("stats", {}).get("rps", {}).get("pve", {}).get("won", 0), reverse=True) + + top_5_pvp: List[dict] = all + top_5_pvp.sort(key=lambda x: dict(x).get("stats", {}).get("rps", {}).get("pvp", {}).get("won", 0), reverse=True) + + embed = discord.Embed(title="Global RPS leaderboard", description="**PVE**", color=0x1400ff) + for pos, player in enumerate(top_5_pve[:5]): + # user = self.client.get_user(player["_id"]) + # if user: + wins = player.get("stats", {}).get("rps", {}).get("pve", {}).get("won", 0) + embed.description += f"\n**{pos+1}.** <@{player['id']}> - {wins} win{'s' if wins != 1 else ''}" + + embed.description += "\n\n**PVP**" + + for pos, player in enumerate(top_5_pvp[:5]): + # user = self.client.get_user(player["_id"]) + # if user: + wins = player.get("stats", {}).get("rps", {}).get("pvp", {}).get("won", 0) + embed.description += f"\n**{pos+1}.** <@{player['id']}> - {wins} win{'s' if wins != 1 else ''}" + + await ctx.send(embed=embed) + + elif game == GameOptions.trivia: + top_5_hard = all + top_5_hard.sort(key=lambda x: dict(x).get("stats", {}).get("trivia", {}).get("hard", {}).get("right", 0), reverse=True) + + top_5_medium = all + top_5_medium.sort(key=lambda x: dict(x).get("stats", {}).get("trivia", {}).get("medium", {}).get("right", 0), reverse=True) + + top_5_easy = all + top_5_easy.sort(key=lambda x: dict(x).get("stats", {}).get("trivia", {}).get("easy", {}).get("right", 0), reverse=True) + + embed = discord.Embed(title="Global Trivia leaderboard", description="**Hard**", color=0x1400ff) + for pos, player in enumerate(top_5_hard[:5]): + # user = self.client.get_user(player["_id"]) + # if user: + right_answers = player.get("stats", {}).get("trivia", {}).get("hard", {}).get("right", 0) + embed.description += f"\n**{pos+1}.** <@{player['id']}> - {right_answers} right answer{'s' if right_answers != 1 else ''}" + + embed.description += "\n\n**Medium**" + + for pos, player in enumerate(top_5_medium[:5]): + # user = self.client.get_user(player["_id"]) + # if user: + right_answers = player.get("stats", {}).get("trivia", {}).get("medium", {}).get("right", 0) + embed.description += f"\n**{pos+1}.** <@{player['id']}> - {right_answers} right answer{'s' if right_answers != 1 else ''}" + + embed.description += "\n\n**Easy**" + + for pos, player in enumerate(top_5_easy[:5]): + # user = self.client.get_user(player["_id"]) + # if user: + right_answers = player.get("stats", {}).get("trivia", {}).get("easy", {}).get("right", 0) + embed.description += f"\n**{pos+1}.** <@{player['id']}> - {right_answers} right answer{'s' if right_answers != 1 else ''}" + + await ctx.send(embed=embed) + + elif game == GameOptions.counting: + top_5_hard = all + top_5_hard.sort(key=lambda x: dict(x).get("stats", {}).get("counting_highscore", {}).get("hard", 0), reverse=True) + + top_5_easy = all + top_5_easy.sort(key=lambda x: dict(x).get("stats", {}).get("counting_highscore", {}).get("easy", 0), reverse=True) + + embed = discord.Embed(title="Global Counting leaderboard", description="**Hard**", color=0x1400ff) + for pos, player in enumerate(top_5_hard[:5]): + # user = self.client.get_user(player["_id"]) + # if user: + embed.description += f"\n**{pos+1}.** <@{player['id']}> - {player.get('stats', {}).get('counting_highscore', {}).get('hard', 0)} high score" + + embed.description += "\n\n**Easy**" + + for pos, player in enumerate(top_5_easy[:5]): + # user = self.client.get_user(player["_id"]) + # if user: + embed.description += f"\n**{pos+1}.** <@{player['id']}> - {player.get('stats', {}).get('counting_highscore', {}).get('easy', 0)} high score" + + await ctx.send(embed=embed) + + +d = [{"a": 1}, {"a": 2}, {"a": 3}, {"b": 1}] +# sort dictionary d by the value of the key "a", then only use the first 2 + +d.sort(key=lambda x: x.get("a", 0), reverse=True) + +Cog = Games \ No newline at end of file diff --git a/tests/killua/cogs/help.py b/tests/killua/cogs/help.py new file mode 100644 index 000000000..0fb28ce0f --- /dev/null +++ b/tests/killua/cogs/help.py @@ -0,0 +1,195 @@ +import discord, os +from typing import List +from discord.ext import commands +from datetime import datetime +from inspect import getsourcelines + +from killua.bot import BaseBot +from killua.utils.classes import Guild +from killua.static.enums import Category +from killua.utils.paginator import Paginator +from killua.utils.interactions import Select, View, Button + +class HelpPaginator(Paginator): + """A normal paginator with a button that returns to the original help command""" + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + self.view.add_item(Button(label="Menu", style=discord.ButtonStyle.blurple, custom_id="1")) + + async def start(self): + view = await self._start() + + if view.ignore or view.timed_out: + return + + await self.view.message.delete() + await self.ctx.command.__call__(self.ctx) + + +class HelpEmbed(discord.Embed): + def __init__(self, av: str, **kwargs): + super().__init__(**kwargs) + self.title = "Help menu" + self.color = 0x1400ff + self.set_thumbnail(url=av) + self.timestamp = datetime.now() + +class HelpCommand(commands.Cog): + + def __init__(self, client: BaseBot) -> None: + self.client = client + self.client.remove_command("help") + self.cache = {} + + def find_source(self, command: commands.HybridCommand) -> str: + """Finds the source of a command and links the GitHub link to it""" + base_url = "https://github.com/kile/killua" + branch = "master" if not self.client.is_dev else "v1.0" + + source = command.callback.__code__ + filename = source.co_filename + + lines, firstlineno = getsourcelines(source) + location = os.path.relpath(filename).replace("\\", "/") + + return f"{base_url}/blob/{branch}/{location}#L{firstlineno}-L{firstlineno + len(lines) - 1}" + + def get_command_help(self, command: commands.HybridCommand, prefix: str) -> discord.Embed: + """Gets the help embed for a command""" + + embed = discord.Embed(title="Infos about command `" + command.qualified_name + "`", description=command.help or "No help found...") + embed.color = 0x1400ff + + embed.add_field(name="Category", value=command.extras["category"].value["name"]) + + checks = command.checks + + premium_guild, premium_user, cooldown = False, False, False + + if [c for c in checks if hasattr(c, "premium_guild_only")]: + premium_guild = True + + if [c for c in checks if hasattr(c, "premium_user_only")]: + premium_user = True + + if (res := [c for c in checks if hasattr(c, "cooldown")]): + check = res[0] + cooldown = getattr(check, "cooldown", False) + + if premium_guild or premium_user: + embed.description += f"\n{'<:premium_guild_badge:883473807292121149>' if premium_guild else '<:tier_one_badge:879390548857880597>'} `[Premium {'servers' if premium_guild else 'users'} only]`" + + if cooldown: + embed.add_field(name="Cooldown", value=f"{cooldown} seconds") + + usage = "```css\n/" + command.qualified_name.replace(command.name, "") + command.usage + "\n```" + embed.add_field(name="Usage", value=usage, inline=False) + + if len(prefix) < 100: # We don't want large prefixes to break the embed and make the help command unusable + embed.set_footer(text=f"Message prefix: {prefix}") + + return embed + + def get_group_help(self, ctx: commands.Context, group: Category, prefix: str) -> HelpPaginator: + """Gets the help embed for a group""" + + c = self.cache[group]["commands"] + + def make_embed(page, embed, pages): + embed = self.get_command_help(c[page-1], prefix) + source = self.find_source(c[page-1]) + embed.description += f"\n[Source code]({source})" + if len(prefix) < 100: # We don't want large prefixes to break the embed and make the help command unusable + embed.set_footer(text=f"Page {page}/{len(pages)} | Message prefix: {prefix}") + else: + embed.set_footer(text=f"Page {page}/{len(pages)}") + return embed + + return HelpPaginator(ctx, c, timeout=100, func=make_embed) + + async def help_autocomplete( + self, + _: discord.Interaction, + current: str, + ) -> List[discord.app_commands.Choice[str]]: + """Autocomplete for all cards""" + if not self.cache: + self.cache = self.client.get_formatted_commands() + + all_commands = [v["commands"] for v in self.cache.values()] + # combine all individual lists in all_commands into one in one line + all_commands: List[commands.Command] = [item for sublist in all_commands for item in sublist] + + return [command.qualified_name for command in all_commands if current.lower() in command.qualified_name] + + @commands.hybrid_command() + @discord.app_commands.describe(group="The group to get help for", command="The command to get help for") + async def help(self, ctx: commands.Context, group: Category = None, command: str = None) -> None: + """Displays helfpul information about a command, group, or the bot itself.""" + message_prefix = Guild(ctx.guild.id).prefix if ctx.guild else "k!" + + if not self.cache: + self.cache = self.client.get_formatted_commands() + + if not (group or command): + embed = HelpEmbed(str(ctx.me.avatar.url)) + + for k, v in self.cache.items(): + embed.add_field(name=f"{v['emoji']['normal']} `{k}` ({len(v['commands'])} commands)", value=v["description"], inline=False) + + embed.add_field(name="** **", value="\nFor more info to a specific command, use ```css\nhelp ```", inline=False) + view = View(user_id=ctx.author.id, timeout=None) + view.add_item(Select([discord.SelectOption(label=k, value=str(i), emoji=v["emoji"]["unicode"]) for i, (k, v) in enumerate(self.cache.items())], placeholder="Select a command group")) + + view.add_item(discord.ui.Button(url=self.client.support_server_invite, label="Support server")) + view.add_item(discord.ui.Button(url="https://github.com/kile/killua", label="Source code")) + view.add_item(discord.ui.Button(url="https://killua.dev", label="Website")) + view.add_item(discord.ui.Button(url="https://patreon.com/kilealkuri", label="Premium")) + + msg = await ctx.send(embed=embed, view=view) + + + await view.wait() + if view.timed_out: + view.children[0].disabled = True # Instead of looping through all the children, we just disable the select menu since we want the links to remain clickable + return await msg.edit(view=view) + else: + #await msg.edit(embed=msg.embeds[0], view=discord.ui.View()) + await msg.delete() + paginator = self.get_group_help(ctx, list(self.cache.keys())[view.value], message_prefix) + return await paginator.start() + + elif command: # if both command and group are specified, command takes priority + all_commands = [v["commands"] for v in self.cache.values()] + # combine all individual lists in all_commands into one in one line + all_commands: List[commands.Command] = [item for sublist in all_commands for item in sublist] + + # if command not in [c.qualified_name for c in self.client.commands]: + # return await ctx.send(f"No command called \"{command}\" found.", ephemeral=True) + if not command.lower() in [c.qualified_name for c in all_commands]: + return await ctx.send(f"No command called \"{command}\" found.", ephemeral=True) + + cmd = [c for c in all_commands if c.qualified_name == command.lower()][0] + + if isinstance(cmd, commands.HybridGroup) or isinstance(cmd, discord.app_commands.ContextMenu) or cmd.hidden or cmd.qualified_name.startswith("jishaku") or cmd.name == "help": # not showing what it's not supposed to. Hacky I know + return await ctx.send(f"No command called \"{command}\" found.", ephemeral=True) + + source_link = self.find_source(cmd) + + embed = self.get_command_help(cmd, message_prefix) + + source_view = View(user_id=ctx.author.id, timeout=None) + source_view.add_item(discord.ui.Button(url=source_link, label="Source code", style=discord.ButtonStyle.link)) + + return await ctx.send(embed=embed, view=source_view) + + elif group: + if group.name not in self.cache: + return await ctx.send(f"No group called \"{group.name}\" found.", ephemeral=True) + + paginator = self.get_group_help(ctx, group.name, message_prefix) + return await paginator.start() + +Cog = HelpCommand \ No newline at end of file diff --git a/tests/killua/cogs/image_manipulation.py b/tests/killua/cogs/image_manipulation.py new file mode 100644 index 000000000..271a5e38f --- /dev/null +++ b/tests/killua/cogs/image_manipulation.py @@ -0,0 +1,328 @@ +import discord +from discord.ext import commands +from typing import Union, Any, List, Coroutine, Optional +import re +import io +from PIL import Image, ImageDraw, ImageChops + +from pypxl import PxlClient # My own library ✨ + +from killua.bot import BaseBot +from killua.utils.gif import save_transparent_gif +from killua.utils.checks import check +from killua.static.enums import Category, SnapOptions, EyesOptions #, FlagOptions +from killua.static.constants import NOKIA_CODE, PXLAPI, URL_REGEX + +class ImageManipulation(commands.Cog): + + def __init__(self, client: BaseBot): + self.client = client + self.wtf_meme = None + self.wtf_meme_url = "https://i.redd.it/pvdxasy5z7k41.jpg" + self.pxl = PxlClient(token=PXLAPI, stop_on_error=False, session=self.client.session) + + async def _get_image_bytes(self, url: str) -> io.BytesIO: + """Gets the bytes from the image behind the url""" + res = await self.client.session.get(url) + _bytes = await res.read() + return io.BytesIO(_bytes) + + def _crop_to_circle(self, im): + """Crops the given image to a circle""" + bigsize = (im.size[0] * 3, im.size[1] * 3) + mask = Image.new("L", bigsize, 0) + ImageDraw.Draw(mask).ellipse((0, 0) + bigsize, fill=255) + mask = mask.resize(im.size, Image.ANTIALIAS) + mask = ImageChops.darker(mask, im.split()[-1]) + im.putalpha(mask) + + return im.copy() + + def _create_frames(self, image: Image.Image) -> List[Image.Image]: + """Creates the frames for the spin, sligtly rotating each frame""" + res = [] + for i in range(17): + res.append(image.rotate(i*20-1)) + return res + + async def _create_spin_gif(self, url:str) -> io.BytesIO: + """Takes in a url and returns io bytes of a spinning GIF""" + image = Image.open(await self._get_image_bytes(url)).convert("RGB") + # Crops the image to a square in the middle with the smallest side being the size of the largest side + image = image.crop((image.width/2 - min(image.width, image.height)/2, image.height/2 - min(image.width, image.height)/2, image.width/2 + min(image.width, image.height)/2, image.height/2 + min(image.width, image.height)/2)) + new_image = self._crop_to_circle(image) + image.close() + frames = self._create_frames(new_image) + new_image.close() + buffer = io.BytesIO() + save_transparent_gif(frames, durations=1, save_file=buffer) # making sure the gif is transparent. This is necessarry because of a pillow bug and slows this down quite significantly + buffer.seek(0) + return buffer + + def _put_horizontally(self, im1: Image.Image, im2: Image.Image, reduce_by: int = 5) -> Image.Image: + """Puts im2 below im2 with regards to each others sizes""" + heigth_avatar = int(im2.width * (im1.height/im1.width)) + height_meme = int((heigth_avatar + im2.height)/reduce_by) + + dst = Image.new("RGBA", (im2.width, heigth_avatar + height_meme)) + + im1 = im1.resize((im2.width, heigth_avatar)) + dst.paste(im1, (0, 0)) + im2 = im2.resize((im2.width, height_meme)) + dst.paste(im2, (0, heigth_avatar)) + return dst + + async def create_wtf_meme(self, url: str) -> io.BytesIO: + """Puts a "excuse me what the frick" below the image provided""" + if not self.wtf_meme: + self.wtf_meme = await self._get_image_bytes(self.wtf_meme_url) + + image = Image.open(self.wtf_meme).copy().convert("RGBA") + url_image = Image.open(await self._get_image_bytes(url)).convert("RGBA") + + buffer = io.BytesIO() + self._put_horizontally(url_image, image).save(buffer, "PNG") + buffer.seek(0) + return buffer + + async def _validate_input(self, ctx: commands.Context, target: Optional[str]) -> str: # a useful check that looks for what url to pass pxlapi + """Finds an image url to use from a command""" + if target: + try: + m = await commands.MemberConverter().convert(ctx, target) + return str(m.avatar.url) + except commands.MemberNotFound: + pass + + try: + e = await commands.EmojiConverter().convert(ctx, target) + return str(e.url) + except commands.EmojiNotFound: + pass + + if target.isdigit(): + try: + user = await self.client.fetch_user(int(target)) + return str(user.avatar.url) + except discord.NotFound: + pass + else: + url = re.search(URL_REGEX, target) + # Makes sure the url is valid. + # This check is not perfect but it works for most cases and if it's a false positive itdoesn't matter too much + if not url: + pass + else: + return url.group(0) + + if len(ctx.message.attachments) > 0: + return ctx.message.attachments[0].url + + async for message in ctx.channel.history(limit=5): + if len(message.attachments) > 0: + return message.attachments[0].url + elif len(message.embeds) > 0: + embed = message.embeds[0] + if embed.image: + return embed.image.url + if embed.thumbnail: + return embed.thumbnail.url + + return str(ctx.author.avatar.url) # if all else fails, return the author"s avatar + + async def handle_command( + self, + ctx: commands.Context, + target: Union[discord.Member, discord.Emoji, str], + function: Coroutine, + t: Any = None, + censor: bool = False, + validate: bool = True + ) -> discord.Message: + """Handles the command and returns the message""" + if validate: + data = await self._validate_input(ctx, target) + if not data: + return await ctx.send(f"Invalid arguments passed. For help with the command, use `{self.client.command_prefix(self.client, ctx.message)[2]}help {ctx.command.name}`", allowed_mentions=discord.AllowedMentions.none(), ephemeral=True) + else: + data = target + + await ctx.channel.typing() + await ctx.send(f"Processing...", ephemeral=True) + r = await function(data, t) + if r.success: + f = discord.File(r.convert_to_ioBytes(), filename=f"{ctx.command.name}.{r.file_type}", spoiler=censor) + return await self.client.send_message(ctx, file=f, reference=ctx.message, allowed_mentions=discord.AllowedMentions.none()) + return await ctx.send(f":x: "+r.error, allowed_mentions=discord.AllowedMentions.none()) + + async def flag_autocomplete( + self, + _: commands.Context, + current: str + ) -> List[discord.app_commands.Choice[str]]: + """Returns a list of flags that match the current string since there are too many flags for it to use the options feature""" + return [discord.app_commands.Choice(name=i, value=i) for i in self.pxl.flags if i.startswith(current)][:25] + + @commands.hybrid_group() + async def image(self, _: commands.Context): + """ + Image related commands + """ + ... + + @check(120) # Big cooldown >_< + @image.command(aliases=["ej", "emojimosaic"], extras={"category":Category.FUN}, usage="emojaic ") + @discord.app_commands.describe(target="A user, url or emoji to take the image from") + async def emojaic(self, ctx: commands.Context, target: str = None): + """Emoji mosaic an image; let emojis recreate an image you gave Killua!""" + async def func(data, *_): + return await self.pxl.emojaic([data], groupSize=6) + await self.handle_command(ctx, target, func) + + @check(5) + @image.command(extras={"category":Category.FUN}, usage="flag ") + @discord.app_commands.describe( + flag="The flag to overlay the image with", + target="A user, url or emoji to take the image from" + ) + @discord.app_commands.autocomplete(flag=flag_autocomplete) #has to be done as autocomplete and not options because there are more than 25 flags + async def flag(self, ctx: commands.Context, flag: str, target: str = None): + """Overlay an image with a flag""" + async def func(data, flag): + return await self.pxl.flag(flag=flag, images=[data]) + await self.handle_command(ctx, target, func, flag) + + @check(5) + @image.command(extras={"category":Category.FUN}, usage="glitch ") + @discord.app_commands.describe(target="A user, url or emoji to take the image from") + async def glitch(self, ctx: commands.Context, target: str = None): + """Tranform a users pfp into a glitchy GIF!""" + async def func(data, *_): + return await self.pxl.glitch(images=[data], gif=True) + await self.handle_command(ctx, target, func) + + @check(10) + @image.command(extras={"category":Category.FUN}, usage="lego ") + @discord.app_commands.describe(target="A user, url or emoji to take the image from") + async def lego(self, ctx: commands.Context, target: str = None): + """Legofies an image""" + async def func(data, *_): + return await self.pxl.lego(images=[data], scale=True, groupSize=10) + await self.handle_command(ctx, target, func) + + @check(3) + @image.command(aliases=["snap"], extras={"category":Category.FUN}, usage="snapchat ") + @discord.app_commands.describe( + filter="The snap filter to apply to the image", + target="A user, url or emoji to take the image from" + ) + async def snapchat(self, ctx: commands.Context, filter: SnapOptions, target: str = None): + """Put a snapchat filter on an image with a face""" + async def func(data, filter): + return await self.pxl.snapchat(filter=filter, images=[data]) + await self.handle_command(ctx, target, func, filter.name) + + @check(3) + @image.command(aliases=["eye"], extras={"category":Category.FUN}, usage="eyes ") + @discord.app_commands.describe( + type="The type of eyes to put on the image", + target="A user, url or emoji to take the image from" + ) + async def eyes(self, ctx: commands.Context, type: EyesOptions, target: str = None): + """Put some crazy eyes on a person""" + async def func(data, type): + return await self.pxl.eyes(eyes=type, images=[data]) + await self.handle_command(ctx, target, func, type.name) + + @check(4) + @image.command(aliases=["8bit", "blurr"], extras={"category":Category.FUN}, usage="jpeg ") + @discord.app_commands.describe(target="A user, url or emoji to take the image from") + async def jpeg(self, ctx: commands.Context, target: str = None): + """Did you ever want to decrease image quality? Then this is the command for you!""" + async def func(data, *_): + return await self.pxl.jpeg(images=[data]) + await self.handle_command(ctx, target, func) + + @check(4) + @image.command(extras={"category":Category.FUN}, usage="ajit ") + @discord.app_commands.describe(target="A user, url or emoji to take the image from") + async def ajit(self, ctx: commands.Context, target: str = None): + """ Overlays an image of Ajit Pai snacking on some popcorn!""" + async def func(data, *_): + return await self.pxl.ajit(images=[data]) + await self.handle_command(ctx, target, func) + + @check() + @image.command(extras={"category":Category.FUN}, usage="nokia ") + @discord.app_commands.describe(target="A user, url or emoji to take the image from") + async def nokia(self, ctx: commands.Context, target: str = None): + """Add the image onto a nokia display""" + async def func(data, *_): + d = "const url = "" + data + ";"" + NOKIA_CODE + return await self.pxl.imagescript(version="1.2.0", code=d) + await self.handle_command(ctx, target, func) + + @check(4) + @image.command(extras={"category":Category.FUN}, usage="flash ") + @discord.app_commands.describe(target="A user, url or emoji to take the image from") + async def flash(self, ctx: commands.Context, target: str = None): + """Greates a flashing GIF. WARNING FOR PEOPLE WITH EPILEPSY!""" + async def func(data, *_): + return await self.pxl.flash(images=[data]) + await self.handle_command(ctx, target, func, censor=True) + + @check(3) + @image.command(extras={"category":Category.FUN}, usage="thonkify ") + @discord.app_commands.describe(text="The text to thonkify") + async def thonkify(self, ctx: commands.Context, *, text: str): + """Turn text into thonks!""" + async def func(data, *_): + return await self.pxl.thonkify(text=data) + await self.handle_command(ctx, text, func, validate=False) + + @check(5) + @image.command(aliases=["screen"], extras={"category":Category.FUN}, usage="screenshot ") + @discord.app_commands.describe(website="The url of the website to screenshot") + async def screenshot(self, ctx: commands.Context, website:str): + """Screenshot the specified webste!""" + async def func(data, *_): + return await self.pxl.screenshot(url=data) + await self.handle_command(ctx, website, func, validate=False) + + @check(2) + @image.command(extras={"category":Category.FUN}, usage="sonic ") + @discord.app_commands.describe(text="The text to let sonic say") + async def sonic(self, ctx: commands.Context, *, text: str): + """Let sonic say anything you want""" + async def func(data, *_): + return await self.pxl.sonic(text=data) + await self.handle_command(ctx, text, func, validate=False) + + @check(30) # long check because this is exhausting for the poor computer + @image.command(alises=["s"], extras={"category": Category.FUN}, usage="spin ") + @discord.app_commands.describe(target="A user, url or emoji to take the image from") + async def spin(self, ctx: commands.Context, target: str = None): + """Spins an image 'round and 'round and 'round and 'round...""" + data = await self._validate_input(ctx, target) + if not data: + return await ctx.send(f"Invalid arguments passed. For help with the command, use `{self.client.command_prefix(self.client, ctx.message)[2]}help {ctx.command.name}`", allowed_mentions=discord.AllowedMentions.none()) + + await ctx.channel.typing() + await ctx.send("Processing...", ephemeral=True) + buffer = await self._create_spin_gif(data) + await self.client.send_message(ctx, file=discord.File(fp=buffer, filename="spin.gif"), reference=ctx.message, allowed_mentions=discord.AllowedMentions.none()) + + @check(10) + @image.command(extras= {"category": Category.FUN}, usage= "wtf ") + @discord.app_commands.describe(target="A user, url or emoji to take the image from") + async def wtf(self, ctx: commands.Context, target: str = None): + """Puts the wtf meme below the image provided""" + data = await self._validate_input(ctx, target) + if not data: + return await ctx.send(f"Invalid arguments passed. For help with the command, use `{self.client.command_prefix(self.client, ctx.message)[2]}help {ctx.command.name}`", allowed_mentions=discord.AllowedMentions.none()) + await ctx.channel.typing() + await ctx.send("Processing...", ephemeral=True) + buffer = await self.create_wtf_meme(data) + await self.client.send_message(ctx, file=discord.File(fp=buffer, filename="wtf.png"), reference=ctx.message, allowed_mentions=discord.AllowedMentions.none()) + +Cog = ImageManipulation \ No newline at end of file diff --git a/tests/killua/cogs/moderation.py b/tests/killua/cogs/moderation.py new file mode 100644 index 000000000..4b280c0a3 --- /dev/null +++ b/tests/killua/cogs/moderation.py @@ -0,0 +1,232 @@ +import discord +from discord.ext import commands +from typing import List, Union +from datetime import datetime + +from killua.bot import BaseBot +from killua.utils.converters import TimeConverter +from killua.utils.checks import check +from killua.utils.classes import Guild +from killua.static.enums import Category + +Choice = discord.app_commands.Choice + +class Moderation(commands.Cog): + + def __init__(self, client: BaseBot): + self.client = client + + async def check_perms(self, ctx, member) -> Union[None, discord.Message]: + if member == ctx.me: + return await ctx.send("Hey!", ephemeral=True) + + if member == ctx.author: + return await ctx.send(f"You can't {ctx.command.name} yourself!", ephemeral=True) + + if ctx.author.top_role < member.top_role: + return await ctx.send(f"You can't {ctx.command.name} someone with a higher role than you", ephemeral=True) + + if ctx.me.top_role < member.top_role: + return await ctx.send(f"My role needs to be moved higher up to grant me permission to {ctx.command.name} this person", ephemeral=True) + return None + + @commands.hybrid_group() + async def moderation(self, _: commands.Context): + """ + Moderation commands + """ + ... + + @check() + @commands.has_permissions(ban_members=True) + @commands.bot_has_permissions(ban_members=True) + @moderation.command(extras={"category":Category.MODERATION}, usage="ban ") + @discord.app_commands.describe( + member= "The member to ban", + delete_days="The number of days worth of messages to delete", + config="The options on notifying the user", + reason="The reason for the ban" + ) + @discord.app_commands.choices(config=[ + Choice(name="Send no dm", value=0), + Choice(name="Send dm on ban", value=1), + Choice(name="Send dm on ban with acting moderator", value=2) + ]) + async def ban( + self, + ctx: commands.Context, + member: str, + delete_days: int = 1, + config: Choice[int] = 1, + *, reason: str = None + ): + """Bans a user from the server.""" + try: + member = await commands.MemberConverter().convert(ctx, member) + except commands.MemberNotFound: + if member.isdigit(): + try: + await ctx.guild.ban(discord.Object(id=member)) + user = self.client.get_user(member) or await self.client.fetch_user(member) + return await ctx.send(f":hammer: Banned **{user}** because of: ```\n{reason or 'No reason provided'}```Operating moderator: **{ctx.author}**") + except discord.HTTPException: + return await ctx.send("Something went wrong! Did you specify a valid user id?", ephemeral=True) + else: + return await ctx.send("Invalid user!", ephemeral=True) + + r = await self.check_perms(ctx, member) + if r: return + + if config in [1, 2]: + try: + await member.send(f"You have been banned from {ctx.guild.name} because of: ```\n{reason or 'No reason provided'}```" + f" by `{ctx.author}`" if config == 2 else "") + except discord.HTTPException: + pass + + await member.ban(reason=reason, delete_message_days=delete_days) + await ctx.send(f":hammer: Banned **{member}** because of: ```\n{reason or 'No reason provided'}```Operating moderator: **{ctx.author}**") + + + @check() + @commands.has_permissions(ban_members=True) + @commands.bot_has_permissions(ban_members=True, view_audit_log=True) + @moderation.command(extras={"category":Category.MODERATION}, usage="unban ") + @discord.app_commands.describe(member="The member to be unbanned") + async def unban(self, ctx: commands.Context, *, member: str): + """Unbans a user by ID or by tag, meaning `unban Kile#0606` will also work""" + banned_users = [] + async for ban in ctx.guild.bans(limit=100): # The last 100 band should be enough + banned_users.append(ban.user) + + if member.isdigit(): + try: + user = discord.Object(id=int(member)) + await ctx.guild.unban(user) + await ctx.send(f":ok_hand: Unbanned user with id **{member}**\nOperating moderator: **{ctx.author}**") + except discord.HTTPException as e: + if e.code == 10013: + return await ctx.send(f"No user with the user ID {member} found") + if e.code == 10026: + return await ctx.send("The user is not currently banned") + + else: + data = member.split("#") + if len(data) != 2: + return await ctx.send("Invalid user specified! (Did you not use the User#0000 format or does the user have a # in their name?)") + member_name, member_discriminator = data + + for ban_entry in banned_users: + + if (ban_entry.name, ban_entry.discriminator) == (member_name, member_discriminator): + await ctx.guild.unban(ban_entry) + return await ctx.send(f":ok_hand: Unbanned {ban_entry.mention}\nOperating moderator: **{ctx.author}**") + + return await ctx.send("User is not currently banned") + + @check() + @commands.has_permissions(kick_members=True) + @commands.bot_has_permissions(kick_members=True) + @moderation.command(extras={"category":Category.MODERATION}, usage="kick ") + @discord.app_commands.describe( + member="The member to be kicked", + reason="The reason for the kick" + ) + @discord.app_commands.choices(config=[ + Choice(name="Send no dm", value=0), + Choice(name="Send dm on kick", value=1), + Choice(name="Send dm on kick with acting moderator", value=2) + ]) + async def kick( + self, ctx: commands.Context, + member: discord.Member, + config: Choice[int] = 1, + *, reason: str = None + ): + """Kicks a user from the server.""" + + r = await self.check_perms(ctx, member) + if r: + return + + if config in [1, 2]: + try: + await member.send(f"You have been kicked from {ctx.guild.name} because of: ```\n{reason or 'No reason provided'}```"+ f" by `{ctx.author}`" if config == 2 else "") + except discord.HTTPException: + pass + + await member.kick(reason=reason or "No reason provided") + await ctx.send(f":hammer: Kicked **{member}** because of: ```\n{reason or 'No reason provided'}```Operating moderator: **{ctx.author}**") + + async def shush_autocomplete( + self, + _: discord.Interaction, + current: str + ) -> List[Choice[TimeConverter]]: + """ + Autocomplete for shush command + """ + times = ["1m", "5m", "10m", "30m", "1h", "12h", "1d", "7d"] + return list([ + Choice(name=opt, value=opt) + for opt in times if opt.lower().startswith(current.lower()) + ]) + + @check() + @commands.has_permissions(moderate_members=True) + @commands.bot_has_permissions(moderate_members=True) + @moderation.command(extras={"category":Category.MODERATION}, usage="shush