diff --git a/LICENSE b/LICENSE deleted file mode 100644 index 0ad25db..0000000 --- a/LICENSE +++ /dev/null @@ -1,661 +0,0 @@ - GNU AFFERO GENERAL PUBLIC LICENSE - Version 3, 19 November 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 Affero General Public License is a free, copyleft license for -software and other kinds of works, specifically designed to ensure -cooperation with the community in the case of network server software. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -our General Public Licenses are 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. - - 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. - - Developers that use our General Public Licenses protect your rights -with two steps: (1) assert copyright on the software, and (2) offer -you this License which gives you legal permission to copy, distribute -and/or modify the software. - - A secondary benefit of defending all users' freedom is that -improvements made in alternate versions of the program, if they -receive widespread use, become available for other developers to -incorporate. Many developers of free software are heartened and -encouraged by the resulting cooperation. However, in the case of -software used on network servers, this result may fail to come about. -The GNU General Public License permits making a modified version and -letting the public access it on a server without ever releasing its -source code to the public. - - The GNU Affero General Public License is designed specifically to -ensure that, in such cases, the modified source code becomes available -to the community. It requires the operator of a network server to -provide the source code of the modified version running there to the -users of that server. Therefore, public use of a modified version, on -a publicly accessible server, gives the public access to the source -code of the modified version. - - An older license, called the Affero General Public License and -published by Affero, was designed to accomplish similar goals. This is -a different license, not a version of the Affero GPL, but Affero has -released a new version of the Affero GPL which permits relicensing under -this license. - - 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 Affero 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. Remote Network Interaction; Use with the GNU General Public License. - - Notwithstanding any other provision of this License, if you modify the -Program, your modified version must prominently offer all users -interacting with it remotely through a computer network (if your version -supports such interaction) an opportunity to receive the Corresponding -Source of your version by providing access to the Corresponding Source -from a network server at no charge, through some standard or customary -means of facilitating copying of software. This Corresponding Source -shall include the Corresponding Source for any work covered by version 3 -of the GNU General Public License that is incorporated pursuant to the -following paragraph. - - 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 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 work with which it is combined will remain governed by version -3 of the GNU General Public License. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU Affero 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 Affero 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 Affero 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 Affero 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 Affero 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 Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If your software can interact with users remotely through a computer -network, you should also make sure that it provides a way for users to -get its source. For example, if your program is a web application, its -interface could display a "Source" link that leads users to an archive -of the code. There are many ways you could offer source, and different -solutions will be better for different programs; see section 13 for the -specific requirements. - - 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 AGPL, see -. diff --git a/README.md b/README.md deleted file mode 100644 index c1e9957..0000000 --- a/README.md +++ /dev/null @@ -1,9 +0,0 @@ -knockoff of genai basically :p - - -Special thanks to [Charlie's Computers](https://github.com/PowerPCFan) for being the only one I know of that's hosting Goober 24/7 - -[Goober Central](https://github.com/whatdidyouexpect/goober-central) - -[Another mirror](https://forgejo.expect.ovh/gooberinc/goober) -no promises that it'll be stable diff --git a/assets/cogs/README.md b/assets/cogs/README.md deleted file mode 100644 index 7d2ddee..0000000 --- a/assets/cogs/README.md +++ /dev/null @@ -1,28 +0,0 @@ -# goobers custom commands -[Hello World!](https://github.com/WhatDidYouExpect/goober/blob/main/cogs/hello.py) -by expect - -[WhoAmI (lists username and nickname)](https://github.com/WhatDidYouExpect/goober/blob/main/cogs/whoami.py) -by PowerPCFan - -[Cog Manager](https://github.com/WhatDidYouExpect/goober/blob/main/cogs/cogmanager.py) -by expect - -[TensorFlow integration](https://github.com/WhatDidYouExpect/goober/blob/main/cogs/tf.py) -by SuperSilly2 (requires Python 3.7 - 3.10, tensorflow-metal/tensorflow-gpu and tensorflow/tensorflow-macos) - -[Web Scraper](https://raw.githubusercontent.com/WhatDidYouExpect/goober/refs/heads/main/cogs/webscraper.py) -by expect (requires goober version 0.11.7.2 or higher) - -[Status Changer](https://raw.githubusercontent.com/WhatDidYouExpect/goober/refs/heads/main/cogs/songchanger.py) -by expect (requires goober version 0.11.8 or higher) - -[Status Changer](https://raw.githubusercontent.com/WhatDidYouExpect/goober/refs/heads/main/cogs/songchanger.py) -by expect (requires goober version 0.11.8 or higher) - -[webUI](https://raw.githubusercontent.com/WhatDidYouExpect/goober/refs/heads/main/cogs/webserver.py) -by expect (requires goober version 0.11.8 or higher) - -[LastFM](https://raw.githubusercontent.com/WhatDidYouExpect/goober/refs/heads/main/cogs/webserver.py) -by expect (no idea what version it needs i've only tried it on 1.0.3) -- you have to add LASTFM_USERNAME and LASTFM_API_KEY to your .env \ No newline at end of file diff --git a/assets/cogs/cogmanager.py b/assets/cogs/cogmanager.py deleted file mode 100644 index 017f021..0000000 --- a/assets/cogs/cogmanager.py +++ /dev/null @@ -1,67 +0,0 @@ -import discord -from discord.ext import commands -from modules.globalvars import ownerid - -COG_PREFIX = "assets.cogs." - -class CogManager(commands.Cog): - def __init__(self, bot): - self.bot = bot - - @commands.command() - async def load(self, ctx, cog_name: str = None): - if ctx.author.id != ownerid: - await ctx.send("You do not have permission to use this command.") - return - if cog_name is None: - await ctx.send("Please provide the cog name to load.") - return - try: - await self.bot.load_extension(COG_PREFIX + cog_name) - await ctx.send(f"Loaded cog `{cog_name}` successfully.") - except Exception as e: - await ctx.send(f"Error loading cog `{cog_name}`: {e}") - - @commands.command() - async def unload(self, ctx, cog_name: str = None): - if ctx.author.id != ownerid: - await ctx.send("You do not have permission to use this command.") - return - if cog_name is None: - await ctx.send("Please provide the cog name to unload.") - return - try: - await self.bot.unload_extension(COG_PREFIX + cog_name) - await ctx.send(f"Unloaded cog `{cog_name}` successfully.") - except Exception as e: - await ctx.send(f"Error unloading cog `{cog_name}`: {e}") - - @commands.command() - async def reload(self, ctx, cog_name: str = None): - if ctx.author.id != ownerid: - await ctx.send("You do not have permission to use this command.") - return - if cog_name is None: - await ctx.send("Please provide the cog name to reload.") - return - try: - await self.bot.unload_extension(COG_PREFIX + cog_name) - await self.bot.load_extension(COG_PREFIX + cog_name) - await ctx.send(f"Reloaded cog `{cog_name}` successfully.") - except Exception as e: - await ctx.send(f"Error reloading cog `{cog_name}`: {e}") - - @commands.command() - async def listcogs(self, ctx): - """Lists all currently loaded cogs in an embed.""" - cogs = list(self.bot.cogs.keys()) - if not cogs: - await ctx.send("No cogs are currently loaded.") - return - - embed = discord.Embed(title="Loaded Cogs", description="Here is a list of all currently loaded cogs:") - embed.add_field(name="Cogs", value="\n".join(cogs), inline=False) - await ctx.send(embed=embed) - -async def setup(bot): - await bot.add_cog(CogManager(bot)) diff --git a/assets/cogs/eightball.py b/assets/cogs/eightball.py deleted file mode 100644 index ec6c955..0000000 --- a/assets/cogs/eightball.py +++ /dev/null @@ -1,57 +0,0 @@ -import random -import discord -from discord.ext import commands - -class eightball(commands.Cog): - def __init__(self, bot): - self.bot = bot - - @commands.command() - async def eightball(self, ctx): - answer = random.randint(1, 20) - text = "Nothing" - if answer==1: - text = "It is certain." - elif answer==2: - text = "It is decidedly so." - elif answer==3: - text = "Without a doubt." - elif answer==4: - text = "Yes definitely." - elif answer==5: - text = "You may rely on it." - elif answer==6: - text = "As I see it, yes." - elif answer==7: - text = "Most likely." - elif answer==8: - text = "Outlook good." - elif answer==9: - text = "Yes." - elif answer==10: - text = "Signs point to yes." - elif answer==11: - text = "Reply hazy, try again." - elif answer==12: - text = "Ask again later." - elif answer==13: - text = "Better not tell you now." - elif answer==14: - text = "Cannot predict now." - elif answer==15: - text = "Concentrate and ask again." - elif answer==16: - text = "Don't count on it." - elif answer==17: - text = "My reply is no." - elif answer==18: - text = "My sources say no." - elif answer==19: - text = "Outlook not so good." - elif answer==20: - text = "Very doubtful." - - await ctx.send(text) - -async def setup(bot): - await bot.add_cog(eightball(bot)) diff --git a/assets/cogs/filesharing.py b/assets/cogs/filesharing.py deleted file mode 100644 index ad6ac98..0000000 --- a/assets/cogs/filesharing.py +++ /dev/null @@ -1,48 +0,0 @@ -import discord -from discord.ext import commands -from modules.globalvars import ownerid -class FileSync(commands.Cog): - def __init__(self, bot): - self.bot = bot - self.mode = None - self.peer_id = None - self.awaiting_file = False - - @commands.command() - async def syncfile(self, ctx, mode: str, peer: discord.User): - self.mode = mode.lower() - self.peer_id = peer.id - if ctx.author.id != ownerid: - await ctx.send("You don't have permission to execute this command.") - return - if self.mode == "s": - await ctx.send(f"<@{self.peer_id}> FILE_TRANSFER_REQUEST") - await ctx.send(file=discord.File("memory.json")) - await ctx.send("File sent in this channel.") - elif self.mode == "r": - await ctx.send("Waiting for incoming file...") - self.awaiting_file = True - else: - await ctx.send("Invalid mode, use 's' or 'r'.") - - - @commands.Cog.listener() - async def on_message(self, message): - if message.author == self.bot.user or not self.awaiting_file: - return - if message.author.id != self.peer_id: - return - - if message.content == "FILE_TRANSFER_REQUEST": - print("Ping received. Awaiting file...") - if message.attachments: - for attachment in message.attachments: - if attachment.filename.endswith(".json"): - filename = "received_memory.json" - await attachment.save(filename) - print(f"File saved as {filename}") - await message.channel.send("File received and saved.") - self.awaiting_file = False - -async def setup(bot): - await bot.add_cog(FileSync(bot)) diff --git a/assets/cogs/fuckup.py b/assets/cogs/fuckup.py deleted file mode 100644 index 1dbc4d0..0000000 --- a/assets/cogs/fuckup.py +++ /dev/null @@ -1,98 +0,0 @@ -import discord -from discord.ext import commands -from modules.image import * -from modules.volta.main import _ -from PIL import Image, ImageEnhance, ImageFilter, ImageOps, ImageChops, ImageColor -import os, random, shutil, tempfile - -async def deepfryimage(path): - with Image.open(path).convert("RGB") as im: - # make it burn - for _ in range(3): - im = im.resize((int(im.width * 0.7), int(im.height * 0.7))) - im = im.resize((int(im.width * 1.5), int(im.height * 1.5))) - im = ImageEnhance.Contrast(im).enhance(random.uniform(5, 10)) - im = ImageEnhance.Sharpness(im).enhance(random.uniform(10, 50)) - im = ImageEnhance.Brightness(im).enhance(random.uniform(1.5, 3)) - r, g, b = im.split() - r = r.point(lambda i: min(255, i * random.uniform(1.2, 2.0))) - g = g.point(lambda i: min(255, i * random.uniform(0.5, 1.5))) - b = b.point(lambda i: min(255, i * random.uniform(0.5, 2.0))) - channels = [r, g, b] - random.shuffle(channels) - im = Image.merge("RGB", tuple(channels)) - overlay_color = tuple(random.randint(0, 255) for _ in range(3)) - overlay = Image.new("RGB", im.size, overlay_color) - im = ImageChops.add(im, overlay, scale=2.0, offset=random.randint(-64, 64)) - - im = im.filter(ImageFilter.EDGE_ENHANCE_MORE) - im = im.filter(ImageFilter.GaussianBlur(radius=random.uniform(0.5, 2))) - for _ in range(3): - tmp_path = tempfile.mktemp(suffix=".jpg") - im.save(tmp_path, format="JPEG", quality=random.randint(5, 15)) - im = Image.open(tmp_path) - if random.random() < 0.3: - im = ImageOps.posterize(im, bits=random.choice([2, 3, 4])) - if random.random() < 0.2: - im = ImageOps.invert(im) - out_path = tempfile.mktemp(suffix=".jpg") - im.save(out_path, format="JPEG", quality=5) - return out_path - - -class whami(commands.Cog): - def __init__(self, bot): - self.bot = bot - - - @commands.command() - async def fuckup(self, ctx): - assets_folder = "assets/images" - temp_input = None - - def get_random_asset_image(): - files = [f for f in os.listdir(assets_folder) if f.lower().endswith(('.png', '.jpg', '.jpeg', '.webp'))] - if not files: - return None - return os.path.join(assets_folder, random.choice(files)) - - if ctx.message.attachments: - attachment = ctx.message.attachments[0] - if attachment.content_type and attachment.content_type.startswith("image/"): - ext = os.path.splitext(attachment.filename)[1] - temp_input = f"tempy{ext}" - await attachment.save(temp_input) - input_path = temp_input - else: - fallback_image = get_random_asset_image() - if fallback_image is None: - await ctx.reply(_('no_image_available')) - return - temp_input = tempfile.mktemp(suffix=os.path.splitext(fallback_image)[1]) - shutil.copy(fallback_image, temp_input) - input_path = temp_input - else: - fallback_image = get_random_asset_image() - if fallback_image is None: - await ctx.reply(_('no_image_available')) - return - temp_input = tempfile.mktemp(suffix=os.path.splitext(fallback_image)[1]) - shutil.copy(fallback_image, temp_input) - input_path = temp_input - - output_path = await gen_meme(input_path) - - if output_path is None or not os.path.isfile(output_path): - if temp_input and os.path.exists(temp_input): - os.remove(temp_input) - await ctx.reply(_('failed_generate_image')) - return - - deepfried_path = await deepfryimage(output_path) - await ctx.send(file=discord.File(deepfried_path)) - - if temp_input and os.path.exists(temp_input): - os.remove(temp_input) - -async def setup(bot): - await bot.add_cog(whami(bot)) diff --git a/assets/cogs/lastfm.py b/assets/cogs/lastfm.py deleted file mode 100644 index 822305a..0000000 --- a/assets/cogs/lastfm.py +++ /dev/null @@ -1,84 +0,0 @@ -import os -import discord -from discord.ext import commands, tasks -import aiohttp -from dotenv import load_dotenv - -load_dotenv() - -#stole most of this code from my old expect bot so dont be suprised if its poorly made - -LASTFM_API_KEY = os.getenv("LASTFM_API_KEY") -LASTFM_USERNAME = os.getenv("LASTFM_USERNAME") - -class LastFmCog(commands.Cog): - def __init__(self, bot): - self.bot = bot - self.current_track = None - self.update_presence_task = None - self.ready = False - bot.loop.create_task(self.wait_until_ready()) - - async def wait_until_ready(self): - await self.bot.wait_until_ready() - self.ready = True - self.update_presence.start() - - @tasks.loop(seconds=60) - async def update_presence(self): - print("Looped!") - if not self.ready: - return - track = await self.fetch_current_track() - if track and track != self.current_track: - self.current_track = track - artist, song = track - activity_name = f"{artist} - {song}" - await self.bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name=activity_name)) - print(f"Updated song to {artist} - {song}") - else: - print("LastFM gave me the same track! not updating...") - - @update_presence.before_loop - async def before_update_presence(self): - await self.bot.wait_until_ready() - - @commands.command(name="lastfm") - async def lastfm_command(self, ctx): - track = await self.fetch_current_track() - if not track: - await ctx.send("No track currently playing or could not fetch data") - return - self.current_track = track - artist, song = track - activity_name = f"{artist} - {song}" - await self.bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name=activity_name)) - await ctx.send(f"Updated presence to: Listening to {activity_name}") - - async def fetch_current_track(self): - url = ( - f"http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks" - f"&user={LASTFM_USERNAME}&api_key={LASTFM_API_KEY}&format=json&limit=1" - ) - async with aiohttp.ClientSession() as session: - async with session.get(url) as resp: - if resp.status != 200: - return None - data = await resp.json() - - recenttracks = data.get("recenttracks", {}).get("track", []) - if not recenttracks: - return None - - track = recenttracks[0] - if '@attr' in track and track['@attr'].get('nowplaying') == 'true': - artist = track.get('artist', {}).get('#text', 'Unknown Artist') - song = track.get('name', 'Unknown Song') - return artist, song - return None - -async def setup(bot): - if not LASTFM_API_KEY or not LASTFM_USERNAME: - return - else: - await bot.add_cog(LastFmCog(bot)) diff --git a/assets/cogs/pulse.py b/assets/cogs/pulse.py deleted file mode 100644 index f717221..0000000 --- a/assets/cogs/pulse.py +++ /dev/null @@ -1,66 +0,0 @@ -from discord.ext import commands -import discord -from collections import defaultdict, Counter -import datetime -from modules.globalvars import ownerid -class StatsCog(commands.Cog): - def __init__(self, bot): - self.bot = bot - self.start_time = datetime.datetime.utcnow() - self.active_users = set() - self.total_messages = 0 - self.command_usage = Counter() - self.user_message_counts = Counter() - self.messages_per_hour = defaultdict(int) - - @commands.Cog.listener() - async def on_message(self, message): - if message.author.bot: - return - self.active_users.add(message.author.id) - self.total_messages += 1 - self.user_message_counts[message.author.id] += 1 - - now = datetime.datetime.utcnow() - hour_key = now.strftime("%Y-%m-%d %H") - self.messages_per_hour[hour_key] += 1 - - @commands.Cog.listener() - async def on_command(self, ctx): - self.command_usage[ctx.command.qualified_name] += 1 - - @commands.command() - async def spyware(self, ctx): - if ctx.author.id != ownerid: - return - uptime = datetime.datetime.utcnow() - self.start_time - hours_elapsed = max((uptime.total_seconds() / 3600), 1) - avg_per_hour = self.total_messages / hours_elapsed - if self.messages_per_hour: - peak_hour, peak_count = max(self.messages_per_hour.items(), key=lambda x: x[1]) - else: - peak_hour, peak_count = "N/A", 0 - - top_users = self.user_message_counts.most_common(5) - - embed = discord.Embed(title="Community Stats", color=discord.Color.blue()) - embed.add_field(name="Uptime", value=str(uptime).split('.')[0], inline=False) - embed.add_field(name="Total Messages", value=str(self.total_messages), inline=True) - embed.add_field(name="Active Users", value=str(len(self.active_users)), inline=True) - embed.add_field(name="Avg Messages/Hour", value=f"{avg_per_hour:.2f}", inline=True) - embed.add_field(name="Peak Hour (UTC)", value=f"{peak_hour}: {peak_count} messages", inline=True) - - top_str = "\n".join( - f"<@{user_id}>: {count} messages" for user_id, count in top_users - ) or "No data" - embed.add_field(name="Top Chatters", value=top_str, inline=False) - - cmd_str = "\n".join( - f"{cmd}: {count}" for cmd, count in self.command_usage.most_common(5) - ) or "No commands used yet" - embed.add_field(name="Top Commands", value=cmd_str, inline=False) - - await ctx.send(embed=embed) - -async def setup(bot): - await bot.add_cog(StatsCog(bot)) diff --git a/assets/cogs/slashcomandexample.py b/assets/cogs/slashcomandexample.py deleted file mode 100644 index 63b45f1..0000000 --- a/assets/cogs/slashcomandexample.py +++ /dev/null @@ -1,22 +0,0 @@ -import discord -from discord.ext import commands -from discord import app_commands - -class Ping(commands.Cog): - def __init__(self, bot): - self.bot = bot - - @app_commands.command(name="slashcommand", description="slashcommandexample") - async def ping(self, interaction: discord.Interaction): - await interaction.response.defer() - exampleembed = discord.Embed( - title="Pong!!", - description="The Beretta fires fast and won't make you feel any better!", - color=discord.Color.blue() - ) - exampleembed.set_footer(text=f"Requested by {interaction.user.name}", icon_url=interaction.user.avatar.url) - - await interaction.followup.send(embed=exampleembed) - -async def setup(bot): - await bot.add_cog(Ping(bot)) diff --git a/assets/cogs/songchanger.py b/assets/cogs/songchanger.py deleted file mode 100644 index 36fde47..0000000 --- a/assets/cogs/songchanger.py +++ /dev/null @@ -1,33 +0,0 @@ -import discord -from discord.ext import commands -from modules.globalvars import RED, GREEN, RESET, LOCAL_VERSION_FILE -import os - -class songchange(commands.Cog): - def __init__(self, bot): - self.bot = bot - - def get_local_version(): - if os.path.exists(LOCAL_VERSION_FILE): - with open(LOCAL_VERSION_FILE, "r") as f: - return f.read().strip() - return "0.0.0" - - global local_version - local_version = get_local_version() - - @commands.command() - async def changesong(self, ctx): - if LOCAL_VERSION_FILE > "0.11.8": - await ctx.send(f"Goober is too old! you must have version 0.11.8 you have {local_version}") - return - await ctx.send("Check the terminal! (this does not persist across restarts)") - song = input("\nEnter a song:\n") - try: - await self.bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name=f"{song}")) - print(f"{GREEN}Changed song to {song}{RESET}") - except Exception as e: - print(f"{RED}An error occurred while changing songs..: {str(e)}{RESET}") - -async def setup(bot): - await bot.add_cog(songchange(bot)) diff --git a/assets/cogs/tf.py.disabled b/assets/cogs/tf.py.disabled deleted file mode 100644 index 28609e6..0000000 --- a/assets/cogs/tf.py.disabled +++ /dev/null @@ -1,155 +0,0 @@ -import discord -from discord.ext import commands -import os -import numpy as np -import json -import pickle -import functools -import re -import time -import asyncio - -ready = True -MODEL_MATCH_STRING = r"[0-9]{2}_[0-9]{2}_[0-9]{4}-[0-9]{2}_[0-9]{2}" - -try: - import tensorflow as tf - from tensorflow import keras - from tensorflow.keras.preprocessing.text import Tokenizer - from tensorflow.keras.preprocessing.sequence import pad_sequences - from tensorflow.keras.models import Sequential, load_model - from tensorflow.keras.layers import Embedding, LSTM, Dense - from tensorflow.keras.backend import clear_session - - if tf.config.list_physical_devices('GPU'): - print("Using GPU acceleration") - elif tf.config.list_physical_devices('Metal'): - print("Using Metal for macOS acceleration") -except ImportError: - print("ERROR: Failed to import TensorFlow. Ensure you have the correct dependencies:") - print("tensorflow>=2.15.0") - print("For macOS (Apple Silicon): tensorflow-metal") - ready = False - - -class TFCallback(keras.callbacks.Callback): - def __init__(self, bot, progress_embed: discord.Embed, message): - self.embed = progress_embed - self.bot = bot - self.message = message - self.times = [time.time()] - - async def send_message(self, message: str, description: str, **kwargs): - if "epoch" in kwargs: - self.times.append(time.time()) - avg_epoch_time = np.mean(np.diff(self.times)) - description = f"ETA: {round(avg_epoch_time)}s" - self.embed.add_field(name=f" - {message}", value=description, inline=False) - await self.message.edit(embed=self.embed) - - def on_train_end(self, logs=None): - self.bot.loop.create_task(self.send_message("Training stopped", "Training has been stopped.")) - - def on_epoch_begin(self, epoch, logs=None): - self.bot.loop.create_task(self.send_message(f"Starting epoch {epoch}", "This might take a while", epoch=True)) - - def on_epoch_end(self, epoch, logs=None): - self.bot.loop.create_task(self.send_message(f"Epoch {epoch} ended", f"Accuracy: {round(logs.get('accuracy', 0.0), 4)}")) - - -class Ai: - def __init__(self): - model_path = settings.get("model_path") - if model_path: - self.__load_model(model_path) - self.is_loaded = model_path is not None - self.batch_size = 64 - - def generate_model_name(self): - return time.strftime('%d_%m_%Y-%H_%M', time.localtime()) - - def __load_model(self, model_path): - clear_session() - self.model = load_model(os.path.join(model_path, "model.h5")) - model_name = os.path.basename(model_path) - try: - with open(os.path.join(model_path, "tokenizer.pkl"), "rb") as f: - self.tokenizer = pickle.load(f) - except FileNotFoundError: - print("Failed to load tokenizer, using default.") - self.tokenizer = Tokenizer() - with open("memory.json", "r") as f: - self.tokenizer.fit_on_texts(json.load(f)) - self.is_loaded = True - - def reload_model(self): - clear_session() - model_path = settings.get("model_path") - if model_path: - self.__load_model(model_path) - self.is_loaded = True - - async def run_async(self, func, bot, *args, **kwargs): - return await bot.loop.run_in_executor(None, functools.partial(func, *args, **kwargs)) - - -class Learning(Ai): - def create_model(self, memory, epochs=2): - memory = memory[:2000] - tokenizer = Tokenizer() - tokenizer.fit_on_texts(memory) - sequences = tokenizer.texts_to_sequences(memory) - X, y = [], [] - for seq in sequences: - for i in range(1, len(seq)): - X.append(seq[:i]) - y.append(seq[i]) - maxlen = max(map(len, X)) - X = pad_sequences(X, maxlen=maxlen, padding="pre") - y = np.array(y) - - model = Sequential([ - Embedding(input_dim=VOCAB_SIZE, output_dim=128, input_length=maxlen), - LSTM(64), - Dense(VOCAB_SIZE, activation="softmax") - ]) - - model.compile(optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"]) - history = model.fit(X, y, epochs=epochs, batch_size=64, callbacks=[tf_callback]) - self.save_model(model, tokenizer, history) - - def save_model(self, model, tokenizer, history, name=None): - name = name or self.generate_model_name() - model_dir = os.path.join("models", name) - os.makedirs(model_dir, exist_ok=True) - - with open(os.path.join(model_dir, "info.json"), "w") as f: - json.dump(history.history, f) - with open(os.path.join(model_dir, "tokenizer.pkl"), "wb") as f: - pickle.dump(tokenizer, f) - model.save(os.path.join(model_dir, "model.h5")) - - -class Generation(Ai): - def generate_sentence(self, word_amount, seed): - if not self.is_loaded: - return False - for _ in range(word_amount): - token_list = self.tokenizer.texts_to_sequences([seed])[0] - token_list = pad_sequences([token_list], maxlen=self.model.input_shape[1], padding="pre") - predicted_word_index = np.argmax(self.model.predict(token_list, verbose=0), axis=-1)[0] - output_word = next((w for w, i in self.tokenizer.word_index.items() if i == predicted_word_index), "") - seed += " " + output_word - return seed - - -VOCAB_SIZE = 100_000 -settings = {} -learning = Learning() -generation = Generation() - -tf_callback = None - - -async def setup(bot): - await bot.add_cog(Tf(bot)) \ No newline at end of file diff --git a/assets/cogs/webscraper.py.disabled b/assets/cogs/webscraper.py.disabled deleted file mode 100644 index 351e2e8..0000000 --- a/assets/cogs/webscraper.py.disabled +++ /dev/null @@ -1,113 +0,0 @@ -import discord -from discord.ext import commands -import aiohttp -from bs4 import BeautifulSoup -import json -import asyncio -from urllib.parse import urljoin -from modules.globalvars import ownerid -class WebScraper(commands.Cog): - def __init__(self, bot): - self.bot = bot - self.visited_urls = set() - - async def fetch(self, session, url): - """Fetch the HTML content of a URL.""" - try: - async with session.get(url, timeout=10) as response: - return await response.text() - except Exception as e: - print(f"Failed to fetch {url}: {e}") - return None - - def extract_sentences(self, text): - """Extract sentences from text.""" - sentences = text.split('.') - return [sentence.strip() for sentence in sentences if sentence.strip()] - - def save_to_json(self, sentences): - """Save sentences to memory.json.""" - try: - try: - with open("memory.json", "r") as file: - data = json.load(file) - except (FileNotFoundError, json.JSONDecodeError): - data = [] - data.extend(sentences) - with open("memory.json", "w") as file: - json.dump(data, file, indent=4) - except Exception as e: - print(f"Failed to save to JSON: {e}") - - def undo_last_scrape(self): - """Undo the last scrape by removing the most recent sentences.""" - try: - with open("memory.json", "r") as file: - data = json.load(file) - - if not data: - print("No data to undo.") - return False - - - data = data[:-1] - - with open("memory.json", "w") as file: - json.dump(data, file, indent=4) - - return True - except (FileNotFoundError, json.JSONDecodeError): - print("No data to undo or failed to load JSON.") - return False - except Exception as e: - print(f"Failed to undo last scrape: {e}") - return False - - async def scrape_links(self, session, url, depth=2): - print(f"Scraping: {url}") - self.visited_urls.add(url) - - html = await self.fetch(session, url) - if not html: - return - - soup = BeautifulSoup(html, "html.parser") - - for paragraph in soup.find_all('p'): - sentences = self.extract_sentences(paragraph.get_text()) - self.save_to_json(sentences) - - - @commands.command() - async def start_scrape(self, ctx, start_url: str): - """Command to start the scraping process.""" - if ctx.author.id != ownerid: - await ctx.send("You do not have permission to use this command.") - return - - if not start_url.startswith("http"): - await ctx.send("Please provide a valid URL.") - return - - await ctx.send(f"Starting scrape from {start_url}... This may take a while!") - - async with aiohttp.ClientSession() as session: - await self.scrape_links(session, start_url) - - await ctx.send("Scraping complete! Sentences saved to memory.json.") - - @commands.command() - async def undo_scrape(self, ctx): - """Command to undo the last scrape.""" - if ctx.author.id != ownerid: - await ctx.send("You do not have permission to use this command.") - return - - success = self.undo_last_scrape() - if success: - await ctx.send("Last scrape undone successfully.") - else: - await ctx.send("No data to undo or an error occurred.") - -async def setup(bot): - await bot.add_cog(WebScraper(bot)) diff --git a/assets/cogs/webserver.py.disabled b/assets/cogs/webserver.py.disabled deleted file mode 100644 index 110c20d..0000000 --- a/assets/cogs/webserver.py.disabled +++ /dev/null @@ -1,880 +0,0 @@ -import discord -from discord.ext import commands, tasks -import asyncio -from aiohttp import web -import psutil -import os -import json -from datetime import datetime -import time -import aiohttp -import re -from aiohttp import WSMsgType -from modules.globalvars import VERSION_URL -import sys -import subprocess - -class GooberWeb(commands.Cog): - def __init__(self, bot): - self.bot = bot - self.app = web.Application() - self.runner = None - self.site = None - self.last_command = "No commands executed yet" - self.last_command_time = "Never" - self.start_time = time.time() - self.websockets = set() - - self.app.add_routes([ - web.get('/', self.handle_index), - web.get('/changesong', self.handle_changesong), - web.get('/stats', self.handle_stats), - web.get('/data', self.handle_json_data), - web.get('/ws', self.handle_websocket), - web.get('/styles.css', self.handle_css), - web.get('/settings', self.handle_settings), - web.post('/update_settings', self.handle_update_settings), - web.post('/restart_bot', self.handle_restart_bot), - ]) - - self.bot.loop.create_task(self.start_web_server()) - self.update_clients.start() - - async def restart_bot(self): - await asyncio.sleep(1) - python = sys.executable - os.execl(python, python, *sys.argv) - - async def handle_restart_bot(self, request): - asyncio.create_task(self.restart_bot()) - return web.Response(text="Bot is restarting...") - - async def get_blacklisted_users(self): - blacklisted_ids = os.getenv("BLACKLISTED_USERS", "").split(",") - blacklisted_users = [] - - for user_id in blacklisted_ids: - if not user_id.strip(): - continue - - try: - user = await self.bot.fetch_user(int(user_id)) - blacklisted_users.append({ - "name": f"{user.name}", - "avatar_url": str(user.avatar.url) if user.avatar else str(user.default_avatar.url), - "id": user.id - }) - except discord.NotFound: - blacklisted_users.append({ - "name": f"Unknown User ({user_id})", - "avatar_url": "", - "id": user_id - }) - except discord.HTTPException as e: - print(f"Error fetching user {user_id}: {e}") - continue - - return blacklisted_users - - async def get_enhanced_guild_info(self): - guilds = sorted(self.bot.guilds, key=lambda g: g.member_count, reverse=True) - guild_info = [] - - for guild in guilds: - icon_url = str(guild.icon.url) if guild.icon else "" - guild_info.append({ - "name": guild.name, - "member_count": guild.member_count, - "icon_url": icon_url, - "id": guild.id - }) - - return guild_info - - async def start_web_server(self): - self.runner = web.AppRunner(self.app) - await self.runner.setup() - self.site = web.TCPSite(self.runner, '0.0.0.0', 8080) - await self.site.start() - print("Goober web server started on port 8080") - - async def stop_web_server(self): - await self.site.stop() - await self.runner.cleanup() - print("Web server stopped") - - def cog_unload(self): - self.update_clients.cancel() - self.bot.loop.create_task(self.stop_web_server()) - - @tasks.loop(seconds=5) - async def update_clients(self): - if not self.websockets: - return - - stats = await self.get_bot_stats() - message = json.dumps(stats) - - for ws in set(self.websockets): - try: - await ws.send_str(message) - except ConnectionResetError: - self.websockets.remove(ws) - except Exception as e: - print(f"Error sending to websocket: {e}") - self.websockets.remove(ws) - - async def handle_websocket(self, request): - ws = web.WebSocketResponse() - await ws.prepare(request) - self.websockets.add(ws) - - try: - async for msg in ws: - if msg.type == WSMsgType.ERROR: - print(f"WebSocket error: {ws.exception()}") - finally: - self.websockets.remove(ws) - - return ws - - async def handle_css(self, request): - css_path = os.path.join(os.path.dirname(__file__), 'styles.css') - if os.path.exists(css_path): - return web.FileResponse(css_path) - return web.Response(text="CSS file not found", status=404) - - @commands.Cog.listener() - async def on_message(self, message): - if message.author.bot: - return - - ctx = await self.bot.get_context(message) - if ctx.valid and ctx.command: - self._update_command_stats(ctx.command.name, ctx.author) - - @commands.Cog.listener() - async def on_app_command_completion(self, interaction, command): - self._update_command_stats(command.name, interaction.user) - - def _update_command_stats(self, command_name, user): - self.last_command = f"{command_name} (by {user.name})" - self.last_command_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") - if self.websockets: - asyncio.create_task(self.update_clients()) - - async def get_bot_stats(self): - process = psutil.Process(os.getpid()) - mem_info = process.memory_full_info() - cpu_percent = psutil.cpu_percent() - process_cpu = process.cpu_percent() - - memory_json_size = "N/A" - if os.path.exists("memory.json"): - memory_json_size = f"{os.path.getsize('memory.json') / 1024:.2f} KB" - - guild_info = await self.get_enhanced_guild_info() - blacklisted_users = await self.get_blacklisted_users() - - uptime_seconds = int(time.time() - self.start_time) - uptime_str = f"{uptime_seconds // 86400}d {(uptime_seconds % 86400) // 3600}h {(uptime_seconds % 3600) // 60}m {uptime_seconds % 60}s" - - return { - "ram_usage": f"{mem_info.rss / 1024 / 1024:.2f} MB", - "cpu_usage": f"{process_cpu}%", - "system_cpu": f"{cpu_percent}%", - "memory_json_size": memory_json_size, - "guild_count": len(guild_info), - "bl_count": len(blacklisted_users), - "guilds": guild_info, - "blacklisted_users": blacklisted_users, - "last_command": self.last_command, - "last_command_time": self.last_command_time, - "bot_uptime": uptime_str, - "latency": f"{self.bot.latency * 1000:.2f} ms", - "bot_name": self.bot.user.name, - "bot_avatar_url": str(self.bot.user.avatar.url) if self.bot.user.avatar else "", - "authenticated": os.getenv("gooberauthenticated"), - "lastmsg": os.getenv("gooberlatestgen"), - "localversion": os.getenv("gooberlocal_version"), - "latestversion": os.getenv("gooberlatest_version"), - "owner": os.getenv("ownerid") - } - - async def handle_update(self, request): - if os.path.exists("goob/update.py"): - return web.FileResponse("goob/update.py") - return web.Response(text="Update file not found", status=404) - - async def handle_changesong(self, request): - song = request.query.get('song', '') - if song: - await self.bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name=song)) - return web.Response(text=f"Changed song to: {song}") - return web.Response(text="Please provide a song parameter", status=400) - - async def handle_changes(self, request): - if os.path.exists("goob/changes.txt"): - return web.FileResponse("goob/changes.txt") - return web.Response(text="Changelog not found", status=404) - - async def read_env_file(self): - env_vars = {} - try: - with open('.env', 'r') as f: - for line in f: - line = line.strip() - if not line or line.startswith('#') or '=' not in line: - continue - - key, value = line.split('=', 1) - key = key.strip() - if key in ['splashtext', 'DISCORD_BOT_TOKEN']: - continue - - env_vars[key] = value.strip('"\'') - except FileNotFoundError: - print(".env file not found") - return env_vars - - - async def handle_settings(self, request): - env_vars = await self.read_env_file() - - # Get config.py variables - config_vars = {} - try: - with open('config.py', 'r') as f: - for line in f: - if line.startswith('VERSION_URL'): - config_vars['VERSION_URL'] = line.split('=', 1)[1].strip().strip('"') - except FileNotFoundError: - pass - - settings_html = """ - - - - Goober Settings - - - -
-

Goober Settings

-
- """ - - for key, value in env_vars.items(): - settings_html += f""" -
- - -
- """ - - for key, value in config_vars.items(): - settings_html += f""" -
- - -
- """ - - settings_html += """ - -
-
- -
-
- - - """ - - return web.Response(text=settings_html, content_type='text/html') - - async def handle_update_settings(self, request): - data = await request.post() - env_text = "" - - try: - with open('.env', 'r') as f: - env_text = f.read() - except FileNotFoundError: - pass - - def replace_match(match): - key = match.group(1) - value = match.group(2) - if key in ['splashtext', 'DISCORD_BOT_TOKEN']: - return match.group(0) - if key in data: - new_value = data[key] - if not (new_value.startswith('"') and new_value.endswith('"')): - new_value = f'"{new_value}"' - return f'{key}={new_value}' - return match.group(0) - - env_text = re.sub(r'^(\w+)=([\s\S]+?)(?=\n\w+=|\Z)', replace_match, env_text, flags=re.MULTILINE) - - with open('.env', 'w') as f: - f.write(env_text.strip() + '\n') - - if 'VERSION_URL' in data: - config_text = "" - try: - with open('config.py', 'r') as f: - config_text = f.read() - except FileNotFoundError: - pass - - config_text = re.sub(r'^(VERSION_URL\s*=\s*").+?"', f'\\1{data["VERSION_URL"]}"', config_text, flags=re.MULTILINE) - - with open('config.py', 'w') as f: - f.write(config_text.strip() + '\n') - - return aiohttp.web.Response(text="Settings updated successfully!") - - async def handle_index(self, request): - stats = await self.get_bot_stats() - - guild_list_html = "" - for guild in stats['guilds']: - icon_html = f'guild icon' if guild["icon_url"] else '
' - guild_list_html += f""" -
- {icon_html} -
-
{guild["name"]}
-
{guild["member_count"]} members
-
-
- """ - blacklisted_users_html = "" - for user in stats['blacklisted_users']: - avatar_html = f'user avatar' if user["avatar_url"] else '
' - blacklisted_users_html += f""" -
- {avatar_html} - -
- """ - - owner_id = stats.get('owner') - owner = None - owner_username = "Owner" - owner_pfp = "" - - if owner_id: - try: - owner = await self.bot.fetch_user(int(owner_id)) - owner_username = f"{owner.name}" - owner_pfp = str(owner.avatar.url) if owner and owner.avatar else "" - except: - pass - - - html_content = f""" - - - - goobs central - - - -
- -
Welcome, {owner_username}
-
-
-
- RAM: - {stats['ram_usage']} -
-
- CPU: - {stats['system_cpu']} -
-
- Latency: - {stats['latency']} -
-
- JSON Size: - {stats['memory_json_size']} -
-
- Uptime: - {stats['bot_uptime']} -
-
- -
-
- botvatar -

{stats['bot_name']}

-
-
-

your stupid little goober that learns off other people's messages

-
- -
-
-
Last Command
-
{stats['last_command']}
-
at {stats['last_command_time']}
-
-
Logged into goober central
-
{stats['authenticated']}
-
-
Last generated message
-
{stats['lastmsg']}
-
-
Version
-
Installed Version: {stats['localversion']}
-
Latest Version: {stats['latestversion']}
-
-
goober-central URL
-
{VERSION_URL}
-
-
Change song
-
- - -
-
- -
-
Servers ({stats['guild_count']})
-
- {guild_list_html} -
-
-
Blacklisted Users ({stats['bl_count']})
-
- {blacklisted_users_html if stats['blacklisted_users'] else "
No blacklisted users
"} -
-
-
- - - - """ - - return web.Response(text=html_content, content_type='text/html') - - async def handle_stats(self, request): - return await self.handle_index(request) - - async def handle_json_data(self, request): - stats = await self.get_bot_stats() - return web.json_response(stats) - -async def setup(bot): - await bot.add_cog(GooberWeb(bot)) diff --git a/assets/cogs/whoami.py b/assets/cogs/whoami.py deleted file mode 100644 index a60633f..0000000 --- a/assets/cogs/whoami.py +++ /dev/null @@ -1,24 +0,0 @@ -import discord -from discord.ext import commands - -class whoami(commands.Cog): - def __init__(self, bot): - self.bot = bot - - @commands.command() - async def whoami(self, ctx): - user_id = ctx.author.id - username = ctx.author.name - - embed = discord.Embed( - title="User Information", - description=f"Your User ID is: {user_id}\n" - f"Your username is: {username}\n" - f"Your nickname in this server is: <@{user_id}>", - color=discord.Color.blue() - ) - - await ctx.send(embed=embed) - -async def setup(bot): - await bot.add_cog(whoami(bot)) diff --git a/assets/fonts/Impact.ttf b/assets/fonts/Impact.ttf deleted file mode 100644 index 7b7956f..0000000 Binary files a/assets/fonts/Impact.ttf and /dev/null differ diff --git a/assets/fonts/TNR.ttf b/assets/fonts/TNR.ttf deleted file mode 100644 index 51261a0..0000000 Binary files a/assets/fonts/TNR.ttf and /dev/null differ diff --git a/assets/images/attention.webp b/assets/images/attention.webp deleted file mode 100644 index f680665..0000000 Binary files a/assets/images/attention.webp and /dev/null differ diff --git a/assets/images/bibinos.png b/assets/images/bibinos.png deleted file mode 100644 index 5a7b846..0000000 Binary files a/assets/images/bibinos.png and /dev/null differ diff --git a/assets/images/crash.webp b/assets/images/crash.webp deleted file mode 100644 index 60d918b..0000000 Binary files a/assets/images/crash.webp and /dev/null differ diff --git a/assets/images/crash2.png b/assets/images/crash2.png deleted file mode 100644 index 12f7616..0000000 Binary files a/assets/images/crash2.png and /dev/null differ diff --git a/assets/images/genuineidiot.png b/assets/images/genuineidiot.png deleted file mode 100644 index 226ca47..0000000 Binary files a/assets/images/genuineidiot.png and /dev/null differ diff --git a/assets/images/smashedphone.webp b/assets/images/smashedphone.webp deleted file mode 100644 index 845070f..0000000 Binary files a/assets/images/smashedphone.webp and /dev/null differ diff --git a/assets/images/thisisfine.png b/assets/images/thisisfine.png deleted file mode 100644 index 41977dc..0000000 Binary files a/assets/images/thisisfine.png and /dev/null differ diff --git a/assets/locales/README.md b/assets/locales/README.md deleted file mode 100644 index 5fd0e77..0000000 --- a/assets/locales/README.md +++ /dev/null @@ -1,8 +0,0 @@ -# Locales Directory - -This folder contains localization files for the project. - -**Notice:** -The Spanish and French locales currently do not have maintainers. If you are interested in helping maintain or improve these translations, please consider contributing! - -Thank you for supporting localization efforts! \ No newline at end of file diff --git a/assets/locales/empty.json b/assets/locales/empty.json deleted file mode 100644 index 544b7b4..0000000 --- a/assets/locales/empty.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - -} \ No newline at end of file diff --git a/assets/locales/en.json b/assets/locales/en.json deleted file mode 100644 index 61f4778..0000000 --- a/assets/locales/en.json +++ /dev/null @@ -1,136 +0,0 @@ -{ - "memory_file_valid": "The memory.json file is valid!", - "file_aint_uft8": "File is not valid UTF-8 text. Might be binary or corrupted.", - "psutil_not_installed": "Memory check skipped.", - "not_cloned": "Goober is not cloned! Please clone it from GitHub.", - "checks_disabled": "Checks are disabled!", - "unhandled_exception": "An unhandled exception occurred. Please report this issue on GitHub.", - "active_users:": "Active users:", - "spacy_initialized": "spaCy and spacytextblob are ready.", - "spacy_model_not_found": "The spaCy model was not found! Downloading it....`", - "env_file_not_found": "The .env file was not found! Please create one with the required variables.", - "error_fetching_active_users": "Error fetching active users: {error}", - "error_sending_alive_ping": "Error sending alive ping: {error}", - "already_started": "I've already started! I'm not updating...", - "please_restart": "Please Restart goober!", - "local_ahead": "Local {remote}/{branch} is ahead and/or up to par. Not Updating...", - "remote_ahead": "Remote {remote}/{branch} is ahead. Updating...", - "cant_find_local_version": "I can't find the local_version variable! Or it's been tampered with and it's not an integer!", - "running_prestart_checks": "Running pre-start checks...", - "continuing_in_seconds": "Continuing in {seconds} seconds... Press any key to skip.", - "missing_requests_psutil": "Missing requests and psutil! Please install them using pip: `pip install requests psutil`", - "requirements_not_found": "requirements.txt not found at {path} was it tampered with?", - "warning_failed_parse_imports": "Warning: Failed to parse imports from {filename}: {error}", - "cogs_dir_not_found": "Cogs directory not found at {path}, skipping scan.", - "std_lib_local_skipped": "STD LIB / LOCAL {package} (skipped check)", - "ok_installed": "OK", - "missing_package": "MISSING", - "missing_package2": "is not installed", - "missing_packages_detected": "Missing packages detected:", - "telling_goober_central": "Telling goober central at {url}", - "failed_to_contact": "Failed to contact {url}: {error}", - "all_requirements_satisfied": "All requirements are satisfied.", - "ping_to": "Ping to {host}: {latency} ms", - "high_latency": "High latency detected! You may experience delays in response times.", - "could_not_parse_latency": "Could not parse latency.", - "ping_failed": "Ping to {host} failed.", - "error_running_ping": "Error running ping: {error}", - "memory_usage": "Memory Usage: {used} GB / {total} GB ({percent}%)", - "memory_above_90": "Memory usage is above 90% ({percent}%). Consider freeing up memory.", - "total_memory": "Total Memory: {total} GB", - "used_memory": "Used Memory: {used} GB", - "low_free_memory": "Low free memory detected! Only {free} GB available.", - "measuring_cpu": "Measuring CPU usage per core...", - "core_usage": "Core {idx}: [{bar}] {usage}%", - "total_cpu_usage": "Total CPU Usage: {usage}%", - "high_avg_cpu": "High average CPU usage: {usage}%", - "really_high_cpu": "Really high CPU load! System may throttle or hang.", - "memory_file": "Memory file: {size} MB", - "memory_file_large": "Memory file is 1GB or higher, consider clearing it to free up space.", - "memory_file_corrupted": "Memory file is corrupted! JSON decode error: {error}", - "consider_backup_memory": "Consider backing up and recreating the memory file.", - "memory_file_encoding": "Memory file has encoding issues: {error}", - "error_reading_memory": "Error reading memory file: {error}", - "memory_file_not_found": "Memory file not found.", - "modification_warning": "Goober has been modified! Any changes will be lost in an update!", - "reported_version": "Reported Version:", - "current_hash": "Current Hash:", - "not_found": "is not found!", - "version_error": "Unable to fetch version info. Status code", - "loaded_cog": "Loaded cog:", - "loaded_cog2": "Loaded module:", - "cog_fail": "Failed to load cog:", - "cog_fail2": "Failed to load module:", - "no_model": "No saved Markov model found. Starting from scratch.", - "folder_created": "Folder '{folder_name}' created.", - "folder_exists": "Folder '{folder_name}' already exists. skipping...", - "logged_in": "Logged in as", - "synced_commands": "Synced", - "synced_commands2": "commands!", - "fail_commands_sync": "Failed to sync commands:", - "started": "{name} has started!\nYou're the star of the show now baby!", - "name_check": "Error checking name availability:", - "name_taken": "Name is already taken. Please choose a different name.", - "name_check2": "Error during name availability check:", - "add_token": "Token: {token}\nPlease add this token to your .env file as", - "token_exists": "Token already exists in .env. Continuing with the existing token.", - "registration_error": "Error during registration:", - "version_backup": "Backup created:", - "backup_error": "Error: {LOCAL_VERSION_FILE} not found for backup.", - "model_loaded": "Markov model loaded from", - "fetch_update_fail": "Could not fetch update information.", - "invalid_server": "Error: Invalid version information received from server.", - "goober_server_alert": "Alert from goober central!\n", - "new_version": "New version available: {latest_version} (Current: {local_version})", - "changelog": "Check {VERSION_URL}/goob/changes.txt to check out the changelog\n\n", - "invalid_version": "The version: {local_version} isnt valid!", - "invalid_version2": "If this is intended then ignore this message, else press Y to pull a valid version from the server regardless of the version of goober currently running", - "invalid_version3": "The current version will be backed up to current_version.bak..", - "input": "(Y or any other key to ignore....)", - "modification_ignored": "You've modified", - "modification_ignored2": "IGNOREWARNING is set to false..", - "latest_version": "You're using the latest version:", - "latest_version2": "Check {VERSION_URL}/goob/changes.txt to check out the changelog", - "pinging_disabled": "Pinging is disabled! Not telling the server im on...", - "goober_ping_success": "Logged into goober central as {NAME}", - "goober_ping_fail": "Failed to send data. Server returned status code:", - "goober_ping_fail2": "An error occurred while sending data:", - "sentence_positivity": "Positivity of sentence is:", - "command_edit_fail": "Failed to edit message:", - "command_desc_retrain": "Retrains the Markov model manually.", - "command_markov_retrain": "Retraining the Markov model... Please wait.", - "command_markov_memory_not_found": "Error: memory file not found!", - "command_markov_memory_is_corrupt": "Error: memory file is corrupt!", - "command_markov_retraining": "Processing {data_size} data points...", - "command_markov_retrain_successful": "Markov model retrained successfully using {data_size} data points!", - "command_desc_talk":"talks n like stuf", - "command_talk_insufficent_text": "I need to learn more from messages before I can talk.", - "command_talk_generation_fail": "I have nothing to say right now!", - "command_desc_help": "help", - "command_help_embed_title": "Bot Help", - "command_help_embed_desc": "List of commands grouped by category.", - "command_help_categories_general": "General", - "command_help_categories_admin": "Administration", - "command_help_categories_custom": "Custom Commands", - "command_ran": "Info: {message.author.name} ran {message.content}", - "command_ran_s": "Info: {interaction.user} ran ", - "command_desc_ping": "ping", - "command_desc_setlang": "Set a new language for the bot (temporarily)", - "command_ping_embed_desc": "Bot Latency:", - "command_ping_footer": "Requested by", - "command_about_desc": "about", - "command_about_embed_title": "About me", - "command_about_embed_field1": "Name", - "command_about_embed_field2name": "Version", - "command_about_embed_field2value": "Local: {local_version} \nLatest: {latest_version}", - "command_desc_stats": "stats", - "command_stats_embed_title": "Bot stats", - "command_stats_embed_desc": "Data about the the bot's memory.", - "command_stats_embed_field1name": "File Stats", - "command_stats_embed_field1value": "Size: {file_size} bytes\nLines: {line_count}", - "command_stats_embed_field2name": "Version", - "command_stats_embed_field2value": "Local: {local_version} \nLatest: {latest_version}", - "command_stats_embed_field3name": "Variable Info", - "command_stats_embed_field3value": "Name: {NAME} \nPrefix: {PREFIX} \nOwner ID: {ownerid}\nPing line: {PING_LINE} \nMemory Sharing Enabled: {showmemenabled} \nUser Training Enabled: {USERTRAIN_ENABLED}\nSong: {song} \nSplashtext: ```{splashtext}```" -} - diff --git a/assets/locales/es.json b/assets/locales/es.json deleted file mode 100644 index 4444a9c..0000000 --- a/assets/locales/es.json +++ /dev/null @@ -1,77 +0,0 @@ -{ - "modification_warning": "Goober ha sido modificado! Se omiten las comprobaciones del servidor por completo...", - "reported_version": "Version reportada:", - "current_hash": "Hash actual:", - "not_found": "no existe!", - "version_error": "No se puede obtener la informacion de la version. Codigo de estado", - "loaded_cog": "Engranaje cog:", - "cog_fail": "No se pudo cargar el cog:", - "no_model": "No se encontro ningún modelo de Markov guardado. Empezando desde cero.", - "folder_created": "Directorio '{folder_name}' creado.", - "folder_exists": "El directorio '{folder_name}' ya existe. Se omite...", - "logged_in": "Inicio sesion como", - "synced_commands": "Sincronizado", - "synced_commands2": "comandos!", - "fail_commands_sync": "Error al sincronizar comandos:", - "started": "{name} ha empezado!", - "name_check": "Error al comprobar la disponibilidad del nombre:", - "name_taken": "El nombre ya está en uso. Elija otro.", - "name_check2": "Error durante la comprobacion de disponibilidad del nombre:", - "add_token": "Token: {token}\nAgregue este token a su archivo .env como", - "token_exists": "Hay un token en el archivo .env. Continue con el token existente.", - "registration_error": "Error durante el registro:", - "version_backup": "Copia de seguridad creada:", - "backup_error": "Error: {LOCAL_VERSION_FILE} no encontrado para la copia de seguridad.", - "model_loaded": "Modelo de Markov cargado desde", - "fetch_update_fail": "No se pudo obtener la informacion de actualizacion.", - "invalid_server": "Error: Se recibio informacion de version no valida del servidor.", - "new_version": "Nueva version disponible: {latest_version} (Version actual: {local_version})", - "changelog": "Consulte {VERSION_URL}/goob/changes.txt para ver el registro de cambios\n\n", - "invalid_version": "La version: {local_version} no es valida!", - "invalid_version2": "Si esto es lo que pretende, ignore este mensaje; si no, haga clic en Y en su teclado para descargar una version valida del servidor, independientemente de la version que se este ejecutando actualmente.", - "invalid_version3": "La version actual se copiara a current_version.bak..", - "input": "(Y o cualquier otra tecla para ignorar....)", - "modification_ignored": "Has modificado", - "modification_ignored2": "IGNOREWARNING es falso", - "latest_version": "Usando la ultima version:", - "latest_version2": "Consulte {VERSION_URL}/goob/changes.txt para ver el registro de cambios", - "pinging_disabled": "El ping esta deshabilitado", - "goober_ping_success": "Envie ping a Goober Central!", - "goober_ping_fail": "Error al enviar datos. El servidor devolvio el codigo de estado:", - "goober_ping_fail2": "Se produjo un error al enviar los datos:", - "sentence_positivity": "La positividad de la sentencia es:", - "command_edit_fail": "No se pudo editar el mensaje:", - "command_desc_retrain": "Vuelve a entrenar el modelo de Markov manualmente.", - "command_markov_retrain": "Reentrenando el modelo de Markov... Por favor espere", - "command_markov_memory_not_found": "Error: no hay archivo de memoria!", - "command_markov_memory_is_corrupt": "Error: el archivo de memoria esta danado!", - "command_markov_retraining": "Procesando {processed_data}/{data_size} puntos de datos...", - "command_markov_retrain_successful": "Modelo de Markov reentrenado exitosamente usando {data_size} puntos de datos!", - "command_desc_talk":"hace que el bot hable", - "command_talk_insufficent_text": "Necesito aprender más sobre los mensajes antes de hablar.", - "command_talk_generation_fail": "No tengo nada que decir ahora!", - "command_desc_help": "Ayuda", - "command_help_embed_title": "Ayuda del bot", - "command_help_embed_desc": "Lista de comandos agrupados por categoria", - "command_help_categories_general": "General", - "command_help_categories_admin": "Administracion", - "command_help_categories_custom": "Comandos personalizados", - "command_ran": "Informacion: {message.author.name} ejecuto {message.content}", - "command_desc_ping": "ping", - "command_ping_embed_desc": "Latencia del bot:", - "command_ping_footer": "Solicitado por", - "command_about_desc": "Acerca", - "command_about_embed_title": "Acerca de mi", - "command_about_embed_field1": "Nombre", - "command_about_embed_field2name": "Version", - "command_about_embed_field2value": "Version local: {local_version} \nUltima version: {latest_version}", - "command_desc_stats": "Estadistica", - "command_stats_embed_title": "Estadisticas de bot", - "command_stats_embed_desc": "Datos sobre la memoria del bot", - "command_stats_embed_field1name": "Estadisticas", - "command_stats_embed_field1value": "Tamano: {file_size} bytes\nLineas: {line_count}", - "command_stats_embed_field2name": "Version", - "command_stats_embed_field2value": "Version local: {local_version} \nUltima version: {latest_version}", - "command_stats_embed_field3name": "informacion sobre las variables", - "command_stats_embed_field3value": "Nombre: {NAME} \nPrefijo: {PREFIX} \nID del propietario: {ownerid}\nLinea de ping: {PING_LINE} \nCompartir memoria habilitada: {showmemenabled} \nEntrenamiento de usuario habilitado: {USERTRAIN_ENABLED} \nCancion: {song} \nTexto de bienvenida: ```{splashtext}```" -} \ No newline at end of file diff --git a/assets/locales/fi.json b/assets/locales/fi.json deleted file mode 100644 index 93141cc..0000000 --- a/assets/locales/fi.json +++ /dev/null @@ -1,135 +0,0 @@ -{ - "memory_file_valid": "memory.json on toimiva!", - "file_aint_uft8": "Tiedosto ei ole UTF-8 tekstiä. Saattaa olla binääriä tai korruptoitunut.", - "active_users:": "Aktiiviset käyttäjät:", - "cog_fail2": "Moduulin lataaminen epäonnistui:", - "command_ran_s": "Info: {interaction.user} suoritti", - "error_fetching_active_users": "Aktiivisten käyttäjien hankkimisessa tapahtui ongelma: {error}", - "error_sending_alive_ping": "Pingin lähettäminen goober centraliin epäonnistui: {error}", - "goober_server_alert": "Viesti goober centralista!\n", - "loaded_cog2": "Ladattiin moduuli:", - "spacy_initialized": "spaCy ja spacytextblob ovat valmiita.", - "spacy_model_not_found": "spaCy mallia ei löytynyt! Ladataan se....`", - "checks_disabled": "Tarkistukset on poistettu käytöstä!", - "unhandled_exception": "Käsittelemätön virhe tapahtui. Ilmoita tästä GitHubissa.", - "active_users": "Aktiiviset käyttäjät", - "env_file_not_found": ".env-tiedostoa ei löytnyt! Luo tiedosto jossa on tarvittavat muuttujat", - "already_started": "Olen jo käynnistynyt! Ei päivitetä...", - "please_restart": "Käynnistä uudelleen, hölmö!", - "local_ahead": "Paikallinen {remote}/{branch} on edellä ja/tai ajan tasalla. Ohitetaan päivitys...", - "remote_ahead": "Etärepositorio {remote}/{branch} on edellä. Päivitetään...", - "cant_find_local_version": "Muuttujaa local_version ei löytynyt, tai sitä on muokattu eikä ole kokonaisluku!", - "running_prestart_checks": "Suoritetaan esikäynnistystarkistuksia...", - "continuing_in_seconds": "Jatketaan {seconds} sekunnin kuluttua... Paina mitä tahansa näppäintä ohittaaksesi.", - "missing_requests_psutil": "Kirjastot requests ja psutil puuttuvat! Asenna ne komennolla: `pip install requests psutil`", - "requirements_not_found": "Tiedostoa requirements.txt ei löytynyt polusta {path} – onko sitä muokattu?", - "warning_failed_parse_imports": "Varoitus: tuontien jäsentäminen epäonnistui tiedostossa {filename}: {error}", - "cogs_dir_not_found": "Cogs-kansiota ei löytynyt polusta {path}, ohitetaan tarkistus.", - "std_lib_local_skipped": "STD LIB / PAIKALLINEN {package} (tarkistus ohitettu)", - "ok_installed": "OK", - "missing_package": "PUUTTUU", - "missing_package2": "ei ole asennettu", - "missing_packages_detected": "Puuttuvia kirjastoja havaittu:", - "telling_goober_central": "Ilmoitetaan goober-centralille osoitteessa {url}", - "failed_to_contact": "Yhteyden muodostus epäonnistui osoitteeseen {url}: {error}", - "all_requirements_satisfied": "Kaikki vaatimukset täyttyvät.", - "ping_to": "Ping osoitteeseen {host}: {latency} ms", - "high_latency": "Korkea viive havaittu! Vastaukset saattavat hidastua.", - "could_not_parse_latency": "Viivettä ei voitu tulkita.", - "ping_failed": "Ping osoitteeseen {host} epäonnistui.", - "error_running_ping": "Virhe ping-komennon suorittamisessa: {error}", - "memory_usage": "Muistin käyttö: {used} Gt / {total} Gt ({percent}%)", - "memory_above_90": "Muistin käyttö ylittää 90 % ({percent}%). Harkitse muistin vapauttamista.", - "total_memory": "Kokonaismuisti: {total} Gt", - "used_memory": "Käytetty muisti: {used} Gt", - "low_free_memory": "Vapaa muisti vähissä! Vain {free} Gt jäljellä.", - "measuring_cpu": "Mitataan suorittimen käyttöä ytimittäin...", - "core_usage": "Ydin {idx}: [{bar}] {usage}%", - "total_cpu_usage": "Kokonaisprosessorin käyttö: {usage}%", - "high_avg_cpu": "Korkea keskimääräinen prosessorin käyttö: {usage}%", - "really_high_cpu": "Erittäin korkea prosessorikuorma! Järjestelmä saattaa hidastua tai jumittua.", - "memory_file": "Muistitiedosto: {size} Mt", - "memory_file_large": "Muistitiedosto on enemmän kuin 1 Gt – harkitse sen tyhjentämistä tilan vapauttamiseksi.", - "memory_file_corrupted": "Muistitiedosto on vioittunut! JSON purkuvirhe: {error}", - "consider_backup_memory": "Harkitse muistitiedoston varmuuskopioimista ja uudelleenluontia.", - "memory_file_encoding": "Muistitiedostossa on koodausongelmia: {error}", - "error_reading_memory": "Virhe muistitiedoston lukemisessa: {error}", - "memory_file_not_found": "Muistitiedostoa ei löytynyt.", - - "modification_warning": "Gooberia on muokattu! Ohitetaan palvelimen tarkistus kokonaan...", - "reported_version": "Ilmoitettu versio:", - "current_hash": "Tämänhetkinen hash:", - "not_found": "ei löytynyt!", - "version_error": "Versiotietojen saanti epäonnistui.. Tilakoodi:", - "loaded_cog": "Ladatut cogit:", - "cog_fail": "Cogin lataus epäonnistui kohteelle:", - "no_model": "Olemassaolevaa markov-mallia ei löydetty. Aloitetaan alusta.", - "folder_created": "Kansio '{folder_name}' luotu.", - "folder_exists": "Kansio '{folder_name}' on jo olemassa...", - "logged_in": "Kirjauduttiin sisään käyttäjänä", - "synced_commands": "Synkronoitiin", - "synced_commands2": "komennot!", - "fail_commands_sync": "Komentojen synkronointi epäonnistui:", - "started": "{name} on käynnistynyt!\nOlet nyt sarjan tähti, beibi!", - "name_check": "Nimen saatavuuden tarkistus epäonnistui:", - "name_taken": "Nimi on jo käytössä. Valitse toinen nimi.", - "name_check2": "Virhe tapahtui nimen saatavuuden tarkistamisessa:", - "add_token": "Token: {token}\nLisää tämä .env-tiedostoosi nimellä", - "token_exists": "Token on jo olemassa .env-tiedostossa. Jatketaan määritetyllä tokenilla.", - "registration_error": "Virhe rekisteröinnissä:", - "version_backup": "Varmuuskopio luotu:", - "backup_error": "Virhe: {LOCAL_VERSION_FILE}-tiedostoa ei löytynyt varmuuskopiota varten.", - "model_loaded": "Markov-malli ladattu", - "fetch_update_fail": "Päivitystietojen hankkiminen epäonnistui.", - "invalid_server": "Virhe: Palvelin antoi virheellisen versiotietoraportin.", - "new_version": "Uusi versio saatavilla: {latest_version} (Tämänhetkinen: {local_version})", - "changelog": "Mene osoitteeseen {VERSION_URL}/goob/changes.txt katsotakseen muutoslokin\n\n", - "invalid_version": "Versio: {local_version} on virheellinen!", - "invalid_version2": "Jos tämä on tahallista, voit jättää tämän viestin huomiotta. Jos tämä ei ole tahallista, paina Y-näppäintä hankkiaksesi kelvollisen version, riippumatta Gooberin tämänhetkisestä versiosta.", - "invalid_version3": "Tämänhetkinen versio varmuuskopioidaan kohteeseen current_version.bak..", - "input": "(Y:tä tai mitä vaan muuta näppäintä jättää tämän huomioimatta....)", - "modification_ignored": "Olet muokannut", - "modification_ignored2": "IGNOREWARNING on asetettu false:ksi..", - "latest_version": "Käytät uusinta versiota:", - "latest_version2": "Tarkista {VERSION_URL}/goob/changes.txt katsotakseen muutosloki", - "pinging_disabled": "Pingaus on poistettu käytöstä! En kerro palvelimelle, että olen päällä...", - "goober_ping_success": "Lähetettiin olemassaolo ping goober centraliin!", - "goober_ping_fail": "Tiedon lähetys epäonnistui. Palvelin antoi tilakoodin:", - "goober_ping_fail2": "Tiedon lähettämisen aikana tapahtui virhe:", - "sentence_positivity": "Lauseen positiivisuus on:", - "command_edit_fail": "Viestin muokkaus epäonnistui:", - "command_desc_retrain": "Uudelleenkouluttaa markov-mallin manuaalisesti.", - "command_markov_retrain": "Uudelleenkoulutetaan markov-mallia... Odota.", - "command_markov_memory_not_found": "Virhe: muistitiedostoa ei löytynyt!", - "command_markov_memory_is_corrupt": "Virhe: muistitiedosto on korruptoitu!", - "command_markov_retraining": "Käsitellään {processed_data}/{data_size} datapisteestä...", - "command_markov_retrain_successful": "Markov-malli koulutettiin uudestaan {data_size} datapisteellä!", - "command_desc_talk":"puhuu ja sillei", - "command_talk_insufficent_text": "Minun pitää oppia lisää viesteistä ennen kun puhun.", - "command_talk_generation_fail": "Minulla ei ole mitään sanottavaa!", - "command_desc_help": "auta", - "command_help_embed_title": "Botin apu", - "command_help_embed_desc": "Komennot ryhmitelty kategorioilla", - "command_help_categories_general": "Yleiset", - "command_help_categories_admin": "Ylläpito", - "command_help_categories_custom": "Mukautetut komennot", - "command_ran": "Tietoa: {message.author.name} suoritti {message.content}", - "command_desc_ping": "ping", - "command_ping_embed_desc": "Botin viive:", - "command_ping_footer": "Pyytäjä: ", - "command_about_desc": "tietoa", - "command_about_embed_title": "Tietoa minusta", - "command_about_embed_field1": "Nimi", - "command_about_embed_field2name": "Versio", - "command_about_embed_field2value": "Paikallinen: {local_version} \nUusin: {latest_version}", - "command_desc_stats": "statistiikat", - "command_stats_embed_title": "Botin statistiikat", - "command_stats_embed_desc": "Tietoa botin muistista.", - "command_stats_embed_field1name": "Tiedostostatistiikat", - "command_stats_embed_field1value": "Koko: {file_size} tavua\nLinjoja: {line_count}", - "command_stats_embed_field2name": "Versio", - "command_stats_embed_field2value": "Paikallinen: {local_version} \nUusin: {latest_version}", - "command_stats_embed_field3name": "Muuttajainformaatio", - "command_stats_embed_field3value": "Nimi: {NAME} \nEtuliite: {PREFIX} \nOmistajan ID: {ownerid}\nPing-linja: {PING_LINE} \nMuistin jako päällä: {showmemenabled} \nOppiminen käyttäjistä: {USERTRAIN_ENABLED}\nLaulu: {song} \nRoisketeksti: ```{splashtext}```" -} - diff --git a/assets/locales/fr.json b/assets/locales/fr.json deleted file mode 100644 index 572d2f4..0000000 --- a/assets/locales/fr.json +++ /dev/null @@ -1,130 +0,0 @@ -{ - "checks_disabled": "Les vérifications sont désactivées !", - "unhandled_exception": "Une exception non gérée est survenue. Merci de rapporter ce problème sur GitHub.", - "active_users:": "Utilisateurs actifs :", - "spacy_initialized": "spaCy et spacytextblob sont prêts.", - "spacy_model_not_found": "Le modèle spaCy est introuvable ! Téléchargement en cours...", - "env_file_not_found": "Le fichier .env est introuvable ! Créez-en un avec les variables nécessaires.", - "error_fetching_active_users": "Erreur lors de la récupération des utilisateurs actifs : {error}", - "error_sending_alive_ping": "Erreur lors de l’envoi du ping actif : {error}", - "already_started": "J’ai déjà démarré ! Je ne me mets pas à jour...", - "please_restart": "Redémarre, stp !", - "local_ahead": "Local {remote}/{branch} est en avance ou à jour. Pas de mise à jour...", - "remote_ahead": "Remote {remote}/{branch} est en avance. Mise à jour en cours...", - "cant_find_local_version": "Je ne trouve pas la variable local_version ! Ou elle a été modifiée et ce n’est pas un entier !", - "running_prestart_checks": "Exécution des vérifications préalables au démarrage...", - "continuing_in_seconds": "Reprise dans {seconds} secondes... Appuie sur une touche pour passer.", - "missing_requests_psutil": "requests et psutil manquants ! Installe-les avec pip : `pip install requests psutil`", - "requirements_not_found": "requirements.txt introuvable à {path}, a-t-il été modifié ?", - "warning_failed_parse_imports": "Avertissement : Échec du parsing des imports depuis {filename} : {error}", - "cogs_dir_not_found": "Répertoire des cogs introuvable à {path}, scan ignoré.", - "std_lib_local_skipped": "LIB STD / LOCAL {package} (vérification sautée)", - "ok_installed": "OK", - "missing_package": "MANQUANT", - "missing_package2": "n’est pas installé", - "missing_packages_detected": "Packages manquants détectés :", - "telling_goober_central": "Envoi à goober central à {url}", - "failed_to_contact": "Impossible de contacter {url} : {error}", - "all_requirements_satisfied": "Toutes les dépendances sont satisfaites.", - "ping_to": "Ping vers {host} : {latency} ms", - "high_latency": "Latence élevée détectée ! Tu pourrais avoir des délais de réponse.", - "could_not_parse_latency": "Impossible d’analyser la latence.", - "ping_failed": "Ping vers {host} échoué.", - "error_running_ping": "Erreur lors du ping : {error}", - "memory_usage": "Utilisation mémoire : {used} Go / {total} Go ({percent}%)", - "memory_above_90": "Usage mémoire au-dessus de 90% ({percent}%). Pense à libérer de la mémoire.", - "total_memory": "Mémoire totale : {total} Go", - "used_memory": "Mémoire utilisée : {used} Go", - "low_free_memory": "Mémoire libre faible détectée ! Seulement {free} Go disponibles.", - "measuring_cpu": "Mesure de l’usage CPU par cœur...", - "core_usage": "Cœur {idx} : [{bar}] {usage}%", - "total_cpu_usage": "Usage total CPU : {usage}%", - "high_avg_cpu": "Moyenne CPU élevée : {usage}%", - "really_high_cpu": "Charge CPU vraiment élevée ! Le système pourrait ralentir ou planter.", - "memory_file": "Fichier mémoire : {size} Mo", - "memory_file_large": "Fichier mémoire de 1 Go ou plus, pense à le nettoyer pour libérer de l’espace.", - "memory_file_corrupted": "Fichier mémoire corrompu ! Erreur JSON : {error}", - "consider_backup_memory": "Pense à sauvegarder et recréer le fichier mémoire.", - "memory_file_encoding": "Problèmes d’encodage du fichier mémoire : {error}", - "error_reading_memory": "Erreur lecture fichier mémoire : {error}", - "memory_file_not_found": "Fichier mémoire introuvable.", - "modification_warning": "Goober a été modifié ! Toutes les modifications seront perdues lors d'une mise à jour !", - "reported_version": "Version rapportée :", - "current_hash": "Hachage actuel :", - "not_found": "n'est pas trouvé !", - "version_error": "Impossible de récupérer les informations de version. Code d'état", - "loaded_cog": "Cog chargé :", - "loaded_cog2": "Module chargé :", - "cog_fail": "Échec du chargement du cog :", - "cog_fail2": "Échec du chargement du module :", - "no_model": "Aucun modèle Markov sauvegardé trouvé. Démarrage à partir de zéro.", - "folder_created": "Dossier '{folder_name}' créé.", - "folder_exists": "Le dossier '{folder_name}' existe déjà. Ignorons...", - "logged_in": "Connecté en tant que", - "synced_commands": "Synchronisé", - "synced_commands2": "commandes !", - "fail_commands_sync": "Échec de la synchronisation des commandes :", - "started": "{name} a démarré !", - "name_check": "Erreur lors de la vérification de la disponibilité du nom :", - "name_taken": "Le nom est déjà pris. Veuillez choisir un autre nom.", - "name_check2": "Erreur lors de la vérification de la disponibilité du nom :", - "add_token": "Token : {token}\nVeuillez ajouter ce token à votre fichier .env comme", - "token_exists": "Le token existe déjà dans .env. Utilisation du token existant.", - "registration_error": "Erreur lors de l'enregistrement :", - "version_backup": "Sauvegarde créée :", - "backup_error": "Erreur : {LOCAL_VERSION_FILE} introuvable pour la sauvegarde.", - "model_loaded": "Modèle Markov chargé depuis", - "fetch_update_fail": "Impossible de récupérer les informations de mise à jour.", - "invalid_server": "Erreur : Informations de version invalides reçues du serveur.", - "goober_server_alert": "Alerte du serveur Goober central !\n", - "new_version": "Nouvelle version disponible : {latest_version} (Actuelle : {local_version})", - "changelog": "Consultez {VERSION_URL}/goob/changes.txt pour voir les modifications\n\n", - "invalid_version": "La version : {local_version} n'est pas valide !", - "invalid_version2": "Si c'est intentionnel, ignorez ce message. Sinon, appuyez sur Y pour récupérer une version valide depuis le serveur, quelle que soit la version actuelle de Goober.", - "invalid_version3": "La version actuelle sera sauvegardée dans current_version.bak..", - "input": "(Y ou toute autre touche pour ignorer...)", - "modification_ignored": "Vous avez modifié", - "modification_ignored2": "IGNOREWARNING est désactivé..", - "latest_version": "Vous utilisez la dernière version :", - "latest_version2": "Consultez {VERSION_URL}/goob/changes.txt pour voir les modifications", - "pinging_disabled": "Le ping est désactivé ! Je ne préviens pas le serveur que je suis en ligne...", - "goober_ping_success": "Connecté à Goober central en tant que {NAME}", - "goober_ping_fail": "Échec de l'envoi des données. Le serveur a retourné le code d'état :", - "goober_ping_fail2": "Une erreur est survenue lors de l'envoi des données :", - "sentence_positivity": "La positivité de la phrase est :", - "command_edit_fail": "Échec de la modification du message :", - "command_desc_retrain": "Réentraîne manuellement le modèle Markov.", - "command_markov_retrain": "Réentraînement du modèle Markov... Veuillez patienter.", - "command_markov_memory_not_found": "Erreur : fichier de mémoire introuvable !", - "command_markov_memory_is_corrupt": "Erreur : le fichier de mémoire est corrompu !", - "command_markov_retraining": "Traitement de {processed_data}/{data_size} points de données...", - "command_markov_retrain_successful": "Modèle Markov réentraîné avec succès en utilisant {data_size} points de données !", - "command_desc_talk": "parle et tout ça", - "command_talk_insufficent_text": "Je dois apprendre plus de messages avant de pouvoir parler.", - "command_talk_generation_fail": "Je n'ai rien à dire pour le moment !", - "command_desc_help": "aide", - "command_help_embed_title": "Aide du bot", - "command_help_embed_desc": "Liste des commandes regroupées par catégorie.", - "command_help_categories_general": "Général", - "command_help_categories_admin": "Administration", - "command_help_categories_custom": "Commandes personnalisées", - "command_ran": "Info : {message.author.name} a exécuté {message.content}", - "command_ran_s": "Info : {interaction.user} a exécuté ", - "command_desc_ping": "ping", - "command_ping_embed_desc": "Latence du bot :", - "command_ping_footer": "Demandé par", - "command_about_desc": "à propos", - "command_about_embed_title": "À propos de moi", - "command_about_embed_field1": "Nom", - "command_about_embed_field2name": "Version", - "command_about_embed_field2value": "Locale : {local_version} \nDernière : {latest_version}", - "command_desc_stats": "statistiques", - "command_stats_embed_title": "Statistiques du bot", - "command_stats_embed_desc": "Données sur la mémoire du bot.", - "command_stats_embed_field1name": "Statistiques du fichier", - "command_stats_embed_field1value": "Taille : {file_size} octets\nLignes : {line_count}", - "command_stats_embed_field2name": "Version", - "command_stats_embed_field2value": "Locale : {local_version} \nDernière : {latest_version}", - "command_stats_embed_field3name": "Informations variables", - "command_stats_embed_field3value": "Nom : {NAME} \nPréfixe : {PREFIX} \nID du propriétaire : {ownerid}\nLigne de ping : {PING_LINE} \nPartage de mémoire activé : {showmemenabled} \nEntraînement utilisateur activé : {USERTRAIN_ENABLED} \nChanson : {song} \nTexte de démarrage : ```{splashtext}```" -} \ No newline at end of file diff --git a/assets/locales/it.json b/assets/locales/it.json deleted file mode 100644 index 954b0ce..0000000 --- a/assets/locales/it.json +++ /dev/null @@ -1,137 +0,0 @@ -{ - "memory_file_valid": "Il file JSON è valido!", - "file_aint_utf8": "Il file non è un UTF-8 valido. Forse è binario?", - "psutil_not_installed": "Controllo memoria saltato.", - "not_cloned": "Goober non è stato clonato! Clonalo da GitHub.", - "checks_disabled": "I controlli sono disabilitati!", - "unhandled_exception": "Si è verificata un'eccezione non gestita. Segnala questo problema su GitHub, per favore.", - "active_users:": "Utenti attivi:", - "spacy_initialized": "spaCy e spacytextblob sono pronti.", - "error_fetching_active_users": "Errore nel recupero degli utenti attivi: {error}", - "spacy_model_not_found": "Il modello spaCy non è stato trovato! Lo sto scaricando...", - "env_file_not_found": "Il file .env non è stato trovato! Crea un file con le variabili richieste.", - "error fetching_active_users": "Errore nel recupero degli utenti attivi:", - "error_sending_alive_ping": "Errore nell'invio di aliveping:", - "already_started": "Sono già avviato! Non aggiorno...", - "please_restart": "Riavvia goober!", - "local_ahead": "Il ramo locale {remote}/{branch} è aggiornato o avanti. Nessun aggiornamento...", - "remote_ahead": "Il ramo remoto {remote}/{branch} è avanti. Aggiornamento in corso...", - "cant_find_local_version": "Impossibile trovare la variabile local_version! O è stata manomessa e non è un intero!", - "running_prestart_checks": "Esecuzione dei controlli pre-avvio...", - "continuing_in_seconds": "Continuo tra {seconds} secondi... Premi un tasto per saltare.", - "missing_requests_psutil": "Mancano requests e psutil! Installali con pip: `pip install requests psutil`", - "requirements_not_found": "requirements.txt non trovato in {path} è stato manomesso?", - "warning_failed_parse_imports": "Attenzione: impossibile analizzare le importazioni da {filename}: {error}", - "cogs_dir_not_found": "Cartella cogs non trovata in {path}, scansione saltata.", - "std_lib_local_skipped": "LIB STD / LOCALE {package} (controllo saltato)", - "ok_installed": "OK", - "missing_package": "REQUISITO MANCANTE", - "missing_package2": "non è installato", - "missing_packages_detected": "Pacchetti mancanti rilevati:", - "telling_goober_central": "Segnalazione a goober central su {url}", - "failed_to_contact": "Impossibile contattare {url}: {error}", - "all_requirements_satisfied": "Tutti i requisiti sono soddisfatti.", - "ping_to": "Ping a {host}: {latency} ms", - "high_latency": "Latenza elevata rilevata! Potresti riscontrare ritardi nelle risposte.", - "could_not_parse_latency": "Impossibile analizzare la latenza.", - "ping_failed": "Ping a {host} fallito.", - "error_running_ping": "Errore durante l'esecuzione del ping: {error}", - "memory_usage": "Utilizzo memoria: {used} GB / {total} GB ({percent}%)", - "memory_above_90": "Utilizzo memoria sopra il 90% ({percent}%). Considera di liberare memoria.", - "total_memory": "Memoria totale: {total} GB", - "used_memory": "Memoria usata: {used} GB", - "low_free_memory": "Poca memoria libera! Solo {free} GB disponibili.", - "measuring_cpu": "Misurazione utilizzo CPU per core...", - "core_usage": "Core {idx}: [{bar}] {usage}%", - "total_cpu_usage": "Utilizzo totale CPU: {usage}%", - "high_avg_cpu": "Utilizzo medio CPU elevato: {usage}%", - "really_high_cpu": "Carico CPU molto alto! Il sistema potrebbe rallentare o bloccarsi.", - "memory_file": "File memoria: {size} MB", - "memory_file_large": "Il file di memoria è 1GB o più, valuta di svuotarlo.", - "memory_file_corrupted": "File memoria corrotto! Errore JSON decode: {error}", - "consider_backup_memory": "Valuta di fare un backup e ricreare il file di memoria.", - "memory_file_encoding": "Problemi di codifica nel file memoria: {error}", - "error_reading_memory": "Errore nella lettura del file memoria: {error}", - "memory_file_not_found": "File memoria non trovato.", - "modification_warning": "Goober è stato modificato! Verifiche del server saltate completamente...", - "reported_version": "Versione segnalata:", - "current_hash": "Hash attuale:", - "not_found": "non trovato!", - "version_error": "Impossibile recuperare le informazioni sulla versione. Codice di stato", - "loaded_cog": "Cog caricato:", - "cog_fail": "Impossibile caricare il cog:", - "loaded_cog2": "Module caricato:", - "cog_fail2": "Impossibile caricare il module:", - "no_model": "Nessun modello Markov salvato trovato. Iniziamo da zero.", - "folder_created": "Cartella '{folder_name}' creata.", - "folder_exists": "La cartella '{folder_name}' esiste già. Saltando...", - "logged_in": "Accesso effettuato come", - "synced_commands": "Sincronizzati", - "synced_commands2": "comandi!", - "fail_commands_sync": "Impossibile sincronizzare i comandi:", - "started": "{name} è stato avviato!\nIl palco è tuo!", - "name_check": "Errore nel controllo disponibilità del nome:", - "name_taken": "Il nome è già preso. Scegli un nome diverso.", - "name_check2": "Errore durante il controllo della disponibilità del nome:", - "add_token": "Token: {token}\nAggiungi questo token al tuo file .env come", - "token_exists": "Il token esiste già in .env. Continuando con il token esistente.", - "goober_server_alert": "Avviso da goober central!\n", - "registration_error": "Errore durante la registrazione:", - "version_backup": "Backup creato:", - "backup_error": "Errore: {LOCAL_VERSION_FILE} non trovato per il backup.", - "model_loaded": "Modello Markov caricato da", - "fetch_update_fail": "Impossibile recuperare le informazioni sull'aggiornamento.", - "invalid_server": "Errore: informazioni sulla versione non valide ricevute dal server.", - "new_version": "Nuova versione disponibile: {latest_version} (Attuale: {local_version})", - "changelog": "Controlla {VERSION_URL}/goob/changes.txt per vedere il changelog\n\n", - "invalid_version": "La versione: {local_version} non è valida!", - "invalid_version2": "Se è intenzionale ignora questo messaggio, altrimenti premi Y per scaricare una versione valida dal server indipendentemente dalla versione attuale di goober", - "invalid_version3": "La versione attuale sarà salvata come current_version.bak..", - "input": "(Y o qualsiasi altro tasto per ignorare....)", - "modification_ignored": "Hai modificato", - "modification_ignored2": "IGNOREWARNING è impostato su false..", - "latest_version": "Stai utilizzando l'ultima versione:", - "latest_version2": "Controlla {VERSION_URL}/goob/changes.txt per vedere il changelog", - "pinging_disabled": "Il ping è disabilitato! Non dico al server che sono online...", - "goober_ping_success": "Accesso a goober central come {NAME}", - "goober_ping_fail": "Impossibile inviare i dati. Il server ha restituito il codice di stato:", - "goober_ping_fail2": "Si è verificato un errore durante l'invio dei dati:", - "sentence_positivity": "La positività della frase è:", - "command_edit_fail": "Impossibile modificare il messaggio:", - "command_desc_retrain": "Rafforza manualmente il modello Markov.", - "command_markov_retrain": "Rafforzamento del modello Markov in corso... Attendere.", - "command_markov_memory_not_found": "Errore: file di memoria non trovato!", - "command_markov_memory_is_corrupt": "Errore: file di memoria corrotto!", - "command_markov_retraining": "Elaborazione di {data_size} punti dati...", - "command_markov_retrain_successful": "Modello Markov rafforzato con successo utilizzando {data_size} punti dati!", - "command_desc_talk": "parla n come stuf", - "command_talk_insufficent_text": "Ho bisogno di imparare di più dai messaggi prima di poter parlare.", - "command_talk_generation_fail": "Non ho nulla da dire in questo momento!", - "command_desc_help": "aiuto", - "command_help_embed_title": "Aiuto Bot", - "command_help_embed_desc": "Elenco dei comandi raggruppati per categoria.", - "command_help_categories_general": "Generale", - "command_help_categories_admin": "Amministrazione", - "command_help_categories_custom": "Comandi personalizzati", - "command_ran": "Info: {message.author.name} ha eseguito {message.content}", - "command_ran_s": "Info: {interaction.user} ha eseguito ", - "command_desc_ping": "ping", - "command_desc_setlang": "Imposta una nuova lingua per il bot (temporaneamente)", - "command_ping_embed_desc": "Latenza del bot:", - "command_ping_footer": "Richiesto da", - "command_about_desc": "informazioni", - "command_about_embed_title": "Informazioni su di me", - "command_about_embed_field1": "Nome", - "command_about_embed_field2name": "Versione", - "command_about_embed_field2value": "Locale: {local_version} \nUltima: {latest_version}", - "command_desc_stats": "statistiche", - "command_stats_embed_title": "Statistiche del bot", - "command_stats_embed_desc": "Dati sulla memoria del bot.", - "command_stats_embed_field1name": "Statistiche del file", - "command_stats_embed_field1value": "Dimensione: {file_size} byte\nLinee: {line_count}", - "command_stats_embed_field2name": "Versione", - "command_stats_embed_field2value": "Locale: {local_version} \nUltima: {latest_version}", - "command_stats_embed_field3name": "Informazioni sulle variabili", - "command_stats_embed_field3value": "Nome: {NAME} \nPrefisso: {PREFIX} \nID Proprietario: {ownerid}\nLinea ping: {PING_LINE} \nMemoria Condivisa Abilitata: {showmemenabled} \nAddestramento Utente Abilitato: {USERTRAIN_ENABLED}\nCanzone: {song} \nSplashtext: ```{splashtext}```" - } - diff --git a/bot.py b/bot.py index 74cf0b7..9a0d416 100644 --- a/bot.py +++ b/bot.py @@ -1,513 +1,203 @@ -import os -import re -import json -import time -import random -import traceback -import subprocess -import tempfile -import shutil -import uuid -import asyncio -import sys -from typing import List, Dict, Set, Optional, Tuple, Any, Union, Callable, Coroutine, TypeVar, Type -import logging -from modules.globalvars import * -from modules.prestartchecks import start_checks -from modules.logger import GooberFormatter -import logging - -logger = logging.getLogger("goober") -logger.setLevel(logging.DEBUG) - -console_handler = logging.StreamHandler() -console_handler.setLevel(logging.DEBUG) -console_handler.setFormatter(GooberFormatter()) - -file_handler = logging.FileHandler("log.txt", mode="w+", encoding="UTF-8") -file_handler.setLevel(logging.DEBUG) -file_handler.setFormatter(GooberFormatter(colors=False)) - -logger.addHandler(console_handler) -logger.addHandler(file_handler) - -# Print splash text and check for updates -print(splashtext) # Print splash text (from modules/globalvars.py) -start_checks() - -import requests import discord -from discord.ext import commands -from discord import app_commands -from discord import Colour, Embed, File, Interaction, Message -from discord.abc import Messageable +from discord.ext import commands, tasks +import json +import markovify +import nltk +from nltk.tokenize import word_tokenize +import random +import os +import time +import re +from dotenv import load_dotenv +import psutil +load_dotenv() +# download NLTK data files +nltk.download('punkt') +MEMORY_FILE = "memory.json" +MEMORY_LOADED_FILE = "MEMORY_LOADED" +MESSAGEAIID = int(os.getenv("MESSAGEAIID")) +def load_memory(): + data = [] -from better_profanity import profanity -from discord.ext import commands + # Try to load data from MEMORY_FILE + try: + with open(MEMORY_FILE, "r") as f: + data = json.load(f) + except FileNotFoundError: + pass -from modules.volta.main import _, set_language -from modules.markovmemory import * -from modules.version import * -from modules.sentenceprocessing import * -from modules.unhandledexception import handle_exception -from modules.image import gen_meme, gen_demotivator + return data -sys.excepthook = handle_exception -check_for_update() # Check for updates (from modules/version.py) +# Save memory data to MEMORY_FILE +def save_memory(memory): + with open(MEMORY_FILE, "w") as f: + json.dump(memory, f, indent=4) -# Type aliases -T = TypeVar('T') -MessageContext = Union[commands.Context, discord.Interaction] -MessageReference = Union[Message, discord.WebhookMessage] +def train_markov_model(memory, additional_data=None): + if not memory: + return None + filtered_memory = [line for line in memory if isinstance(line, str)] + if additional_data: + filtered_memory.extend(line for line in additional_data if isinstance(line, str)) + if not filtered_memory: + return None + text = "\n".join(filtered_memory) + model = markovify.NewlineText(text, state_size=2) + return model -# Constants with type hints -positive_gifs: List[str] = os.getenv("POSITIVE_GIFS", "").split(',') -currenthash: str = "" -launched: bool = False -slash_commands_enabled: bool = False +#this doesnt work and im extremely pissed and mad +def append_mentions_to_18digit_integer(message): + pattern = r'\b\d{18}\b' + return re.sub(pattern, lambda match: f"<@{match.group(0)}>", message) -# Set up Discord bot intents and create bot instance -intents: discord.Intents = discord.Intents.default() +def preprocess_message(message): + message = append_mentions_to_18digit_integer(message) + tokens = word_tokenize(message) + tokens = [token for token in tokens if token.isalnum()] + return " ".join(tokens) + + +intents = discord.Intents.default() intents.messages = True intents.message_content = True -bot: commands.Bot = commands.Bot( - command_prefix=PREFIX, - intents=intents, - allowed_mentions=discord.AllowedMentions(everyone=False, roles=False, users=False, replied_user=True) -) +bot = commands.Bot(command_prefix="g!", intents=intents) +memory = load_memory() +markov_model = train_markov_model(memory) -# Load memory and Markov model for text generation -memory: List[str] = load_memory() -markov_model: Optional[markovify.Text] = load_markov_model() -if not markov_model: - logger.error(_('markov_model_not_found')) - memory = load_memory() - markov_model = train_markov_model(memory) - -generated_sentences: Set[str] = set() -used_words: Set[str] = set() - -async def load_cogs_from_folder(bot, folder_name="assets/cogs"): - for filename in os.listdir(folder_name): - if filename.endswith(".py") and not filename.startswith("_"): - cog_name = filename[:-3] - module_path = folder_name.replace("/", ".").replace("\\", ".") + f".{cog_name}" - try: - await bot.load_extension(module_path) - logger.info(f"{(_('loaded_cog'))} {cog_name}") - except Exception as e: - logger.error(f"{(_('cog_fail'))} {cog_name} {e}") - traceback.print_exc() - -async def send_alive_ping_periodically() -> None: - while True: - try: - requests.post(f"{VERSION_URL}/aliveping", json={"name": NAME}) - except Exception as e: - logger.error(f"{(_('error_sending_alive_ping'))}{RESET} {e}") - await asyncio.sleep(60) - -# Event: Called when the bot is ready -@bot.event -async def on_ready() -> None: - global launched - global slash_commands_enabled - global NAME - - folder_name: str = "cogs" - if launched: - return - - await load_cogs_from_folder(bot) - try: - synced: List[discord.app_commands.AppCommand] = await bot.tree.sync() - logger.info(f"{_('synced_commands')} {len(synced)} {(_('synced_commands2'))}") - slash_commands_enabled = True - logger.info(f"{(_('started')).format(name=NAME)}") - - bot.loop.create_task(send_alive_ping_periodically()) - except discord.errors.Forbidden as perm_error: - logger.error(f"Permission error while syncing commands: {perm_error}") - logger.error("Make sure the bot has the 'applications.commands' scope and is invited with the correct permissions.") - quit() - except Exception as e: - logger.error(f"{_('fail_commands_sync')} {e}") - traceback.print_exc() - quit() - - if not song: - return - await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name=f"{song}")) - launched = True +generated_sentences = set() +used_words = set() @bot.event -async def on_command_error(ctx: commands.Context, error: commands.CommandError) -> None: - from modules.unhandledexception import handle_exception - - if isinstance(error, commands.CommandInvokeError): - original: Exception = error.original - handle_exception( - type(original), original, original.__traceback__, - context=f"Command: {ctx.command} | User: {ctx.author}" - ) - else: - handle_exception( - type(error), error, error.__traceback__, - context=f"Command: {ctx.command} | User: {ctx.author}" - ) +async def on_ready(): + print(f"Logged in as {bot.user}") + post_message.start() -# Command: Retrain the Markov model from memory -@bot.hybrid_command(description=f"{(_('command_desc_retrain'))}") -async def retrain(ctx: commands.Context) -> None: - if ctx.author.id != ownerid: - return +@bot.command() +async def mem(ctx): + process = psutil.Process(os.getpid()) + mem = process.memory_info().rss + await ctx.send(f"Total memory used: {mem / 1024 / 1024:.2f} MB") - message_ref: MessageReference = await send_message(ctx, f"{(_('command_markov_retrain'))}") - try: - with open(MEMORY_FILE, 'r') as f: - memory: List[str] = json.load(f) - except FileNotFoundError: - await send_message(ctx, f"{(_('command_markov_memory_not_found'))}") - return - except json.JSONDecodeError: - await send_message(ctx, f"{(_('command_markov_memory_is_corrupt'))}") - return - - data_size: int = len(memory) - processed_data: int = 0 - processing_message_ref: MessageReference = await send_message(ctx, f"{(_('command_markov_retraining')).format(processed_data=processed_data, data_size=data_size)}") - start_time: float = time.time() - - for i, data in enumerate(memory): - processed_data += 1 +positive_keywords = ["happy", "good", "great", "amazing", "awesome", "joy", "love", "fantastic", "positive", "cheerful", "victory", "favorite", "lmao", "lol", "xd", "XD", "xD", "Xd"] - global markov_model - markov_model = train_markov_model(memory) - save_markov_model(markov_model) +positive_gifs = [ + "https://tenor.com/view/chill-guy-my-new-character-gif-2777893510283028272", + "https://tenor.com/view/goodnight-goodnight-friends-weezer-weezer-goodnight-gif-7322052181075806988" +] - await send_message(ctx, f"{_('command_markov_retrain_successful').format(data_size=data_size)}", edit=True, message_reference=processing_message_ref) +def is_positive(sentence): + sentence_lower = sentence.lower() + return any(keyword in sentence_lower for keyword in positive_keywords) -# Command: Generate a sentence using the Markov model -@bot.hybrid_command(description=f"{(_('command_desc_talk'))}") -async def talk(ctx: commands.Context, sentence_size: int = 5) -> None: - if not markov_model: - await send_message(ctx, f"{(_('command_talk_insufficent_text'))}") - return - response: Optional[str] = None - for _ in range(20): - if sentence_size == 1: - response = markov_model.make_short_sentence(max_chars=100, tries=100) +def improve_sentence_coherence(sentence): + + sentence = sentence.replace(" i ", " I ") + return sentence + +def rephrase_for_coherence(sentence): + + words = sentence.split() + + coherent_sentence = " ".join(words) + return coherent_sentence + +bot.help_command = None + + +@bot.event +async def on_message(message): + global memory, markov_model, last_random_talk_time + + if message.author.bot and message.author.id != bot.user.id: + if markov_model: + response = None + for _ in range(10): + response = markov_model.make_sentence(tries=100) + if response and response not in generated_sentences: + response = improve_sentence_coherence(response) + generated_sentences.add(response) + break + if response: - response = response.split()[0] + async with message.channel.typing(): + cleaned_response = re.sub(r'[^\w\s]', '', response).lower() + coherent_response = rephrase_for_coherence(cleaned_response) + if random.random() < 0.9: + if is_positive(coherent_response): + gif_url = random.choice(positive_gifs) + combined_message = f"{coherent_response}\n[jif]({gif_url})" + await message.channel.send(combined_message) + else: + await message.channel.send(coherent_response) + else: + await message.channel.send(coherent_response) + else: + await message.channel.send("I have nothing to say right now!") else: - response = markov_model.make_sentence(tries=100, max_words=sentence_size) - - if response and response not in generated_sentences: - if sentence_size > 1: - response = improve_sentence_coherence(response) - generated_sentences.add(response) - break - - if response: - cleaned_response: str = re.sub(r'[^\w\s]', '', response).lower() - coherent_response: str = rephrase_for_coherence(cleaned_response) - if random.random() < 0.9 and is_positive(coherent_response): - gif_url: str = random.choice(positive_gifs) - combined_message: str = f"{coherent_response}\n[jif]({gif_url})" - else: - combined_message: str = coherent_response - logger.info(combined_message) - os.environ['gooberlatestgen'] = combined_message - await send_message(ctx, combined_message) - else: - await send_message(ctx, f"{(_('command_talk_generation_fail'))}") - -# Command: Generate an image -@bot.hybrid_command(description=f"{(_('command_desc_help'))}") -async def impact(ctx: commands.Context) -> None: - assets_folder: str = "assets/images" - temp_input: Optional[str] = None - - def get_random_asset_image() -> Optional[str]: - files: List[str] = [f for f in os.listdir(assets_folder) if f.lower().endswith(('.png', '.jpg', '.jpeg', '.webp'))] - if not files: - return None - return os.path.join(assets_folder, random.choice(files)) - - if ctx.message.attachments: - attachment: discord.Attachment = ctx.message.attachments[0] - if attachment.content_type and attachment.content_type.startswith("image/"): - ext: str = os.path.splitext(attachment.filename)[1] - temp_input = f"tempy{ext}" - await attachment.save(temp_input) - input_path: str = temp_input - else: - fallback_image: Optional[str] = get_random_asset_image() - if fallback_image is None: - await ctx.reply(_('no_image_available')) - return - temp_input = tempfile.mktemp(suffix=os.path.splitext(fallback_image)[1]) - shutil.copy(fallback_image, temp_input) - input_path = temp_input - else: - fallback_image = get_random_asset_image() - if fallback_image is None: - await ctx.reply(_('no_image_available')) - return - temp_input = tempfile.mktemp(suffix=os.path.splitext(fallback_image)[1]) - shutil.copy(fallback_image, temp_input) - input_path = temp_input - - output_path: Optional[str] = await gen_meme(input_path) - - if output_path is None or not os.path.isfile(output_path): - if temp_input and os.path.exists(temp_input): - os.remove(temp_input) - await ctx.reply(_('failed_generate_image')) - return - - await ctx.send(file=discord.File(output_path)) - - if temp_input and os.path.exists(temp_input): - os.remove(temp_input) - -# New demotivator command -@bot.hybrid_command(description="Generate a demotivator poster with two lines of text") -async def demotivator(ctx: commands.Context) -> None: - assets_folder: str = "assets/images" - temp_input: Optional[str] = None - - def get_random_asset_image() -> Optional[str]: - files: List[str] = [f for f in os.listdir(assets_folder) if f.lower().endswith(('.png', '.jpg', '.jpeg', '.webp'))] - if not files: - return None - return os.path.join(assets_folder, random.choice(files)) - - if ctx.message.attachments: - attachment: discord.Attachment = ctx.message.attachments[0] - if attachment.content_type and attachment.content_type.startswith("image/"): - ext: str = os.path.splitext(attachment.filename)[1] - temp_input = f"tempy{ext}" - await attachment.save(temp_input) - input_path: str = temp_input - else: - fallback_image: Optional[str] = get_random_asset_image() - if fallback_image is None: - await ctx.reply(_('no_image_available')) - return - temp_input = tempfile.mktemp(suffix=os.path.splitext(fallback_image)[1]) - shutil.copy(fallback_image, temp_input) - input_path = temp_input - else: - fallback_image = get_random_asset_image() - if fallback_image is None: - await ctx.reply(_('no_image_available')) - return - temp_input = tempfile.mktemp(suffix=os.path.splitext(fallback_image)[1]) - shutil.copy(fallback_image, temp_input) - input_path = temp_input - - output_path: Optional[str] = await gen_demotivator(input_path) - - if output_path is None or not os.path.isfile(output_path): - if temp_input and os.path.exists(temp_input): - os.remove(temp_input) - await ctx.reply("Failed to generate demotivator.") - return - - await ctx.send(file=discord.File(output_path)) - - if temp_input and os.path.exists(temp_input): - os.remove(temp_input) - -bot.remove_command('help') -# Command: Show help information -@bot.hybrid_command(description=f"{(_('command_desc_help'))}") -async def help(ctx: commands.Context) -> None: - embed: discord.Embed = discord.Embed( - title=f"{(_('command_help_embed_title'))}", - description=f"{(_('command_help_embed_desc'))}", - color=Colour(0x000000) - ) - - command_categories: Dict[str, List[str]] = { - f"{(_('command_help_categories_general'))}": ["mem", "talk", "about", "ping", "impact", "demotivator", "help"], - f"{(_('command_help_categories_admin'))}": ["stats", "retrain", "setlanguage"] - } - - custom_commands: List[str] = [] - for cog_name, cog in bot.cogs.items(): - for command in cog.get_commands(): - if command.name not in command_categories[f"{(_('command_help_categories_general'))}"] and command.name not in command_categories[f"{(_('command_help_categories_admin'))}"]: - custom_commands.append(command.name) - - if custom_commands: - embed.add_field(name=f"{(_('command_help_categories_custom'))}", value="\n".join([f"{PREFIX}{command}" for command in custom_commands]), inline=False) - - for category, commands_list in command_categories.items(): - commands_in_category: str = "\n".join([f"{PREFIX}{command}" for command in commands_list]) - embed.add_field(name=category, value=commands_in_category, inline=False) - - await send_message(ctx, embed=embed) - -@bot.hybrid_command(description=f"{(_('command_desc_setlang'))}") -@app_commands.describe(locale="Choose your language") -async def setlanguage(ctx: commands.Context, locale: str) -> None: - if ctx.author.id != ownerid: - await ctx.send(":thumbsdown:") - return - await ctx.defer() - set_language(locale) - await ctx.send(":thumbsup:") - -# Event: Called on every message -@bot.event -async def on_message(message: discord.Message) -> None: - global memory, markov_model - EMOJIS = ["\U0001F604", "\U0001F44D", "\U0001F525", "\U0001F4AF", "\U0001F389", "\U0001F60E"] # originally was emojis but it would probably shit itself on systems without unicode so.... - if message.author.bot: - return - - if str(message.author.id) in BLACKLISTED_USERS: - return - - if message.content.startswith((f"{PREFIX}talk", f"{PREFIX}mem", f"{PREFIX}help", f"{PREFIX}stats", f"{PREFIX}")): - logger.info(f"{(_('command_ran')).format(message=message)}") - await bot.process_commands(message) - return - - if profanity.contains_profanity(message.content): - return - - if message.content: - if not USERTRAIN_ENABLED: - return - formatted_message: str = append_mentions_to_18digit_integer(message.content) - cleaned_message: str = preprocess_message(formatted_message) + await message.channel.send("I need to learn more from messages before I can talk.") + if message.content and message.author.id != bot.user.id : + formatted_message = append_mentions_to_18digit_integer(message.content) + cleaned_message = preprocess_message(formatted_message) if cleaned_message: memory.append(cleaned_message) - message_metadata = { - "user_id": str(message.author.id), - "user_name": str(message.author), - "guild_id": str(message.guild.id) if message.guild else "DM", - "guild_name": str(message.guild.name) if message.guild else "DM", - "channel_id": str(message.channel.id), - "channel_name": str(message.channel), - "message": message.content, - "timestamp": time.time() - } - try: - if isinstance(memory, list): - memory.append({"_meta": message_metadata}) - else: - logger.warning("Memory is not a list; can't append metadata") - except Exception as e: - logger.warning(f"Failed to append metadata to memory: {e}") - save_memory(memory) + markov_model = train_markov_model(memory) + # Still process commands even from humans + if message.content and not message.author.bot: + await bot.process_commands(message) - sentiment_score = is_positive(message.content) # doesnt work but im scared to change the logic now please ignore - if sentiment_score > 0.8: - if REACT != "True": - return - emoji = random.choice(EMOJIS) - try: - await message.add_reaction(emoji) - except Exception as e: - logger.info(f"Failed to react with emoji: {e}") - await bot.process_commands(message) - -# Event: Called on every interaction (slash command, etc.) -@bot.event -async def on_interaction(interaction: discord.Interaction) -> None: - logger.info(f"{(_('command_ran_s')).format(interaction=interaction)}{interaction.data['name']}") - -# Global check: Block blacklisted users from running commands -@bot.check -async def block_blacklisted(ctx: commands.Context) -> bool: - if str(ctx.author.id) in BLACKLISTED_USERS: - try: - if isinstance(ctx, discord.Interaction): - if not ctx.response.is_done(): - await ctx.response.send_message(_('blacklisted'), ephemeral=True) - else: - await ctx.followup.send(_('blacklisted'), ephemeral=True) - else: - await ctx.send(_('blacklisted_user'), ephemeral=True) - except: - pass - return False - return True - -# Command: Show bot latency -@bot.hybrid_command(description=f"{(_('command_desc_ping'))}") -async def ping(ctx: commands.Context) -> None: +@bot.command() +async def ping(ctx): await ctx.defer() - latency: int = round(bot.latency * 1000) + #stolen from my expect bot very proud + latency = round(bot.latency * 1000) - LOLembed: discord.Embed = discord.Embed( + LOLembed = discord.Embed( title="Pong!!", description=( - f"{PING_LINE}\n" - f"`{(_('command_ping_embed_desc'))}: {latency}ms`\n" + f"The Beretta fires fast and won't make you feel any better!\n" + f"`Bot Latency: {latency}ms`\n" ), - color=Colour(0x000000) + color=discord.Color.blue() ) - LOLembed.set_footer(text=f"{(_('command_ping_footer'))} {ctx.author.name}", icon_url=ctx.author.avatar.url) + LOLembed.set_footer(text=f"Requested by {ctx.author.name}", icon_url=ctx.author.avatar.url) - await ctx.send(embed=LOLembed) + await ctx.send(embed=LOLembed) # use ctx.send instead of respond because it has nothing to respond to and its not a slash command -# Command: Show about information -@bot.hybrid_command(description=f"{(_('command_about_desc'))}") -async def about(ctx: commands.Context) -> None: - print("-----------------------------------\n\n") - latest_version: str = check_for_update() - print("-----------------------------------") - embed: discord.Embed = discord.Embed(title=f"{(_('command_about_embed_title'))}", description="", color=Colour(0x000000)) - embed.add_field(name=f"{(_('command_about_embed_field1'))}", value=f"{NAME}", inline=False) - embed.add_field(name=f"{(_('command_about_embed_field2name'))}", value=f"{(_('command_about_embed_field2value')).format(local_version=local_version, latest_version=latest_version)}", inline=False) - embed.add_field(name=f"Github", value=f"https://github.com/gooberinc/goober") - - await send_message(ctx, embed=embed) +@bot.command() +async def show_memory(ctx): + memory = load_memory() + memory_text = json.dumps(memory, indent=4) + if len(memory_text) > 1024: + with open(MEMORY_FILE, "r") as f: + await ctx.send(" ", file=discord.File(f, MEMORY_FILE)) + else: + embed = discord.Embed(title="Memory Contents", description="The bot's memory.", color=discord.Color.blue()) + embed.add_field(name="Memory Data", value=f"```json\n{memory_text}\n```", inline=False) + await ctx.send(embed=embed) -# Command: Show bot statistics (admin only) -@bot.hybrid_command(description="stats") -async def stats(ctx: commands.Context) -> None: - if ctx.author.id != ownerid: - return - print("-----------------------------------\n\n") - latest_version: str = check_for_update() - print("-----------------------------------") - memory_file: str = 'memory.json' - file_size: int = os.path.getsize(memory_file) - - with open(memory_file, 'r') as file: - line_count: int = sum(1 for _ in file) - - embed: discord.Embed = discord.Embed(title=f"{(_('command_stats_embed_title'))}", description=f"{(_('command_stats_embed_desc'))}", color=Colour(0x000000)) - embed.add_field(name=f"{(_('command_stats_embed_field1name'))}", value=f"{(_('command_stats_embed_field1value')).format(file_size=file_size, line_count=line_count)}", inline=False) - embed.add_field(name=f"{(_('command_stats_embed_field2name'))}", value=f"{(_('command_stats_embed_field2value')).format(local_version=local_version, latest_version=latest_version)}", inline=False) - embed.add_field(name=f"{(_('command_stats_embed_field3name'))}", value=f"{(_('command_stats_embed_field3value')).format(NAME=NAME, PREFIX=PREFIX, ownerid=ownerid, PING_LINE=PING_LINE, showmemenabled=showmemenabled, USERTRAIN_ENABLED=USERTRAIN_ENABLED, song=song, splashtext=splashtext)}", inline=False) - - await send_message(ctx, embed=embed) - -# Command: Upload memory.json to litterbox.catbox.moe and return the link -@bot.hybrid_command() -async def mem(ctx: commands.Context) -> None: - if showmemenabled != "true": - return - command: str = """curl -F "reqtype=fileupload" -F "time=1h" -F "fileToUpload=@memory.json" https://litterbox.catbox.moe/resources/internals/api.php""" - memorylitter: subprocess.CompletedProcess = subprocess.run(command, shell=True, capture_output=True, text=True) - logger.debug(memorylitter) - await send_message(ctx, memorylitter.stdout.strip()) - -# Helper: Improve sentence coherence (simple capitalization fix) -def improve_sentence_coherence(sentence: str) -> str: - # Capitalizes "i" to "I" in the sentence +def improve_sentence_coherence(sentence): sentence = sentence.replace(" i ", " I ") return sentence -# Start the bot -bot.run(TOKEN) \ No newline at end of file +@tasks.loop(minutes=60) +async def post_message(): + channel_id = 1296141985253691433 + channel = bot.get_channel(channel_id) + if channel and markov_model: + response = None + for _ in range(10): + response = markov_model.make_sentence(tries=100) + if response and response not in generated_sentences: + generated_sentences.add(response) + break + + if response: + await channel.send(response) + +# run the bot +TOKEN = os.getenv("DISCORDBOTTOKEN", "0") +bot.run(TOKEN) + diff --git a/example.env b/example.env deleted file mode 100644 index fe40023..0000000 --- a/example.env +++ /dev/null @@ -1,28 +0,0 @@ -DISCORDBOTTOKEN= -BOTPREFIX="g." -PINGLINE="The Beretta fires fast and won't make you feel any better!" -BLACKLISTEDUSERS= -OWNERID= -USERTRAINENABLED="true" -SHOWMEMENABLED="true" -LOCALE=fi -NAME=goober -AUTOUPDATE="True" -SONG="Basket Case - Green Day" -CHECKSDISABLED="Frue" -REACT="True" -POSITIVEGIFS="https://media.discordapp.net/attachments/821047460151427135/1181371808566493184/jjpQGeno.gif, https://tenor.com/view/chill-guy-my-new-character-gif-2777893510283028272,https://tenor.com/view/goodnight-goodnight-friends-weezer-weezer-goodnight-gif-7322052181075806988" -SPLASHTEXT=" - - SS\ - SS | - SSSSSS\ SSSSSS\ SSSSSS\ SSSSSSS\ SSSSSS\ SSSSSS\ -SS __SS\ SS __SS\ SS __SS\ SS __SS\ SS __SS\ SS __SS\ -SS / SS |SS / SS |SS / SS |SS | SS |SSSSSSSS |SS | \__| -SS | SS |SS | SS |SS | SS |SS | SS |SS ____|SS | -\SSSSSSS |\SSSSSS |\SSSSSS |SSSSSSS |\SSSSSSS\ SS | - \____SS | \______/ \______/ \_______/ \_______|\__| -SS\ SS | -\SSSSSS | - \______/ -" \ No newline at end of file diff --git a/modules/README.MD b/modules/README.MD deleted file mode 100644 index 43ce53b..0000000 --- a/modules/README.MD +++ /dev/null @@ -1,8 +0,0 @@ -# Modules Directory - -This folder contains core module files for the project. - -**Important:** -Do **not** modify the files in this directory if you plan to update the project in the future. Any changes made here may be overwritten during updates, or may cause Git to detect modifications and refuse to update properly. - -If you need to make changes, consider contributing upstream or using extension mechanisms provided by the project. \ No newline at end of file diff --git a/modules/__init__.py b/modules/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/modules/globalvars.py b/modules/globalvars.py deleted file mode 100644 index 2281388..0000000 --- a/modules/globalvars.py +++ /dev/null @@ -1,59 +0,0 @@ -import os -import platform -from dotenv import load_dotenv -import pathlib -import subprocess -def get_git_branch(): - try: - branch = subprocess.check_output( - ["git", "rev-parse", "--abbrev-ref", "HEAD"], - stderr=subprocess.DEVNULL - ).decode('utf-8').strip() - return branch - except subprocess.CalledProcessError: - return None - -env_path = pathlib.Path(__file__).parent.parent / '.env' -load_dotenv(dotenv_path=env_path) - -ANSI = "\033[" -RED = f"{ANSI}31m" -GREEN = f"{ANSI}32m" -YELLOW = f"{ANSI}33m" -PURPLE = f"{ANSI}35m" -DEBUG = f"{ANSI}1;30m" -RESET = f"{ANSI}0m" -VERSION_URL = "https://raw.githubusercontent.com/gooberinc/version/main" -UPDATE_URL = VERSION_URL+"/latest_version.json" -print(UPDATE_URL) -LOCAL_VERSION_FILE = "current_version.txt" -TOKEN = os.getenv("DISCORDBOTTOKEN", "0") -PREFIX = os.getenv("BOTPREFIX", "g.") -PING_LINE = os.getenv("PINGLINE") -CHECKS_DISABLED = os.getenv("CHECKSDISABLED") -LOCALE = os.getenv("LOCALE", "en") -gooberTOKEN = os.getenv("GOOBERTOKEN") -splashtext = os.getenv("SPLASHTEXT") -ownerid = int(os.getenv("OWNERID", "0")) -showmemenabled = os.getenv("SHOWMEMENABLED") -BLACKLISTED_USERS = os.getenv("BLACKLISTEDUSERS", "").split(",") -USERTRAIN_ENABLED = os.getenv("USERTRAINENABLED", "true").lower() == "true" -NAME = os.getenv("NAME") -MEMORY_FILE = "memory.json" -MEMORY_LOADED_FILE = "MEMORY_LOADED" # is this still even used?? okay just checked its used in the markov module -ALIVEPING = os.getenv("ALIVEPING") -AUTOUPDATE = os.getenv("AUTOUPDATE") -# IGNOREWARNING = False # is this either??? i don't think so? -song = os.getenv("song") -arch = platform.machine() -slash_commands_enabled = True # 100% broken, its a newer enough version so its probably enabled by default.... fix this at somepoint or hard code it in goober central code -launched = False -latest_version = "0.0.0" -local_version = "2.3.3" -os.environ['gooberlocal_version'] = local_version -REACT = os.getenv("REACT") -if get_git_branch() == "dev": - beta = True - # this makes goober think its a beta version, so it will not update to the latest stable version or run any version checks -else: - beta = False \ No newline at end of file diff --git a/modules/image.py b/modules/image.py deleted file mode 100644 index 58180d5..0000000 --- a/modules/image.py +++ /dev/null @@ -1,174 +0,0 @@ -import os -import re -import random -import shutil -import tempfile -from typing import Optional, List -from PIL import Image, ImageDraw, ImageFont, ImageOps -from modules.markovmemory import load_markov_model -from modules.sentenceprocessing import improve_sentence_coherence, rephrase_for_coherence - -generated_sentences = set() - -def load_font(size): - return ImageFont.truetype("assets/fonts/Impact.ttf", size=size) - -def load_tnr(size): - return ImageFont.truetype("assets/fonts/TNR.ttf", size=size) - -def draw_text_with_outline(draw, text, x, y, font): - outline_offsets = [(-2, -2), (-2, 2), (2, -2), (2, 2), (0, -2), (0, 2), (-2, 0), (2, 0)] - for ox, oy in outline_offsets: - draw.text((x + ox, y + oy), text, font=font, fill="black") - draw.text((x, y), text, font=font, fill="white") - -def fits_in_width(text, font, max_width, draw): - bbox = draw.textbbox((0, 0), text, font=font) - text_width = bbox[2] - bbox[0] - return text_width <= max_width - -def split_text_to_fit(text, font, max_width, draw): - words = text.split() - for i in range(len(words), 0, -1): - top_text = " ".join(words[:i]) - bottom_text = " ".join(words[i:]) - if fits_in_width(top_text, font, max_width, draw) and fits_in_width(bottom_text, font, max_width, draw): - return top_text, bottom_text - midpoint = len(words) // 2 - return " ".join(words[:midpoint]), " ".join(words[midpoint:]) - -async def gen_meme(input_image_path, sentence_size=5, max_attempts=10): - markov_model = load_markov_model() - if not markov_model or not os.path.isfile(input_image_path): - return None - - attempt = 0 - while attempt < max_attempts: - with Image.open(input_image_path).convert("RGBA") as img: - draw = ImageDraw.Draw(img) - width, height = img.size - - font_size = int(height / 10) - font = load_font(font_size) - - response = None - for _ in range(20): - if sentence_size == 1: - candidate = markov_model.make_short_sentence(max_chars=100, tries=100) - if candidate: - candidate = candidate.split()[0] - else: - candidate = markov_model.make_sentence(tries=100, max_words=sentence_size) - - if candidate and candidate not in generated_sentences: - if sentence_size > 1: - candidate = improve_sentence_coherence(candidate) - generated_sentences.add(candidate) - response = candidate - break - - if not response: - response = "NO TEXT GENERATED" - - cleaned_response = re.sub(r'[^\w\s]', '', response).lower() - coherent_response = rephrase_for_coherence(cleaned_response).upper() - - bbox = draw.textbbox((0, 0), coherent_response, font=font) - text_width = bbox[2] - bbox[0] - text_height_px = bbox[3] - bbox[1] - max_text_height = height // 4 - - if text_width <= width and text_height_px <= max_text_height: - draw_text_with_outline(draw, coherent_response, (width - text_width) / 2, 0, font) - img.save(input_image_path) - return input_image_path - else: - top_text, bottom_text = split_text_to_fit(coherent_response, font, width, draw) - - top_bbox = draw.textbbox((0, 0), top_text, font=font) - bottom_bbox = draw.textbbox((0, 0), bottom_text, font=font) - - top_height = top_bbox[3] - top_bbox[1] - bottom_height = bottom_bbox[3] - bottom_bbox[1] - - if top_height <= max_text_height and bottom_height <= max_text_height: - draw_text_with_outline(draw, top_text, (width - (top_bbox[2] - top_bbox[0])) / 2, 0, font) - y_bottom = height - bottom_height - int(height * 0.04) - draw_text_with_outline(draw, bottom_text, (width - (bottom_bbox[2] - bottom_bbox[0])) / 2, y_bottom, font) - img.save(input_image_path) - return input_image_path - - attempt += 1 - - with Image.open(input_image_path).convert("RGBA") as img: - draw = ImageDraw.Draw(img) - width, height = img.size - font_size = int(height / 10) - font = load_font(font_size) - - truncated = coherent_response[:100] - bbox = draw.textbbox((0, 0), truncated, font=font) - text_width = bbox[2] - bbox[0] - draw_text_with_outline(draw, truncated, (width - text_width) / 2, 0, font) - img.save(input_image_path) - return input_image_path - -async def gen_demotivator(input_image_path, max_attempts=5): - markov_model = load_markov_model() - if not markov_model or not os.path.isfile(input_image_path): - return None - - attempt = 0 - while attempt < max_attempts: - with Image.open(input_image_path).convert("RGB") as img: - size = max(img.width, img.height) - frame_thick = int(size * 0.0054) - inner_size = size - 2 * frame_thick - resized_img = img.resize((inner_size, inner_size), Image.LANCZOS) - framed = Image.new("RGB", (size, size), "white") - framed.paste(resized_img, (frame_thick, frame_thick)) - landscape_w = int(size * 1.5) - caption_h = int(size * 0.3) - canvas_h = framed.height + caption_h - canvas = Image.new("RGB", (landscape_w, canvas_h), "black") - # the above logic didnt even work, fml - fx = (landscape_w - framed.width) // 2 - canvas.paste(framed, (fx, 0)) - - draw = ImageDraw.Draw(canvas) - - title = subtitle = None - for _ in range(20): - t = markov_model.make_sentence(tries=100, max_words=4) - s = markov_model.make_sentence(tries=100, max_words=5) - if t and s and t != s: - title = t.upper() - subtitle = s.capitalize() - break - if not title: title = "DEMOTIVATOR" - if not subtitle: subtitle = "no text generated" - - title_sz = int(caption_h * 0.4) - sub_sz = int(caption_h * 0.25) - title_font = load_tnr(title_sz) - sub_font = load_tnr(sub_sz) - - bbox = draw.textbbox((0, 0), title, font=title_font) - txw, txh = bbox[2] - bbox[0], bbox[3] - bbox[1] - tx = (landscape_w - txw) // 2 - ty = framed.height + int(caption_h * 0.1) - draw_text_with_outline(draw, title, tx, ty, title_font) - - bbox = draw.textbbox((0, 0), subtitle, font=sub_font) - sxw, sxh = bbox[2] - bbox[0], bbox[3] - bbox[1] - sx = (landscape_w - sxw) // 2 - sy = ty + txh + int(caption_h * 0.05) - for ox, oy in [(-1, -1), (1, -1), (-1, 1), (1, 1)]: - draw.text((sx + ox, sy + oy), subtitle, font=sub_font, fill="black") - draw.text((sx, sy), subtitle, font=sub_font, fill="#AAAAAA") - - canvas.save(input_image_path) - return input_image_path - - attempt += 1 - return None diff --git a/modules/logger.py b/modules/logger.py deleted file mode 100644 index 76f5f10..0000000 --- a/modules/logger.py +++ /dev/null @@ -1,25 +0,0 @@ -import logging -from modules.globalvars import * - -class GooberFormatter(logging.Formatter): - def __init__(self, colors: bool = True): # Disable colors for TXT output - self.colors = colors - - self._format = f"[ %(levelname)-8s ]: %(message)s {DEBUG} [%(asctime)s.%(msecs)03d] (%(filename)s:%(funcName)s) {RESET}" - - self.FORMATS = { - logging.DEBUG: DEBUG + self._format + RESET, - logging.INFO: self._format.replace("%(levelname)-8s", f"{GREEN}%(levelname)-8s{RESET}"), - logging.WARNING: YELLOW + self._format + RESET, - logging.ERROR: RED + self._format + RESET, - logging.CRITICAL: PURPLE + self._format + RESET - } - - def format(self, record: logging.LogRecord): - if self.colors: - log_fmt = self.FORMATS.get(record.levelno) # Add colors - else: - log_fmt = self._format # Just use the default format - - formatter = logging.Formatter(log_fmt, datefmt="%m/%d/%y %H:%M:%S") - return formatter.format(record) diff --git a/modules/markovmemory.py b/modules/markovmemory.py deleted file mode 100644 index 3235035..0000000 --- a/modules/markovmemory.py +++ /dev/null @@ -1,64 +0,0 @@ -import os -import json -import markovify -import pickle -from modules.globalvars import * -from modules.volta.main import _ -import logging -logger = logging.getLogger("goober") -# Get file size and line count for a given file path -def get_file_info(file_path): - try: - file_size = os.path.getsize(file_path) - with open(file_path, "r") as f: - lines = f.readlines() - return {"file_size_bytes": file_size, "line_count": len(lines)} - except Exception as e: - return {"error": str(e)} - -# Load memory data from file, or use default dataset if not loaded yet -def load_memory(): - data = [] - - # Try to load data from MEMORY_FILE - try: - with open(MEMORY_FILE, "r") as f: - data = json.load(f) - except FileNotFoundError: - pass - - return data - -# Save memory data to MEMORY_FILE -def save_memory(memory): - with open(MEMORY_FILE, "w") as f: - json.dump(memory, f, indent=4) - -def train_markov_model(memory, additional_data=None): - if not memory: - return None - filtered_memory = [line for line in memory if isinstance(line, str)] - if additional_data: - filtered_memory.extend(line for line in additional_data if isinstance(line, str)) - if not filtered_memory: - return None - text = "\n".join(filtered_memory) - model = markovify.NewlineText(text, state_size=2) - return model - -# Save the Markov model to a pickle file -def save_markov_model(model, filename='markov_model.pkl'): - with open(filename, 'wb') as f: - pickle.dump(model, f) - logger.info(f"Markov model saved to {filename}.") - -# Load the Markov model from a pickle file -def load_markov_model(filename='markov_model.pkl'): - try: - with open(filename, 'rb') as f: - model = pickle.load(f) - logger.info(f"{_('model_loaded')} {filename}.{RESET}") - return model - except FileNotFoundError: - logger.error(f"{filename} {_('not_found')}{RESET}") - return None \ No newline at end of file diff --git a/modules/prestartchecks.py b/modules/prestartchecks.py deleted file mode 100644 index bb952f4..0000000 --- a/modules/prestartchecks.py +++ /dev/null @@ -1,255 +0,0 @@ -from modules.globalvars import * -from modules.volta.main import _, check_missing_translations -import time -import os -import sys -import subprocess -import sysconfig -import ast -import json -import re -from spacy.util import is_package -import importlib.metadata -import logging - -logger = logging.getLogger("goober") - -# import shutil -psutilavaliable = True -try: - import requests - import psutil -except ImportError: - psutilavaliable = False - logger.error(_('missing_requests_psutil')) - -def check_for_model(): - if is_package("en_core_web_sm"): - logger.info("Model is installed.") - else: - logger.info("Model is not installed.") - - -def iscloned(): - if os.path.exists(".git"): - return True - else: - logger.error(f"{_('not_cloned')}") - sys.exit(1) - -def get_stdlib_modules(): - stdlib_path = pathlib.Path(sysconfig.get_paths()['stdlib']) - modules = set() - if hasattr(sys, 'builtin_module_names'): - modules.update(sys.builtin_module_names) - for file in stdlib_path.glob('*.py'): - if file.stem != '__init__': - modules.add(file.stem) - for folder in stdlib_path.iterdir(): - if folder.is_dir() and (folder / '__init__.py').exists(): - modules.add(folder.name) - for file in stdlib_path.glob('*.*'): - if file.suffix in ('.so', '.pyd'): - modules.add(file.stem) - - return modules - -def check_requirements(): - STD_LIB_MODULES = get_stdlib_modules() - PACKAGE_ALIASES = { - "discord": "discord.py", - "better_profanity": "better-profanity", - "dotenv": "python-dotenv", - "pil": "pillow" - } - - parent_dir = os.path.dirname(os.path.abspath(__file__)) - requirements_path = os.path.abspath(os.path.join(parent_dir, '..', 'requirements.txt')) - - if not os.path.exists(requirements_path): - logger.error(f"{(_('requirements_not_found')).format(path=requirements_path)}") - return - - with open(requirements_path, 'r') as f: - lines = f.readlines() - requirements = set() - for line in lines: - line = line.strip() - if line and not line.startswith('#'): - base_pkg = line.split('==')[0].lower() - aliased_pkg = PACKAGE_ALIASES.get(base_pkg, base_pkg) - requirements.add(aliased_pkg) - - installed_packages = {dist.metadata['Name'].lower() for dist in importlib.metadata.distributions()} - missing = [] - - for req in sorted(requirements): - if req in STD_LIB_MODULES or req == 'modules': - print((_('std_lib_local_skipped')).format(package=req)) - continue - - check_name = req.lower() - - if check_name in installed_packages: - logger.info(f"{_('ok_installed').format(package=check_name)} {check_name}") - else: - logger.error(f"{(_('missing_package')).format(package=check_name)} {check_name} {(_('missing_package2'))}") - missing.append(check_name) - - if missing: - logger.error(_('missing_packages_detected')) - for pkg in missing: - print(f" - {pkg}") - sys.exit(1) - else: - logger.info(_('all_requirements_satisfied')) - -def check_latency(): - host = "1.1.1.1" - system = platform.system() - - if system == "Windows": - cmd = ["ping", "-n", "1", "-w", "1000", host] - latency_pattern = r"Average = (\d+)ms" - - elif system == "Darwin": - cmd = ["ping", "-c", "1", host] - latency_pattern = r"time=([\d\.]+) ms" - - else: - cmd = ["ping", "-c", "1", "-W", "1", host] - latency_pattern = r"time=([\d\.]+) ms" - - try: - result = subprocess.run( - cmd, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - text=True - ) - - if result.returncode == 0: - match = re.search(latency_pattern, result.stdout) - if match: - latency_ms = float(match.group(1)) - logger.info((_('ping_to')).format(host=host, latency=latency_ms)) - if latency_ms > 300: - logger.warning(f"{(_('high_latency'))}") - else: - logger.warning((_('could_not_parse_latency'))) - else: - print(result.stderr) - logger.error(f"{(_('ping_failed')).format(host=host)}{RESET}") - except Exception as e: - logger.error((_('error_running_ping')).format(error=e)) - -def check_memory(): - if psutilavaliable == False: - return - try: - memory_info = psutil.virtual_memory() # type: ignore - total_memory = memory_info.total / (1024 ** 3) - used_memory = memory_info.used / (1024 ** 3) - free_memory = memory_info.available / (1024 ** 3) - - logger.info((_('memory_usage')).format(used=used_memory, total=total_memory, percent=(used_memory / total_memory) * 100)) - if used_memory > total_memory * 0.9: - print(f"{YELLOW}{(_('memory_above_90')).format(percent=(used_memory / total_memory) * 100)}{RESET}") - logger.info((_('total_memory')).format(total=total_memory)) - logger.info((_('used_memory')).format(used=used_memory)) - if free_memory < 1: - logger.warning(f"{(_('low_free_memory')).format(free=free_memory)}") - sys.exit(1) - except ImportError: - logger.error(_('psutil_not_installed')) # todo: translate this into italian and put it in the translations "psutil is not installed. Memory check skipped." - -def check_cpu(): - if psutilavaliable == False: - return - logger.info((_('measuring_cpu'))) - cpu_per_core = psutil.cpu_percent(interval=1, percpu=True) # type: ignore - total_cpu = sum(cpu_per_core) / len(cpu_per_core) - logger.info((_('total_cpu_usage')).format(usage=total_cpu)) - if total_cpu > 85: - logger.warning(f"{(_('high_avg_cpu')).format(usage=total_cpu)}") - if total_cpu > 95: - logger.error(_('really_high_cpu')) - sys.exit(1) - -def check_memoryjson(): - try: - logger.info((_('memory_file')).format(size=os.path.getsize(MEMORY_FILE) / (1024 ** 2))) - if os.path.getsize(MEMORY_FILE) > 1_073_741_824: - logger.warning(f"{(_('memory_file_large'))}") - try: - with open(MEMORY_FILE, 'r', encoding='utf-8') as f: - json.load(f) - except json.JSONDecodeError as e: - logger.error(f"{(_('memory_file_corrupted')).format(error=e)}") - logger.warning(f"{(_('consider_backup_memory'))}") - except UnicodeDecodeError as e: - logger.error(f"{(_('memory_file_encoding')).format(error=e)}") - logger.warning(f"{(_('consider_backup_memory'))}") - except Exception as e: - logger.error(f"{(_('error_reading_memory')).format(error=e)}") - except FileNotFoundError: - logger(f"{(_('memory_file_not_found'))}") - -def presskey2skip(timeout): - if os.name == 'nt': - import msvcrt - start_time = time.time() - while True: - if msvcrt.kbhit(): - msvcrt.getch() - break - if time.time() - start_time > timeout: - break - time.sleep(0.1) - else: - import select - import sys - import termios - import tty - - fd = sys.stdin.fileno() - old_settings = termios.tcgetattr(fd) - try: - tty.setcbreak(fd) - start_time = time.time() - while True: - if select.select([sys.stdin], [], [], 0)[0]: - sys.stdin.read(1) - break - if time.time() - start_time > timeout: - break - time.sleep(0.1) - finally: - termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) -beta = beta -def start_checks(): - if CHECKS_DISABLED == "True": - logger.warning(f"{(_('checks_disabled'))}") - return - logger.info(_('running_prestart_checks')) - check_for_model() - iscloned() - check_missing_translations() - check_requirements() - check_latency() - check_memory() - check_memoryjson() - check_cpu() - if os.path.exists(".env"): - pass - else: - logger.warning(f"{(_('env_file_not_found'))}") - sys.exit(1) - if beta == True: - logger.warning(f"this build isnt finished yet, some things might not work as expected") - else: - pass - logger.info(_('continuing_in_seconds').format(seconds=5)) - presskey2skip(timeout=5) - os.system('cls' if os.name == 'nt' else 'clear') - print(splashtext) \ No newline at end of file diff --git a/modules/sentenceprocessing.py b/modules/sentenceprocessing.py deleted file mode 100644 index 993ba90..0000000 --- a/modules/sentenceprocessing.py +++ /dev/null @@ -1,80 +0,0 @@ -import re -from modules.globalvars import * -from modules.volta.main import _ - -import spacy -from spacy.tokens import Doc -from spacytextblob.spacytextblob import SpacyTextBlob - -import logging -logger = logging.getLogger("goober") - - -def check_resources(): - try: - nlp = spacy.load("en_core_web_sm") - except OSError: - logging.critical((_('spacy_model_not_found'))) - spacy.cli.download("en_core_web_sm") - nlp = spacy.load("en_core_web_sm") - if "spacytextblob" not in nlp.pipe_names: - nlp.add_pipe("spacytextblob") - logger.info((_('spacy_initialized'))) - -check_resources() - -nlp = spacy.load("en_core_web_sm") -nlp.add_pipe("spacytextblob") -Doc.set_extension("polarity", getter=lambda doc: doc._.blob.polarity) - -def is_positive(sentence): - doc = nlp(sentence) - sentiment_score = doc._.polarity # from spacytextblob - - debug_message = f"{(_('sentence_positivity'))} {sentiment_score}{RESET}" - logger.debug(debug_message) - - return sentiment_score > 0.6 # had to raise the bar because it kept saying "death to jews" was fine and it kept reacting to them - -async def send_message(ctx, message=None, embed=None, file=None, edit=False, message_reference=None): - if edit and message_reference: - try: - await message_reference.edit(content=message, embed=embed) - except Exception as e: - await ctx.send(f"{RED}{(_('edit_fail'))} {e}{RESET}") - else: - if hasattr(ctx, "respond"): - sent_message = None - if embed: - sent_message = await ctx.respond(embed=embed, ephemeral=False) - elif message: - sent_message = await ctx.respond(message, ephemeral=False) - if file: - sent_message = await ctx.respond(file=file, ephemeral=False) - else: - sent_message = None - if embed: - sent_message = await ctx.send(embed=embed) - elif message: - sent_message = await ctx.send(message) - if file: - sent_message = await ctx.send(file=file) - return sent_message - -def append_mentions_to_18digit_integer(message): - pattern = r'\b\d{18}\b' - return re.sub(pattern, lambda match: "", message) - -def preprocess_message(message): - message = append_mentions_to_18digit_integer(message) - doc = nlp(message) - tokens = [token.text for token in doc if token.is_alpha or token.is_digit] - return " ".join(tokens) - -def improve_sentence_coherence(sentence): - return re.sub(r'\bi\b', 'I', sentence) - -def rephrase_for_coherence(sentence): - words = sentence.split() - coherent_sentence = " ".join(words) - return coherent_sentence diff --git a/modules/unhandledexception.py b/modules/unhandledexception.py deleted file mode 100644 index 9521e72..0000000 --- a/modules/unhandledexception.py +++ /dev/null @@ -1,25 +0,0 @@ -import sys -import traceback -import os -from modules.globalvars import RED, RESET, splashtext -from modules.volta.main import _ - -def handle_exception(exc_type, exc_value, exc_traceback, *, context=None): - os.system('cls' if os.name == 'nt' else 'clear') - - if issubclass(exc_type, KeyboardInterrupt): - sys.__excepthook__(exc_type, exc_value, exc_traceback) - return - - print(splashtext) - print(f"{RED}=====BEGINNING OF TRACEBACK====={RESET}") - traceback.print_exception(exc_type, exc_value, exc_traceback) - print(f"{RED}========END OF TRACEBACK========{RESET}") - print(f"{RED}{_('unhandled_exception')}{RESET}") - - - if context: - print(f"{RED}Context: {context}{RESET}") - - - diff --git a/modules/version.py b/modules/version.py deleted file mode 100644 index a5c1132..0000000 --- a/modules/version.py +++ /dev/null @@ -1,105 +0,0 @@ -from modules.volta.main import _ -from modules.globalvars import * -import requests -import subprocess -import sys -import logging -import json -import time -import random -logger = logging.getLogger("goober") -launched = False - -# Run a shell command and return its output -def run_cmd(cmd): - result = subprocess.run(cmd, shell=True, capture_output=True, text=True) - return result.stdout.strip() - -# Check if the remote branch is ahead of the local branch -def is_remote_ahead(branch='main', remote='origin'): - run_cmd(f'git fetch {remote}') - count = run_cmd(f'git rev-list --count HEAD..{remote}/{branch}') - return int(count) > 0 - -# Automatically update the local repository if the remote is ahead -def auto_update(branch='main', remote='origin'): - if launched == True: - print(_("already_started")) - return - if AUTOUPDATE != "True": - pass # Auto-update is disabled - if is_remote_ahead(branch, remote): - print(_( "remote_ahead").format(remote=remote, branch=branch)) - pull_result = run_cmd(f'git pull {remote} {branch}') - logger.info(pull_result) - logger.info(_( "please_restart")) - sys.exit(0) - else: - logger.info(_( "local_ahead").format(remote=remote, branch=branch)) - -def get_latest_version_info(): - try: - unique_suffix = f"{int(time.time())}_{random.randint(0, 9999)}" - url = f"{UPDATE_URL}?_={unique_suffix}" - - curl_cmd = [ - "curl", - "-s", - "-H", "Cache-Control: no-cache", - "-H", "Pragma: no-cache", - url - ] - - result = subprocess.run(curl_cmd, capture_output=True, text=True, timeout=5) - content = result.stdout - - if result.returncode != 0: - logger.error(f"curl failed with return code {result.returncode}") - return None - - try: - data = json.loads(content) - return data - except json.JSONDecodeError: - logger.error("JSON decode failed") - logger.error(content[:500]) - return None - - except Exception as e: - logger.error(f"Exception in get_latest_version_info: {e}") - return None - -# Check if an update is available and perform update if needed -def check_for_update(): - global latest_version, local_version, launched - - latest_version_info = get_latest_version_info() - if not latest_version_info: - logger.error(f"{_('fetch_update_fail')}") - return None, None - - latest_version = latest_version_info.get("version") - os.environ['gooberlatest_version'] = latest_version - download_url = latest_version_info.get("download_url") - - if not latest_version or not download_url: - logger.error(f"{RED}{_('invalid_server')}{RESET}") - return None, None - # Check if local_version is valid - if local_version == "0.0.0" or None: - logger.error(f"{RED}{_('cant_find_local_version')}{RESET}") - return - # Compare local and latest versions - if local_version < latest_version: - logger.info(f"{YELLOW}{_('new_version').format(latest_version=latest_version, local_version=local_version)}{RESET}") - logger.info(f"{YELLOW}{_('changelog').format(VERSION_URL=VERSION_URL)}{RESET}") - auto_update() - elif beta == True: - logger.warning(f"You are running an \"unstable\" version of Goober, do not expect it to work properly.\nVersion {local_version}\nServer: {latest_version}{RESET}") - elif local_version > latest_version: - logger.warning(f"{_('modification_warning')}") - elif local_version == latest_version: - logger.info(f"{_('latest_version')} {local_version}") - logger.info(f"{_('latest_version2').format(VERSION_URL=VERSION_URL)}\n\n") - launched = True - return latest_version \ No newline at end of file diff --git a/modules/volta/main.py b/modules/volta/main.py deleted file mode 100644 index fb6a080..0000000 --- a/modules/volta/main.py +++ /dev/null @@ -1,207 +0,0 @@ -# If you're seeing this after cloning the Goober repo, note that this is a standalone module for translations. -# While it's used by Goober Core, it lives in its own repository and should not be modified here. -# For updates or contributions, visit: https://github.com/gooberinc/volta -# Also, Note to self: Add more comments it needs more love -import os -import locale -import json -import pathlib -import threading -import time -from dotenv import load_dotenv - -ANSI = "\033[" -RED = f"{ANSI}31m" -GREEN = f"{ANSI}32m" -YELLOW = f"{ANSI}33m" -DEBUG = f"{ANSI}1;30m" -RESET = f"{ANSI}0m" - -LOCALE = os.getenv("LOCALE") -module_dir = pathlib.Path(__file__).parent.parent -working_dir = pathlib.Path.cwd() -EXCLUDE_DIRS = {'.git', '__pycache__'} - -locales_dirs = [] -ENGLISH_MISSING = False -FALLBACK_LOCALE = "en" -if os.getenv("fallback_locale"): - FALLBACK_LOCALE = os.getenv("fallback_locale") -def find_locales_dirs(base_path): - found = [] - for root, dirs, files in os.walk(base_path): - dirs[:] = [d for d in dirs if d not in EXCLUDE_DIRS] - - if 'locales' in dirs: - locales_path = pathlib.Path(root) / 'locales' - found.append(locales_path) - dirs.remove('locales') - return found - -def find_dotenv(start_path: pathlib.Path) -> pathlib.Path | None: - current = start_path.resolve() - while current != current.parent: - candidate = current / ".env" - if candidate.exists(): - return candidate - current = current.parent - return None - -env_path = find_dotenv(pathlib.Path(__file__).parent) -if env_path: - load_dotenv(dotenv_path=env_path) - print(f"[VOLTA] {GREEN}Loaded .env from {env_path}{RESET}") -else: - print(f"[VOLTA] {YELLOW}No .env file found from {__file__} upwards.{RESET}") - -locales_dirs.extend(find_locales_dirs(module_dir)) -if working_dir != module_dir: - locales_dirs.extend(find_locales_dirs(working_dir)) - -translations = {} -_file_mod_times = {} - -import locale -import platform -import os -import sys - -def get_system_locale(): - system = platform.system() # fallback incase locale isnt set - if system == "Windows": - lang, _ = locale.getdefaultlocale() - return lang or os.getenv("LANG") - elif system == "Darwin": - try: - import subprocess - result = subprocess.run( - ["defaults", "read", "-g", "AppleLocale"], - stdout=subprocess.PIPE, - stderr=subprocess.DEVNULL, - text=True - ) - return result.stdout.strip() or locale.getdefaultlocale()[0] - except Exception: - return locale.getdefaultlocale()[0] - elif system == "Linux": - return ( - os.getenv("LC_ALL") or - os.getenv("LANG") or - locale.getdefaultlocale()[0] - ) - return locale.getdefaultlocale()[0] - - -def load_translations(): - global translations, _file_mod_times - translations.clear() - _file_mod_times.clear() - - for locales_dir in locales_dirs: - for filename in os.listdir(locales_dir): - if filename.endswith(".json"): - lang_code = filename[:-5] - file_path = locales_dir / filename - try: - with open(file_path, "r", encoding="utf-8") as f: - data = json.load(f) - if lang_code not in translations: - translations[lang_code] = {} - translations[lang_code].update(data) - _file_mod_times[(lang_code, file_path)] = file_path.stat().st_mtime - except Exception as e: - print(f"[VOLTA] {RED}Failed loading {file_path}: {e}{RESET}") - -def reload_if_changed(): - while True: - for (lang_code, file_path), last_mtime in list(_file_mod_times.items()): - try: - current_mtime = file_path.stat().st_mtime - if current_mtime != last_mtime: - print(f"[VOLTA] {RED}Translation file changed: {file_path}, reloading...{RESET}") - load_translations() - break - except FileNotFoundError: - print(f"[VOLTA] {RED}Translation file removed: {file_path}{RESET}") - _file_mod_times.pop((lang_code, file_path), None) - if lang_code in translations: - translations.pop(lang_code, None) - -def set_language(lang: str): - global LOCALE, ENGLISH_MISSING - if not LOCALE: - LOCALE = get_system_locale() - elif lang in translations: - LOCALE = lang - else: - print(f"[VOLTA] {RED}Language '{lang}' not found, defaulting to 'en'{RESET}") - if FALLBACK_LOCALE in translations: - LOCALE = FALLBACK_LOCALE - else: - print(f"[VOLTA] {RED}The fallback translations cannot be found! No fallback available.{RESET}") - ENGLISH_MISSING = True - -def check_missing_translations(): - global LOCALE, ENGLISH_MISSING - load_translations() - if FALLBACK_LOCALE not in translations: - print(f"[VOLTA] {RED}Fallback translations ({FALLBACK_LOCALE}.json) missing from assets/locales.{RESET}") - ENGLISH_MISSING = True - return - if LOCALE == "en": - print("[VOLTA] Locale is English, skipping missing key check.") - return - - - en_keys = set(translations.get("en", {}).keys()) - locale_keys = set(translations.get(LOCALE, {}).keys()) - - missing_keys = en_keys - locale_keys - total_keys = len(en_keys) - missing_count = len(missing_keys) - - if missing_count > 0: - percent_missing = (missing_count / total_keys) * 100 - if percent_missing == 100: - print(f"[VOLTA] {YELLOW}Warning: All keys are missing in locale '{LOCALE}'! Defaulting back to {FALLBACK_LOCALE}{RESET}") - set_language(FALLBACK_LOCALE) - elif percent_missing > 0: - print(f"[VOLTA] {YELLOW}Warning: {missing_count}/{total_keys} keys missing in locale '{LOCALE}' ({percent_missing:.1f}%)!{RESET}") - for key in sorted(missing_keys): - print(f" - {key}") - time.sleep(2) - else: - print(f"[VOLTA] All translation keys present for locale: {LOCALE}") - -printedsystemfallback = False - -def get_translation(lang: str, key: str): - global printedsystemfallback - if ENGLISH_MISSING: - return f"[VOLTA] {RED}No fallback available!{RESET}" - fallback_translations = translations.get(FALLBACK_LOCALE, {}) - sys_lang = get_system_locale().split("_")[0] if get_system_locale() else None - sys_translations = translations.get(sys_lang, {}) if sys_lang else {} - lang_translations = translations.get(lang, {}) - if key in lang_translations: - return lang_translations[key] - if sys_lang and sys_lang != lang and key in sys_translations: - if not printedsystemfallback: - print(f"[VOLTA] {YELLOW}Falling back to system language {sys_lang}!{RESET}") - printedsystemfallback = True - return sys_translations[key] - if key in fallback_translations: - print(f"[VOLTA] {YELLOW}Missing key: '{key}' in '{lang}', falling back to fallback locale '{FALLBACK_LOCALE}'{RESET}") - return fallback_translations[key] - return f"[VOLTA] {YELLOW}Missing key: '{key}' in all locales!{RESET}" - -def _(key: str) -> str: - return get_translation(LOCALE, key) - -load_translations() - -watchdog_thread = threading.Thread(target=reload_if_changed, daemon=True) -watchdog_thread.start() - -if __name__ == '__main__': - print("Volta should not be run directly! Please use it as a module..") diff --git a/requirements.txt b/requirements.txt deleted file mode 100644 index c53d758..0000000 --- a/requirements.txt +++ /dev/null @@ -1,10 +0,0 @@ -discord.py -markovify -spacy -spacytextblob -requests -psutil -better_profanity -python-dotenv -dotenv -pillow \ No newline at end of file diff --git a/specialthanks.txt b/specialthanks.txt deleted file mode 100644 index c509086..0000000 --- a/specialthanks.txt +++ /dev/null @@ -1,3 +0,0 @@ -- The catbox.moe team for memory.json file uploads -- Charlie's Computers -- ctih1 diff --git a/todo.txt b/todo.txt deleted file mode 100644 index 428c6c8..0000000 --- a/todo.txt +++ /dev/null @@ -1,4 +0,0 @@ -- fix missing translations in some cases -- revamp wiki -- clean the rest -- alot