Repository: hyarsan/YukikoBot Branch: master Commit: 7c54d503645a Files: 30 Total size: 168.3 KB Directory structure: gitextract_9pp31cgz/ ├── .gitattributes ├── .gitignore ├── .idea/ │ ├── YukikoBot.iml │ ├── deployment.xml │ ├── misc.xml │ ├── modules.xml │ ├── vcs.xml │ ├── webServers.xml │ └── workspace.xml ├── LICENSE ├── README.md ├── assets/ │ ├── dice/ │ │ ├── hd/ │ │ │ └── resize.py │ │ └── old/ │ │ └── dice.pdn │ ├── sounds/ │ │ ├── README.md │ │ └── lowercase.py │ └── whitney-medium.otf ├── cogs/ │ ├── coins.py │ ├── copypasta.py │ ├── guild.py │ ├── image.py │ ├── info.py │ ├── nsfw.py │ ├── owner.py │ ├── stars.py │ ├── tests.py │ ├── text.py │ └── utils.py ├── frontend.pyw ├── minigames.py └── yuki.py ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitattributes ================================================ # Auto detect text files and perform LF normalization * text=auto ================================================ FILE: .gitignore ================================================ trash/ test.py config.ini .floo .flooignore # Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ *.egg-info/ .installed.cfg *.egg MANIFEST # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *.cover .hypothesis/ .pytest_cache/ # Translations *.mo *.pot # Django stuff: *.log local_settings.py db.sqlite3 # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder target/ # Jupyter Notebook .ipynb_checkpoints # pyenv .python-version # celery beat schedule file celerybeat-schedule # SageMath parsed files *.sage.py # Environments .env .venv env/ venv/ ENV/ env.bak/ venv.bak/ # Spyder project settings .spyderproject .spyproject # Rope project settings .ropeproject # mkdocs documentation /site # mypy .mypy_cache/ ================================================ FILE: .idea/YukikoBot.iml ================================================ ================================================ FILE: .idea/deployment.xml ================================================ ================================================ FILE: .idea/misc.xml ================================================ ================================================ FILE: .idea/modules.xml ================================================ ================================================ FILE: .idea/vcs.xml ================================================ ================================================ FILE: .idea/webServers.xml ================================================ ================================================ FILE: .idea/workspace.xml ================================================ about attac with ctx.typing(): py thonk self.getImage #800000 #80000 0x8000 0x800000 yuki.color nick .format format Fil session clientSession \U "".join( \u == None: getImage imgBytes outputBuffer embedColor formatTime starttyping sendError prefix if len(gld.channels) <= 100: guild logging.info @commands.command async with ctx.typing(): yuki.color ykColor session \u ''.join( \U get_image img_bytes output_buf get_check embed_color guild_created format_time send_error if len(gld.channels) <= 500: D:\GitHub\YukikoBot\cogs true DEFINITION_ORDER 1526774209823 ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: README.md ================================================ # YukikoBot [![Discord Bots](https://discordbots.org/api/widget/447493600167591936.svg)](https://discordbots.org/bot/447493600167591936) [![Discord Bot List](https://discordbotlist.com/bots/447493600167591936/widget)](https://discordbotlist.com/bots/447493600167591936) ================================================ FILE: assets/dice/hd/resize.py ================================================ from os import listdir from os.path import isfile, join from PIL import Image a = [f for f in listdir("./") if isfile(join("./", f))] a.remove("resize.py") for file in a: img = Image.open(file) img.thumbnail([128,128], Image.ANTIALIAS) img.save(file) ================================================ FILE: assets/sounds/README.md ================================================ ## Credits [YouTube SFX Pack](https://www.youtube.com/watch?v=B-uIfFgMPyw) ================================================ FILE: assets/sounds/lowercase.py ================================================ import os def lowercase_rename(dir): # renames all subforders of dir, not including dir itself def rename_all(root, items): for name in items: try: os.rename( os.path.join(root, name), os.path.join(root, name.lower()) ) except OSError: pass # can't rename it, so what # starts from the bottom so paths further up remain valid after renaming for root, dirs, files in os.walk(dir, topdown = False): rename_all(root, dirs) rename_all(root, files) if __name__ == '__main__': lowercase_rename("./") ================================================ FILE: cogs/coins.py ================================================ import discord from discord.ext import commands from yuki import color as ykColor import logging import dataset # class to make a database table like a key-value store class KeyValueTable: """operate a database table like a key-value store""" # initiate the KeyValueDB def __init__(self, table): """ initiate the KeyValueDB :param table: a dataset table """ self.table = table # retrieve a key-value pair from the database def __getitem__(self, key): """ retrieve an item from the key-value store :param key: the name of the requested item :return: the requested item :raises KeyError: it raises KeyError if it cannot be found """ # attempt to find the requested item res = self.table.find_one(key=key)["value"] # check if it returned something if not res: # raise IndexError if it cannot be found raise KeyError(f"unable to find key-value pair with key { key }") else: # otherwise return the requested item return res # set a key-value pair in the database def __setitem__(self, key, value): """ set an item in the key-value store :param key: the key to set :param value: the value for the key to have """ # upsert it (insert if it doesn't exist, update it if it does) self.table.upsert(dict(key=key, value=value), ["key"]) # delete a key-value pair in the database def __delitem__(self, key): """ delete a value in the key-value store if it exists :param key: the key to delete """ # attempt to delete it self.table.delete(key=key) # when the key is missing def __missing__(self, key): # just return none return None class Coins: def __init__(self, bot): self.bot = bot @commands.command(hidden = True) @commands.is_owner() async def cointest(self, ctx, member: discord.Member = None): if member == None: mem = ctx.message.author else: mem = member database = dataset.connect("sqlite:///yukiko.db") table = KeyValueTable(database["coins"]) try: table[mem.id]["amount"] += 500 except: table[mem.id] = {"amount": 0, "minutesLeft": 60} await ctx.send(table[mem.id]["amount"]) def setup(bot): bot.add_cog(Coins(bot)) ================================================ FILE: cogs/copypasta.py ================================================ import discord from discord.ext import commands from yuki import color as ykColor class Copypasta: def __init__(self, bot): self.bot = bot @commands.command(aliases = ["interject", u"\U0001f427"]) async def linux(self, ctx, a: commands.clean_content = "GNU", b: commands.clean_content = "Linux"): """Interjects for a moment, about your favorite thing.""" message = f""" I'd just like to interject for moment. What you're refering to as {b}, is in fact, {a}/{b}, or as I've recently taken to calling it, {a} plus {b}. {b} is not an operating system unto itself, but rather another free component of a fully functioning {a} system made useful by the {a} corelibs, shell utilities and vital system components comprising a full OS as defined by POSIX. Many computer users run a modified version of the {a} system every day, without realizing it. Through a peculiar turn of events, the version of {a} which is widely used today is often called {b}, and many of its users are not aware that it is basically the {a} system, developed by the {a} Project. There really is a {b}, and these people are using it, but it is just a part of the system they use. {b} is the kernel: the program in the system that allocates the machine's resources to the other programs that you run. The kernel is an essential part of an operating system, but useless by itself; it can only function in the context of a complete operating system. {b} is normally used in combination with the {a} operating system: the whole system is basically {a} with {b} added, or {a}/{b}. All the so-called {b} distributions are really distributions of {a}/{b}. """ await ctx.send(message) @commands.command(aliases = ["cemu"]) async def botw(self, ctx, a: commands.clean_content = "Breath of the Dicknut"): """Rants about Breath of the Dicknut.""" message = f""" Are you retarded? Like legit retarded? You keep breaking more and more games, for fucking {a}. Many games before, were fully playable with some minor glitches, then you started breaking them more and more with ear rape sound, slow fps, visual glitches, and then eventually just not booting up. Oh I'm sorry, you seem to be focusing on ONLINE and System Menu shit too. You're not very bright as a developer if you're okay with making huge regressions quite a number of other games just to focus on 1 or 2. You don't BREAK 20+ working games just for 2. That's just retarded. Also whether you like it or not, Vulckan would improve performance a lot, just because you don't THINK it will or you just lack the skill to implement it doesn't matter, it's better than OpenGL. Now, just to make sure your small mind understands... STOP BREAKING OTHER GAMES FOR {a.upper()}, STOP FOCUSING ON ONLINE PLAY AND SYSTEM MENUS, AND FIX THE SHIT YOU'VE BROKEN! DON'T WORK ON NEW FEATURES UNTIL YOU GET OTHER THINGS WORKING IN THE FIRST PLACE, HOLY FUCKING SHIT! AND MAYBE TAKE THE TIME YOU NEED TO IMPLEMENT VULKAN! IF YOU CAN'T DO THAT THEN MAKE IT OPEN SOURCE AND WE WILL, BUT WAIT, YOU NEED THOSE FUNDS FOR {a.upper()} RIGHT? LOL Point is your decisions and lack of skills suck as a Dev and people are sick of the "{a} Emulator", fucking focus on something else, Jesus Christ. """ await ctx.send(message) def setup(bot): bot.add_cog(Copypasta(bot)) ================================================ FILE: cogs/guild.py ================================================ import discord from discord.ext import commands from yuki import color as ykColor import yuki import logging class Guild: def __init__(self, bot): self.bot = bot @commands.command(aliases = ["prune"]) @commands.has_permissions(manage_messages = True) async def purge(self, ctx, amount: int = 1): """Purge the amount of messages you specify. The purge limit is 50 by default.""" purgeLimit = 50 if amount > purgeLimit: # await ctx.send(f"Can't purge more than {purgeLimit} messages at a time. <:cross_mark:465215264439664650>") await ctx.message.add_reaction(yuki.cross_mark) return 0 else: msg1 = ctx.message await ctx.message.delete() await msg1.channel.purge(limit = amount) logging.info(f"Deleted {amount} messages in #{msg1.channel} from guild: {msg1.guild} with ID {msg1.guild.id}.") @commands.command() @commands.has_permissions(kick_members = True) async def kick(self, ctx, *members: discord.Member): """Kicks member(s). Requires kick permission.""" if len(members) == 0: await yuki.send_error("No members were passed.", ctx) return output = "" for mem in members: if mem.id == self.bot.user.id: output += u"\U000026d4 **{}:**\n{}\n\n".format(mem, f"Can't kick self.") continue if ctx.guild.owner != mem: try: await mem.kick(reason = f"{ctx.author} used the kick command.") output += u"\U00002705 **{}:**\n{}\n\n".format(mem, f"Successfully kicked.") except: output += u"\U000026a0 **{}:**\n{}\n\n".format(mem, f"Couldn't kick.") else: output += u"\U000026d4 **{}:**\n{}\n\n".format(mem, f"Server owner, can't be kicked.") embed = discord.Embed(title = "Attempted to Kick", description = output, color = ykColor) await ctx.send(embed = embed) @commands.command() @commands.has_permissions(ban_members = True) async def ban(self, ctx, *members: discord.Member): """Bans member(s). Requires ban permission.""" if len(members) == 0: await yuki.send_error("No members were passed.", ctx) return output = "" for mem in members: if mem.id == self.bot.user.id: output += u"\U000026d4 **{}:**\n{}\n*ID: {}*\n\n".format(mem, f"Can't ban self.", mem.id) continue if ctx.guild.owner != mem: try: await mem.ban(reason = f"{ctx.author} used the ban command.") output += u"\U00002705 **{}:**\n{}\n*ID: {}*\n\n".format(mem, f"Successfully banned.", mem.id) except: output += "<:cross_mark:465215264439664650> **{}:**\n{}\n*ID: {}*\n\n".format(mem, f"Couldn't ban.", mem.id) else: output += u"\U000026d4 **{}:**\n{}\n*ID: {}*\n\n".format(mem, f"Server owner, can't be banned.", mem.id) embed = discord.Embed(title = "Attempted to Ban", description = output, color = ykColor) await ctx.send(embed = embed) @commands.command(aliases = ["nickname", "changenick", "changenickname"]) @commands.has_permissions(manage_nicknames = True) async def nick(self, ctx, member: discord.Member, nickname: str = None): """Changes other member's nickname.""" """if member == None: if ctx.message.author.permissions_in(ctx.message.channel).change_nickname: mem = ctx.message.author else: mem = member """ mem = member oldName = mem.display_name if ctx.guild.owner == mem: await yuki.send_error("Can't change nick of the server owner.", ctx) else: try: await mem.edit(nick = nickname, reason = f"{ctx.author} used the nick command.") embed = discord.Embed(description = "", color = ykColor) embed.set_author( name = f"Successfully changed nickname of {mem}, from {oldName} to {nickname}.", icon_url = "https://cdn.discordapp.com/attachments/447500690932367361/476214759071678474/nickname_icon.png" ) await ctx.send(embed = embed) except: await yuki.send_error(f"Couldn't change nickname of {mem}.", ctx) @commands.group() async def create(self, ctx): pass @create.command(aliases = ["chan", "cha"]) @commands.has_permissions(manage_channels = True) async def channel(self, ctx, *name: str): """Creates a channel.""" gld = ctx.guild name = '-'.join(name).lower() try: await gld.create_text_channel(name = name, reason = f"{ctx.author} used the create channel command.") embed = discord.Embed(description = "", color = ykColor) embed.set_author( name = f"Successfully created channel #{name}.", icon_url = "https://cdn.discordapp.com/attachments/447786789563006986/476225004015452160/plus_icon.png" ) await ctx.send(embed = embed) except: if len(gld.channels) <= 500: await yuki.send_error(f"No space left to create #{name}.", ctx) else: await yuki.send_error(f"Couldn't create channel #{name}.", ctx) @create.command(aliases = ["emo"]) @commands.has_permissions(manage_emojis = True) async def emoji(self, ctx, name: str, link: str = None): """Creates an emoji.""" if len(ctx.guild.emojis) >= 50: await yuki.send_error("No space left to create emoji.", ctx) else: img_bytes = await yuki.get_image(link, ctx) try: emo = await ctx.guild.create_custom_emoji( name = '_'.join(name.split()), image = img_bytes, reason = f"{ctx.author} used the create emoji command." ) embed = discord.Embed(description = f"Successfully created emoji {emo}.", color = ykColor) await ctx.send(embed = embed) except: await yuki.send_error("Couldn't create emoji.", ctx) @commands.command(aliases = ["slowmode", "slow", u"\U0001f40c"]) @commands.has_permissions(manage_channels = True) async def setslow(self, ctx, secs: int = 0): """Sets the slowmode delay of the channel you're in.""" if secs > 120: await yuki.send_error("The delay can't be longer than 120 seconds!", ctx) else: cha = ctx.channel try: await cha.edit(slowmode_delay = secs) if secs != 0: await yuki.send_error(f"Successfully set slowmode delay to {secs}.", ctx, icon = u"\U00002705") else: await yuki.send_error(f"Successfully reset the slowmode delay.", ctx, icon = u"\U00002705") except: await yuki.send_error(f"Couldn't set slowmode delay for channel {cha.mention}.", ctx) def setup(bot): bot.add_cog(Guild(bot)) ================================================ FILE: cogs/image.py ================================================ import discord from discord.ext import commands from yuki import color as ykColor import yuki import aiohttp from PIL import Image, ImageFont, ImageDraw, ImageFilter, ImageEnhance import PIL.ImageOps from io import BytesIO # import tinify import qrcode import random import codecs from bs4 import BeautifulSoup import urllib.request from os import listdir class Images: def __init__(self, bot): self.bot = bot @commands.command() async def flip(self, ctx, xy: str, link: str = None): """Flips image horizontally, or vertically.""" # messages = await ctx.message.channel.history().flatten() async with ctx.typing(): img_bytes = await yuki.get_image(link, ctx) with Image.open(BytesIO(img_bytes)) as img: if xy.lower() in ('x', 'h', 'horizontal', 'horizontally'): img = img.transpose(Image.FLIP_LEFT_RIGHT) flipped = 'X' elif xy.lower() in ('y', 'v', "vertical", "vertically"): img = img.transpose(Image.FLIP_TOP_BOTTOM) flipped = 'Y' else: img = img.transpose(Image.FLIP_LEFT_RIGHT) flipped = 'X' output_buf = BytesIO() img.save(output_buf, "png") output_buf.seek(0) file = discord.File(filename = "result.png", fp = output_buf) embed = discord.Embed(title = f"Flipped {flipped}", color = ykColor) file = discord.File(filename = "result.png", fp = output_buf) embed.set_image(url = "attachment://result.png") await ctx.send(embed = embed, file = file) @commands.command(aliases = ["pokefuse"]) async def pfuse(self, ctx, body: int, head: int): """ Fuses two Pokémon together. This command uses [this website](https://pokemon.alexonsager.net/) to output fused Pokémon. """ if False: await yuki.send_error("Only Kanto Pokémon are supported.", ctx) return async with ctx.typing(): fusion_link = f"http://images.alexonsager.net/pokemon/fused/{body}/{body}.{head}.png" async with aiohttp.ClientSession() as session: async with session.get(fusion_link) as response: img_bytes = await response.read() embed = discord.Embed(title = "Pokémon Fusion", color = ykColor) file = discord.File(filename = "result.png", fp = BytesIO(img_bytes)) embed.set_image(url = "attachment://result.png") await ctx.send(embed = embed, file = file) @commands.command() async def clyde(self, ctx, *, text: str = None): """Gives you an image that mocks clyde.""" if text == None: txt = "This emoji doesn't work here because it's from a different server. Discord Nitro can solve all of that, check User Settings > Nitro for details" else: txt = text.replace('\n', ' ') async with ctx.typing(): img = Image.open("assets/clyde.png") font = ImageFont.truetype("assets/fonts/discord/normal.woff", 15) draw = ImageDraw.Draw(img) draw.text((88, 46), txt, font = font, fill = (192, 193, 194)) output_buf = BytesIO() img.save(output_buf, "png") output_buf.seek(0) file = discord.File(filename = "result.png", fp = output_buf) await ctx.send(file = file) @commands.command(aliases = [u"\U0001f914"]) async def thonk(self, ctx, link: str = None): """Thonkifies the image you provide.""" async with ctx.typing(): img_bytes = await yuki.get_image(link, ctx) with Image.open(BytesIO(img_bytes)) as img: imgThonk = Image.open("assets/thonk.png") imgThonk = imgThonk.resize(img.size, Image.ANTIALIAS) img.paste(imgThonk, (0, 0), imgThonk) output_buf = BytesIO() # img.save(output_buf, "png", optimize = True, quality = 95) img.save(output_buf, "png") output_buf.seek(0) a = random.choice(("think", "thonk", "thenk", "thank", "thunk", "thuck")) b = random.choice(("ing", "eng", "eeng", "ang")) c = random.choice( ( "<:thunking:438870072870830100> ", "<:thuck:457358934127149056>", "<:thonkDIY:457359669673852958>", "<:thonk:457359658357620746>", "<:thenkeng:416429946538295298>", "<:thanking:416429946441957377>", "<:hmm:438870239158075407>", "<:hmm:457359215070019585>", "<:blobthonkang:416430096291987467>" ) ) embed = discord.Embed(title = f"{a}{b} {c}", color = 0xFFCC4D) file = discord.File(filename = "result.png", fp = output_buf) embed.set_image(url = "attachment://result.png") await ctx.send(embed = embed, file = file) @commands.command(aliases = [u"\U0001f4ad"]) async def thought(self, ctx, link: str = None): """Thoughts about the image you provide.""" # TODO: Blocks a huge amount, fix it. async with ctx.typing(): img_bytes = await yuki.get_image(link, ctx) with Image.open(BytesIO(img_bytes)) as img: layer1 = Image.open("assets/thonk3.png") layer1 = layer1.resize((int(img.width * 2.5), int(img.width * 2.5)), Image.ANTIALIAS) layer3 = Image.new("RGBA", (int(img.width * 2.5), int(img.width * 2.5)), (0, 0, 0, 0)) layer3.paste(img, (0, 0), img.convert("RGBA")) layer2 = Image.open("assets/thonk2.png") layer2 = layer2.resize((int(img.width * 1.75), int(img.width * 1.75)), Image.ANTIALIAS) layer2_canvas = Image.new("RGBA", (int(img.width * 2.5), int(img.width * 2.5)), (0, 0, 0, 0)) layer2_canvas.paste(layer2, (int((img.width * 2.5) - layer2.width), int((img.width * 2.5) - layer2.height)), layer2) layer2 = layer2_canvas # layer2.paste(layer3, (0, 0), layer3) layer2 = Image.alpha_composite(layer2, layer3) # layer1.paste(layer2, (0, 0), layer2) layer1 = Image.alpha_composite(layer1, layer2) result = layer1 output_buf = BytesIO() result.save(output_buf, "png") output_buf.seek(0) file = discord.File(filename = "result.png", fp = output_buf) await ctx.send(file = file) @commands.group(aliases = ["f", u"\U0001f578"]) async def filter(self, ctx): pass @filter.command() async def invert(self, ctx, link: str = None): """Inverts image.""" # messages = await ctx.message.channel.history().flatten() async with ctx.typing(): img_bytes = await yuki.get_image(link, ctx) with Image.open(BytesIO(img_bytes)) as img: if img.mode == "RGBA": r, g, b, a = img.split() img_rgb = Image.merge("RGB", (r, g, b)) img_inv = PIL.ImageOps.invert(img_rgb) r2, g2, b2 = img_inv.split() img = Image.merge("RGBA", (r2, g2, b2, a)) else: img = PIL.ImageOps.invert(img) output_buf = BytesIO() img.save(output_buf, "png") output_buf.seek(0) file = discord.File(filename = "result.png", fp = output_buf) await ctx.send(file = file) @filter.command(aliases = [u"\u0001f4a7"]) async def blur(self, ctx, radius: int = 2, link: str = None): """Blurs image.""" if radius > 100: await yuki.send_error("Radius is limited to 100.", ctx) else: async with ctx.typing(): img_bytes = await yuki.get_image(link, ctx) with Image.open(BytesIO(img_bytes)) as img: img = img.filter(ImageFilter.GaussianBlur(radius = radius)) output_buf = BytesIO() img.save(output_buf, "png") output_buf.seek(0) embed = discord.Embed(color = 0x36393F) file = discord.File(filename = "result.png", fp = output_buf) embed.set_image(url = "attachment://result.png") embed.set_footer(text = f"Radius: {radius}") await ctx.send(embed = embed, file = file) @filter.command() async def emboss(self, ctx, link: str = None): """Applies emboss filter to image.""" async with ctx.typing(): img_bytes = await yuki.get_image(link, ctx) with Image.open(BytesIO(img_bytes)) as img: img = img.filter(ImageFilter.EMBOSS) output_buf = BytesIO() img.save(output_buf, "png") output_buf.seek(0) file = discord.File(filename = "result.png", fp = output_buf) await ctx.send(file = file) @filter.command() async def contour(self, ctx, link: str = None): """Applies contour filter to image.""" async with ctx.typing(): img_bytes = await yuki.get_image(link, ctx) with Image.open(BytesIO(img_bytes)) as img: img = img.filter(ImageFilter.CONTOUR) output_buf = BytesIO() img.save(output_buf, "png") output_buf.seek(0) file = discord.File(filename = "result.png", fp = output_buf) await ctx.send(file = file) @filter.command() async def mosaic(self, ctx, link: str = None): """Applies mosaic filter to image.""" async with ctx.typing(): img_bytes = await yuki.get_image(link, ctx) with Image.open(BytesIO(img_bytes)) as img: output = Image.new("RGBA", img.size, color = (0, 0, 0, 0)) quarter_img = img.resize((int(img.width / 2), int(img.height / 2)), resample = Image.BICUBIC) locations = ( (0, 0), (int(img.width / 2), 0), (0, int(img.height / 2)), (int(img.width / 2), int(img.height / 2)) ) for location in locations: output.paste(quarter_img, location) output_buf = BytesIO() output.save(output_buf, "png") output_buf.seek(0) file = discord.File(filename = "result.png", fp = output_buf) await ctx.send(file = file) @commands.command(aliases = ["qr", u"\U0001f4d3"]) async def qrcode(self, ctx, *, text: str = None): """Gives you a QR Code that includes text.""" async with ctx.typing(): qr = qrcode.QRCode( box_size = 20 ) qr.add_data(text) qr.make() img = qr.make_image(fill_color = "black", back_color = "white") output_buf = BytesIO() img.save(output_buf, "png") output_buf.seek(0) embed = discord.Embed(title = "Scan it!", color = 0xFFFFFF) file = discord.File(filename = "result.png", fp = output_buf) embed.set_image(url = "attachment://result.png") await ctx.send(embed = embed, file = file) @commands.command(aliases = [u"\U0001f47e"]) async def rashot(self, ctx): """Gives you a random RetroArch screenshot.""" async with ctx.typing(): ss_path = "D:/RetroArch/screenshots/" img_path = random.choice(listdir(ss_path)) file = discord.File(f"{ss_path}/{img_path}", filename = "image.png") embed = discord.Embed(title = "RetroArch Screenshot", url = "http://retroarch.com/", color = 0x2196f3) embed.set_image(url = "attachment://image.png") embed.set_thumbnail(url = "https://image.ibb.co/kayTNd/invader.png") await ctx.send(embed = embed, file = file) def setup(bot): bot.add_cog(Images(bot)) ================================================ FILE: cogs/info.py ================================================ import discord from discord.ext import commands from yuki import color as ykColor import yuki import aiohttp from io import BytesIO from os.path import isfile class Info: def __init__(self, bot): self.bot = bot async def get_check(self, is_true): if is_true: is_true = u"\u2705" else: is_true = str(yuki.cross_mark) # u"\u274C" return is_true async def format_time(self, datetime): months = ( "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ) return "{:02} {} {} at {:02}:{:02} and {}s".format( datetime.day, months[datetime.month - 1], datetime.year, datetime.hour, datetime.minute, datetime.second ) @commands.command(aliases = [u"\U00002753"]) async def help(self, ctx, command = None): """Shows the help.""" cog_display_dict = { "Coins": "\N{MONEY BAG} Coins", "Copypasta": "\N{SPAGHETTI} Copypasta", "Experimental": "\N{CONSTRUCTION SIGN} Experimental", "Images": "\N{FRAME WITH PICTURE} Image", "Info": "\N{INFORMATION SOURCE} Info", "Guild": "\N{HOUSE WITH GARDEN} Server", "Text": "\N{KEYBOARD} Text", "Utilities": "\N{HAMMER AND WRENCH} Utils", "NSFW": "\N{AUBERGINE} NSFW", "Stars": "\N{WHITE MEDIUM STAR} Stars" } prefix = self.bot.command_prefix(self.bot, ctx)[-1] if not command: embed = discord.Embed(title = None, description = f"__{self.bot.description}__", color = ykColor) embed.set_author(name = self.bot.user.name, icon_url = self.bot.user.avatar_url) embed.set_thumbnail(url = self.bot.user.avatar_url) for cog_name in sorted(self.bot.cogs): # Hide the NSFW category in non-NSFW channels. if ctx.guild: if cog_name == "NSFW" and not ctx.channel.nsfw: continue """ cmds = "" for cmd in self.bot.get_cog_commands(cogName): # lastAlias = "" if len(command.aliases) == 0 else '|' + command.aliases[-1] if not cmd.hidden: cmds += f"``{prefix}{cmd.name}`` " """ cmds = [] for cmd in self.bot.get_cog_commands(cog_name): if not cmd.hidden: cmds.append(cmd) cmds = u" \u25CF ".join([f"{cmd}" for cmd in cmds]) if cmds != "": embed.add_field(name = cog_display_dict.get(cog_name, cog_name), value = cmds, inline = False) embed.set_footer(text = f"Type {prefix}help for info on a command.") await ctx.send(embed = embed) else: cmd = self.bot.all_commands[command.lower()] if not isinstance(cmd, commands.Group): embed = discord.Embed( title = "{}{}".format(prefix, cmd.signature.replace('[', '<').replace(']', '>')), description = cmd.help, color = ykColor ) embed.set_footer(text = cog_display_dict.get(cmd.cog_name, cmd.cog_name)) path = f"assets/usage/{cmd.name}.png" filename = f"{cmd.name}.png" if isfile(path): file = discord.File(path, filename = filename) embed.set_image(url = f"attachment://{filename}") await ctx.send(embed = embed, file = file) else: await ctx.send(embed = embed) else: embed = discord.Embed(title = f"{prefix}{cmd.name}", description = cmd.help, color = ykColor) for command in cmd.commands: if not command.hidden: embed.add_field( name = command.signature.split(' ', 1)[1].replace('[', '<').replace(']', '>'), value = command.help if command.help else "No help info.", inline = False ) embed.set_footer(text = cog_display_dict.get(cmd.cog_name, cmd.cog_name)) await ctx.send(embed = embed) @commands.command(aliases = ["support"]) async def about(self, ctx): """Outputs info about the bot.""" """await ctx.send( "```" + self.bot.description + "\nhyarsan is not held responsible for ANYTHING you do with the bot." + "```" + "\nInvite: \nPermanent Invite Link For Support: https://discord.gg/qfYekaJ" )""" embed = discord.Embed( title = "About Yukiko", description = self.bot.description, color = ykColor ) embed.set_author( name = "Yukiko", url = "https://discordbots.org/bot/447493600167591936", icon_url = self.bot.user.avatar_url ) embed.add_field( name = "Bot Invite:", value = "[Link](https://discordapp.com/oauth2/authorize?client_id=447493600167591936&permissions=8&scope=bot)", inline = True ) embed.add_field( name = "Support Server Invite:", value = "[Link](https://discord.gg/qfYekaJ)", inline = True ) embed.add_field( name = "Vote", value = "[Discord Bots](https://discordbots.org/bot/447493600167591936/vote)\n" "[Discord Bot List](https://discordbotlist.com/bots/447493600167591936)", inline = True ) embed.set_thumbnail(url = self.bot.user.avatar_url) await ctx.send(embed = embed) @commands.command() async def invite(self, ctx): """Outputs the bot's invite link.""" embed = discord.Embed(title = "", color = ykColor) embed.set_author( name = "Click here to invite Yukiko to your server.", url = "https://discordapp.com/oauth2/authorize?client_id=447493600167591936&permissions=8&scope=bot", icon_url = self.bot.user.avatar_url ) await ctx.send(embed = embed) @commands.command(aliases = ["pfp", u"\U0001f464"]) async def avatar(self, ctx, member: discord.Member = None): """Outputs the member's avatar.""" if member == None: mem = ctx.message.author else: mem = member # mem = ctx.message.guild.get_member_named(member) embed_color = mem.top_role.color if ctx.guild else ykColor embed = discord.Embed(title = "", description = "Avatar", color = embed_color) embed.set_author( name = str(mem), icon_url = mem.avatar_url ) embed.set_image(url = mem.avatar_url_as(static_format = "png")[:-4] + "4096") await ctx.send(embed = embed) @commands.command(aliases = ["user", "member", u"\U0001f465"]) async def userinfo(self, ctx, member: discord.Member = None): """Outputs info about the member.""" if member == None: mem = ctx.message.author else: mem = member status_dict = { "online": "Online<:online:461118969575899136>", "idle": "Idle<:idle:461118969433161748>", "dnd": "Do Not Disturb<:dnd:461118969441419264>", "offline": "Offline<:offline:461118969424904193>" } status = status_dict[str(mem.status)] if ctx.guild else None activity_dict = { discord.ActivityType.playing: "Playing", discord.ActivityType.streaming: "Streaming", discord.ActivityType.listening: "Listening to", discord.ActivityType.watching: "Watching" } try: try: activity_type = activity_dict[mem.activity.type] except: activity_type = "Playing" except: activity_type = None cleaned_nick = await commands.clean_content(escape_markdown = True).convert(ctx, mem.nick) activity_name = mem.activity.name if mem.activity else "None" embed_color = mem.top_role.color if ctx.guild else ykColor embed = discord.Embed(title = "", color = embed_color) embed.set_author( name = str(mem), icon_url = mem.avatar_url ) embed.set_thumbnail(url = mem.avatar_url) embed.add_field(name = "ID", value = mem.id, inline = True) if ctx.guild: embed.add_field(name = "Nickname", value = cleaned_nick, inline = True) embed.add_field(name = "Bot?", value = await self.get_check(mem.bot), inline = True) if ctx.guild: embed.add_field(name = "Status", value = status, inline = True) embed.add_field(name = activity_type, value = activity_name, inline = True) embed.add_field(name = "Joined Guild", value = await self.format_time(mem.joined_at), inline = True) embed.add_field(name = "Joined Discord", value = await self.format_time(mem.created_at), inline = True) embed.add_field(name = "Mention", value = mem.mention, inline = False) if ctx.guild: embed.add_field(name = "Roles", value = "@everyone " + ' '.join([r.mention for r in mem.roles[1:]]), inline = True) await ctx.send(embed = embed) @commands.command(aliases = ["guild", "server", "serverinfo"]) @commands.guild_only() async def guildinfo(self, ctx): """Outputs info about the guild.""" """if guild == None: gld = ctx.message.guild elif guild.isdigit(): # gld = ctx.message.guild await ctx.send("Specifying guild not supported yet.")""" gld = ctx.guild roles_list = ["@everyone"] if len(gld.roles) > 10: roles_list = [f"{len(gld.roles)} roles."] else: for role in gld.roles[1:]: roles_list.append(role.mention) if len(roles_list) == 0: roles_list.append("None") text_channels_list = [] if len(gld.text_channels) > 10: text_channels_list.append(f"{len(gld.text_channels)} channels.") else: for channel in gld.text_channels: text_channels_list.append(channel.mention) if len(text_channels_list) == 0: text_channels_list.append("None") voice_channels_list = [] if len(gld.voice_channels) > 10: voice_channels_list.append(f"{len(gld.voice_channels)} voice channels.") else: for channel in gld.voice_channels: voice_channels_list.append(channel.name) if len(voice_channels_list) == 0: voice_channels_list.append("None") emojis_list = [] if len(' '.join(str(gld.emojis))) > 1024: emojis_list.append(f"{len(gld.emojis)} emojis.") else: for emoji in gld.emojis: emojis_list.append(str(emoji)) if len(emojis_list) == 0: emojis_list.append("None") afk_timeout_dict = { 60: "1 minute", 300: "5 minutes", 900: "15 minutes", 1800: "30 minutes", 3600: "1 hour" } content_filter_dict = { "disabled": "Don't scan any messages.", "no_role": "Scan messages from members without a role.", "all_members": "Scan messages sent by all members." } region_dict = { "us-west": "US West", "us-east": "US East", "us-south": "US South", "us-central": "US Central", "eu-west": "EU West", "eu-central": "EU Central", "singapore": "Singapore", "london": "London", "sydney": "Sydney", "amsterdam": "Amsterdam", "frankfurt": "Frankfurt", "brazil": "Brazil", "hongkong": "Hong Kong", "russia": "Russia", "vip-us-east": "VIP US East", "vip-us-west": "VIP US West", "vip-amsterdam": "VIP Amsterdam", "japan": "Japan", "southafrica": "South Africa" } verification_level_dict = { "none": "None", "low": "Low", "medium": "Medium", "high": "High", "extreme": "Extreme" } afk_timeout = afk_timeout_dict[gld.afk_timeout] afk_channel = str(gld.afk_channel.mention if gld.afk_channel else None) content_filter = content_filter_dict[gld.explicit_content_filter.name] region = region_dict[str(gld.region)] verification_level = verification_level_dict[str(gld.verification_level)] embed = discord.Embed(title = "", color = ykColor) embed.set_author(name = gld.name, icon_url = gld.icon_url) embed.set_thumbnail(url = gld.icon_url) embed.add_field(name = "ID", value = str(gld.id), inline = True) embed.add_field(name = "Owner", value = gld.owner.mention, inline = True) embed.add_field(name = "Region", value = region, inline = True) embed.add_field(name = "Created at", value = await self.format_time(gld.created_at), inline = True) embed.add_field(name = "Member Count", value = str(gld.member_count), inline = True) embed.add_field(name = "Roles", value = ' '.join(roles_list), inline = True) embed.add_field(name = "Text Channels", value = ' '.join(text_channels_list), inline = True) embed.add_field(name = "Voice Channels", value = ", ".join(voice_channels_list), inline = True) # embed.add_field(name = "Default Channel", value = "Soon...", inline = True) embed.add_field(name = "Emojis", value = ''.join(emojis_list), inline = True) embed.add_field(name = "Verification Level", value = verification_level, inline = True) # embed.add_field(name = "MFA Level", value = "Soon...", inline = True) # embed.add_field(name = "Default Notification Level", value = "Soon...", inline = True) embed.add_field(name = "Invite Splash", value = str(gld.splash), inline = True) embed.add_field(name = "Explicit Content Filter", value = content_filter, inline = True) embed.add_field(name = "AFK Voice Timeout", value = afk_timeout, inline = True) embed.add_field(name = "AFK Voice Channel", value = afk_channel, inline = True) embed.add_field(name = "Has VIP Regions?", value = await self.get_check("VIP_REGIONS" in gld.features), inline = True) embed.add_field(name = "Has a Custom URL?", value = await self.get_check("VANITY_URL" in gld.features), inline = True) embed.add_field(name = "Has Special Invite Splash?", value = await self.get_check("INVITE_SPLASH" in gld.features), inline = True) embed.add_field(name = "Verified?", value = await self.get_check("VERIFIED" in gld.features), inline = True) embed.add_field(name = "More Emoji?", value = await self.get_check("MORE_EMOJI" in gld.features), inline = True) await ctx.send(embed = embed) @commands.command(aliases = ["emoji", "emote", "emoteinfo", u"\U0001f61c"]) async def emojiinfo(self, ctx, emoji: discord.Emoji = None): """Outputs info about the emoji.""" # emoID = int(emoji.split(":")[2][:-1]) emo = emoji roles_list = [] if False: # len(gld.roles) > 10 roles_list.append(f"{len(gld.roles)} roles.") else: for role in emo.roles[1:]: roles_list.append(role.mention) if len(roles_list) == 0: roles_list.append("@everyone") # "Unrestricted" embed = discord.Embed(title = "", color = ykColor) embed.set_author(name = emo.name, icon_url = emo.url) embed.set_thumbnail(url = emo.url) embed.add_field(name = "ID", value = emo.id, inline = True) embed.add_field(name = "Guild", value = str(emo.guild), inline = True) embed.add_field(name = "Guild ID", value = str(emo.guild_id), inline = True) embed.add_field(name = "Created at", value = await self.format_time(emo.created_at), inline = True) embed.add_field(name = "Roles", value = ' '.join(roles_list), inline = True) embed.add_field(name = "Animated", value = await self.get_check(emo.animated), inline = True) embed.add_field(name = "Managed?", value = await self.get_check(emo.managed), inline = True) embed.add_field(name = "Require Colons?", value = await self.get_check(emo.require_colons), inline = True) await ctx.send(embed = embed) @commands.command(aliases = ("channel", "chan", "cha", "ct")) async def channelinfo(self, ctx, channel: discord.TextChannel = None): """Outputs info about the channel.""" if ctx.guild: if channel == None: cha = ctx.channel else: cha = channel if not len(cha.changed_roles) == 0: changed_roles = "@everyone " + ' '.join([r.mention for r in cha.changed_roles[1:]]) else: changed_roles = None embed = discord.Embed(title = '#' + cha.name, description = cha.topic, color = ykColor) embed.add_field(name = "Guild", value = cha.guild.name, inline = True) embed.add_field(name = "Category", value = str(cha.category), inline = True) embed.add_field(name = "NSFW?", value = await self.get_check(cha.nsfw), inline = True) embed.add_field(name = "Position in List", value = cha.position + 1, inline = True) embed.add_field(name = "Created at", value = await self.format_time(cha.created_at), inline = True) embed.add_field(name = "Mention", value = cha.mention, inline = True) embed.add_field(name = "Changed Roles", value = str(changed_roles), inline = True) await ctx.send(embed = embed) @commands.command(aliases = ["role"]) @commands.guild_only() async def roleinfo(self, ctx, role: discord.Role): """Outputs info about the role.""" rol = role embed = discord.Embed(description = rol.mention, color = rol.color) embed.add_field(name = "ID", value = rol.id, inline = False) embed.add_field(name = "Name", value = rol.name, inline = True) embed.add_field(name = "Guild", value = str(rol.guild), inline = True) # embed.add_field(name = "Permissions", value = "Coming soon..", inline = True) embed.add_field(name = "Created at", value = await self.format_time(rol.created_at), inline = True) embed.add_field(name = "Position", value = rol.position + 1, inline = True) embed.add_field(name = "Show in Online List?", value = await self.get_check(rol.hoist), inline = True) embed.add_field(name = "Managed?", value = await self.get_check(rol.managed), inline = True) embed.add_field(name = "Mentionable", value = await self.get_check(rol.mentionable), inline = True) embed.add_field(name = "Default Role?", value = await self.get_check(rol.is_default()), inline = True) embed.add_field(name = "Members with Role", value = ' '.join([m.mention for m in rol.members]), inline = True) await ctx.send(embed = embed) @commands.command(aliases = ["bot", "dbs", "dbsinfo", u"\U0001f916"]) async def botinfo(self, ctx, bot: discord.Member = None): """Outputs the DiscordBots stats of a bot.""" bot = self.bot.get_user(447_493_600_167_591_936) if bot == None else bot if bot.bot: async with aiohttp.ClientSession() as session: async with session.get(f"https://discordbots.org/api/widget/{bot.id}.png") as response: img_bytes = await response.read() file = discord.File(filename = f"{bot.id}.png", fp = BytesIO(img_bytes)) await ctx.send(file = file) else: await yuki.send_error("User isn't a bot.", ctx) """"@commands.command(aliases = ["urbandict", u"\U0001f916"]) async def urban(self, ctx, word: str = None):""" def setup(bot): bot.add_cog(Info(bot)) ================================================ FILE: cogs/nsfw.py ================================================ import discord from discord.ext import commands from yuki import color as ykColor import yuki import aiohttp import asyncio from rule34 import Rule34 from random import choice, sample class NSFW: def __init__(self, bot): self.bot = bot self.nsfw_emojis = ( "", "", "<:grip_nsfw:481828361069658147>", "<:lenny_nsfw:481828458230579200>", "<:fruitsex_nsfw:480755216505896972>", "<:peachy_nsfw:497799370897489923>", "<:eggblow_nsfw:497799325695475732>" ) @commands.group(aliases = ["r34"]) @commands.is_nsfw() async def rule34(self, ctx): pass @rule34.group(aliases = ["rand", "r"]) async def random(self, ctx, *, tags: str): """Outputs a random image from Rule 34.""" tags = ['_'.join(tag.strip().split()) for tag in tags.split('+')] async with ctx.typing(): r34 = Rule34(asyncio.get_event_loop()) results = await r34.getImageURLS(*tags) if results: result = choice(results) emoji = choice(self.nsfw_emojis) embed = discord.Embed(description = f"{emoji} Rule34", color = ykColor) embed.set_image(url = result) embed.set_footer(text = "Tag(s): {}".format(", ".join(tags))) await ctx.send(embed = embed) else: await yuki.send_error("No results found.", ctx) @rule34.group(aliases = ["b"]) async def bomb(self, ctx, *, tags: str): """Outputs random images from Rule 34.""" tags = ['_'.join(tag.strip().split()) for tag in tags.split('+')] async with ctx.typing(): r34 = Rule34(asyncio.get_event_loop()) results = await r34.getImageURLS(*tags) if results: if len(results) >= 5: output = '\n'.join(sample(results, 5)) else: output = '\n'.join(results) await ctx.send(output) else: await yuki.send_error("No results found.", ctx) def setup(bot): bot.add_cog(NSFW(bot)) ================================================ FILE: cogs/owner.py ================================================ import discord from discord.ext import commands from yuki import color as ykColor import yuki import sys from io import StringIO import traceback import platform import logging import asyncio # import lupa # from lupa import LuaRuntime import time class Owner: def __init__(self, bot): self.bot = bot self.allowed_users = ( self.bot.owner_id, 357_641_367_507_435_531, # Slick9000#7159 314_885_561_552_994_305, # Simon#2018 992_727_670_603_284_48, # Netux#2308 ) @commands.group(hidden = True, aliases = ["py", u"\U0001f40d"]) async def python(self, ctx): """Commands to do with using Python.""" pass @python.command(name = "exec", aliases = ["run"]) async def exec_(self, ctx, *, code: str = "print(\"Hello, World!\")"): """Executes Python 3 code.""" if ctx.author.id not in self.allowed_users: # await ctx.send("You don't have access to this command.") await yuki.send_error("You don't have access to this command.", ctx, icon = u"\U000026d4") else: async with ctx.typing(): old_stdout = sys.stdout old_stderr = sys.stderr sys.stdout = redir_stdout = StringIO() sys.stderr = redir_stderr = StringIO() try: exec(code) # If the code was successful, it would set exc to "". # If not, it would do except anyway. exc = "" except: exc = traceback.format_exc() out = redir_stdout.getvalue() err = redir_stderr.getvalue() out = f"```\n{out}```" if out else "No standard output." err = f"```\n{err}```" if err else "No error output." exc = f"```\n{exc}```" if exc else "No exception." embed = discord.Embed(title = "", color = ykColor) embed.set_author(name = f"Python { platform.python_version() }", icon_url = "https://cdn.discordapp.com/emojis/447523942949715969.png?v=1") embed.add_field(name = "Executed", value = f"```py\n{code}```", inline = False) embed.add_field(name = "Standard Output", value = out, inline = False) embed.add_field(name = "Error Output", value = err, inline = False) embed.add_field(name = "Exception", value = exc, inline = False) embed.set_thumbnail(url = "https://cdn.discordapp.com/emojis/447523942949715969.png?v=1") # embed.set_footer(text = "Python " + platform.python_version(), icon_url = "https://cdn.discordapp.com/emojis/447523942949715969.png?v=1") sys.stdout = old_stdout sys.stderr = old_stderr await ctx.send(embed = embed) @python.command(name = "eval") async def eval_(self, ctx, *, code: str): """Evaluates Python 3 code.""" if ctx.author.id not in self.allowed_users: # await ctx.send("You don't have access to this command.") await yuki.send_error("You don't have access to this command.", ctx, icon = u"\U000026d4") else: async with ctx.typing(): try: ret = eval(code) # If the code was successful, it would set exc to "". # If not, it would do except anyway. exc = "" except: exc = traceback.format_exc() output = f"```{ret}```" if not exc else f"```{exc}```" await ctx.send(output) @commands.command(name = "load", hidden = True) @commands.is_owner() async def cog_load(self, ctx, *, cog: str): """Loads a cog.""" try: self.bot.load_extension(cog) except Exception as e: # await ctx.send(f'**`ERROR:`** {type(e).__name__} - {e}') await ctx.message.add_reaction(yuki.cross_mark) logging.error(f'Load Cog Error: {type(e).__name__} - {e}') else: # await ctx.send('**`SUCCESS`**') await ctx.message.add_reaction(u"\u2705") @commands.command(name = "unload", hidden = True) @commands.is_owner() async def cog_unload(self, ctx, *, cog: str): """Unloads a cog.""" try: self.bot.unload_extension(cog) except Exception as e: # await ctx.send(f'**`ERROR:`** {type(e).__name__} - {e}') await ctx.message.add_reaction(yuki.cross_mark) logging.error(f'Unload Cog Error: {type(e).__name__} - {e}') else: # await ctx.send('**`SUCCESS`**') await ctx.message.add_reaction(u"\u2705") @commands.command(name = "reload", hidden = True) @commands.is_owner() async def cog_reload(self, ctx, *, cog: str): """Reloads a cog.""" try: self.bot.unload_extension(cog) self.bot.load_extension(cog) except Exception as e: # await ctx.send(f'**`ERROR:`** {type(e).__name__} - {e}') await ctx.message.add_reaction(yuki.cross_mark) logging.error(f'Reload Cog Error: {type(e).__name__} - {e}') else: # await ctx.send('**`SUCCESS`**') await ctx.message.add_reaction(u"\u2705") def setup(bot): bot.add_cog(Owner(bot)) ================================================ FILE: cogs/stars.py ================================================ import discord from discord.ext import commands from yuki import color as ykColor import yuki import typing from io import BytesIO class Stars: def __init__(self, bot): self.bot = bot # self.prefix = self.bot.command_prefix(self.bot, ctx)[-1] self.star_color = 0xffac33 self.star_icon = "https://discordapp.com/assets/e4d52f4d69d7bba67e5fd70ffe26b70d.svg" self.star_emoji = u"\u2B50" self.channel_topic = u"\u2B50 A starboard where you can star messages by doing {prefix}star. \u2B50" self.webhook_name = "Star" self.webhook_icon = "https://cdn.discordapp.com/attachments/447786789563006986/494581408661110794/star.png" async def _star(self, ctx, messageid): msg = await ctx.channel.get_message(messageid) cha = await self._get_starboard(ctx.guild) star_content = await commands.clean_content().convert(ctx, msg.content) star_username = msg.author.display_name star_avatar = msg.author.avatar_url_as(format = "png") star_embed = discord.Embed( colour = self.star_color, description = f"[Jump to the message!]({msg.jump_url})", timestamp = msg.created_at ) star_embed.set_footer(text = "Starred", icon_url = self.webhook_icon) star_embed.add_field(name = "Author", value = msg.author.mention, inline = True) star_embed.add_field(name = "Channel", value = msg.channel.mention, inline = True) if len(msg.embeds) <= 10: star_embeds = list(msg.embeds[:9]) + [star_embed] else: star_embeds = list(msg.embeds) + [star_embed] webhook = discord.utils.get(await cha.webhooks(), name = self.webhook_name) if len(msg.attachments) == 0: star_file = None else: fp = BytesIO() attachment = msg.attachments[0] await attachment.save(fp) star_file = discord.File(fp = fp, filename = attachment.filename) await webhook.send( content = star_content, embeds = star_embeds, file = star_file, username = star_username, avatar_url = star_avatar ) async def _get_starboard(self, guild): # cha = discord.utils.get(gld.channels, name = cha_name) for channel in guild.text_channels: if await self._check_if_starboard(channel): return channel async def _check_if_starboard(self, channel): webhook = discord.utils.get(await channel.webhooks(), name = self.webhook_name) return bool(webhook) @commands.command(hidden = True) @commands.has_permissions(manage_webhooks = True) @commands.is_owner() async def setupstar(self, ctx, channel: typing.Union[discord.TextChannel, str] = None): """Creates a starboard for ``.yk star``.""" gld = ctx.guild prefix = self.bot.command_prefix(self.bot, ctx)[-1] if isinstance(channel, str): cha_name = channel.lower() elif isinstance(channel, str): cha_name = channel.name else: cha_name = "starboard" # Create the channel if it doesn't exist already. if isinstance(channel, discord.TextChannel): cha = channel elif isinstance(channel, str): cha = discord.utils.get(gld.channels, name = cha_name) if cha: pass else: try: cha = await gld.create_text_channel(name = cha_name, reason = f"{ctx.author} used the setupstar command.") """embed = discord.Embed(description = "", color = self.star_color) embed.set_author( name = f"Successfully created channel #{cha_name}.", icon_url = "https://cdn.discordapp.com/attachments/447786789563006986/476225004015452160/plus_icon.png" ) await ctx.send(embed = embed)""" except: if len(gld.channels) <= 500: await yuki.send_error(f"No space left to create #{cha_name}.", ctx) else: await yuki.send_error(f"Couldn't create starboard channel #{cha_name}.", ctx) return # Edit the channel topic if it isn't the same. if cha.topic == self.channel_topic: pass else: await cha.edit(topic = self.channel_topic.format(prefix = prefix)) # Create the webhook if it doesn't exist already. webhook = discord.utils.get(await cha.webhooks(), name = self.webhook_name) if webhook: pass else: try: await cha.create_webhook(name = self.webhook_name, avatar = self.webhook_icon) except: await yuki.send_error("Couldn't create webhook.", ctx) return embed = discord.Embed(color = self.star_color) embed.set_author(name = f"Successfully setup #{cha_name} for use with stars.", icon_url = self.star_icon) await ctx.send(embed = embed) self.star_icon = "https://discordapp.com/assets/e4d52f4d69d7bba67e5fd70ffe26b70d.svg" self.channel_topic = u"\u2B50 A starboard where you can star messages by doing {prefix}star. \u2B50" self.webhook_name = "Star" self.webhook_icon = "https://cdn.discordapp.com/attachments/447786789563006986/494581408661110794/star.png" @commands.command(hidden = True) async def star(self, ctx, messageid: int): """Stars a message.""" await self._star(ctx, messageid) def setup(bot): bot.add_cog(Stars(bot)) ================================================ FILE: cogs/tests.py ================================================ import discord from discord.ext import commands from yuki import color as ykColor import yuki """ import js2py import aiohttp from minigames import TicTacToe from discord.ext.commands.formatter import HelpFormatter""" from minigames import FloodIt from io import BytesIO import asyncio class Experimental: def __init__(self, bot): self.bot = bot @commands.command(aliases = [u"\U0001f50a"]) @commands.guild_only() @commands.is_owner() async def play(self, ctx, *, sound: str = "YOU SUCK"): """Plays a sound.""" """voice = await bot.join_voice_channel(ctx.message.author.voice.voice_channel) player = voice.create_ffmpeg_player("./sounds/suck.mp3") player.start() if ctx.me.voice.channel == ctx.message.author.voice.channel:""" """if ctx.message.guild.voice_client.channel != ctx.message.author.voice.channel: await ctx.message.guild.voice_client.move_to(ctx.message.author.voice.channel) elif ctx.message.guild.voice_client.channel == ctx.message.author.voice.channel: await ctx.message.guild.voice_client.disconnect() elif ctx.message.guild.voice_client.channel == None: pass voice = await ctx.message.author.voice.channel.connect() # voice.move_to(ctx.message.author.voice.channel) voice.play(discord.FFmpegPCMAudio("./assets/sounds/" + sound.upper() + ".mp3"))""" if ctx.guild.voice_client == None: voice = await ctx.message.author.voice.channel.connect() else: voice = ctx.guild.voice_client await voice.move_to(ctx.message.author.voice.channel) voice.play(discord.FFmpegPCMAudio(f"./assets/sounds/{ sound.lower() }.mp3")) """@commands.command(aliases = ("member", "memberinfo", "user", "pfp")) async def userinfo(self, ctx, *, member: str): Gives info about the member. mem = ctx.message.guild.get_member_named(member) embed = discord.Embed(title = mem.name + "'s Avatar", description = mem.name, color = ykColor) await ctx.send(embed = embed)""" """@commands.command() async def exec(self, ctx): js = var repl = new ReplitClient('api.repl.it', 80, 'ruby', token); repl.connect().then(() => repl.evaluate( 'puts "hello world"', { stdout: out => return(out) } ); }); .replace("document.write", "return ") result = js2py.eval_js(js) await ctx.send(result)""" """@commands.command(aliases = ["ttt"]) async def tictactoe(self, ctx, *, sound: str = "YOU SUCK"):""" """@commands.command(aliases = ["type"]) async def typewrite(self, ctx, *, text: str): Bot typewrites whatever text you give. text = ''.join(text) a = text[0] msg = await ctx.send(text[0]) async with ctx.typing(): for char in text[1:]: await asyncio.sleep(0.1) a += char await msg.edit(content = a)""" """@commands.command() async def joke(self, ctx): Gives you a random joke. async with aiohttp.ClientSession() as session: async with session.get("https://icanhazdadjoke.com/") as resp: print(await resp.json())""" @commands.command(aliases = ["flood-it"]) async def floodit(self, ctx): game = FloodIt() output_buf = BytesIO() game.field.save(output_buf, "png") output_buf.seek(0) embed = discord.Embed(title = "Flood-It", color = ykColor) file = discord.File(filename = "floodit.png", fp = output_buf) embed.set_image(url = "attachment://floodit.png") msg = await ctx.send(embed = embed, file = file) for color in game.colors.keys(): emoji = discord.utils.get(self.bot.get_guild(459754073382715393).emojis, name = color) await msg.add_reaction(emoji) def check(reaction, user): return user == ctx.author while not game.isFull(): try: reaction, user = await self.bot.wait_for("reaction_add", timeout = 60 * 2, check = check) game.next(str(reaction).split(':')[1]) output_buf = BytesIO() game.field.save(output_buf, "png") output_buf.seek(0) embed = msg.embeds[0] file = discord.File(filename = "floodit.png", fp = output_buf) embed.set_image(url = "attachment://floodit.png") # await msg.edit(embed = embed, file = file) await msg.remove_reaction(reaction, ctx.author) except asyncio.TimeoutError: # await ctx.send("Flood-It game ended!") await msg.clear_reactions() return @commands.command(aliases = [u"\U0001f4cc"]) @commands.has_permissions(manage_messages = True) async def pin(self, ctx, messageid: int = None): """Pins a message by either reacting to the message or specifying the id.""" if messageid: try: message = await ctx.get_message(id = messageid) except: message = None await yuki.send_error("Message doesn't exist.", ctx) if message and message.pinned: await yuki.send_error("Message is already pinned.", ctx) else: try: await message.pin() return except: await yuki.send_error("Couldn't pin message.", ctx) else: check = lambda r, u: u == ctx.author and r == '\N{PUSHPIN}' try: reaction, user = await self.bot.wait_for("reaction_add", check = check) except asyncio.TimeoutError: await yuki.send_error("Ran out of time to pin message.", ctx) def setup(bot): bot.add_cog(Experimental(bot)) ================================================ FILE: cogs/text.py ================================================ import discord from discord.ext import commands from yuki import color as ykColor import yuki import upsidedown from pyfiglet import Figlet import cowsay import sys from io import StringIO # import emoji class Text: def __init__(self, bot): self.bot = bot @commands.command(aliases = [u"\U0001f4ac"]) async def say(self, ctx, *, text: str): """Outputs text deleting the original message.""" if not ctx.author.guild_permissions.administrator: text = await commands.clean_content().convert(ctx, text) await ctx.send(text) await ctx.message.delete() @commands.command(aliases = ["talk", "speak", u"\U0001f5e3"]) async def tts(self, ctx, *, text: commands.clean_content): """Text-to-speech text.""" await ctx.send(text, tts = True) # await ctx.message.delete() @commands.command() async def echo(self, ctx, *, text: commands.clean_content): """Outputs text.""" await ctx.send(text) @commands.command(aliases = ["upside", "upsidedown", u"\U0001f643"]) async def updown(self, ctx, *, text: commands.clean_content): """Outputs text upside down.""" output = await commands.clean_content().convert(ctx, upsidedown.transform(text)) await ctx.send(output) @commands.command() async def dank(self, ctx, *, text: commands.clean_content): """Outputs text in **``d a n k l e t t e r s``**.""" dankText = (' ' * 1).join(text) await ctx.send(f"**```{dankText}```**") @commands.command(aliases = ["uppercase", "caps"]) async def upper(self, ctx, *, text: commands.clean_content): """Outputs text in uppercase letters.""" output = await commands.clean_content().convert(ctx, text.upper()) await ctx.send(output) @commands.command(aliases = ["lowercase"]) async def lower(self, ctx, *, text: commands.clean_content): """Outputs text in lowercase letters.""" output = await commands.clean_content().convert(ctx, text.lower()) await ctx.send(output) @commands.command() async def title(self, ctx, *, text: commands.clean_content): """Outputs text Like A Title.""" output = await commands.clean_content().convert(ctx, text.title()) await ctx.send(output) @commands.command() async def capitalize(self, ctx, *, text: commands.clean_content): """Outputs text that's Capitalized.""" output = await commands.clean_content().convert(ctx, text.capitalize()) await ctx.send(output) @commands.command() async def swapcase(self, ctx, *, text: commands.clean_content): """Outputs text iN sWAPCASE.""" output = await commands.clean_content().convert(ctx, text.swapcase()) await ctx.send(output) @commands.command() async def reverse(self, ctx, *, text: commands.clean_content): """Outputs text in reverse.""" output = await commands.clean_content().convert(ctx, text[::-1]) await ctx.send(output) @commands.command(aliases = ["\U0001f44f"]) async def clap(self, ctx, *text: commands.clean_content): u"""Outputs \U0001f44f text \U0001f44f like \U0001f44f this.""" text = ("Meme", "Review") if text == () else text seperator = " \N{CLAPPING HANDS SIGN} " await ctx.send(seperator.join(text)) @commands.command(aliases = ["capsizer", "altcase"]) async def altcaps(self, ctx, *, text: commands.clean_content): """Outputs text, iN "aLtCaPs".""" output = "" upper = False for char in text: if upper: output += char.upper() else: output += char.lower() if char.isalpha(): upper = not upper output = await commands.clean_content().convert(ctx, output) await ctx.send(output) @commands.command() async def figlet(self, ctx, *, text: commands.clean_content): """Outputs text in FIGlet letters.""" f = Figlet(font = "standard") rendered_text = f.renderText(text) output = f"```{rendered_text}```" if rendered_text != "" else "No output." await ctx.send(output) @commands.command(aliases = ["meemspeak", "meemspeek", "memespeek"]) async def memespeak(self, ctx, *, text: commands.clean_content): """Outputs text in memespeak.""" # NOTE: Don't take any of this seriously translations = { "boy": "boi", "meme": "meem", "play": "plae", "game": "gaem", "stupid": "stoopid", "vagina": "vagene", "dick": "dic", "libretro": "libret", "lol": "lole", "think": "thonk", "spanish": "despacito", "gay": "gae", "lesbian": "les", "spaghetti": "spaget", "cute": "kewt", "love": "luv", "sex": "secks", "sexy": "secksy", "suck": "succ", "sucks": "sux", "thick": "thicc", "haha": "lole", "rofl": "rolf", "youtube": "utoob", "nigga": "nibba", "fucking": "fakking", "pussy": "pussi", "boobs": "bobs", "boob": "bob", "roblox": "roblocks", "blocks": "blox", "bucks": "bux", "please": "pls", " though ": " tho ", "yeah": "yeh", "sup": "suh", "what's up": "wassup", "speak": "speek", "okay": "ok", "when": "wen", "what": "wat", "I ": "me ", "you": "u", "oh ": "o ", "your ": "ur ", "you ": "u", "you're ": "u r ", "and ": "& " } output = text for word, translation in translations.items(): output = output.replace(word, translation) output = await commands.clean_content().convert(ctx, output) await ctx.send(output) @commands.command(aliases = [u"\U0001f42e", u"\U0001f404"]) async def cowsay(self, ctx, *, text: commands.clean_content): """Cow says whatever text you give.""" old_stdout = sys.stdout sys.stdout = redir_stdout = StringIO() cowsay.cow(text) out = redir_stdout.getvalue() sys.stdout = old_stdout await ctx.send(f"```{out}```") def setup(bot): bot.add_cog(Text(bot)) ================================================ FILE: cogs/utils.py ================================================ import discord from discord.ext import commands from yuki import color as ykColor import yuki import time import aiohttp import random import json from base64 import b64decode class Utilities: def __init__(self, bot): self.bot = bot self.ping_emoji = u"\U0001F3D3" # self.ping_emoji = "\N{TABLE TENNIS PADDLE AND BALL}" self.answers = ( "Very doubtful", "Most likely no", "Perhaps", "Definitely no", "Not sure", "No", "NO - It may cause disease contraction", "Nope", "Don't even think about it", "Don't count on it", "It is uncertain", "Ask again later", "Yes", "Of course!", "Perhaps", "My sources say yes" ) @commands.command(aliases = [u"\U0001f3d3"]) async def ping(self, ctx): """Outputs the bot's ping.""" t1 = time.perf_counter() await ctx.trigger_typing() # Tell Discord that the bot is typing. t2 = time.perf_counter() time_delta = abs(round((t1 - t2) * 1000, 2)) # Calculate the time. await ctx.send(content = f"{self.ping_emoji} Pong! That took **{time_delta} ms**.") """@commands.command(aliases = [u"\U0001f3d3"]) async def ping(self, ctx): Outputs the bot's ping. start = time.perf_counter() message = await ctx.send(f"_{self.pingEmoji}_") end = time.perf_counter() duration = (end - start) * 1000 output = "{} Pong! That took **{:.2f} ms**.".format(self.pingEmoji, duration) await message.edit(content = output)""" @commands.command() async def poll(self, ctx, question: str = "What game should we play?", *options: str): """Starts a simple poll.""" # ABCDEFGHI letters = ( u"\U0001F1E6", u"\U0001F1E7", u"\U0001F1E8", u"\U0001F1E9", u"\U0001F1EA", u"\U0001F1EB", u"\U0001F1EC", u"\U0001F1ED", u"\U0001F1EE" ) mem = ctx.message.author if ctx.guild: embed_color = mem.top_role.color else: embed_color = ykColor options = ("Fortnite", "PUBG") if options == () else options embed = discord.Embed(title = question, color = embed_color) embed.set_author(name = str(mem), icon_url = mem.avatar_url) for i, option in enumerate(options): embed.add_field(name = letters[i], value = option, inline = True) msg = await ctx.send(embed = embed) for i, option in enumerate(options): await msg.add_reaction(letters[i]) """@commands.command(pass_context = True) async def reddit(self, ctx, *, subreddit: str = "examplesubreddit"): subreddit = ''.join(subreddit).lower().replace(" ", "_") async with aiohttp.ClientSession() as cs: async with cs.get(f"https://api.reddit.com/r/{subreddit}/random") as r: data = await r.json() embed = discord.Embed(title = "T", color = ykColor) # str(data[1]["data"]["children"][0]["data"]["body"]) embed.set_image(url = data[0]["data"]["children"][0]["data"]["url"]) embed.set_footer(text = subreddit) await ctx.send(embed = embed)""" @commands.command(aliases = ["meow", "kitten", "purr", u"\U0001f431", u"\U0001f408"]) async def cat(self, ctx): """Outputs a random cat.""" async with ctx.typing(): async with aiohttp.ClientSession() as cs: async with cs.get("http://aws.random.cat/meow") as r: data = await r.json() embed = discord.Embed(title = u"Meow \U0001F431", color = ykColor) embed.set_image(url = data["file"]) embed.set_footer(text = "http://random.cat/") await ctx.send(embed = embed) @commands.command(aliases = ["bark", "puppy", u"\U0001f436", u"\U0001f415"]) async def dog(self, ctx): """Outputs a random dog.""" async with ctx.typing(): async with aiohttp.ClientSession() as cs: async with cs.get("https://dog.ceo/api/breeds/image/random") as r: data = await r.json() embed = discord.Embed(title = u"Bark \U0001F436", color = ykColor) embed.set_image(url = data["message"]) embed.set_footer(text = "https://dog.ceo/dog-api/") await ctx.send(embed = embed) @commands.command(aliases = ["choice"]) async def choose(self, ctx, *, options: commands.clean_content): """Chooses an option from a list of options.""" options_list = ''.join(options).split(',') options_list = [option.strip() for option in options_list] # fOptionsList = [f"**{option}**" for option in options_list] output = "\N{THINKING FACE} From ``{}`` I choose **{}**".format( ", ".join(options_list), random.choice(options_list) ) await ctx.send(output) @commands.command() async def shuffle(self, ctx, *, list: commands.clean_content): """Shuffles a list of things.""" shuffled_list = ''.join(list).split(',') shuffled_list = [thing.strip() for thing in shuffled_list] random.shuffle(shuffled_list) output = "``{}`` \N{BLACK RIGHTWARDS ARROW} ``{}``".format( list, ", ".join(shuffled_list) ) await ctx.send(output) @commands.command() async def sort(self, ctx, *, list: commands.clean_content): """Sorts a list of things in alphabetic order.""" sorted_list = ''.join(list).split(',') sorted_list = [thing.strip() for thing in sorted_list] sorted_list.sort() output = "``{}`` \N{BLACK RIGHTWARDS ARROW} ``{}``".format( list, ", ".join(sorted_list) ) await ctx.send(output) @commands.command() async def quote(self, ctx): """Outputs a random quote.""" async with aiohttp.ClientSession() as cs: async with cs.get("https://talaikis.com/api/quotes/random/") as r: data = await r.json() embed = discord.Embed(title = data["author"], description = data["quote"], color = ykColor) embed.set_footer(text = "https://talaikis.com/api/") await ctx.send(embed = embed) @commands.command(aliases = ["die", u"\U0001F3B2"]) async def dice(self, ctx): """Rolls a dice.""" a = random.randint(1, 6) b = '!' if a == 6 else '.' file = discord.File(f"assets/dice/{a}.png", filename = "dice.png") embed = discord.Embed(title = u"\U0001F3B2" + f" You rolled a {a}{b}", color = discord.Color.blurple()) embed.set_image(url = "attachment://dice.png") await ctx.send(embed = embed, file = file) @commands.command(aliases = ["skin"]) async def mcskin(self, ctx, username: str = "Steve"): """Gets a Minecraft skin.""" async with ctx.typing(): async with aiohttp.ClientSession() as cs: async with cs.get(f"https://api.mojang.com/users/profiles/minecraft/{username}") as r: try: data = await r.json() except: await yuki.send_error("Minecraft user doesn't exist!", ctx) return uuid = data["id"] name = data["name"] async with cs.get(f"https://sessionserver.mojang.com/session/minecraft/profile/{uuid}") as r: data1 = await r.json() value = data1["properties"][0]["value"] skinURL = json.loads(b64decode(value))["textures"]["SKIN"]["url"] embed = discord.Embed(title = f"{name}'s Skin", color = ykColor) embed.set_image(url = skinURL) await ctx.send(embed = embed) @commands.command(aliases = ["bc", "bcp", "bitcoinprice"]) async def bitcoin(self, ctx): """Outputs the current Bitcoin price.""" bc_logo = "https://raw.githubusercontent.com/roslinpl/bitcoin.it-promotional_graphics/master/bitcoinLogo1000.png" async with aiohttp.ClientSession() as cs: async with cs.get("https://api.coindesk.com/v1/bpi/currentprice.json") as r: data = json.loads(await r.content.read()) usd = data["bpi"]["USD"]["rate"] gbp = data["bpi"]["GBP"]["rate"] eur = data["bpi"]["EUR"]["rate"] embed = discord.Embed(title = "", color = 0xf7931a) embed.set_author( name = "Current Bitcoin Price", url = "https://www.coindesk.com/price/", icon_url = bc_logo ) embed.add_field(name = "United States Dollar", value = f"$ {usd}") embed.add_field(name = "British Pound Sterling", value = f"£ {gbp}") embed.add_field(name = "Euro", value = f"€ {eur}") embed.set_footer(text = "Powered by CoinDesk") await ctx.send(embed = embed) @commands.command(name = "8ball", aliases = ["ask", u"\U0001f3b1"]) async def ask(self, ctx, *, text: str): """Ask the 8-ball questions.""" if ''.join(text).endswith('?'): answer = random.choice(self.answers) else: answer = "Ask me something next time" embed = discord.Embed(color = ykColor) embed.set_author(name = "8-ball") # "https://image.ibb.co/drgwj8/8ball.png" embed.set_thumbnail(url = "https://image.ibb.co/drgwj8/8ball.png") embed.add_field(name = u"\U00002753 Question", value = ''.join(text), inline = False) embed.add_field(name = u"\U0001f3b1 Answer", value = answer, inline = True) embed.set_footer(text = "Put a ? for it to count as a question!") # await ctx.send(u"\U0001F3B1" + f" The 8-ball said ``{answer}``") await ctx.send(embed = embed) @commands.command(aliases = ["pm"]) async def dm(self, ctx, user: discord.User = None, *, text: str): """DMs text to the user.""" # await member.send(''.join(text)) msg_author = ctx.author embed = discord.Embed( title = "", description = ''.join(text), color = ykColor ) embed.set_author( name = str(msg_author), icon_url = msg_author.avatar_url ) embed.set_footer(text = f"User ID: {msg_author.id}") await user.send(embed = embed) await ctx.message.add_reaction(u"\u2705") # else: # await ctx.message.add_reaction(self.bot.get_emoji(465215264439664650)) @commands.command(aliases = ["plus", "\U00002795"]) async def sum(self, ctx, *numbers: float): """Adds numbers together.""" numbers = (3, 6) if numbers == () else numbers """ nums = [] for num in numbers: if num % 1 == 0: # If it ends with .0 nums.append(int(num)) else: nums.append(num) """ # Get rid of .0 nums = [int(num) if num % 1 == 0 else num for num in numbers] # Make every number a bold string f_numbers = [f"**{num}**" for num in nums] output = "{} = __**{}**__".format(" + ".join(f_numbers), sum(nums)) await ctx.send(output) def setup(bot): bot.add_cog(Utilities(bot)) ================================================ FILE: frontend.pyw ================================================ import sys from PyQt5.QtWidgets import * from PyQt5.QtGui import * # from PyQt5.QtCore import * import yuki import threading import logging import asyncio from functools import partial class QTextEditLogger(logging.Handler): def __init__(self, parent): super().__init__() self.widget = QTextEdit(parent) self.widget.setReadOnly(True) def emit(self, record): colorDict = { "INFO": "", "ERROR": "", "WARNING": "" } self.widget.append( colorDict.get(record.levelname, "") + self.format(record) + "" ) # self.widget.append("") app.processEvents() class AppForm(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): self.resize(640, 480) self.setWindowTitle("Yukiko") self.setWindowIcon(QIcon("assets/yukikoIcon.png")) self.channelTextBox = QLineEdit(self) self.channelTextBox.setPlaceholderText("Channel ID") # self.channelTextBox.textChanged.connect(partial(await yuki.start_typing, self.channelTextBox.text())) self.msgTextBox = QLineEdit(self) self.msgTextBox.setPlaceholderText("Message Content") # self.applyPlayingBtn.clicked.connect(self.applyPlayingStatus) self.sendMSGButton = QPushButton("Send Message", self) self.logTextBox = QTextEditLogger(self) self.logTextBox.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")) logging.getLogger().addHandler(self.logTextBox) logging.getLogger().setLevel(logging.INFO) self.layout = QVBoxLayout() self.layout.addWidget(self.logTextBox.widget) self.layout.addWidget(self.channelTextBox) self.layout.addWidget(self.msgTextBox) self.layout.addWidget(self.sendMSGButton) self.setLayout(self.layout) def applyPlayingStatus(self): yuki.changePlayingStatus(self.playingTextbox.text()) class RedirToLogger(object): # https://www.electricmonk.nl/log/2011/08/14/redirect-stdout-and-stderr-to-a-logger-in-python/ def __init__(self, logger, log_level = logging.INFO): self.logger = logger self.log_level = log_level self.linebuf = "" def write(self, buf): for line in buf.rstrip().splitlines(): self.logger.log(self.log_level, line.rstrip()) if __name__ == "__main__": """stdout_logger = logging.getLogger("STDOUT") sl = RedirToLogger(stdout_logger, logging.INFO) sys.stdout = sl """ stderr_logger = logging.getLogger("STDERR") sl = RedirToLogger(stderr_logger, logging.ERROR) sys.stderr = sl app = QApplication(sys.argv) # app.setStyle("Fusion") window = AppForm() t = threading.Thread(target = yuki.run_bot, name = "Runs the bot") t.daemon = True t.start() window.show() sys.exit(app.exec_()) ================================================ FILE: minigames.py ================================================ import numpy as np from PIL import Image, ImageDraw, ImageStat import random # gameBoard = np.zeros((7, 6)) class TicTacToe: def __init__(self): self.board = np.zeros((3, 3)) self.move = 1 # 1 is X, 2 is O. def draw(self): print(self.board) def place(self, x, y): if t.check(x, y) not in (1, 2): # Checks if X or O already placed there t.board[y - 1, x - 1] = self.move return 0 else: return 1 def check(self, x, y): return t.board[y -1, x - 1] def checkForWin(self): if self.check(1, 1) == self.check(2, 1) == self.check(3, 1): # Check if won on the first horizontal row return self.check(1, 1) elif self.check(1, 2) == self.check(2, 2) == self.check(3, 2): # Check if won on the second horizontal row return self.check(1, 2) elif self.check(1, 3) == self.check(2, 3) == self.check(3, 3): # Check if won on the third horizontal row return self.check(1, 3) elif self.check(1, 1) == self.check(1, 2) == self.check(1, 3): # Check if won on the first vertical row return self.check(1, 1) elif self.check(2, 1) == self.check(2, 2) == self.check(2, 3): # Check if won on the second vertical row return self.check(2, 1) elif self.check(3, 1) == self.check(3, 2) == self.check(3, 3): # Check if won on the third vertical row return self.check(3, 1) elif self.check(1, 1) == self.check(2, 2) == self.check(3, 3): # Check if won diagonally 1 return self.check(1, 1) elif self.check(3, 1) == self.check(2, 2) == self.check(1, 3): # Check if won diagonally 2 return self.check(1, 1) else: return None def isFull(self): a = 0 for list in self.board: if 0 in list: a += 1 if a == 0: return "tie" else: return "not full" def next(self): win = self.checkForWin() if win: return win elif self.isFull(): return self.isFull() if self.move == 1: self.move = 2 elif self.move == 2: self.move = 1 """if __name__ == "__main__": t = TicTacToe() running = True while running: t.draw() # Draw the game board a = input().split(" ") # Gets x and y and puts it into a tuple placed = t.place(int(a[0]), int(a[1])) # Returns 1 if no space there, otherwise 0 if placed == 1: print("There's no space there! Try again!") else: win = t.next() # Next move, and checks if someone won if win in (1, 2): # If someone won print(str(win), "wins!") input() running = False elif win == "tie": # Otherwise if it was a tie... print("It was a tie.") input() running = False""" class FloodIt: def __init__(self): self.colors = { "blue": (90, 192, 234), "orange": (230, 89, 50), "green": (156, 198, 58), "yellow": (250, 231, 75), "pink": (247, 150, 218), "dark_blue": (34, 122, 160) } self.field = Image.new("RGB", (14, 14)) pixels = self.field.load() for y in range(self.field.height): for x in range(self.field.width): pixels[y, x] = random.choice(tuple(self.colors.values())) self.field = self.field.resize((256, 256)) def next(self, fill): ImageDraw.floodfill(self.field, (0, 0), self.colors[fill]) # self.field.show() def isFull(self): extrema = ImageStat.Stat(self.field)._getextrema() return extrema.count(extrema[0]) == len(extrema) if __name__ == "__main__": game = FloodIt() game.isFull() ================================================ FILE: yuki.py ================================================ import discord from discord.ext import commands import logging import sys, traceback import webcolors from os.path import isfile from os import listdir from configparser import RawConfigParser import aiohttp import asyncio description = """A multi-purpose bot with fun commands""" prefix = ".yk " """async def get_pre(bot, msg): if msg.content.startswith(prefix) and msg.guild: return prefix elif msg.content.startswith(prefix) and not msg.guild: return prefix elif not msg.guild: return ''""" bot = commands.Bot( command_prefix = commands.when_mentioned_or(prefix), # , u"\U0001f916"), description = description, owner_id = 393_041_441_301_200_896 ) bot.remove_command("help") # Removes the default help command. color = 0xFF033E for file in listdir("cogs"): if file.endswith(".py") and not file.startswith('_'): name = file[:-3] try: bot.load_extension(f"cogs.{name}") except Exception as exc: print(f"Failed to load cog {name}.", file = sys.stderr) traceback.print_exc() @bot.event async def on_ready(): logging.info("Logged in as") logging.info(bot.user) logging.info(bot.user.id) logging.info("------") await bot.change_presence(activity = discord.Game(name = f"on {len(bot.guilds)} servers | {prefix}help")) global cross_mark cross_mark = bot.get_emoji(465_215_264_439_664_650) @bot.event async def on_guild_join(guild): await bot.change_presence(activity = discord.Game(name = f"on {len(bot.guilds)} servers | {prefix}help")) @bot.event async def on_guild_remove(guild): await bot.change_presence(activity = discord.Game(name = f"on {len(bot.guilds)} servers | {prefix}help")) @bot.event async def on_message(msg): if msg.author == bot.user: return if msg.author.bot: return await bot.process_commands(msg) @bot.event async def on_command_error(ctx, error): if isinstance(error, commands.MissingRequiredArgument): await send_error(f"<{ error.param.name.split(':')[0] }> is a required argument!", ctx) elif isinstance(error, commands.NoPrivateMessage): await send_error("Command can't be used in DM.", ctx) elif isinstance(error, commands.CommandNotFound): await ctx.message.add_reaction(bot.get_emoji(493_196_667_336_654_858)) elif isinstance(error, commands.DisabledCommand): await send_error("Command is disabled.", ctx) elif isinstance(error, commands.TooManyArguments): await send_error("Too many arguments were passed!", ctx) elif isinstance(error, commands.NotOwner): await send_error("Command may only be used by the bot owner.", ctx) elif isinstance(error, commands.MissingPermissions): if len(error.missing_perms) == 1: output = "You are missing the permission: ``{}``".format( error.missing_perms[0].replace('_', ' ').title() ) await send_error(output, ctx, icon = u"\U000026d4") else: perms = [] for perm in error.missing_perms: perms += f"``{ error.missing_perms[0].replace('_', ' ').title() }``" perms = '\n'.join(perms) output = f"You are missing the following perms: {perms}" await send_error(output, ctx, icon = u"\U000026d4") async def get_image(link, ctx): if link == None: # If no link is passed if len(ctx.message.attachments) >= 1: # Attachment used_link = ctx.message.attachments[0].url else: # Last Attachment async for message in ctx.channel.history(limit = 10): # If it has a height value it's an image if len(message.attachments) >= 1 and message.attachments[-1].height: used_link = message.attachments[-1].url break elif len(message.embeds) >= 1 and message.embeds[-1].image: used_link = message.embeds[-1].image.url break elif link.startswith("<:"): # (Custom) Emoji id = link.split(':')[2][:-1] used_link = bot.get_emoji(id).url print(id, used_link) else: used_link = link async with aiohttp.ClientSession() as session: # Link async with session.get(used_link) as response: return await response.read() async def send_error(error, ctx, icon = u"\U000026a0"): """Sends an error message.""" embed = discord.Embed(description = f"{icon} **{error}**", color = color) await ctx.send(embed = embed) async def start_typing(channelID): cha = await bot.get_channel(id = int(channelID)) await cha.trigger_typing() """def clean_text(text, ctx): return re.sub(r"\<\@(.*?)\>", Squeaky(ctx), text, flags = re)""" def run_bot(): config = RawConfigParser() config.read("config.ini") try: token = config["Secret"]["bot_token"] except KeyError: token = input("Type in your bot token: ") try: config["Secret"] except KeyError: config.add_section("Secret") config["Secret"]["bot_token"] = token with open("config.ini", "w") as f: config.write(f) """ try: mashapeKey = config["Secret"]["mashape_key"] except KeyError: mashapeKey = input("Type in your Mashape API key (Press enter if you don't have one): ") try: config["Secret"] except KeyError: config.add_section("Secret") config["Secret"]["bot_token"] = token with open("config.ini", "w") as f: config.write(f) """ bot.run(token, bot = True, reconnect = True) if __name__ == "__main__": run_bot()