[
  {
    "path": ".gitignore",
    "content": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packaging\n.Python\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\nwheels/\nshare/python-wheels/\n*.egg-info/\n.installed.cfg\n*.egg\nMANIFEST\n\n# PyInstaller\n#  Usually these files are written by a python script from a template\n#  before PyInstaller builds the exe, so as to inject date/other infos into it.\n*.manifest\n*.spec\n\n# Installer logs\npip-log.txt\npip-delete-this-directory.txt\n\n# Unit test / coverage reports\nhtmlcov/\n.tox/\n.nox/\n.coverage\n.coverage.*\n.cache\nnosetests.xml\ncoverage.xml\n*.cover\n*.py,cover\n.hypothesis/\n.pytest_cache/\ncover/\n\n# Translations\n*.mo\n*.pot\n\n# Django stuff:\n*.log\nlocal_settings.py\ndb.sqlite3\ndb.sqlite3-journal\n\n# Flask stuff:\ninstance/\n.webassets-cache\n\n# Scrapy stuff:\n.scrapy\n\n# Sphinx documentation\ndocs/_build/\n\n# PyBuilder\n.pybuilder/\ntarget/\n\n# Jupyter Notebook\n.ipynb_checkpoints\n\n# IPython\nprofile_default/\nipython_config.py\n\n# pyenv\n#   For a library or package, you might want to ignore these files since the code is\n#   intended to run in multiple environments; otherwise, check them in:\n# .python-version\n\n# pipenv\n#   According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.\n#   However, in case of collaboration, if having platform-specific dependencies or dependencies\n#   having no cross-platform support, pipenv may install dependencies that don't work, or not\n#   install all needed dependencies.\n#Pipfile.lock\n\n# PEP 582; used by e.g. github.com/David-OConnor/pyflow\n__pypackages__/\n\n# Celery stuff\ncelerybeat-schedule\ncelerybeat.pid\n\n# SageMath parsed files\n*.sage.py\n\n# Environments\n.env\n.venv\nenv/\nvenv/\nENV/\nenv.bak/\nvenv.bak/\n\n# Spyder project settings\n.spyderproject\n.spyproject\n\n# Rope project settings\n.ropeproject\n\n# mkdocs documentation\n/site\n\n# mypy\n.mypy_cache/\n.dmypy.json\ndmypy.json\n\n# Pyre type checker\n.pyre/\n\n# pytype static type analyzer\n.pytype/\n\n# Cython debug symbols\ncython_debug/\n\n# PyCharm IDEA\n.idea/*\n\n# SQLITE database\n*.db\n\n# Log file\ndiscord.log\n\ngraphs/\nlogs/\nssl/\npickle/\n\n.pem\n.key\nconfig.json\n\n*.out\n"
  },
  {
    "path": "Dockerfile",
    "content": "# Use an official Python runtime as a parent image\nFROM python:3.9-slim-buster\n\n# Set the working directory in the container to /app\nWORKDIR /app\n\n# Add the current directory contents into the container at /app\nADD . /app\n\n# Install any needed packages specified in requirements.txt\nRUN pip install --no-cache-dir -r requirements.txt\n\n# Make port 443 available to the world outside this container\nEXPOSE 443\n\n# Run app.py when the container launches\nCMD [\"python\", \"main.py\"]\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "# PotatoBot\n> The best AIO bot on Discord.\n\ntop.gg: https://top.gg/bot/1226487228914602005 \\\nInvite: https://discord.com/oauth2/authorize?client_id=1226487228914602005\n\n\n## Run Locally\n\n1. Clone the project:\n\n```bash\n  git clone https://github.com/Cyteon/potatobot\n```\n\n2. Go to the project directory:\n\n```bash\n  cd potatobot\n```\n\n3. Install the required Python dependencies:\n\n```bash\n  pip install -r requirements.txt\n```\n\n4. Rename `.env.example` to `.env`, and populate the required values.\n5. Rename `config.example.json` to `config.json` and populate the required values.\n\n6. Run the bot:\n\n```bash\n  python main.py\n```\n\n7. Profit.\n"
  },
  {
    "path": "bot.py",
    "content": "# pylint: disable-all\n\n# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon\n\nimport json\nimport logging\nimport os\nimport platform\nimport random\nimport sys\nimport time\nimport aiohttp\n\nfrom pickledb import PickleDB\nimport pymongo\n\nimport discord\nfrom discord import Webhook\nfrom discord.ext import commands, tasks\n\nfrom dotenv import load_dotenv\nload_dotenv()\n\nfrom utils import ErrorLogger, Errors\n\nif not os.path.isfile(f\"{os.path.realpath(os.path.dirname(__file__))}/config.json\"):\n    sys.exit(\"'config.json' not found! Please add it and try again.\")\nelse:\n    with open(f\"{os.path.realpath(os.path.dirname(__file__))}/config.json\") as file:\n        config = json.load(file)\n\nintents = discord.Intents.default()\nintents.message_content = True\nintents.members = True\n\nclient = pymongo.MongoClient(os.getenv(\"MONGODB_URL\"))\ndb = client.potatobot\n\nos.makedirs(\"pickle\", exist_ok=True)\nprefixDB = PickleDB(\"pickle/prefix.db\")\nstatsDB = PickleDB(\"pickle/stats.db\")\n\ncant_react_in = []\n\nclass LoggingFormatter(logging.Formatter):\n    black = \"\\x1b[30m\"\n    red = \"\\x1b[31m\"\n    green = \"\\x1b[32m\"\n    yellow = \"\\x1b[33m\"\n    blue = \"\\x1b[34m\"\n    gray = \"\\x1b[38m\"\n    reset = \"\\x1b[0m\"\n    bold = \"\\x1b[1m\"\n\n    COLORS = {\n        logging.DEBUG: gray + bold,\n        logging.INFO: blue + bold,\n        logging.WARNING: yellow + bold,\n        logging.ERROR: red,\n        logging.CRITICAL: red + bold,\n    }\n\n    def format(self, record):\n        log_color = self.COLORS[record.levelno]\n        format = \"(black){asctime}(reset) (levelcolor){levelname:<8}(reset) \\x1b[32m{name}(reset) {message}\"\n        format = format.replace(\"(black)\", self.black + self.bold)\n        format = format.replace(\"(reset)\", self.reset)\n        format = format.replace(\"(levelcolor)\", log_color)\n        formatter = logging.Formatter(format, \"%Y-%m-%d %H:%M:%S\", style=\"{\")\n        return formatter.format(record)\n\nlogger = logging.getLogger(\"discord_bot\")\nlogger.setLevel(logging.INFO)\n\nconsole_handler = logging.StreamHandler()\nconsole_handler.setFormatter(LoggingFormatter())\nfile_handler = logging.FileHandler(filename=\"discord.log\", encoding=\"utf-8\", mode=\"w\")\nfile_handler_formatter = logging.Formatter(\n    \"[{asctime}] [{levelname:<8}] {name}: {message}\", \"%Y-%m-%d %H:%M:%S\", style=\"{\"\n)\nfile_handler.setFormatter(file_handler_formatter)\n\nlogger.addHandler(console_handler)\nlogger.addHandler(file_handler)\n\nclass DiscordBot(commands.AutoShardedBot):\n    def __init__(self) -> None:\n        super().__init__(\n            command_prefix=self.get_prefix,\n            intents=intents,\n            help_command=None,\n            owner_ids=set([int(os.getenv(\"OWNER_ID\"))]),\n        )\n        self.logger = logger\n        self.config = config\n        self.version = \"2.1.8\"\n        self.start_time = time.time()\n        self.prefixDB = prefixDB\n        self.statsDB = statsDB\n\n    async def get_prefix(self, message):\n        if message.guild:\n            guild_id = str(message.guild.id)\n            if prefixDB.get(guild_id):\n                return prefixDB.get(guild_id)\n            else:\n                return config[\"prefix\"]\n        else:\n            return config[\"prefix\"]\n\n    async def load_cogs(self) -> None:\n        for file in os.listdir(f\"{os.path.realpath(os.path.dirname(__file__))}/cogs\"):\n            if file.endswith(\".py\"):\n                extension = file[:-3]\n                try:\n                    await self.load_extension(f\"cogs.{extension}\")\n                    self.logger.info(f\"Loaded extension '{extension}'\")\n                except Exception as e:\n                    exception = f\"{type(e).__name__}: {e}\"\n                    self.logger.error(\n                        f\"Failed to load extension {extension}\\n{exception}\"\n                    )\n\n    @tasks.loop(minutes=1.0)\n    async def status_task(self) -> None:\n        statuses = [\"youtube\", \"netflix\"]\n        await self.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=random.choice(statuses)))\n\n    @status_task.before_loop\n    async def before_status_task(self) -> None:\n        await self.wait_until_ready()\n\n\n    async def setup_hook(self) -> None:\n        self.logger.info(f\"Logged in as {self.user.name}\")\n        self.logger.info(f\"discord.py API version: {discord.__version__}\")\n        self.logger.info(f\"Python version: {platform.python_version()}\")\n        self.logger.info(\n            f\"Running on: {platform.system()} {platform.release()} ({os.name})\"\n        )\n\n        self.logger.info(\"-------------------\")\n\n        self.logger.info(f\"Connection to db successful: {client.address}\")\n\n        self.logger.info(\"-------------------\")\n\n        await self.load_cogs()\n\n        self.logger.info(\"-------------------\")\n\n        self.logger.info(f\"Command count (slash+chat): {len([x for x in self.walk_commands() if isinstance(x, commands.HybridCommand)])}\")\n        self.logger.info(f\"Command count (chat only): {len([x for x in self.walk_commands() if isinstance(x, commands.Command) and not isinstance(x, commands.HybridCommand)])}\")\n        self.logger.info(f\"Total command count: {len([x for x in self.walk_commands()])}\")\n\n        self.logger.info(\n            f\"Command groups: {len([x for x in self.walk_commands() if isinstance(x, commands.HybridGroup) or isinstance(x, commands.Group)])}\"\n        )\n        self.logger.info(f\"Cog count: {len([x for x in self.cogs])}\")\n\n        self.logger.info(\n            f\"Discord slash command limit: {len([x for x in self.commands if isinstance(x, commands.HybridCommand) or isinstance(x, commands.HybridGroup)])}/100\"\n        )\n        self.logger.info(\"(Dosent include subcommands)\")\n\n        self.logger.info(\"-------------------\")\n\n        self.status_task.start()\n\n    async def on_guild_remove(self, guild: discord.Guild):\n        async with aiohttp.ClientSession() as session:\n            to_send = Webhook.from_url(config[\"join_leave_webhook\"], session=session)\n\n            embed = discord.Embed(\n                title=\"Bot left a guild!\",\n                description=f\"**Guild Name:** {guild.name}\\n**Guild ID:** {guild.id}\\n**Owner:** {guild.owner.mention if guild.owner else None} ({guild.owner})\\n **Member Count:** {guild.member_count}\",\n                color=0xE02B2B\n            )\n\n            await to_send.send(embed=embed, username=\"PotatoBot - Guild Logger\")\n\n        self.logger.info(\"Bot left guild \" + guild.name)\n\n    async def on_guild_join(self, guild: discord.Guild):\n        async with aiohttp.ClientSession() as session:\n            to_send = Webhook.from_url(config[\"join_leave_webhook\"], session=session)\n\n            embed = discord.Embed(\n                title=\"Bot joined a guild!\",\n                description=f\"**Guild Name:** {guild.name}\\n**Guild ID:** {guild.id}\\n**Owner:** {guild.owner.mention if guild.owner else None} ({guild.owner})\\n **Member Count:** {guild.member_count}\",\n                color=0x57F287\n            )\n\n            await to_send.send(embed=embed, username=\"PotatoBot - Guild Logger\")\n\n        self.logger.info(\"Bot joined guild: \" + guild.name)\n\n    async def on_error(self, event_method, *args, **kwargs):\n        await ErrorLogger.error(self, event_method, *args, **kwargs)\n\n    async def on_message(self, message: discord.Message) -> None:\n        if message.author.id in config[\"fully_ignore\"]:\n            return\n\n        if message.author == self.user or message.author.bot:\n            return\n\n        arr = message.content.split(\" \")\n\n        arr[0] = arr[0].lower()\n\n        message.content = \" \".join(arr)\n\n        ctx = await self.get_context(message)\n        if ctx.command is not None:\n            self.dispatch('command', ctx)\n            try:\n                if await self.can_run(ctx, call_once=True):\n                    await ctx.command.invoke(ctx)\n                else:\n                    raise commands.errors.CheckFailure('The global check once functions failed.')\n            except commands.errors.CommandError as exc:\n                await ctx.command.dispatch_error(ctx, exc)\n            else:\n                self.dispatch('command_completion', ctx)\n        elif ctx.invoked_with:\n            exc = commands.errors.CommandNotFound(f'Command \"{ctx.invoked_with}\" is not found')\n            self.dispatch('command_error', ctx, exc)\n        else:\n            if f\"<@{str(self.user.id)}>\" in message.content:\n                await message.reply(f\"> My prefix is `{await self.get_prefix(message)}`\")\n\n\n    async def on_command_completion(self, context: commands.Context) -> None:\n        full_command_name = context.command.qualified_name\n        split = full_command_name.split(\" \")\n        executed_command = str(split[0])\n\n        if context.guild is not None:\n            self.logger.info(\n                f\"Executed {executed_command} command in {context.guild.name} (ID: {context.guild.id}) by {context.author} (ID: {context.author.id})\"\n            )\n        else:\n            self.logger.info(\n                f\"Executed {executed_command} command by {context.author} (ID: {context.author.id}) in DMs\"\n            )\n\n        commands_ran = (statsDB.get(\"commands_ran\") if statsDB.get(\"commands_ran\") else 0) + 1\n        statsDB.set(\"commands_ran\", commands_ran)\n        statsDB.save()\n\n    async def on_command_error(self, context: commands.Context, error) -> None:\n        if isinstance(error, commands.CommandOnCooldown):\n            minutes, seconds = divmod(error.retry_after, 60)\n            hours, minutes = divmod(minutes, 60)\n            hours = hours % 24\n            embed = discord.Embed(\n                description=f\"**Please slow down** - You can use this command again in {f'{round(hours)} hours' if round(hours) > 0 else ''} {f'{round(minutes)} minutes' if round(minutes) > 0 else ''} {f'{round(seconds)} seconds' if round(seconds) > 0 else ''}.\",\n                color=0xE02B2B,\n            )\n            await context.send(embed=embed)\n        elif isinstance(error, commands.NotOwner):\n            embed = discord.Embed(\n                description=\"You are not the owner of the bot!\", color=0xE02B2B\n            )\n            await context.send(embed=embed)\n            if context.guild:\n                self.logger.warning(\n                    f\"{context.author} (ID: {context.author.id}) tried to execute an owner only command in the guild {context.guild.name} (ID: {context.guild.id}), but the user is not an owner of the bot.\"\n                )\n            else:\n                self.logger.warning(\n                    f\"{context.author} (ID: {context.author.id}) tried to execute an owner only command in the bot's DMs, but the user is not an owner of the bot.\"\n                )\n        elif isinstance(error, commands.MissingPermissions):\n            embed = discord.Embed(\n                description=\"You are missing the permission(s) `\"\n                + \", \".join(error.missing_permissions)\n                + \"` to execute this command!\",\n                color=0xE02B2B,\n            )\n            await context.send(embed=embed)\n        elif isinstance(error, commands.BotMissingPermissions):\n            embed = discord.Embed(\n                description=\"I am missing the permission(s) `\"\n                + \", \".join(error.missing_permissions)\n                + \"` to fully perform this command!\",\n                color=0xE02B2B,\n            )\n            await context.send(embed=embed)\n        elif isinstance(error, commands.MissingRequiredArgument):\n            embed = discord.Embed(\n                title=\"Error!\",\n                description=str(error).capitalize(),\n                color=0xE02B2B,\n            )\n            await context.send(embed=embed)\n        elif isinstance(error, commands.CheckFailure):\n            embed = discord.Embed(\n                title=\"Error!\",\n                description=str(error).capitalize(),\n                color=0xE02B2B,\n            )\n            await context.send(embed=embed)\n        elif isinstance(error, commands.CommandNotFound):\n            if not context.channel in cant_react_in:\n                try:\n                    await context.message.add_reaction(\"❓\")\n                except discord.errors.Forbidden:\n                    cant_react_in.append(context.channel)\n                    logger.warning(\n                        f\"Couldn't react to a message in {context.channel.name} (ID: {context.channel.id}) in {context.guild.name} (ID: {context.guild.id})\"\n                    )\n        elif isinstance(error, Errors.CommandDisabled):\n            embed = discord.Embed(\n                title=\"Error!\",\n                description=str(error).capitalize(),\n                color=0xE02B2B,\n            )\n            await context.send(embed=embed)\n        elif isinstance(error, Errors.UserBlacklisted):\n            embed = discord.Embed(\n                title=\"Error!\",\n                description=str(error).capitalize(),\n                color=0xE02B2B,\n            )\n            await context.send(embed=embed)\n        elif isinstance(error, commands.CommandError):\n            embed = discord.Embed(\n                title=\"Error!\",\n                description=str(error).capitalize(),\n                color=0xE02B2B,\n            )\n            await context.send(embed=embed)\n\n            await ErrorLogger.command_error(error, context)\n        else:\n            if \"not found\" in str(error):\n                embed = discord.Embed(\n                    title=\"Error!\",\n                    description=str(error).capitalize(),\n                    color=0xE02B2B,\n                )\n                await context.send(embed=embed)\n            else:\n                embed = discord.Embed(\n                    title=\"Error!\",\n                    description=str(error).capitalize(),\n                    color=0xE02B2B,\n                )\n                await context.send(embed=embed)\n                await ErrorLogger.command_error(error, context)\n                raise error\n"
  },
  {
    "path": "cogs/ai.py",
    "content": "# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon\n\nFILTERS = [\n    {\n        \"old\": \"@everyone\",\n        \"new\": \"@​everyone\"\n    },\n    {\n        \"old\": \"@here\",\n        \"new\": \"@​here\"\n    },\n    {\n        \"old\": \"<@&\",\n        \"new\": \"<@&​\"\n    },\n    {\n        \"old\": \"discord.gg\",\n        \"new\": \"[filtered]\"\n    },\n    {\n        \"old\": \"discord.com/invite\",\n        \"new\": \"[filtered]\"\n    }\n]\n\nWORD_BLACKLIST = [\"nigger\", \"nigga\", \"n i g g e r\"]\n\nimport discord\nimport requests\nimport io\nimport os\nimport re\nimport time\nimport asyncio\nimport functools\nimport http.client\nimport aiohttp\nimport base64\nimport aiohttp\nimport logging\nimport json\n\nfrom io import BytesIO\nfrom datetime import datetime\n\nfrom better_profanity import profanity\nfrom groq import Groq\n\nfrom discord import app_commands, Webhook\nfrom discord.ext import commands, tasks\nfrom discord.ext.commands import Context\nfrom utils import CONSTANTS, DBClient, Checks, CachedDB\n\nfrom cryptography.fernet import Fernet\n\nclient = DBClient.client\ndb = client.potatobot\n\nlogger = logging.getLogger(\"discord_bot\")\n\nif not os.path.isfile(f\"./config.json\"):\n    sys.exit(\"'config.json' not found! Please add it and try again.\")\nelse:\n    with open(f\"./config.json\") as file:\n        config = json.load(file)\n\nmodels = [\n    \"llama-3.3-70b-versatile\",\n    \"llama-3.2-11b-text-preview\",\n    \"llama-3.1-8b-instant\",\n    \"llama3-groq-70b-8192-tool-use-preview\",\n    \"llama3-groq-8b-8192-tool-use-preview\",\n]\n\napi_key = os.getenv('FUSION_API_KEY')\nsecret_key = os.getenv('FUSION_SECRET_KEY')\n\nai_temp_disabled = False\n\nai_channels = []\nc = db[\"ai_channels\"]\ndata = c.find_one({ \"listOfChannels\": True })\nlogger.info(\"Initing AI channels\")\n\nif data:\n    ai_channels = data[\"ai_channels\"]\n    logger.info(\"AI Channels data Found\")\nelse:\n    logger.info(\"Creating AI Channels data\")\n    data = {\n    \t\"listOfChannels\": True,\n         \"ai_channels\": []\n    }\n    c.insert_one(data)\n\nlast_api_key = 1\ntotal_api_keys = os.getenv(\"GROQ_API_KEY_COUNT\")\n\ndef get_api_key():\n    global last_api_key\n    global total_api_keys\n\n    if str(last_api_key) == total_api_keys:\n        last_api_key = 1\n    else:\n        last_api_key += 1\n\n    return os.getenv(\"GROQ_API_KEY_\" + str(last_api_key))\n\ndef prompt_ai(\n        prompt=\"Hello\",\n        image_url=None,\n        authorId = 0,\n        channelId = 0,\n        userInfo=\"\",\n        groq_client=Groq(api_key=get_api_key()),\n        systemPrompt=\"none\"\n    ):\n    c = db[\"ai_convos\"]\n    data = {}\n\n    messageArray = []\n\n    if channelId != 0:\n        data = CachedDB.sync_find_one(c, { \"isChannel\": True, \"id\": channelId })\n\n        if data:\n            messageArray = data[\"messageArray\"]\n        else:\n            data = { \"isChannel\": True, \"id\": channelId, \"messageArray\": [], \"expiresAt\": time.time()+604800 }\n\n            c.insert_one(data)\n    elif authorId != 0:\n        data = CachedDB.sync_find_one(c, { \"isChannel\": False, \"id\": authorId })\n\n        if data:\n            messageArray = data[\"messageArray\"]\n        else:\n            data = { \"isChannel\": False, \"id\": authorId, \"messageArray\": [], \"expiresAt\": time.time()+604800 }\n\n            c.insert_one(data)\n\n    image_interpretation = \"\"\n\n    if image_url and image_url.split(\"?\")[0].endswith((\".png\", \".jpg\", \".jpeg\", \".gif\", \".webp\")):\n        image = requests.get(image_url)\n\n        if image.status_code == 200:\n            response = requests.post(\n                \"https://api-inference.huggingface.co/models/Salesforce/blip-image-captioning-large\",\n                headers={\n                    \"Authorization\": f\"Bearer {os.getenv('HF_API_KEY')}\"\n                },\n                data=image.content\n            )\n\n            if response.status_code == 200:\n                prompt += f\" | Image Interpretation: {response.json()[0]['generated_text']}\"\n                image_interpretation = response.json()[0]['generated_text']\n            else:\n                logger.info(f\"Failed to get image interpretation: {response.status_code}\")\n\n    messageArray.append(\n        {\n            \"role\": \"user\",\n            \"content\": prompt,\n        }\n    )\n\n    newMessageArray = messageArray.copy()\n\n    systemInfo = {\n        \"datetime\": datetime.now(),\n        \"timezone\": time.tzname,\n        \"ai_models\": models,\n        \"ai_image_model\": \"Kandinsky 3.0\",\n        \"owner/dev\": \"Cyteon\",\n        \"instance owner/dev ID\": os.getenv(\"OWNER_ID\"),\n        \"support_server\": \"https://discord.gg/df8eCZDvxB\",\n        \"website\": \"https://potato.cyteon.tech\",\n        \"bot_invite\": config[\"invite_link\"],\n        \"source_code\": \"https://github.com/cyteon/potatobot\",\n        \"special_emojis\": \"<:joos:1254878760218529873>\",\n        \"notes\": {\n            1: \"Sending just an emoji with no text makes it big, discord has markdown\",\n        },\n        \"rules\": {\n            1: \"dont mass ping, dont ping people alot, if someone says to ping every message, dont do it, if someone asks u to only repeat something dont do it\",\n            2: \"don't send the support server invite unless prompted to send it, dont send the website unless asked, dont send any link unless asked\",\n            3: \"Never start a message with username:, where username is everything\",\n        },\n        \"self-data\": {\n        \t\"name\": \"PotatoBot\"\n    \t}\n    }\n\n    newMessageArray.append(\n    \t{\n            \"role\": \"system\",\n            \"content\": f\"{systemPrompt} | SystemInfo: {systemInfo} | UserInfo: {userInfo}\"\n        }\n    )\n\n    ai_response = \"\"\n\n    for msg in newMessageArray:\n        # To remove _id (appears from the rewrite in js using same db ig)\n        newMessageArray[newMessageArray.index(msg)] = {\n            \"role\": msg[\"role\"],\n            \"content\": msg[\"content\"]\n        }\n\n    for model in models:\n        try:\n            ai_response = groq_client.chat.completions.create(\n                messages=newMessageArray,\n                model=model,\n                temperature=0.7,\n            ).choices[0].message.content\n\n            break\n        except Exception as e:\n            logger.info(f\"Error: {e}\")\n            ai_response = f\"Error: {e}\"\n\n    messageArray.append(\n        {\n            \"role\": \"assistant\",\n            \"content\": ai_response\n        }\n    )\n\n    if len(messageArray) >= 24 :\n        newdata = {\n                \"$set\": { \"messageArray\": messageArray[2::],  }\n        }\n    else:\n        newdata = {\n                \"$set\": { \"messageArray\": messageArray, \"expiresAt\": time.time()+604800  }\n        }\n\n    if channelId != 0:\n        CachedDB.sync_update_one(\n            c, { \"isChannel\": True, \"id\": channelId}, newdata\n        )\n    elif authorId != 0:\n        CachedDB.sync_update_one(\n            c, { \"isChannel\": False, \"id\": authorId}, newdata\n        )\n\n    ai_response = ai_response.replace(\"</s>\", \" \") # It kept sending this somtimes\n\n    for word in WORD_BLACKLIST:\n        if word.lower() in ai_response.lower():\n            logger.error(f\"AI Response contains blacklisted word: {word}\")\n            return \"The AIs response has been identified as containing blacklisted words, we are sorry for this inconvenience\"\n\n    for filter in FILTERS:\n        if filter[\"old\"] == \"discord.gg\":\n            # TODO: Fix where if someone makes ai say support server invite and another invite it dosent get filtered\n            if systemInfo[\"support_server\"] in ai_response:\n                continue\n        ai_response =  ai_response.replace(filter[\"old\"], filter[\"new\"])\n\n    if image_interpretation:\n        ai_response += f\"\\n-# Image Interpretation: {image_interpretation}\"\n\n    return ai_response\n\nclass Text2ImageAPI:\n    def __init__(self, url):\n        self.URL = url\n\n    global AUTH_HEADERS\n    AUTH_HEADERS = {\n        'X-Key': f'Key {api_key}',\n        'X-Secret': f'Secret {secret_key}',\n    }\n\n    def get_model(self):\n        response = requests.get(self.URL + 'key/api/v1/models', headers=AUTH_HEADERS)\n        data = response.json()\n        return data[0]['id']\n\n    def generate(self, prompt, model, images=1, width=1024, height=1024, style=\"DEFAULT\", negative_prompt=\"\"):\n        params = {\n            \"type\": \"GENERATE\",\n            \"stype\": style,\n            \"numImages\": images,\n            \"width\": width,\n            \"height\": height,\n            \"negativePromptUnclip\": negative_prompt,\n            \"generateParams\": {\n                \"query\": f\"{prompt}\"\n            }\n        }\n        data = {\n            'model_id': (None, model),\n            'params': (None, json.dumps(params), 'application/json')\n        }\n        response = requests.post(self.URL + 'key/api/v1/text2image/run', headers=AUTH_HEADERS, files=data)\n        data = response.json()\n        return data['uuid']\n\n    def check_generation(self, request_id, attempts=10, delay=10):\n        while attempts > 0:\n            response = requests.get(self.URL + 'key/api/v1/text2image/status/' + request_id, headers=AUTH_HEADERS)\n            data = response.json()\n\n            logger.info(data)\n\n            if data['status'] == 'DONE':\n                return data['images']\n            attempts -= 1\n            time.sleep(delay)\n\n        raise Exception(\"An error occured while generating the image\")\n\nclass Ai(commands.Cog, name=\"🤖 AI\"):\n    def __init__(self, bot) -> None:\n        self.bot = bot\n        self.purge_conversations.start()\n        self.ai_temp_disabled = False\n        self.get_prefix = bot.get_prefix\n        self.statsDB = bot.statsDB\n        self.cooldown = commands.CooldownMapping.from_cooldown(5, 10, commands.BucketType.user)\n        self.too_many_violations = commands.CooldownMapping.from_cooldown(3, 10, commands.BucketType.user)\n\n    @commands.Cog.listener()\n    async def on_message(self, message: discord.Message) -> None:\n        if message.author == self.bot or message.author.bot:\n            return\n\n        if not message.channel.id in ai_channels:\n            return\n\n        if message.content.startswith(\"-\"):\n            return\n\n        if message.content.startswith(await self.bot.get_prefix(message)):\n            return\n\n        if self.ai_temp_disabled:\n            await message.reply(\"AI is temporarily disabled due to techincal difficulties\")\n            return\n\n        bucket = self.cooldown.get_bucket(message)\n        retry_after = bucket.update_rate_limit()\n\n        users_global = db[\"users_global\"]\n\n        user_data = await CachedDB.find_one(users_global, {\"id\": message.author.id})\n\n        if not user_data:\n            user_data = CONSTANTS.user_global_data_template(message.author.id)\n            users_global.insert_one(user_data)\n\n        if user_data:\n            if user_data[\"ai_ignore\"]:\n                await message.reply(\"**You are being ignored by the AI, reason: \" + user_data[\"ai_ignore_reason\"] + \"**\")\n                return\n\n            if user_data[\"blacklisted\"]:\n                await message.reply(\"**You are blacklisted from using the bot, reason: \" + user_data[\"blacklist_reason\"] + \"**\")\n                return\n\n        if retry_after:\n            embed = discord.Embed(\n                title=\"Slow Down! Ratelimit hit\",\n                description=f\"Try again <t:{(time.time() + int(retry_after)):.0f}:R>\",\n                color=discord.Color.red()\n            )\n            embed.set_footer(text=\"Further violations may result in a mute or blacklist.\")\n\n            await message.reply(embed=embed)\n\n            bucket = self.too_many_violations.get_bucket(message)\n            retry_after = bucket.update_rate_limit()\n\n            if retry_after:\n                embed = discord.Embed(\n                    title=\"Too many violations! Max ratelimit hit\",\n                    description=f\"You have been blacklisted from using the AI.\",\n                    color=discord.Color.red()\n                )\n                embed.set_footer(text=\" If you believe this is a mistake, please contact the support server.\")\n\n                newdata = {\n                    \"$set\": { \"ai_ignore\": True, \"ai_ignore_reason\": \"Too many violations, max ratelimit hit.\"}\n                }\n\n                users_global.update_one(\n                    { \"id\": message.author.id }, newdata\n                )\n\n                await message.reply(embed=embed)\n\n            return\n\n        if profanity.contains_profanity(message.content):\n            newdata ={\n                \"$inc\": { \"inspect.nsfw_requests\": 1}\n            }\n\n            users_global.update_one(\n                { \"id\": message.author.id }, newdata\n            )\n\n        for word in WORD_BLACKLIST:\n            if word.lower() in message.content.lower():\n                newdata = {\n                    \"$inc\": { \"inspect.times_flagged\": 1}\n                }\n\n                users_global.update_one(\n                    { \"id\": message.author.id }, newdata\n                )\n\n                return await message.reply(\"Your message contains a blacklisted word, please refrain from using it.\")\n\n        if not \"ai_requests\" in user_data[\"inspect\"]:\n            newdata = {\n                \"$set\": { \"inspect.ai_requests\": 0}\n            }\n            users_global.update_one(\n                { \"id\": message.author.id }, newdata\n            )\n\n        if user_data[\"inspect\"][\"ai_requests\"] == 0:\n            embed = discord.Embed(\n                description=\"By interacting with the ai in any way you agree to the following:\\n- We will log: amount of ai requests, times you get flagged, nsfw request count\\n- We will also store all messages you send to the AI in order to give the AI memory, these messages will be deleted after 7 days of inactivity and will not be seen by anyone other than the ai itself.\"\n            )\n            await message.reply(embed=embed)\n\n        newdata ={\n            \"$inc\": { \"inspect.ai_requests\": 1}\n        }\n\n        users_global.update_one(\n            { \"id\": message.author.id }, newdata\n        )\n\n        c = db[\"guilds\"]\n        data = c.find_one({\"id\": message.guild.id})\n\n        if not data:\n            data = CONSTANTS.guild_data_template(message.guild.id)\n            c.insert_one(data)\n\n        if data[\"groq_api_key\"] == \"NONE\":\n            if not data[\"ai_access\"]:\n                await message.channel.send(f\"**This server does not have access to built-in api keys, provide your own from https://console.groq.com/keys using {await self.bot.get_prefix(message)}groq-api-key <api_key>**\")\n                logger.info(f\"{message.author} tried to ask AI in {message.guild.name} ({message.guild.id}): AI Disabled!\")\n                return\n            client = Groq(api_key=get_api_key())\n        else:\n            cipher_suite = Fernet(os.getenv(\"HASHING_SECRET\"))\n            key = cipher_suite.decrypt(data[\"groq_api_key\"]).decode()\n            client = Groq(api_key=key)\n\n        c = db[\"users\"]\n        userInfo = await CachedDB.find_one(c, {\"id\": message.author.id, \"guild_id\": message.guild.id})\n\n        if not userInfo:\n            userInfo = {}\n        else:\n            userInfo[\"whitelisted\"] = \"[REDACTED]\"\n            userInfo[\"trusted\"] = \"[REDACTED]\"\n            userInfo[\"jailed\"] = \"[REDACTED]\"\n            userInfo[\"warnings\"] = \"[REDACTED]\"\n\n        userInfo[\"user\"] = message.author\n        userInfo[\"channel\"] = message.channel\n\n        systemPrompt=\"You are a discord user, you are allowed to have opinions, also controversial ones, send a reply in max 500 characters. \\n\\nSystem info: {systemInfo} \\n\\nThe user's info:  {userInfo}\"\n\n        if \"system_prompt\" in data:\n            if data[\"system_prompt\"] != \"NONE\":\n                systemPrompt = data[\"system_prompt\"]\n\n            if profanity.contains_profanity(systemPrompt):\n                if hasattr(message.channel, \"is_nsfw\"):\n                    if not message.channel.is_nsfw():\n                        await message.reply(\"The system prompt contains profanity and this channel is not marked as NSFW. **Using default system prompt**\")\n                        systemPrompt = \"NONE\"\n\n        image_url = None\n\n        if message.attachments:\n            image_url = message.attachments[0].url\n        else:\n            if message.content:\n                urls = re.findall(r'(https?://[^\\s]+)', message.content)\n                if urls:\n                    image_url = urls[0]\n\n        loop = asyncio.get_running_loop()\n        try:\n            async with message.channel.typing():\n                data = await loop.run_in_executor(\n                    None,\n                    functools.partial(\n                        prompt_ai,\n                        message.author.name + \": \" + message.content,\n                        image_url,\n                        0,\n                        message.channel.id, str(userInfo),\n                        groq_client=client,\n                        systemPrompt=systemPrompt)\n                    )\n\n                if len(data) > 2000:\n                    file = discord.File(io.BytesIO(data.encode()), filename=\"ai_response.txt\")\n\n                    await message.reply(\"-# Response was too long for a normal message\", file=file)\n                else:\n                    await message.reply(data)\n\n                ai_requests = (self.statsDB.get(\"ai_requests\") if self.statsDB.get(\"ai_requests\") else 0) + 1\n                self.statsDB.set(\"ai_requests\", ai_requests)\n                self.statsDB.save()\n\n        except Exception as e:\n            logger.error(f\"Error in AI: {e}\")\n            await message.reply(\"An error in the AI has occured\")\n\n        logger.info(f\"AI replied to {message.author} in {message.guild.name} ({message.guild.id})\")\n\n    @tasks.loop(hours=1)\n    async def purge_conversations(self):\n        convos = db[\"ai_convos\"]\n        result = convos.delete_many({\"expiresAt\": {\"$lt\": time.time()}})\n\n    @commands.hybrid_command(\n        name=\"ai\",\n        description=\"Ask an AI for something\",\n        usage=\"ai <prompt>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @app_commands.allowed_installs(guilds=True, users=True)\n    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)\n    @commands.cooldown(10, 60, commands.BucketType.default)\n    async def ai(self, context: Context, *, prompt: str) -> None:\n        if self.ai_temp_disabled:\n            await context.send(\"AI is temporarily disabled due to techincal difficulties\")\n            return\n\n        await context.defer()\n\n        users_global = db[\"users_global\"]\n        user_data = users_global.find_one({\"id\": context.author.id})\n\n        if not user_data:\n            user_data = CONSTANTS.user_global_data_template(context.author.id)\n            users_global.insert_one(user_data)\n\n        if user_data:\n            if user_data[\"ai_ignore\"]:\n                await context.reply(\"**You are being ignored by the AI, reason: \" + user_data[\"ai_ignore_reason\"] + \"**\")\n                return\n\n        if profanity.contains_profanity(context.message.content):\n            newdata ={\n                \"$inc\": { \"inspect.nsfw_requests\": 1}\n            }\n\n            users_global.update_one(\n                { \"id\": context.author.id }, newdata\n            )\n\n        if user_data[\"inspect\"][\"ai_requests\"] == 0:\n            embed = discord.Embed(\n                description=\"By interacting with the ai in any way you agree to the following:\\n- We will log: amount of ai requests, times you get flagged, nsfw request count\\n- We will also store all messages you send to the AI in order to give the AI memory, these messages will be deleted after 7 days of inactivity and will not be seen by anyone other than the ai itself.\"\n            )\n            await context.send(embed=embed)\n\n        if not \"ai_requests\" in user_data[\"inspect\"]:\n            newdata = {\n                \"$set\": { \"inspect.ai_requests\": 0}\n            }\n            users_global.update_one(\n                { \"id\": context.author.id }, newdata\n            )\n\n        newdata ={\n            \"$inc\": { \"inspect.ai_requests\": 1}\n        }\n\n        users_global.update_one(\n            { \"id\": context.author.id }, newdata\n        )\n\n        client = Groq(api_key=get_api_key())\n\n        userInfo = { \"user\": context.author }\n\n        c = db[\"users\"]\n        userData = c.find_one({\"id\": context.author.id, \"guild_id\": context.guild.id}) if context.guild else {}\n\n        if userData:\n            userData[\"whitelisted\"] = \"[REDACTED]\"\n            userData[\"trusted\"] = \"[REDACTED]\"\n            userData[\"jailed\"] = \"[REDACTED]\"\n            userData[\"warnings\"] = \"[REDACTED]\"\n\n        userInfo[\"data\"] = userData\n\n        loop = asyncio.get_running_loop()\n        try:\n            data = await loop.run_in_executor(\n                None,\n                functools.partial(\n                    prompt_ai,\n                    prompt,\n                    None,\n                    context.author.id,\n                    0,\n                    str(userInfo),\n                    groq_client=client\n                )\n            )\n\n            if len(data) > 2000:\n                file = discord.File(io.BytesIO(data.encode()), filename=\"ai_response.txt\")\n\n                await context.reply(\"-# Response was too long for a normal message\", file=file)\n            else:\n                await context.reply(data)\n\n            ai_requests = (self.statsDB.get(\"ai_requests\") if self.statsDB.get(\"ai_requests\") else 0) + 1\n            self.statsDB.set(\"ai_requests\", ai_requests)\n            self.statsDB.save()\n        except Exception as e:\n            logger.error(f\"Error in AI: {e}\")\n            await context.reply(\"An error in the AI has occured\")\n\n    @commands.hybrid_command(\n        name=\"set-ai-channel\",\n        description=\"Set current channel as an AI channel\",\n        usage=\"set-ai-channel\"\n    )\n    @commands.has_permissions(manage_channels=True)\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    async def set_ai_channel(self, context: Context):\n        c = db[\"guilds\"]\n        data = c.find_one({\"id\": context.guild.id})\n\n        if not data:\n            data = CONSTANTS.guild_data_template(context.guild.id)\n            c.insert_one(data)\n\n        if data[\"groq_api_key\"] == \"NONE\":\n            if not data[\"ai_access\"]:\n                await context.send(f\"**This server does not have access to built-in api keys, provide your own from https://console.groq.com/keys using {await self.bot.get_prefix(context)}groq-api-key <api_key>**\")\n                logger.info(f\"{context.author} tried to set AI channel in {context.guild.name} ({context.guild.id}): AI Disabled!\")\n                return\n\n            client = Groq(api_key=get_api_key())\n        else:\n            cipher_suite = Fernet(os.getenv(\"HASHING_SECRET\"))\n            key = cipher_suite.decrypt(data[\"groq_api_key\"]).decode()\n            client = Groq(api_key=key)\n\n        await context.send(\"Setting channel...\")\n\n        loop = asyncio.get_running_loop()\n        data = await loop.run_in_executor(None, functools.partial(prompt_ai, \"Hello\", groq_client=client))\n\n        try:\n             await context.channel.edit(slowmode_delay=5)\n        except:\n             pass\n\n        await context.send(data)\n\n        ai_channels.append(context.channel.id)\n\n        c = db[\"ai_channels\"]\n        data = c.find_one({ \"listOfChannels\": True })\n\n        newdata = {\n                \"$set\": { \"ai_channels\": ai_channels }\n        }\n\n        c.update_one(\n            { \"listOfChannels\": True }, newdata\n        )\n\n    @commands.hybrid_command(\n        name=\"unset-ai-channel\",\n        description=\"Unset current channel as an AI channel\",\n        usage=\"unset-ai-channel\"\n    )\n    @commands.has_permissions(manage_channels=True)\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    async def unset_ai_channel(self, context: Context):\n        c = db[\"ai_channels\"]\n\n        ai_channels.remove(context.channel.id)\n\n        await context.channel.edit(slowmode_delay=0)\n\n        newdata = {\n                \"$set\": { \"ai_channels\": ai_channels }\n        }\n\n        c.update_one(\n            { \"listOfChannels\": True }, newdata\n        )\n\n        await context.send(\"Channel unset as AI channel\")\n\n    @commands.cooldown(1, 30, commands.BucketType.user)\n    @commands.hybrid_command(\n        name=\"create-ai-thread\",\n        description=\"Create AI thread so u dont have to do !ai\",\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    async def create_ai_thread(self, context: Context, *, prompt = \"Hello\") -> None:\n        c = db[\"guilds\"]\n        data = c.find_one({\"id\": context.guild.id})\n\n        if not data:\n            data = CONSTANTS.guild_data_template(context.guild.id)\n            c.insert_one(data)\n\n        if data[\"groq_api_key\"] == \"NONE\":\n            if not data[\"ai_access\"]:\n                await context.send(f\"**This server does not have access to built-in api keys, provide your own from https://console.groq.com/keys using {await self.bot.get_prefix(context)}groq-api-key <api_key>**\")\n                logger.info(f\"{context.author} tried to create AI thread in {context.guild.name} ({context.guild.id}): AI Disabled!\")\n                return\n\n            client = Groq(api_key=get_api_key())\n        else:\n            cipher_suite = Fernet(os.getenv(\"HASHING_SECRET\"))\n            key = cipher_suite.decrypt(data[\"groq_api_key\"]).decode()\n\n            client = Groq(api_key=key)\n\n        msg = await context.send(\"Creating, please wait\")\n\n        loop = asyncio.get_running_loop()\n        data = await loop.run_in_executor(None, functools.partial(prompt_ai, prompt, groq_client=client))\n\n        ai_requests = (self.statsDB.get(\"ai_requests\") if self.statsDB.get(\"ai_requests\") else 0) + 1\n        self.statsDB.set(\"ai_requests\", ai_requests)\n        self.statsDB.save()\n\n        newChannel = await context.channel.create_thread(\n            name=f\"AI Convo - {context.author}\",\n            type=discord.ChannelType.public_thread,\n            slowmode_delay=5\n        )\n\n        await newChannel.send(data)\n        await msg.delete()\n\n        ai_channels.append(newChannel.id)\n\n        c = db[\"ai_channels\"]\n        data = c.find_one({ \"listOfChannels\": True })\n\n        newdata = {\n                \"$set\": { \"ai_channels\": ai_channels }\n        }\n\n        c.update_one(\n            { \"listOfChannels\": True }, newdata\n        )\n\n        await context.send(\"Thread created: \" + newChannel.mention)\n\n    @commands.hybrid_command(\n        name=\"ai-image\",\n        description=\"Generate an ai image\",\n        usage=\"ai-image <prompt>\",\n        aliases=[\"image\"]\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @app_commands.allowed_installs(guilds=True, users=True)\n    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)\n    async def ai_image(self, context: commands.Context, prompt: str) -> None:\n        users_global = db[\"users_global\"]\n        user_data = users_global.find_one({\"id\": context.author.id})\n\n        if not user_data:\n            user_data = CONSTANTS.user_global_data_template(context.author.id)\n            users_global.insert_one(user_data)\n\n        if user_data:\n            if user_data[\"ai_ignore\"]:\n                await context.reply(\"**You are being ignored by the AI, reason: \" + user_data[\"ai_ignore_reason\"] + \"**\")\n                return\n\n        if profanity.contains_profanity(prompt):\n            newdata ={\n                \"$inc\": { \"inspect.nsfw_requests\": 1}\n            }\n\n            users_global.update_one(\n                { \"id\": context.author.id }, newdata\n            )\n\n            if hasattr(context.channel, \"is_nsfw\"):\n                if not context.channel.is_nsfw():\n                    return await context.send(f\"NSFW requests are not allowed in non nsfw channels!\", ephemeral=True)\n\n        if not \"ai_requests\" in user_data[\"inspect\"]:\n            newdata = {\n                \"$set\": { \"inspect.ai_requests\": 0}\n            }\n            users_global.update_one(\n                { \"id\": context.author.id }, newdata\n            )\n\n        if user_data[\"inspect\"][\"ai_requests\"] == 0:\n            embed = discord.Embed(\n                description=\"By interacting with the ai in any way you agree to the following:\\n- We will log: amount of ai requests, times you get flagged, nsfw request count\\n- We will also store all messages you send to the AI in order to give the AI memory, these messages will be deleted after 7 days of inactivity and will not be seen by anyone other than the ai itself.\"\n            )\n            await context.reply(embed=embed)\n\n        newdata ={\n            \"$inc\": { \"inspect.ai_requests\": 1}\n        }\n\n        users_global.update_one(\n            { \"id\": context.author.id }, newdata\n        )\n\n        eta = int(time.time() + 20)\n\n        msg = await context.send(f\"Generating image... ETA: <t:{eta}:R>\")\n\n        attachments = []\n\n        loop = asyncio.get_running_loop()\n        try:\n            data = await loop.run_in_executor(None, functools.partial(self.generate_image, context, prompt))\n        except Exception as e:\n            await msg.edit(content=\"An error occurred while generating the image\")\n            raise e\n\n        logger.info(data)\n\n        for image in data:\n            attachments.append(discord.File(BytesIO(base64.b64decode(image)), \"ai_image.png\"))\n\n        await msg.edit(content=\"Here you go!\", attachments=attachments)\n\n    @commands.hybrid_command(\n        name=\"imagine\",\n        description=\"Generate an ai image, where you can change the model\",\n        usage=\"imagine <model (run command with no arguments for list)> <prompt>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @app_commands.allowed_installs(guilds=True, users=True)\n    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)\n    async def imagine(self, context: commands.Context, model: str = \"none\", *, prompt: str = \"potato\") -> None:\n        options = {\n            \"openjourney\": \"prompthero/openjourney-v4\",\n            \"realistic-vision\": \"SG161222/Realistic_Vision_V4.0_noVAE\",\n            \"ssd-1b\": \"segmind/SSD-1B\",\n            \"dreamshaper\": \"Lykon/dreamshaper-xl-v2-turbo\",\n            \"mobius\": \"Corcelio/mobius\",\n            \"dalle\": \"ehristoforu/dalle-3-xl-v2\",\n            \"sdxl\": \"stabilityai/stable-diffusion-xl-base-1.0\",\n        }\n\n        nsfw_options = []\n\n        users_global = db[\"users_global\"]\n        user_data = users_global.find_one({\"id\": context.author.id})\n\n        if not user_data:\n            user_data = CONSTANTS.user_global_data_template(context.author.id)\n            users_global.insert_one(user_data)\n\n        if model not in options:\n            return await context.send(\"Invalid model. Available models: \" + \", \".join(options.keys()))\n\n        if model in nsfw_options:\n            if hasattr(context.channel, \"is_nsfw\"):\n                if not context.channel.is_nsfw():\n                    return await context.send(f\"NSFW models are not allowed in non NSFW channels!\", ephemeral=True)\n\n        if user_data:\n            if user_data[\"ai_ignore\"]:\n                await context.reply(\"**You are being ignored by the AI, reason: \" + user_data[\"ai_ignore_reason\"] + \"**\")\n                return\n\n        users_global = db[\"users_global\"]\n\n        user_data = users_global.find_one({\"id\": context.author.id})\n\n        if not user_data:\n            user_data = CONSTANTS.user_global_data_template(context.author.id)\n            users_global.insert_one(user_data)\n\n        if profanity.contains_profanity(prompt):\n            newdata ={\n                \"$inc\": { \"inspect.nsfw_requests\": 1}\n            }\n\n            users_global.update_one(\n                { \"id\": context.author.id }, newdata\n            )\n\n            if hasattr(context.channel, \"is_nsfw\"):\n                if not context.channel.is_nsfw():\n                    return await context.send(f\"NSFW requests are not allowed in non NSFW channels!\", ephemeral=True)\n\n        if not \"ai_requests\" in user_data[\"inspect\"]:\n            newdata = {\n                \"$set\": { \"inspect.ai_requests\": 0}\n            }\n            users_global.update_one(\n                { \"id\": context.author.id }, newdata\n            )\n\n        if user_data[\"inspect\"][\"ai_requests\"] == 0:\n            embed = discord.Embed(\n                description=\"By interacting with the ai in any way you agree to the following:\\n- We will log: amount of ai requests, times you get flagged, nsfw request count\\n- We will also store all messages you send to the AI in order to give the AI memory, these messages will be deleted after 7 days of inactivity and will not be seen by anyone other than the ai itself.\"\n            )\n            await context.reply(embed=embed)\n        newdata ={\n            \"$inc\": { \"inspect.ai_requests\": 1}\n        }\n\n        users_global.update_one(\n            { \"id\": context.author.id }, newdata\n        )\n\n        ETA = int(time.time() + 15)\n        msg = await context.send(\n            f\"This might take a bit of time... ETA: <t:{ETA}:R>\"\n        )\n\n        async with aiohttp.ClientSession() as session:\n            api_key = os.getenv(\"HF_API_KEY\")\n\n            response = await session.post(\n                \"https://api-inference.huggingface.co/models/\" + options[model],\n                json={\"inputs\": prompt},\n                headers={\"Authorization\": f\"Bearer {api_key}\"},\n            )\n\n            if response.status != 200:\n                return await msg.edit(content=\"An error occurred while generating the image: \" + http.client.responses[response.status])\n\n            images = [discord.File(BytesIO(await response.read()), \"ai_image.png\")]\n\n            await msg.edit(attachments=images, content=\"Here you go!\")\n\n    def generate_image(self, context: commands.Context, prompt: str, width=1024, height=1024, style=\"DEFAULT\", negative_prompt=\"\", number_of_images=1) -> None:\n        api_key = os.environ.get('FUSION_API_KEY')\n        secret_key = os.environ.get('FUSION_SECRET_KEY')\n\n        if not api_key or not secret_key:\n            context.send(\"API keys are missing. Please set the FUSION_API_KEY and FUSION_SECRET_KEY environment variables.\")\n            return\n\n        api = Text2ImageAPI('https://api-key.fusionbrain.ai/')\n        model_id = api.get_model()\n        uuid = api.generate(prompt, model_id, images=number_of_images, width=width, height=height, style=style, negative_prompt=negative_prompt)\n        images_data = api.check_generation(uuid)\n\n        return images_data\n\n    @commands.hybrid_command(\n        name=\"system-prompt\",\n        description=\"Set the system prompt for the AI\",\n        usage=\"system-prompt <prompt>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @commands.has_permissions(manage_messages=True)\n    async def system_prompt(self, context: Context, *, prompt: str = \"\") -> None:\n        c = db[\"guilds\"]\n        data = c.find_one({\"id\": context.guild.id})\n\n        if prompt == \"\":\n            if data:\n                if \"system_prompt\" in data:\n                    return await context.send(\"Current system prompt: \" + data[\"system_prompt\"])\n                else:\n                    return await context.send(\"No system prompt set.\")\n\n        if profanity.contains_profanity(prompt):\n            if not context.channel.is_nsfw():\n                prompt = \"NONE\"\n                await context.send(\"The system prompt contains profanity and this channel is not marked as NSFW. Please use an NSFW channel for NSFW prompts.\")\n\n        newdata = {\n                \"$set\": { \"system_prompt\": prompt }\n        }\n\n        c.update_one(\n            { \"id\": context.guild.id }, newdata\n        )\n\n        await context.send(\"System prompt set to: \" + prompt)\n\n    @commands.hybrid_command(\n        name=\"reset-ai\",\n        description=\"Reset AI data\",\n        usage=\"reset-ai\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @commands.has_permissions(manage_messages=True)\n    async def reset_ai(self, context: Context) -> None:\n        c = db[\"ai_convos\"]\n        c.delete_one({\"id\": context.channel.id})\n        await context.send(\"AI data reset for \" + context.channel.mention)\n\n    @commands.command(\n        name=\"toggle-ai\",\n        description=\"Reset AI data (owner only)\",\n    )\n    @commands.is_owner()\n    async def toggle_ai(self, context: Context) -> None:\n        self.ai_temp_disabled = not self.ai_temp_disabled\n\n        if self.ai_temp_disabled:\n            await context.send(\"AI is now disabled globally\")\n        else:\n            await context.send(\"AI is now enabled globally\")\n\nasync def setup(bot) -> None:\n    await bot.add_cog(Ai(bot))\n"
  },
  {
    "path": "cogs/api.py",
    "content": "# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon\n\nimport discord\nimport aiohttp\n\nfrom discord import app_commands\nfrom discord.ext import commands\nfrom discord.ext.commands import Context\n\nfrom utils import Checks\n\nclass Api(commands.Cog, name=\"🌐 API\"):\n    def __init__(self, bot) -> None:\n        self.bot = bot\n\n    @commands.hybrid_group(\n        name=\"api\",\n        description=\"Commands for diffrent APIs\",\n        usage=\"api <subcommand> [args]\",\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @app_commands.allowed_installs(guilds=True, users=True)\n    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)\n    async def api(self, context: Context) -> None:\n        prefix = await self.bot.get_prefix(context)\n\n        cmds = \"\\n\".join([f\"{prefix}api {cmd.name} - {cmd.description}\" for cmd in self.api.walk_commands()])\n\n        embed = discord.Embed(\n            title=f\"Help: Api\", description=\"List of available commands:\", color=0xBEBEFE\n        )\n        embed.add_field(\n            name=\"Commands\", value=f\"```{cmds}```\", inline=False\n        )\n\n        await context.send(embed=embed)\n\n    @api.command(\n        name=\"minecraft\",\n        aliases=[\"mc\"],\n        description=\"Get someones minecraft character\",\n        usage=\"api minecraft <username>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    async def api_minecraft(self, context: Context, *, username: str) -> None:\n        embed = discord.Embed(title=f\"Minecraft character for {username}\", color=0xBEBEFE)\n        embed.set_image(url=f\"https://mc-heads.net/body/{username}\")\n\n        await context.send(embed=embed)\n\n    @api.command(\n        name=\"mc-server\",\n        aliases=[\"mcserver\", \"mc-srv\", \"mcs\"],\n        description=\"Get info on a minecraft server\",\n        usage=\"api mc-server <username>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    async def api_mc_server(self, context: Context, *, host: str) -> None:\n        async with aiohttp.ClientSession() as session:\n            async with session.get(f\"https://api.mcsrvstat.us/3/{host}\") as response:\n                data = await response.json()\n\n                if data[\"online\"]:\n                    embed = discord.Embed(\n                        title=f\"Server info for {host}\", color=0xBEBEFE\n                    )\n                    embed.add_field(\n                        name=\"Players\", value=f\"```{data['players']['online']}/{data['players']['max']}```\", inline=False\n                    )\n\n                    if \"software\" in data:\n                        embed.add_field(\n                            name=\"Version\", value=f\"```{data['version']} ({data['software']})```\", inline=False\n                        )\n                    else:\n                        embed.add_field(\n                            name=\"Version\", value=f\"```{data['version']}```\", inline=False\n                        )\n\n                    embed.add_field(\n                        name=\"MOTD\", value=f\"```{data['motd']['clean'][0]}```\", inline=False\n                    )\n\n                    if \"list\" in data[\"players\"]:\n                        players = [p[\"name\"] for p in data[\"players\"][\"list\"]]\n                        players = \", \".join(players)\n\n\n                        embed.add_field(\n                            name=\"Online players\", value=f\"```{players}```\", inline=False\n                        )\n\n                    if \"plugins\" in data:\n                        plugins = [p[\"name\"] for p in data[\"plugins\"]]\n                        plugins = \", \".join(plugins)\n\n                        embed.add_field(\n                            name=\"Plugins\", value=f\"```{plugins}```\", inline=False\n                        )\n\n                    if \"mods\" in data:\n                        mods = [m[\"name\"] for m in data[\"mods\"]]\n                        mods = \", \".join(mods)\n\n                        embed.add_field(\n                            name=\"Mods\", value=f\"```{mods}```\", inline=False\n                        )\n\n                    await context.send(embed=embed)\n                else:\n                    await context.send(\"The server is offline\")\n\nasync def setup(bot) -> None:\n    await bot.add_cog(Api(bot))\n"
  },
  {
    "path": "cogs/code.py",
    "content": "\"\"\"\nThe MIT License (MIT)\n\nCopyright (c) 2022 Ogiroid Development Team\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the \"Software\"),\nto deal in the Software without restriction, including without limitation\nthe rights to use, copy, modify, merge, publish, distribute, sublicense,\nand/or sell copies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\"\"\"\n\nfrom discord import app_commands\nfrom discord.ext import commands\nfrom discord.ext.commands import Context\n\nfrom utils import Checks\nfrom ui.code import CodeModal\n\nclass Code(commands.Cog, name=\"💻 Code\"):\n    def __init__(self, bot) -> None:\n        self.bot = bot\n\n    @commands.hybrid_command(\n        name=\"code\",\n        description=\"Run code in (almost) any language, a modal will pop up\",\n        usage=\"code\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @app_commands.allowed_installs(guilds=True, users=True)\n    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)\n    async def code(self, context: Context) -> None:\n        if not context.interaction:\n            await context.send(\"This command can only be used as a slash command.\")\n            return\n        await context.interaction.response.send_modal(CodeModal())\n\nasync def setup(bot) -> None:\n    await bot.add_cog(Code(bot))\n"
  },
  {
    "path": "cogs/economy.py",
    "content": "# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon\n\nimport random\nimport discord\nimport time\n\nfrom discord import ui\nfrom discord.ext import commands\nfrom discord.ext.commands import Context\n\nfrom utils import CONSTANTS, DBClient, CachedDB, Checks\nfrom ui.farm import FarmButton\nfrom ui.gambling import GamblingButton\n\nfrom ui.papertrading import start_paper_trading\n\ndb = DBClient.db\n\nclass Economy(commands.Cog, name=\"🪙 Economy\"):\n    def __init__(self, bot) -> None:\n        self.bot = bot\n\n    @commands.hybrid_command(\n        name=\"balance\",\n        aliases=[\"wallet\", \"bal\"],\n        description=\"See yours or someone else's wallet\",\n        usage=\"balance [optional: user]\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @commands.cooldown(3, 10, commands.BucketType.user)\n    async def wallet(self, context: Context, user: discord.Member = None) -> None:\n        if not user:\n            user = context.author\n\n        c = db[\"users\"]\n        data = c.find_one({\"id\": user.id, \"guild_id\": context.guild.id})\n\n        if not data:\n            data = CONSTANTS.user_data_template(user.id, context.guild.id)\n            c.insert_one(data)\n        await context.send(f\"**{user}** has ${data['wallet']} in their wallet\")\n\n    @commands.hybrid_command(\n        name=\"daily\",\n        description=\"Get your daily cash\",\n        usage=\"daily\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    async def daily(self, context: Context) -> None:\n        c = db[\"users\"]\n        data = await CachedDB.find_one(c, {\"id\": context.author.id, \"guild_id\": context.guild.id})\n\n        if not data:\n            data = CONSTANTS.user_data_template(context.author.id, context.guild.id)\n            c.insert_one(data)\n        if time.time() - data[\"last_daily\"] < 86400:\n            eta = data[\"last_daily\"] + 86400\n            await context.send(\n                f\"You can claim your daily cash <t:{int(eta)}:R>\"\n            )\n            return\n\n        guild = db[\"guilds\"]\n        guild_data = await CachedDB.find_one(guild, {\"id\": context.guild.id})\n\n        if not guild_data:\n            guild_data = CONSTANTS.guild_data_template(context.guild.id)\n            guild.insert_one(guild_data)\n\n        data[\"wallet\"] += guild_data[\"daily_cash\"]\n        newdata = {\n            \"$set\": {\"wallet\": data[\"wallet\"], \"last_daily\": time.time()}\n        }\n\n        await CachedDB.update_one(c, {\"id\": context.author.id, \"guild_id\": context.guild.id}, newdata)\n\n        await context.send(f\"Added {guild_data['daily_cash']}$ to wallet\")\n\n    @commands.hybrid_command(\n        name=\"beg\",\n        description=\"Beg for money\",\n        usage=\"beg\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @commands.cooldown(1, 600, commands.BucketType.user)\n    async def beg(self, context: Context) -> None:\n        c = db[\"users\"]\n        data = await CachedDB.find_one(c, {\"id\": context.author.id, \"guild_id\": context.guild.id})\n\n        if not data:\n            data = CONSTANTS.user_data_template(context.author.id, context.guild.id)\n            c.insert_one(data)\n\n        amount = random.randint(5, 200)\n        data[\"wallet\"] += amount\n\n        newdata = {\n            \"$set\": {\"wallet\": data[\"wallet\"]}\n        }\n\n        await CachedDB.update_one(c, {\"id\": context.author.id, \"guild_id\": context.guild.id}, newdata)\n\n        await context.send(f\"Someone gave you {amount}$!\")\n\n    @commands.hybrid_command(\n        name=\"rob\",\n        description=\"Rob someone's wallet\",\n        usage=\"rob <user>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @commands.cooldown(1, 3600, commands.BucketType.user)\n    async def rob(self, context: Context, user: discord.Member) -> None:\n        if user == context.author:\n            await context.send(\"You can't rob yourself\")\n            return\n\n        c = db[\"users\"]\n\n        target_data = await CachedDB.find_one(c, {\"id\": user.id, \"guild_id\": context.guild.id})\n\n        if not target_data:\n            return await context.send(\"User has no money\")\n\n        if target_data[\"wallet\"] == 0:\n            return await context.send(\"User has no money\")\n\n        author_data = await CachedDB.find_one(c, {\"id\": context.author.id, \"guild_id\": context.guild.id})\n\n        if not author_data:\n            author_data = CONSTANTS.user_data_template(context.author.id, context.guild.id)\n            c.insert_one(author_data)\n\n        max_payout = target_data[\"wallet\"] // 5\n\n        if target_data[\"last_robbed_at\"] > time.time() - 10800:\n            eta = target_data[\"last_robbed_at\"] + 10800\n            await context.send(\n                f\"This user can be robbed again <t:{int(eta)}:R>\"\n            )\n            return\n\n        result = random.randint(0, 2)\n        if result == 0:\n            payout = random.randint(1, max_payout)\n            author_data[\"wallet\"] += payout\n            target_data[\"wallet\"] -= payout\n\n            newdata = {\n                \"$set\": {\n                    \"wallet\": author_data[\"wallet\"],\n                }\n            }\n\n            newdata2 = {\n                \"$set\": {\n                    \"wallet\": target_data[\"wallet\"],\n                    \"last_robbed_at\": time.time()\n                }\n            }\n\n            await CachedDB.update_one(c, {\"id\": context.author.id, \"guild_id\": context.guild.id}, newdata)\n            await CachedDB.update_one(c, {\"id\": user.id, \"guild_id\": context.guild.id}, newdata2)\n\n            await context.send(f\"You successfully robbed {user} and got {payout}$\")\n        elif result == 1:\n            payout = min(random.randint(1, max_payout//2), author_data[\"wallet\"]//3, 10000)\n            author_data[\"wallet\"] -= payout\n            target_data[\"wallet\"] += payout\n\n            newdata = {\n                \"$set\": {\n                    \"wallet\": author_data[\"wallet\"],\n                }\n            }\n\n            newdata2 = {\n                \"$set\": {\"wallet\": target_data[\"wallet\"], \"last_robbed_at\": time.time()}\n            }\n\n            await CachedDB.update_one(c, {\"id\": context.author.id, \"guild_id\": context.guild.id}, newdata)\n            await CachedDB.update_one(c, {\"id\": user.id, \"guild_id\": context.guild.id}, newdata2)\n\n            await context.send(f\"You got caught by {user} and they took {payout}$\")\n        else:\n            await context.send(f\"You failed to rob {user}, but lost nothing\")\n\n    @commands.hybrid_command(\n        name=\"baltop\",\n        description=\"See the top 10 richest users\",\n        usage=\"baltop\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    async def baltop(self, context: Context) -> None:\n        c = db[\"users\"]\n        data = c.find({\"guild_id\": context.guild.id}).sort(\"wallet\", -1).limit(10)\n\n        embed = discord.Embed(\n            title=\"Top Balances\",\n            description=\"\",\n            color=discord.Color.gold(),\n        )\n\n        i = 1\n        for _, user in enumerate(data, start=1):\n            member = context.guild.get_member(user[\"id\"])\n            if member != None:\n                if member.bot:\n                    continue\n                embed.add_field(\n                    name=f\"{i}. {member.nick if member.nick else member.display_name if member.display_name else member.name}\",\n                    value=f\"${user['wallet']}\",\n                    inline=False,\n                )\n                i += 1\n\n        await context.send(embed=embed)\n\n    @commands.hybrid_command(\n        name=\"pay\",\n        description=\"Pay someone from your wallet\",\n        usage=\"pay <user> <amount>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    async def pay(self, context: Context, user: discord.Member, amount: int) -> None:\n        if amount < 0:\n            await context.send(\"You can't pay a negative amount\")\n            return\n\n        if user == context.author:\n            await context.send(\"You can't pay yourself\")\n            return\n\n        c = db[\"users\"]\n        data = await CachedDB.find_one(c, {\"id\": context.author.id, \"guild_id\": context.guild.id})\n\n        if not data:\n            data = CONSTANTS.user_data_template(context.author.id, context.guild.id)\n            c.insert_one(data)\n        if data[\"wallet\"] < amount:\n            await context.send(\"You don't have enough money\")\n            return\n\n        target_user_data = c.find_one({\"id\": user.id, \"guild_id\": context.guild.id})\n        if not target_user_data:\n            target_user_data = CONSTANTS.user_data_template(user.id, context.guild.id)\n\n            c.insert_one(target_user_data)\n        data[\"wallet\"] -= amount\n        target_user_data[\"wallet\"] += amount\n        newdata = {\n            \"$set\": {\"wallet\": data[\"wallet\"]}\n        }\n        newdata2 = {\n            \"$set\": {\"wallet\": target_user_data[\"wallet\"]}\n        }\n\n        await CachedDB.update_one(c, {\"id\": context.author.id, \"guild_id\": context.guild.id}, newdata)\n        await CachedDB.update_one(c, {\"id\": user.id, \"guild_id\": context.guild.id}, newdata2)\n\n        await context.send(f\"Paid {amount}$ to {user.mention}\")\n\n    @commands.hybrid_command(\n        name=\"set\",\n        description=\"Set someones wallet (admin only)\",\n        usage=\"set <user> <amount>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @commands.has_permissions(manage_messages=True)\n    async def set(self, context: Context, user: discord.Member, amount: int) -> None:\n        c = db[\"users\"]\n\n        target_user_data = await CachedDB.find_one(c, {\"id\": user.id, \"guild_id\": context.guild.id})\n\n        if not target_user_data:\n            target_user_data = CONSTANTS.user_data_template(context.author.id, context.guild.id)\n\n            c.insert_one(target_user_data)\n\n        newdata = {\n            \"$set\": {\"wallet\": amount}\n        }\n\n        await CachedDB.update_one(c, {\"id\": user.id, \"guild_id\": context.guild.id}, newdata)\n\n        await context.send(f\"Set {user.mention}'s wallet to {amount}$\")\n\n    @commands.hybrid_command(\n        name=\"gamble\",\n        description=\"Gamble your money\",\n        usage=\"gamble <amount>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    async def gamble(self, context: Context, amount: int) -> None:\n        if amount < 0:\n            await context.send(\"You can't gamble a negative amount\")\n            return\n\n        c = db[\"users\"]\n        data = await CachedDB.find_one(c, {\"id\": context.author.id, \"guild_id\": context.guild.id})\n\n        if not data:\n            data = CONSTANTS.user_data_template(context.author.id, context.guild.id)\n            c.insert_one(data)\n        if data[\"wallet\"] < amount:\n            await context.send(\"You don't have enough money\")\n            return\n\n        if amount < 1:\n            await context.send(\"You can't gamble less than 1$\")\n            return\n\n        await context.send(\n            \"How would you like to gamble?\",\n            view=GamblingButton(amount, context.author.id),\n        )\n\n    @commands.hybrid_command(\n        name=\"stockmarket\",\n        description=\"Gamble your money(but like irl but like fake fr)\",\n        usage=\"stockmarket\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    async def stockmarket(self, context: Context) -> None:\n        await start_paper_trading(context)\n\n    # TODO: MORE CACHING AFTER THIS POINT\n\n    @commands.hybrid_command(\n        name=\"farm\",\n        description=\"Farm some potatoes\",\n        usage=\"farm\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    async def farm(self, context: Context) -> None:\n\n        c = db[\"users\"]\n        data = await CachedDB.find_one(c, {\"id\": context.author.id, \"guild_id\": context.guild.id})\n\n        if not data:\n            data = CONSTANTS.user_data_template(context.author.id, context.guild.id)\n            c.insert_one(data)\n\n        if not \"farm\" in data:\n            data[\"farm\"] = {\n                \"saplings\": 0,\n                \"crops\": 0,\n                \"harvestable\": 0,\n                \"ready_in\": 0\n            }\n            newdata = {\n                \"$set\": {\"farm\": data[\"farm\"]}\n            }\n            c.update_one(\n                {\"id\": context.author.id, \"guild_id\": context.guild.id}, newdata\n            )\n\n        farmData = data[\"farm\"]\n\n        if farmData[\"ready_in\"] < time.time():\n            farmData[\"harvestable\"] += farmData[\"crops\"]\n            farmData[\"crops\"] = 0\n\n        embed = discord.Embed(\n            title=\"Farm\",\n            description=\"Buy saplings to farm potatoes\",\n            color=0x77dd77,\n        )\n\n        embed.add_field(\n            name=\"Saplings\",\n            value=farmData[\"saplings\"],\n            inline=False,\n        )\n\n        embed.add_field(\n            name=\"Crops\",\n            value=farmData[\"crops\"],\n            inline=False,\n        )\n\n        embed.add_field(\n            name=\"Harvestable\",\n            value=farmData[\"harvestable\"],\n            inline=False,\n        )\n\n        embed.add_field(\n            name=\"Ready\",\n            value=f\"<t:{int(farmData['ready_in'])}:R>\",\n            inline=False,\n        )\n\n        embed.set_footer(text=f\"Wallet: ${data['wallet']}\")\n\n        await context.send(embed=embed, view=FarmButton(context.author.id))\n\n        new_data = {\n            \"$set\": {\"farm\": farmData}\n        }\n        c.update_one(\n            {\"id\": context.author.id, \"guild_id\": context.guild.id}, new_data\n        )\n\nasync def setup(bot) -> None:\n    await bot.add_cog(Economy(bot))\n"
  },
  {
    "path": "cogs/fun.py",
    "content": "# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon\n\nimport random\nimport discord\nimport os\nimport aiohttp\nimport json\nimport requests\nimport io\nfrom PIL import Image\n\nfrom io import BytesIO\nfrom discord.ui import Button, View\n\nfrom discord import app_commands\nfrom discord.ext import commands\nfrom discord.ext.commands import Context\n\nfrom utils import Checks\n\nTENOR_API_KEY = os.getenv(\"TENOR_API_KEY\")\n\nclass TicTacToeButton(Button):\n    def __init__(self, x: int, y: int, player_x: discord.Member, player_o: discord.Member):\n        super().__init__(style=discord.ButtonStyle.secondary, label=\"\\u200b\", row=y)\n        self.x = x\n        self.y = y\n        self.player_x = player_x\n        self.player_o = player_o\n\n    async def callback(self, interaction: discord.Interaction):\n        view: TicTacToeView = self.view\n        if interaction.user != view.current_player:\n            await interaction.response.send_message(\"It's not your turn!\", ephemeral=True)\n            return\n\n        if self.label == \"\\u200b\":\n            self.label = \"X\" if view.current_player == self.player_x else \"O\"\n            self.style = discord.ButtonStyle.danger if view.current_player == self.player_x else discord.ButtonStyle.primary\n            self.disabled = True\n\n            view.board[self.x][self.y] = 1 if view.current_player == self.player_x else -1\n            view.current_player = self.player_o if view.current_player == self.player_x else self.player_x\n\n            await interaction.response.edit_message(content=f\"{view.current_player.mention}, your turn.\", view=view)\n\n            winner = view.check_winner()\n            if winner:\n                await interaction.followup.send(f\"{winner.mention} wins!\", ephemeral=False)\n                view.stop()\n            elif all(cell != 0 for row in view.board for cell in row):\n                await interaction.followup.send(\"It's a tie!\", ephemeral=False)\n                view.stop()\n        else:\n            await interaction.response.send_message(\"This button is already clicked!\", ephemeral=True)\n\nclass TicTacToeView(View):\n    def __init__(self, player_x: discord.Member, player_o: discord.Member):\n        super().__init__(timeout=None)\n        self.player_x = player_x\n        self.player_o = player_o\n        self.current_player = player_x\n        self.board = [[0 for _ in range(3)] for _ in range(3)]\n\n        for x in range(3):\n            for y in range(3):\n                self.add_item(TicTacToeButton(x, y, player_x, player_o))\n\n    def check_winner(self):\n        for row in self.board:\n            if sum(row) == 3:\n                return self.player_x\n            elif sum(row) == -3:\n                return self.player_o\n\n        for col in range(3):\n            if self.board[0][col] + self.board[1][col] + self.board[2][col] == 3:\n                return self.player_x\n            elif self.board[0][col] + self.board[1][col] + self.board[2][col] == -3:\n                return self.player_o\n\n        if self.board[0][0] + self.board[1][1] + self.board[2][2] == 3:\n            return self.player_x\n        elif self.board[0][0] + self.board[1][1] + self.board[2][2] == -3:\n            return self.player_o\n\n        if self.board[0][2] + self.board[1][1] + self.board[2][0] == 3:\n            return self.player_x\n        elif self.board[0][2] + self.board[1][1] + self.board[2][0] == -3:\n            return self.player_o\n\n        return None\n\nclass Fun(commands.Cog, name=\"🎉 Fun\"):\n    def __init__(self, bot) -> None:\n        self.bot = bot\n\n    @commands.command(\n        name=\"joos\",\n        description=\"joos\",\n        usage=\"joos\",\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    async def joos(self, context: Context) -> None:\n        await context.send(\"<:joos:1254878760218529873>\")\n\n    @commands.hybrid_group(\n        name=\"http\",\n        description=\"Commands for http cat/dog/fish images.\",\n        usage=\"http <subcommand>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @app_commands.allowed_installs(guilds=True, users=True)\n    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)\n    async def http(self, context: Context) -> None:\n        prefix = await self.bot.get_prefix(context)\n\n        cmds = \"\\n\".join([f\"{prefix}http {cmd.name} - {cmd.description}\" for cmd in self.http.walk_commands()])\n\n        embed = discord.Embed(\n            title=f\"Help: Http\", description=\"List of available commands:\", color=0xBEBEFE\n        )\n        embed.add_field(\n            name=\"Commands\", value=f\"```{cmds}```\", inline=False\n        )\n\n        await context.send(embed=embed)\n\n    @http.command(\n        name=\"cat\",\n        description=\"Get a cat image representing a http status code.\",\n        usage=\"http cat <code>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    async def http_cat(self, context: Context, code) -> None:\n        await context.send(f\"https://http.cat/{code}.jpg\")\n\n    @http.command(\n        name=\"dog\",\n        description=\"Get a dog image representing a http status code.\",\n        usage=\"http dog <code>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    async def http_dog(self, context: Context, code) -> None:\n        await context.send(f\"https://http.dog/{code}.jpg\")\n\n    @http.command(\n        name=\"fish\",\n        description=\"Get a fish image representing a http status code.\",\n        usage=\"http fish <code>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    async def http_fish(self, context: Context, code) -> None:\n        await context.send(f\"https://http.fish/{code}.jpg\")\n\n    @http.command(\n        name=\"goat\",\n        description=\"Get a goat image representing a http status code.\",\n        usage=\"http goat <code>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    async def http_goat(self, context: Context, code) -> None:\n        await context.send(f\"https://httpgoats.com/{code}.jpg\")\n\n    @commands.hybrid_command( # TODO: fix this crap\n        name=\"bored\",\n        description=\"Get an activity if you are bored\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @app_commands.allowed_installs(guilds=True, users=True)\n    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)\n    async def bored(self, context: Context) -> None:\n        async with aiohttp.ClientSession() as session:\n            url=\"https://bored-api.appbrewery.com/random\"\n\n            async with session.get(url) as r:\n                if r.status == 200:\n                    data = await r.json()\n\n                    embed = discord.Embed()\n\n                    if \"error\" in data:\n                        embed = discord.Embed(title=data[\"error\"], color=discord.Color.brand_red())\n                    else:\n                        embed = discord.Embed(title=data[\"activity\"], color=discord.Color.teal())\n\n                        embed.add_field(name = \"Type\", value = data[\"type\"].capitalize())\n                        embed.add_field(name = \"Participants\", value = data[\"participants\"])\n                        embed.add_field(name = \"Price\", value = data[\"price\"])\n\n                    await context.send(embed=embed)\n                elif r.status == 404:\n                    embed = discord.Embed(title=\"No activities found\", color=discord.Color.brand_red())\n\n                    await context.send(embed=embed)\n                else:\n                    await context.send(f\"BoredAPI is currently experiencing issues: Status \" + str(r.status))\n\n    @commands.hybrid_command(\n        name=\"advice\",\n        description=\"Get some advice\",\n        usage=\"advice\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @app_commands.allowed_installs(guilds=True, users=True)\n    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)\n    async def advice(self, context: Context) -> None:\n        async with aiohttp.ClientSession() as session:\n            r = requests.get(\"https://api.adviceslip.com/advice\")\n            data = json.loads(r.text)\n\n            await context.send(data[\"slip\"][\"advice\"])\n\n    @commands.hybrid_command(\n        name=\"insult\",\n        description=\"Get an insult\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @app_commands.allowed_installs(guilds=True, users=True)\n    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)\n    async def insult(self, context: Context) -> None:\n        async with aiohttp.ClientSession() as session:\n            async with session.get(f\"https://evilinsult.com/generate_insult.php?lang=en&type=json\") as r:\n                if r.status == 200:\n                    data = await r.json()\n\n                    await context.send(data[\"insult\"])\n\n    @commands.hybrid_command(\n        name=\"gif\",\n        description=\"Get a random gif, unless query is specified\",\n        usage=\"gif [optional: query]\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @app_commands.allowed_installs(guilds=True, users=True)\n    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)\n    async def gif(self, context: Context, *, query=\"NONE\") -> None:\n        rand = False\n        if query == \"NONE\":\n            query = random.choice(\n                [\n                    \"bored\",\n                    \"exited\",\n                    \"happy\",\n                    \"sad\",\n                    \"angry\",\n                    \"confused\",\n                    \"crying\",\n                    \"cat\",\n                    \"dog\",\n                    \"slap\",\n                    \"animal\",\n                    \"building\",\n                    \"car\",\n                    \"technology\",\n                    \"random\",\n                    \"plane\"\n                ]\n            )\n            rand = True\n\n        async with aiohttp.ClientSession() as session:\n            data = await session.get(\n                f\"https://tenor.googleapis.com/v2/search?random={rand}&q={query}&key=\" + TENOR_API_KEY\n            )\n\n            data = await data.json()\n\n            img = await session.get(\n                data[\"results\"][0][\"media_formats\"][\"gif\"][\"url\"]\n            )\n\n            imageData = io.BytesIO(await img.read())\n            await context.send(file=discord.File(imageData, \"gif.gif\"))\n\n    @commands.hybrid_group(\n        name=\"avatar\",\n        description=\"Commands for avatar manipulation\",\n        aliases=[\"av\", \"pfp\"],\n        usage=\"avatar <subcommand>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @app_commands.allowed_installs(guilds=True, users=True)\n    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)\n    async def avatar(self, context: Context) -> None:\n        prefix = await self.bot.get_prefix(context)\n\n        cmds = \"\\n\".join([f\"{prefix}avatar {cmd.name} - {cmd.description}\" for cmd in self.avatar.walk_commands()])\n\n        embed = discord.Embed(\n            title=f\"Help: Avatar\", description=\"List of available commands:\", color=0xBEBEFE\n        )\n        embed.add_field(\n            name=\"Commands\", value=f\"```{cmds}```\", inline=False\n        )\n\n        await context.send(embed=embed)\n\n    @avatar.command(\n        name=\"get\",\n        description=\"Get someone's avatar\",\n        usage=\"avatar get [optional: user]\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    async def get(self, context: Context, user: discord.User = None) -> None:\n        if not user:\n            user = context.author\n\n        embed = discord.Embed(\n            title=f\"{user.name}'s Avatar\",\n            color=discord.Color.blurple()\n        )\n\n        embed.set_image(url=user.display_avatar.url)\n\n        await context.send(embed=embed)\n\n    @avatar.command(\n        name=\"blur\",\n        description=\"Blur someone\",\n        usage=\"avatar blur [optional: user]\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    async def blur(self, context: Context, user: discord.User = None) -> None:\n        if not user:\n            user = context.author\n\n        async with aiohttp.ClientSession() as session:\n            img = await session.get(\n                f\"https://some-random-api.com/canvas/misc/blur?avatar={user.display_avatar.url}\"\n            )\n\n            imageData = io.BytesIO(await img.read())\n            await context.send(file=discord.File(imageData, \"blur.png\"))\n\n    @avatar.command(\n        name=\"pixelate\",\n        description=\"Pixelate someone\",\n        usage=\"avatar pixelate [optional: user]\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    async def pixelate(self, context: Context, user: discord.User = None) -> None:\n        if not user:\n            user = context.author\n\n        async with aiohttp.ClientSession() as session:\n            img = await session.get(\n                f\"https://some-random-api.com/canvas/misc/pixelate?avatar={user.display_avatar.url}\"\n            )\n\n            imageData = io.BytesIO(await img.read())\n            await context.send(file=discord.File(imageData, \"pixelate.png\"))\n\n    @avatar.command(\n        name=\"trigger\",\n        description=\"Trigger someone\",\n        usage=\"avatar trigger [optional: user]\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    async def trigger(self, context: Context, user: discord.User = None) -> None:\n        if not user:\n            user = context.author\n\n        async with aiohttp.ClientSession() as session:\n            img = await session.get(\n                f\"https://some-random-api.com/canvas/overlay/triggered?avatar={user.display_avatar.url}\"\n            )\n\n            imageData = io.BytesIO(await img.read())\n            await context.send(file=discord.File(imageData, \"triggered.gif\"))\n\n    @avatar.command(\n        name=\"jail\",\n        description=\"Put someone in jail\",\n        usage=\"avatar jail [optional: user]\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    async def jail(self, context: Context, user: discord.User = None) -> None:\n        if not user:\n            user = context.author\n\n        async with aiohttp.ClientSession() as session:\n            img = await session.get(\n                f\"https://some-random-api.com/canvas/overlay/jail?avatar={user.display_avatar.url}\"\n            )\n\n            imageData = io.BytesIO(await img.read())\n            await context.send(file=discord.File(imageData, \"jail.png\"))\n\n    @avatar.command(\n        name=\"wasted\",\n        description=\"Wasted\",\n        usage=\"avatar wasted [optional: user]\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    async def wasted(self, context: Context, user: discord.User = None) -> None:\n        if not user:\n            user = context.author\n\n        async with aiohttp.ClientSession() as session:\n            img = await session.get(\n                f\"https://some-random-api.com/canvas/overlay/wasted?avatar={user.display_avatar.url}\"\n            )\n\n            imageData = io.BytesIO(await img.read())\n            await context.send(file=discord.File(imageData, \"wasted.png\"))\n\n    @avatar.command(\n        name=\"passed\",\n        description=\"Passed\",\n        usage=\"avatar passed [optional: user]\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    async def passed(self, context: Context, user: discord.User = None) -> None:\n        if not user:\n            user = context.author\n\n        async with aiohttp.ClientSession() as session:\n            img = await session.get(\n                f\"https://some-random-api.com/canvas/overlay/passed?avatar={user.display_avatar.url}\"\n            )\n\n            imageData = io.BytesIO(await img.read())\n            await context.send(file=discord.File(imageData, \"passed.png\"))\n\n    @avatar.command(\n        name=\"trans\",\n        description=\"Trans border around pfp\",\n        usage=\"avatar trans [optional: user]\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    async def trans(self, context: Context, user: discord.User = None) -> None:\n        if not user:\n            user = context.author\n\n        async with aiohttp.ClientSession() as session:\n            img = await session.get(\n                f\"https://some-random-api.com/canvas/misc/transgender?avatar={user.display_avatar.url}\"\n            )\n\n            imageData = io.BytesIO(await img.read())\n            await context.send(file=discord.File(imageData, \"transgender.png\"))\n\n    @commands.hybrid_group(\n        name=\"random\",\n        description=\"Commands for random stuff\",\n        usage=\"random <subcommand>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @app_commands.allowed_installs(guilds=True, users=True)\n    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)\n    async def random(self, context: Context) -> None:\n        prefix = await self.bot.get_prefix(context)\n\n        cmds = \"\\n\".join([f\"{prefix}random {cmd.name} - {cmd.description}\" for cmd in self.random.walk_commands()])\n\n        embed = discord.Embed(\n            title=f\"Help: Random\", description=\"List of available commands:\", color=0xBEBEFE\n        )\n        embed.add_field(\n            name=\"Commands\", value=f\"```{cmds}```\", inline=False\n        )\n\n        await context.send(embed=embed)\n\n    @random.command(\n        name=\"boykisser\",\n        description=\"Get a random boykisser image\",\n        usage=\"boykisser\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @app_commands.allowed_installs(guilds=True, users=True)\n    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)\n    async def boykisser(self, context: Context) -> None:\n        async with aiohttp.ClientSession() as session:\n            data = await session.get(\n                \"https://api.gizzy.is-a.dev/api/random?redirect=0\"\n            )\n\n            data = await data.json()\n\n            await context.send(data['url'])\n\n    @random.command(\n        name=\"gayrate\",\n        description=\"Get your gay rate\",\n        usage=\"random gayrate <user>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @app_commands.allowed_installs(guilds=True, users=True)\n    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)\n    async def gayrate(self, context: Context, user: discord.User = None) -> None:\n        if not user:\n            user = context.author\n\n        percentage = random.randint(0, 100)\n        emojis = [\"😳\", \"😳\", \"😳\", \"😳\", \"😳\", \"😳\", \"😳\", \"😳\", \"😳\", \"😳\", \"🏳️‍🌈\", \"🔥\"]\n\n        if percentage > 90:\n            emoji = \"🌈\"\n        elif percentage < 10:\n            emoji = \"🔥\"\n        else:\n            emoji = random.choice(emojis)\n\n        await context.send(f\"**{user}** is {percentage}% gay {emoji}\")\n\n\n    @random.command(\n        name=\"coffee\",\n        description=\"Get a random coffee image\",\n        usage=\"random coffee\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @app_commands.allowed_installs(guilds=True, users=True)\n    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)\n    async def random_cat(self, context: Context) -> None:\n        async with aiohttp.ClientSession() as session:\n\n            img = await session.get(\n                \"https://coffee.alexflipnote.dev/random\"\n            )\n\n            imageData = io.BytesIO(await img.read())\n            await context.send(file=discord.File(imageData, \"coffee.png\"))\n\n    @random.command(\n        name=\"cat\",\n        description=\"Get a random cat image\",\n        usage=\"random cat\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @app_commands.allowed_installs(guilds=True, users=True)\n    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)\n    async def random_cat(self, context: Context) -> None:\n\n        async with aiohttp.ClientSession() as session:\n            data = await session.get(\n                \"https://some-random-api.com/animal/cat\"\n            )\n\n            data = await data.json()\n\n            await context.send(data[\"image\"])\n\n    @random.command(\n        name=\"dog\",\n        description=\"Get a random dog image\",\n        usage=\"random dog\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @app_commands.allowed_installs(guilds=True, users=True)\n    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)\n    async def random_dog(self, context: Context) -> None:\n        async with aiohttp.ClientSession() as session:\n            data = await session.get(\n                \"https://some-random-api.com/animal/dog\"\n            )\n\n            data = await data.json()\n\n            await context.send(data[\"image\"])\n\n    @random.command(\n        name=\"bird\",\n        description=\"Get a random bird image\",\n        usage=\"random bird\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @app_commands.allowed_installs(guilds=True, users=True)\n    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)\n    async def random_bird(self, context: Context) -> None:\n\n        async with aiohttp.ClientSession() as session:\n            data = await session.get(\n                \"https://some-random-api.com/animal/bird\"\n            )\n\n            data = await data.json()\n\n            await context.send(data[\"image\"])\n\n    @random.command(\n        name=\"fox\",\n        description=\"Get a random fox image\",\n        usage=\"random fox\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @app_commands.allowed_installs(guilds=True, users=True)\n    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)\n    async def random_fox(self, context: Context) -> None:\n\n        async with aiohttp.ClientSession() as session:\n            data = await session.get(\n                \"https://some-random-api.com/animal/fox\"\n            )\n\n            data = await data.json()\n\n            await context.send(data[\"image\"])\n\n    @random.command(\n        name=\"kangaroo\",\n        description=\"Get a random kangaroo image\",\n        usage=\"random kangaroo\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @app_commands.allowed_installs(guilds=True, users=True)\n    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)\n    async def random_kangaroo(self, context: Context) -> None:\n        async with aiohttp.ClientSession() as session:\n            data = await session.get(\n                \"https://some-random-api.com/animal/kangaroo\"\n            )\n\n            data = await data.json()\n\n            await context.send(data[\"image\"])\n\n    @random.command(\n        name=\"koala\",\n        description=\"Get a random koala image\",\n        usage=\"random koala\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @app_commands.allowed_installs(guilds=True, users=True)\n    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)\n    async def random_koala(self, context: Context) -> None:\n        async with aiohttp.ClientSession() as session:\n            data = await session.get(\n                \"https://some-random-api.com/animal/koala\"\n            )\n\n            data = await data.json()\n\n            await context.send(data[\"image\"])\n\n    @random.command(\n        name=\"panda\",\n        description=\"Get a random panda image\",\n        usage=\"random panda\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @app_commands.allowed_installs(guilds=True, users=True)\n    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)\n    async def random_panda(self, context: Context) -> None:\n\n        async with aiohttp.ClientSession() as session:\n            data = await session.get(\n                \"https://some-random-api.com/animal/panda\"\n            )\n\n            data = await data.json()\n\n            await context.send(data[\"image\"])\n\n    @random.command(\n        name=\"raccoon\",\n        description=\"Get a random raccoon image\",\n        usage=\"random raccoon\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @app_commands.allowed_installs(guilds=True, users=True)\n    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)\n    async def random_raccoon(self, context: Context) -> None:\n\n        async with aiohttp.ClientSession() as session:\n            data = await session.get(\n                \"https://some-random-api.com/animal/raccoon\"\n            )\n\n            data = await data.json()\n\n            await context.send(data[\"image\"])\n\n    @random.command(\n        name=\"red-panda\",\n        description=\"Get a random raccoon image\",\n        usage=\"random red-panda\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @app_commands.allowed_installs(guilds=True, users=True)\n    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)\n    async def random_red_panda(self, context: Context) -> None:\n\n        async with aiohttp.ClientSession() as session:\n            data = await session.get(\n                \"https://some-random-api.com/animal/red_panda\"\n            )\n\n            data = await data.json()\n\n            await context.send(data[\"image\"])\n\n    @commands.hybrid_group(\n        name=\"img\",\n        description=\"Commands for image creation\",\n        usage=\"img <subcommand>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @app_commands.allowed_installs(guilds=True, users=True)\n    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)\n    async def image(self, context: Context) -> None:\n        prefix = await self.bot.get_prefix(context)\n\n        cmds = \"\\n\".join([f\"{prefix}image {cmd.name} - {cmd.description}\" for cmd in self.image.walk_commands()])\n\n        embed = discord.Embed(\n            title=f\"Help: Image\", description=\"List of available commands:\", color=0xBEBEFE\n        )\n        embed.add_field(\n            name=\"Commands\", value=f\"```{cmds}```\", inline=False\n        )\n\n        await context.send(embed=embed)\n\n    @image.command(\n        name=\"youtube\",\n        description=\"Youtube comment\",\n        usage=\"image youtube <user> <text>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    async def youtube(self, context: Context, user: discord.User, *, text: str) -> None:\n        if not user:\n            user = context.author\n\n        async with aiohttp.ClientSession() as session:\n            img = await session.get(\n                f\"https://some-random-api.com/canvas/misc/youtube-comment?avatar={user.display_avatar.url}&username={user.display_name}&comment={text}\"\n            )\n\n            imageData = io.BytesIO(await img.read())\n            await context.send(file=discord.File(imageData, \"youtube.png\"))\n\n    @image.command(\n        name=\"tweet\",\n        description=\"Tweet\",\n        usage=\"image tweet <user> <text>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    async def tweet(self, context: Context, user: discord.User, *, tweet: str) -> None:\n        async with aiohttp.ClientSession() as session:\n            nick = user.nick if hasattr(user, 'nick') else user.display_name\n            if nick == None:\n                nick = user.display_name\n\n            img = await session.get(\n                f\"https://some-random-api.com/canvas/misc/tweet?avatar={user.display_avatar.url}&username={user.global_name if not user.bot else user.display_name}&displayname={nick}&comment={tweet}&replies=-1\"\n            )\n\n            imageData = io.BytesIO(await img.read())\n            await context.send(file=discord.File(imageData, \"tweet.png\"))\n\n    @commands.hybrid_command(\n        name=\"ttt\",\n        aliases=[\"tictactoe\"],\n        description=\"Play a game of Tic-Tac-Toe\",\n        usage=\"ttt <opponent>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @app_commands.allowed_installs(guilds=True, users=True)\n    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)\n    async def tictactoe(self, context: Context, opponent: discord.User) -> None:\n        \"\"\"Start a game of Tic-Tac-Toe with the specified opponent.\"\"\"\n\n        if opponent == context.author:\n            await context.send(\"You cannot play against yourself!\")\n            return\n\n        if opponent.bot:\n            await context.send(\"You cannot play against bots!\")\n            return\n\n        await context.send(f\"{context.author.mention} vs {opponent.mention}!\", view=TicTacToeView(context.author, opponent))\n\n    @commands.hybrid_command(\n        name=\"togif\",\n        description=\"Convert an uploaded image (PNG/JPG) into a GIF\",\n        usage=\"togif [upload image]\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @app_commands.allowed_installs(guilds=True, users=True)\n    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)\n    async def togif(self, context: Context, attachment: discord.Attachment) -> None:\n        if not attachment.content_type or not attachment.content_type.startswith(\"image\"):\n            await context.send(\"Please upload a valid image file!\")\n            return\n\n        if attachment.size > 20 * 1024 * 1024:\n            await context.send(\"The image is too large! Please upload a file smaller than 20MB.\")\n            return\n\n        async with context.typing():\n            image_bytes = await attachment.read()\n            img_input = io.BytesIO(image_bytes)\n            \n            try:\n                with Image.open(img_input) as img:\n                    if img.mode in (\"RGBA\", \"P\"):\n                        img = img.convert(\"RGB\")\n                    \n                    output_buffer = io.BytesIO()\n                    img.save(output_buffer, format=\"GIF\")\n                    output_buffer.seek(0)\n                    \n                    await context.send(\n                        file=discord.File(fp=output_buffer, filename=\"converted.gif\")\n                    )\n            except Exception as e:\n                self.bot.logger.error(f\"Error in togif command: {e}\")\n                await context.send(\"Failed to convert image to GIF. Ensure the file is a valid image.\")\n\nasync def setup(bot) -> None:\n    await bot.add_cog(Fun(bot))\n"
  },
  {
    "path": "cogs/general.py",
    "content": "# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon\n\nimport random\nimport os\nimport aiohttp\nimport time\nimport asyncpraw\nimport inspect\nimport json\nimport sys\n\nimport logging\nlogger = logging.getLogger(\"discord_bot\")\n\nimport discord\nfrom discord import app_commands\nfrom discord.ext import commands\nfrom discord.ext.commands import Context\n\nfrom utils import DBClient, Checks\nfrom ui import translate\n\ndb = DBClient.db\n\nreddit = asyncpraw.Reddit(\n    client_id=os.getenv(\"REDDIT_CLIENT_ID\"),\n    client_secret=os.getenv(\"REDDIT_CLIENT_SECRET\"),\n    user_agent=\"PotatoBot\",\n)\n\nif not os.path.isfile(f\"./config.json\"):\n    sys.exit(\"'config.json' not found! Please add it and try again.\")\nelse:\n    with open(f\"./config.json\") as file:\n        config = json.load(file)\n\nclass General(commands.Cog, name=\"⬜ General\"):\n    def __init__(self, bot) -> None:\n        self.bot = bot\n        self.context_menu_message = app_commands.ContextMenu(\n            name=\"Remove spoilers\", callback=self.ctx_remove_spoilers\n        )\n        self.context_menu_message = app_commands.ContextMenu(\n            name=\"Translate\",\n            callback=self.ctx_translate,\n            allowed_contexts=app_commands.AppCommandContext(guild=True, dm_channel=True, private_channel=True),\n            allowed_installs=app_commands.AppInstallationType(guild=True, user=True)\n        )\n        self.bot.tree.add_command(self.context_menu_message)\n        self.get_prefix = bot.get_prefix\n\n    # Message context menu command\n    async def ctx_remove_spoilers(\n        self, interaction: discord.Interaction, message: discord.Message\n    ) -> None:\n        spoiler_attachment = None\n        for attachment in message.attachments:\n            if attachment.is_spoiler():\n                spoiler_attachment = attachment\n                break\n        embed = discord.Embed(\n            title=\"Message without spoilers\",\n            description=message.content.replace(\"||\", \"\"),\n            color=0xBEBEFE,\n        )\n        if spoiler_attachment is not None:\n            embed.set_image(url=attachment.url)\n        await interaction.response.send_message(embed=embed, ephemeral=True)\n\n    async def ctx_translate(\n        self, interaction: discord.Interaction, message: discord.Message\n    ) -> None:\n        if message.content:\n            await interaction.response.send_modal(translate.TranslateModal(message))\n        else:\n            await interaction.response.send_message(\"No text to translate\", ephemeral=True)\n\n    @commands.hybrid_command(\n        name=\"help\",\n        aliases=[\"h\", \"commands\", \"cmds\"],\n        description=\"Get help with commands\",\n        usage=\"help [optional: command]\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @app_commands.allowed_installs(guilds=True, users=True)\n    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)\n    async def help(self, context: Context, *, command: str = \"none\") -> None:\n        if command != \"none\":\n            cmd = self.bot.get_command(command)\n            if cmd is None:\n                await context.send(\"Command not found\")\n                return\n\n            if cmd.cog_name == \"owner\" and not context.author.id in self.bot.owner_ids:\n                await context.send(\"Command not found\")\n                return\n\n            embed = discord.Embed(\n                title=f\"Command: {cmd.name}\",\n                description=cmd.description,\n                color=0xBEBEFE\n            )\n\n            usage = cmd.usage if cmd.usage else \"Not Found\"\n            example = cmd.extras[\"example\"] if \"example\" in cmd.extras else \"Not Found\"\n            embed.add_field(\n                name=\"Usage\",\n                value=f\"```Syntax: {usage}\\nExample: {example}```\",\n                inline=False\n            )\n\n            aliases = \", \".join(cmd.aliases) if cmd.aliases else \"None\"\n            embed.add_field(\n                name=\"Aliases\",\n                value=f\"```{aliases}```\",\n                inline=True\n            )\n\n            embed.add_field(\n                name=\"Category\",\n                value=f\"```{cmd.cog_name}```\",\n                inline=True\n            )\n\n            cmd_type = \"\"\n\n            if isinstance(cmd, commands.HybridGroup):\n                cmd_type = \"Command Group\"\n            elif isinstance(cmd, commands.HybridCommand):\n                cmd_type = \"Chat+Slash Command\"\n            elif isinstance(cmd, commands.Command):\n                cmd_type = \"Chat Only Command\"\n\n\n            embed.add_field(\n                name=\"Type\",\n                value=f\"```{cmd_type}```\",\n                inline=True\n            )\n\n            params = inspect.signature(cmd.callback).parameters\n            param_list = []\n            for name, param in params.items():\n                if name not in [\"self\", \"context\"]:\n                    if param.default == inspect.Parameter.empty:\n                        param_list.append(f\"{name}: <Required>\")\n                    else:\n                        param_list.append(f\"{name}: [Optional, default: '{param.default}']\")\n\n            params_str = \"\\n\".join(param_list) if param_list else \"None\"\n            embed.add_field(\n                name=\"Parameters\",\n                value=f\"```{params_str}```\",\n                inline=False\n            )\n\n            if isinstance(cmd, commands.HybridGroup):\n                    subcommands = \", \".join([sub.name for sub in cmd.commands])\n                    embed.add_field(\n                        name=\"Subcommands\",\n                        value=f\"```{subcommands}```\",\n                        inline=False\n                    )\n\n            return await context.send(embed=embed)\n\n        cogs = []\n\n        for cog in self.bot.cogs:\n            if cog.startswith(\"-\"):\n                continue\n\n            if \"owner\" in cog and context.author.id != int(os.getenv(\"OWNER_ID\")):\n                continue\n\n            if \"staff\" in cog:\n                author_permissions = context.author.guild_permissions\n\n            cogs.append(cog)\n\n        view = CogSelectView(cogs, context.author)\n\n        await context.send('Pick a cog:', view=view)\n\n    @commands.command(\n        name=\"uptime\",\n        description=\"Get the bot's uptime\",\n        usage=\"uptime\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    async def uptime(self, context: Context):\n        uptime = time.time() - self.bot.start_time\n        str = time.strftime(\"%H:%M:%S\", time.gmtime(uptime))\n        await context.send(\"Uptime: \" + str)\n\n    @commands.hybrid_command(\n        name=\"botinfo\",\n        description=\"See bot info\",\n        usage=\"botinfo\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @app_commands.allowed_installs(guilds=True, users=True)\n    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)\n    async def botinfo(self, context: Context) -> None:\n        dpyVersion = discord.__version__\n        serverCount = len(self.bot.guilds)\n        memberCount = len(set(self.bot.get_all_members()))\n\n        shard_id = context.guild.shard_id if context.guild else None\n        shard = self.bot.get_shard(shard_id) if shard_id is not None else self.bot.shards[0]\n        shard_ping = shard.latency\n        shard_servers = len([guild for guild in self.bot.guilds if guild.shard_id == shard_id])\n        shard_count = len(self.bot.shards)\n\n        embed = discord.Embed(title=f'{self.bot.user.name} - Stats', color = discord.Color.blurple())\n\n        command_count = len([command for command in self.bot.walk_commands()])\n\n        embed.add_field(name=\"Bot Version:\", value=self.bot.version)\n        embed.add_field(name=\"Discord.Py Version:\", value=dpyVersion)\n        embed.add_field(name=\"Ping:\", value=f\"{round(self.bot.latency * 1000)}ms\")\n        embed.add_field(name=\"Total Guilds:\", value=serverCount)\n        embed.add_field(name=\"Total Users:\", value=memberCount)\n        embed.add_field(name=\"Total Commands:\", value=command_count)\n        embed.add_field(name=\"Shard ID:\", value=shard_id)\n        embed.add_field(name=\"Shard Ping:\", value=f\"{round(shard_ping * 1000)}ms\")\n        embed.add_field(name=\"Shard Servers:\", value=shard_servers)\n        embed.add_field(name=\"Shard Count:\", value=shard_count)\n\n        embed.set_footer(text=\"Bot made by Cyteon @ https://github.com/cyteon\")\n        await context.send(embed=embed)\n\n    @commands.hybrid_command(\n        name=\"ping\",\n        description=\"Check if the bot is alive.\",\n        usage=\"ping\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @app_commands.allowed_installs(guilds=True, users=True)\n    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)\n    async def ping(self, context: Context) -> None:\n        embed = discord.Embed(\n            title=\"🏓 Pong!\",\n            description=f\"The bot latency is {round(self.bot.latency * 1000)}ms.\",\n            color=0xBEBEFE,\n        )\n        await context.send(embed=embed)\n\n    @commands.hybrid_command(\n        name=\"bug\",\n        description=\"Send a bug report\",\n        usage=\"bug <bug>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @app_commands.allowed_installs(guilds=True, users=True)\n    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)\n    @commands.cooldown(5, 3600, commands.BucketType.user)\n    async def bug(self, context: Context, *, bug: str) -> None:\n        id = int(config[\"bug_channel\"])\n        channel = self.bot.get_channel(id)\n        embed = discord.Embed(\n        \ttitle=\"Bug Report\",\n            description=bug,\n            color=0xFF0000\n        )\n\n        embed.set_footer(text=f\"By {context.author} ({context.author.id}) in {context.guild if context.guild else 'DM'} ({context.guild.id if context.guild else 'DM'})\")\n\n        await channel.send(embed=embed)\n        await context.send(\"Bug Reported\")\n\n    @commands.hybrid_command(\n        name=\"8ball\",\n        description=\"Ask any question to the bot.\",\n        usage=\"8ball <question>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @app_commands.describe(question=\"The question you want to ask.\")\n    @app_commands.allowed_installs(guilds=True, users=True)\n    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)\n    async def eight_ball(self, context: Context, *, question: str) -> None:\n        answers = [\n            \"It is certain.\",\n            \"It is decidedly so.\",\n            \"You may rely on it.\",\n            \"Without a doubt.\",\n            \"As I see, yes.\",\n            \"Most likely.\",\n            \"Outlook good.\",\n            \"Yes.\",\n            \"Signs point to yes.\",\n            \"Reply hazy, try again.\",\n            \"Ask again later.\",\n            \"Better not tell you now.\",\n            \"Concentrate and ask again later.\",\n            \"Don't count on it.\",\n            \"My reply is no.\",\n            \"My sources say no.\",\n            \"Outlook not so good.\",\n            \"Very doubtful.\",\n            \"Potato\"\n        ]\n        embed = discord.Embed(\n            title=\"**My Answer:**\",\n            description=f\"{random.choice(answers)}\",\n            color=0xBEBEFE,\n        )\n        embed.set_footer(text=f\"The question was: {question}\")\n        await context.send(embed=embed)\n\n    @commands.command(\n        name=\"support\",\n        description=\"Support Server.\",\n        usage=\"support\"\n    )\n    @commands.check(Checks.command_not_disabled)\n    async def support(self, context: commands.Context) -> None:\n        message = await context.send(\"https://discord.gg/wtur9j8uVP\")\n\n    @commands.hybrid_command(\n        name=\"define\",\n        description=\"Get the definition of a word.\",\n        usage=\"define <word>\",\n        aliases=[\"dictionary\", \"dict\", \"word\"]\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @app_commands.allowed_installs(guilds=True, users=True)\n    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)\n    async def define(self, context: Context, *, word: str) -> None:\n        async with aiohttp.ClientSession() as session:\n            async with session.get(f\"https://api.dictionaryapi.dev/api/v2/entries/en/{word}\") as response:\n                if response.status != 200:\n                    return await context.send(\"No results found.\")\n\n                data = await response.json()\n                data = data[0]\n\n                embed = discord.Embed(title=f\"Definition of {data['word']}\", description=data.get(\"phonetic\", \"N/A\"), color=0xBEBEFE)\n\n                def truncate_text(text, limit=1024):\n                    if len(text) > limit:\n                        return text[:limit-3] + \"...\"\n                    return text\n\n                definitions = \"\\n\".join(f\"{i+1}. {definition['definition']}\" for i, meaning in enumerate(data[\"meanings\"]) for definition in meaning[\"definitions\"])\n\n                synonyms = \", \".join(synonym for meaning in data[\"meanings\"] for synonym in meaning.get(\"synonyms\", []))\n                antonyms = \", \".join(antonym for meaning in data[\"meanings\"] for antonym in meaning.get(\"antonyms\", []))\n\n                embed.add_field(name=\"Definition(s)\", value=truncate_text(definitions), inline=False)\n                embed.add_field(name=\"Synonym(s)\", value=truncate_text(synonyms) if synonyms else \"None\", inline=False)\n                embed.add_field(name=\"Antonym(s)\", value=truncate_text(antonyms) if antonyms else \"None\", inline=False)\n\n                await context.send(embed=embed)\n\n    @commands.hybrid_command(\n        name=\"urban-dictionary\",\n        description=\"Get the definition of a word from Urban Dictionary.\",\n        usage=\"urban-dictionary <word>\",\n        aliases=[\"urban\", \"ud\"]\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @app_commands.allowed_installs(guilds=True, users=True)\n    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)\n    async def urban_dict(self, context: Context, *, term: str):\n        async with aiohttp.ClientSession() as session:\n            async with session.get(f\"https://api.urbandictionary.com/v0/define?term={term}\") as response:\n                data = await response.json()\n\n                if not data[\"list\"]:\n                    return await context.send(\"No results found.\")\n\n                definition = data[\"list\"][0][\"definition\"]\n\n                embed = discord.Embed(\n                    title=f\"Definition of {term}\",\n                    description=definition,\n                    color=0xBEBEFE\n                )\n\n                await context.send(embed=embed)\n\n    @commands.hybrid_command(\n        name=\"reddit\",\n        description=\"Returns a random post from reddit, or from a subreddit\",\n        usage=\"reddit [optional: subreddit]\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @app_commands.allowed_installs(guilds=True, users=True)\n    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)\n    async def reddit(self, context: Context, subreddit: str = \"\") -> None:\n        if subreddit == \"\":\n            subreddit = await reddit.subreddit(\"random\")\n        else:\n            subreddit = await reddit.subreddit(subreddit)\n\n        #check if NSFW\n        loaded_sub = subreddit\n        await loaded_sub.load()\n\n        if hasattr(context.channel, \"over18\"):\n            if loaded_sub.over18 and not context.channel.is_nsfw() and not context.channel.id == context.author.id:\n                await context.send(\"This subreddit is NSFW, please use this command in a NSFW channel or dms.\")\n                return\n\n        posts = []\n        async for post in subreddit.hot(limit=25):\n            posts.append(post)\n\n        random_post = None\n\n        if len(posts) == 0:\n            return await context.send(\"No posts found\")\n\n        while True:\n            if len(posts) == 0:\n                await context.send(\"No posts that are not NSFW found, try again or run command in an NSFW channel or dms.\")\n                return\n\n            random_post = random.choice(posts)\n            posts.remove(random_post)\n\n            loaded_post = random_post\n            await loaded_post.load()\n\n            if not context.guild:\n                if loaded_post.over_18 and not context.channel.is_nsfw() and not context.channel.id == context.author.id:\n                    continue\n\n            if loaded_post.stickied:\n                continue\n\n            break\n\n        logger.info(f\"Reddit post: {random_post.url}\")\n\n        title = random_post.title\n        url = random_post.url\n        author = random_post.author\n\n        embed = discord.Embed(\n            title=title,\n            description=random_post.selftext,\n            url=url,\n            color=0xBEBEFE,\n        )\n\n        if random_post.url.endswith(('.jpg', '.jpeg', '.png', '.gif')):\n            embed.set_image(url=random_post.url)\n\n        await context.send(embed=embed)\n\n    @commands.hybrid_command(\n        name=\"vote\",\n        description=\"Vote for the bot on top.gg\",\n        usage=\"vote\"\n    )\n    @commands.check(Checks.command_not_disabled)\n    @app_commands.allowed_installs(guilds=True, users=True)\n    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)\n    async def vote(self, context: Context):\n        embed = discord.Embed(\n            title=\"Vote on top.gg\",\n            description=\"Help out the bot by voting now!\",\n            url=\"https://top.gg/bot/1226487228914602005/vote\",\n            color=0xBEBEFE\n        )\n\n        await context.send(embed=embed, view=VoteView())\n\nclass VoteButton(discord.ui.Button):\n    def __init__(self):\n        super().__init__(style=discord.ButtonStyle.link, label=\"Vote on top.gg\", url=\"https://top.gg/bot/1226487228914602005/vote\")\n\n    async def callback(self, interaction: discord.Interaction):\n        await interaction.response.send_message(\"Thank you for voting!\", ephemeral=True)\n\nclass VoteView(discord.ui.View):\n    def __init__(self):\n        super().__init__(timeout=None)\n        self.add_item(VoteButton())\n\nclass CogSelect(discord.ui.Select):\n    def __init__(self, cogs, author):\n        options = [\n            discord.SelectOption(label=cog, description=f\"Show commands for {cog}\")\n            for cog in cogs\n        ]\n        super().__init__(placeholder='Choose a cog...', min_values=1, max_values=1, options=options)\n        self.author = author\n\n    async def callback(self, interaction: discord.Interaction):\n        if interaction.user != self.author:\n            await interaction.response.send_message(\"You cannot use this select.\", ephemeral=True)\n            return\n\n        await interaction.response.defer()\n\n        cog_name = self.values[0]\n        cog = interaction.client.get_cog(cog_name)\n        commands = cog.get_commands()\n        data = []\n        for command in commands:\n            description = command.description.partition(\"\\n\")[0]\n            data.append(f\"{await interaction.client.get_prefix(interaction)}{command.name} - {description}\")\n        help_text = \"\\n\".join(data)\n        embed = discord.Embed(\n            title=f\"Help: {cog_name}\", description=\"List of available commands:\", color=0xBEBEFE\n        )\n        embed.add_field(\n            name=cog_name.capitalize(), value=f\"```{help_text}```\", inline=False\n        )\n        embed.set_footer(text=f\"To get more info on a command, use {await interaction.client.get_prefix(interaction)}help <command>\")\n\n        await interaction.message.edit(embed=embed)\n\nclass CogSelectView(discord.ui.View):\n    def __init__(self, cogs, author):\n        super().__init__(timeout=None)\n        self.add_item(CogSelect(cogs, author))\n\nasync def setup(bot) -> None:\n    await bot.add_cog(General(bot))\n    bot.add_view(VoteView())\n"
  },
  {
    "path": "cogs/github.py",
    "content": "\"\"\"\nThe MIT License (MIT)\n\nCopyright (c) 2022 Ogiroid Development Team\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the \"Software\"),\nto deal in the Software without restriction, including without limitation\nthe rights to use, copy, modify, merge, publish, distribute, sublicense,\nand/or sell copies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\"\"\"\n\n\nimport aiohttp\nimport discord\nfrom discord import app_commands\nfrom discord.ext import commands\nfrom discord.ext.commands import Context\n\nfrom utils import Checks\n\n\nclass Github(commands.Cog, name=\"🖧 Github\"):\n    def __init__(self, bot) -> None:\n        self.bot = bot\n\n    @commands.hybrid_group(\n        name=\"github\",\n        description=\"Commands related to GitHub\",\n        usage=\"github <subcommand> [args]\",\n        aliases=[\"gh\"],\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @app_commands.allowed_installs(guilds=True, users=True)\n    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)\n    async def github(self, context: Context) -> None:\n        prefix = await self.bot.get_prefix(context)\n\n        cmds = \"\\n\".join([f\"{prefix}github {cmd.name} - {cmd.description}\" for cmd in self.github.walk_commands()])\n\n        embed = discord.Embed(\n            title=f\"Help: Github\", description=\"List of available commands:\", color=0xBEBEFE\n        )\n        embed.add_field(\n            name=\"Commands\", value=f\"```{cmds}```\", inline=False\n        )\n\n        await context.send(embed=embed)\n\n    # Command to get information about a GitHub user\n    @github.command(\n        name=\"user\",\n        description=\"Gets the Profile of the github person.\",\n        usage=\"github user <username>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    async def ghuser(self, context, user: str):\n        async with aiohttp.ClientSession() as session:\n            person_raw = await session.get(\n                f\"https://api.github.com/users/{user}\"\n            )\n            if person_raw.status != 200:\n                return await context.send(\"User not found!\")\n            else:\n                person = await person_raw.json()\n            # Returning an Embed containing all the information:\n            embed = discord.Embed(\n                title=f\"GitHub Profile: {person['login']}\",\n                description=f\"**Bio:** {person['bio']}\",\n                color=0xFFFFFF,\n            )\n            embed.set_thumbnail(url=f\"{person['avatar_url']}\")\n            embed.add_field(\n                name=\"Username 📛: \", value=f\"{person['name']}\", inline=True\n            )\n            # embed.add_field(name=\"Email ✉: \", value=f\"{person['email']}\", inline=True) Commented due to GitHub not responding with the correct email\n            embed.add_field(\n                name=\"Repos 📁: \", value=f\"{person['public_repos']}\", inline=True\n            )\n            embed.add_field(\n                name=\"Location 📍: \", value=f\"{person['location']}\", inline=True\n            )\n            embed.add_field(\n                name=\"Company 🏢: \", value=f\"{person['company']}\", inline=True\n            )\n            embed.add_field(\n                name=\"Followers 👥: \", value=f\"{person['followers']}\", inline=True\n            )\n            embed.add_field(\n                name=\"Website 🖥️: \", value=f\"{person['blog']}\", inline=True\n            )\n\n            await context.send(embed=embed, view=ProfileButton(url=person[\"html_url\"]))\n\n    # Command to get search for GitHub repositories:\n    @github.command(\n        name=\"repo\",\n        description=\"Searches for the specified repo.\",\n        usage=\"github repo <repo>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    async def ghsearchrepo(self, context, query: str):\n        pages = 1\n        url = f\"https://api.github.com/search/repositories?q={query}&{pages}\"\n        async with aiohttp.ClientSession() as session:\n            repos_raw = await session.get(url)\n            if repos_raw.status != 200:\n                return await context.send(\"Repo not found!\")\n            else:\n                repos = (\n                    await repos_raw.json()\n                )  # Getting first repository from the query\n            repo = repos[\"items\"][0]\n            # Returning an Embed containing all the information:\n            embed = discord.Embed(\n                title=f\"GitHub Repository: {repo['name']}\",\n                description=f\"**Description:** {repo['description']}\",\n                color=0xFFFFFF,\n            )\n            embed.set_thumbnail(url=f\"{repo['owner']['avatar_url']}\")\n            embed.add_field(\n                name=\"Author 🖊:\",\n                value=f\"__[{repo['owner']['login']}]({repo['owner']['html_url']})__\",\n                inline=True,\n            )\n            embed.add_field(\n                name=\"Stars ⭐:\", value=f\"{repo['stargazers_count']}\", inline=True\n            )\n            embed.add_field(\n                name=\"Forks 🍴:\", value=f\"{repo['forks_count']}\", inline=True\n            )\n            embed.add_field(\n                name=\"Language 💻:\", value=f\"{repo['language']}\", inline=True\n            )\n            embed.add_field(\n                name=\"Size 🗃️:\",\n                value=f\"{round(repo['size'] / 1000, 2)} MB\",\n                inline=True,\n            )\n            if repo[\"license\"]:\n                spdx_id = repo[\"license\"][\"spdx_id\"]\n                embed.add_field(\n                    name=\"License name 📃:\",\n                    value=f\"{spdx_id if spdx_id != 'NOASSERTION' else repo['license']['name']}\",\n                    inline=True,\n                )\n            else:\n                embed.add_field(\n                    name=\"License name 📃:\",\n                    value=\"This Repo doesn't have a license\",\n                    inline=True,\n                )\n\n            await context.send(embed=embed, view=RepoButton(url=repo[\"html_url\"]))\n\nclass ProfileButton(discord.ui.View):\n    def __init__(self, url: str):\n        super().__init__()\n\n        self.add_item(discord.ui.Button(label=\"GitHub Profile\", style=discord.ButtonStyle.url, url=url))\n\nclass RepoButton(discord.ui.View):\n    def __init__(self, url: str):\n        super().__init__()\n\n        self.add_item(discord.ui.Button(label=\"GitHub Repository\", style=discord.ButtonStyle.url, url=url))\n\nasync def setup(bot) -> None:\n    await bot.add_cog(Github(bot))\n"
  },
  {
    "path": "cogs/giveaway.py",
    "content": "# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon\n\nimport discord\nimport random\n\nfrom discord.ext import commands\nfrom discord.ext.commands import Context\n\nfrom utils import Checks\n\nclass Giveaway(commands.Cog, name=\"🎁 Giveaway\"):\n    def __init__(self, bot) -> None:\n        self.bot = bot\n\n    @commands.hybrid_group(\n        name=\"giveaway\",\n        description=\"Command to start or end giveaways\",\n        usage=\"giveaway\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @commands.has_permissions(manage_messages=True)\n    async def giveaway(self, context: Context) -> None:\n        prefix = await self.bot.get_prefix(context)\n\n        cmds = \"\\n\".join([f\"{prefix}giveaway {cmd.name} - {cmd.description}\" for cmd in self.giveaway.walk_commands()])\n\n        embed = discord.Embed(\n            title=f\"Help: Giveaway\", description=\"List of available commands:\", color=0xBEBEFE\n        )\n        embed.add_field(\n            name=\"Commands\", value=f\"```{cmds}```\", inline=False\n        )\n\n        await context.send(embed=embed)\n\n    @giveaway.command(\n        name=\"start\",\n        description=\"Start a giveaway!\",\n        usage=\"giveaway start <reward>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @commands.has_permissions(manage_messages=True)\n    async def giveaway_start(self, context: Context, *, reward: str) -> None:\n        embed = discord.Embed(title=\"Giveaway!\", description=reward, color=0xBEBEFE)\n\n        message = await context.send(embed=embed)\n\n        await message.add_reaction(\"🎁\")\n\n    @giveaway.command(\n        name = \"end\",\n        description = \"Ends a poll using message id\",\n        usage = \"giveaway end <message_id>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @commands.has_permissions(manage_messages=True)\n    async def giveaway_end(self, context: Context, message_id) -> None:\n        message_id = int(message_id)\n\n        message = await context.fetch_message(message_id)\n\n        users = []\n\n        async for u in message.reactions[0].users():\n            users.append(u)\n\n        users.pop(users.index(self.bot.user))\n        winner = random.choice(users)\n\n        embed = discord.Embed(title=\"Giveaway ended!\", description=\"The winner is: {0} 🎉🎉🎉\".format(winner.mention), color=0xBEBEFE)\n\n        await message.reply(winner.mention, embed=embed)\n\nasync def setup(bot) -> None:\n    await bot.add_cog(Giveaway(bot))\n"
  },
  {
    "path": "cogs/level.py",
    "content": "# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon\n\nimport random\nimport pymongo\n\nimport discord\nfrom discord.ext import commands\nfrom discord.ext.commands import Context\n\nfrom easy_pil import *\n\nfrom utils import CONSTANTS, DBClient, Checks, CachedDB\n\ndb = DBClient.db\n\nclass Level(commands.Cog, name=\"🚀 Level\"):\n    def __init__(self, bot) -> None:\n        self.bot = bot\n\n    @commands.hybrid_command(\n        name=\"level\",\n        description=\"See yours or someone elses current level and xp\",\n        usage=\"level [optional: user]\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @commands.cooldown(3, 10, commands.BucketType.user)\n    async def level(self, context: Context, user: discord.Member = None) -> None:\n        if not user:\n            user = context.author\n\n        c = db[\"users\"]\n        data = await CachedDB.find_one(c, {\"id\": user.id, \"guild_id\": context.guild.id})\n\n        if data:\n            xp_for_next_level = CONSTANTS.LEVELS_AND_XP[data[\"level\"] + 1]\n\n            percentage = round(data[\"xp\"] / xp_for_next_level * 100, 1)\n\n            background = Editor(Canvas((900, 300), color=\"#141414\"))\n            profile_picture = await load_image_async(str(user.avatar.url))\n            profile = Editor(profile_picture).resize((150, 150)).circle_image()\n\n            poppins = Font.poppins(size=40)\n            poppins_small = Font.poppins(size=30)\n\n            card_right_shape = [(600, 0), (750, 300), (900, 300), (900, 0)]\n\n            background.polygon(card_right_shape, color=\"#FFFFFF\")\n            background.paste(profile, (30, 30))\n\n            background.rectangle((30, 220), width=650, height=40, color=\"#FFFFFF\", radius=20)\n            background.bar((30, 220), max_width=650, height=40, percentage=percentage, color=\"orange\", radius=20)\n            background.text((200, 40), user.name, font=poppins, color=\"#FFFFFF\")\n\n            background.rectangle((200, 100), width=350, height=2, fill=\"#FFFFFF\")\n            background.text((200, 130), f\"Level {data['level']} - {data['xp']}/{xp_for_next_level} XP\", font=poppins_small, color=\"#FFFFFF\")\n\n            file = discord.File(fp=background.image_bytes, filename=\"level_card.png\")\n            await context.send(file=file)\n\n        else:\n            await context.send(\"Start chatting to gain a level\")\n\n    @commands.hybrid_command(\n        name=\"leaderboard\",\n        description=\"See the top 10 users with the most xp in this server\",\n        aliases=[\"lb\"],\n        usage=\"leaderboard\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @commands.cooldown(1, 10, commands.BucketType.user)\n    async def leaderboard(self, context: Context) -> None:\n        c = db[\"users\"]\n        data = c.find({\"guild_id\": context.guild.id}).sort([(\"level\", pymongo.DESCENDING), (\"xp\", pymongo.DESCENDING)]).limit(10)\n\n        embed = discord.Embed(\n            title=\"Leaderboard\",\n            description=\"\",\n            color=discord.Color.gold()\n        )\n\n        for index, user in enumerate(data, start=1):\n            member = context.guild.get_member(user[\"id\"])\n\n            if member != None:\n                if not member.bot:\n                    embed.add_field(\n                        name=f\"{index}. {member.nick if member.nick else member.display_name if member.display_name else member.name}\",\n                        value=f\"Level: {user['level']} - XP: {user['xp']}\",\n                        inline=False\n                    )\n            else:\n                fetched = await self.bot.fetch_user(user[\"id\"])\n\n                if fetched == None:\n                    embed.add_field(\n                        name=f\"{index}. Unknown User\",\n                        value=f\"Level: {user['level']} - XP: {user['xp']}\",\n                        inline=False\n                    )\n\n                if not fetched.bot:\n                    embed.add_field(\n                        name=f\"{index}. {fetched.name}\",\n                        value=f\"Level: {user['level']} - XP: {user['xp']}\",\n                        inline=False\n                    )\n\n        await context.send(embed=embed)\n\n    @commands.Cog.listener()\n    async def on_message(self, message: discord.Message) -> None:\n        if message.guild == None:\n            return\n\n        if message.author == self.bot or message.author.bot:\n            return\n\n        author = message.author\n\n        c = db[\"users\"]\n        data = await CachedDB.find_one(c, {\"id\": author.id, \"guild_id\": message.guild.id})\n\n        if not data:\n            data = CONSTANTS.user_data_template(author.id, message.guild.id)\n            c.insert_one(data)\n\n        if data[\"level\"] >= CONSTANTS.MAX_LEVEL:\n            return\n\n        if data[\"xp\"] >= CONSTANTS.MAX_XP:\n            return\n\n        data[\"xp\"] += random.randint(1, 3)\n\n        if data[\"xp\"] >= CONSTANTS.LEVELS_AND_XP[data[\"level\"] + 1]:\n            guilds = db[\"guilds\"]\n            guild_data = await CachedDB.find_one(guilds, {\"id\": message.guild.id})\n\n            if not guild_data:\n                guild_data = CONSTANTS.guild_data_template(message.guild.id)\n                guilds.insert_one(guild_data)\n\n            data[\"level\"] += 1\n            data[\"xp\"] = 0\n\n            if str(data[\"level\"]) in guild_data[\"level_roles\"]:\n                role = message.guild.get_role(guild_data[\"level_roles\"][str(data[\"level\"])])\n                await message.author.add_roles(role)\n\n            channel = message.channel\n            if guild_data:\n                if \"level_announce_channel\" in guild_data:\n                    if guild_data[\"level_announce_channel\"] != 0:\n                        channel = message.guild.get_channel(guild_data[\"level_announce_channel\"])\n\n                if \"should_announce_levelup\" in guild_data:\n                    if guild_data[\"should_announce_levelup\"]:\n                        await channel.send(f\"{author.mention} leveled up to level {data['level']}!\")\n                else:\n                    await channel.send(f\"{author.mention} leveled up to level {data['level']}!\")\n\n        newdata = {\"$set\": {\"xp\": data[\"xp\"], \"level\": data[\"level\"]}}\n\n        await CachedDB.update_one(c, {\"id\": author.id, \"guild_id\": message.guild.id}, newdata)\n\n    @commands.hybrid_command(\n        name=\"create-level-roles\",\n        description=\"Create roles for levels (manage_roles permission)\",\n        usage=\"create-level-roles\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @commands.has_permissions(manage_roles=True)\n    async def create_level_roles(self, context: Context):\n        # create role for level 1/3/5/10/15/20\n\n        guilds = db[\"guilds\"]\n        guild_data = await CachedDB.find_one(guilds, {\"id\": context.guild.id})\n\n        if not guild_data:\n            guild_data = CONSTANTS.guild_data_template(context.guild.id)\n            guilds.insert_one(guild_data)\n\n        for level in [1, 3, 5, 10, 15, 20]:\n            if str(level) not in guild_data[\"level_roles\"]:\n                role = await context.guild.create_role(name=f\"Level {level}\")\n                guild_data[\"level_roles\"][str(level)] = role.id\n\n        newdata = {\"$set\": {\"level_roles\": guild_data[\"level_roles\"]}}\n\n        await CachedDB.update_one(guilds, {\"id\": context.guild.id}, newdata)\n        await context.send(\"Roles created!\")\n\n    @commands.hybrid_command(\n        name=\"delete-level-roles\",\n        description=\"Delete roles for levels\",\n        usage=\"delete-level-roles\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @commands.has_permissions(manage_roles=True)\n    async def delete_level_roles(self, context: Context):\n        guilds = db[\"guilds\"]\n        guild_data = await CachedDB.find_one(guilds, {\"id\": context.guild.id})\n\n        if not guild_data:\n            guild_data = CONSTANTS.guild_data_template(context.guild.id)\n            guilds.insert_one(guild_data)\n\n        for level in guild_data[\"level_roles\"]:\n            role = context.guild.get_role(guild_data[\"level_roles\"][level])\n            if role:\n                try:\n                    await role.delete()\n                except:\n                    pass\n\n        newdata = {\"$set\": {\"level_roles\": {}}}\n\n        await CachedDB.update_one(guilds, {\"id\": context.guild.id}, newdata)\n        await context.send(\"Roles deleted!\")\n\nasync def setup(bot) -> None:\n    await bot.add_cog(Level(bot))\n"
  },
  {
    "path": "cogs/music.py",
    "content": "# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon\n\nimport re\nimport os\nimport logging\n\nimport discord\nimport lavalink\nfrom discord.ext import commands\nfrom discord.ext.commands import Context\nfrom lavalink.events import TrackStartEvent, QueueEndEvent\nfrom lavalink.errors import ClientError\nfrom lavalink.filters import LowPass, Timescale\nfrom lavalink.server import LoadType\n\nurl_rx = re.compile(r'https?://(?:www\\.)?.+')\n\nfrom utils import Checks\n\nlogger = logging.getLogger(\"discord_bot\")\n\n\nhost = os.getenv(\"LAVALINK_HOST\")\nport = os.getenv(\"LAVALINK_PORT\")\npassword = os.getenv(\"LAVALINK_PASSWORD\")\nregion = os.getenv(\"LAVALINK_REGION\")\nname = os.getenv(\"LAVALINK_NAME\")\n\nclass LavalinkVoiceClient(discord.VoiceProtocol):\n    def __init__(self, client: discord.Client, channel: discord.abc.Connectable):\n        self.client = client\n        self.channel = channel\n        self.guild_id = channel.guild.id\n        self._destroyed = False\n\n        if not hasattr(self.client, 'lavalink'):\n            self.client.lavalink = lavalink.Client(client.user.id)\n            self.client.lavalink.add_node(host=host, port=port, password=password,\n                                          region=region, name=name)\n\n        self.lavalink = self.client.lavalink\n\n    async def on_voice_server_update(self, data):\n        lavalink_data = {\n            't': 'VOICE_SERVER_UPDATE',\n            'd': data\n        }\n        await self.lavalink.voice_update_handler(lavalink_data)\n\n    async def on_voice_state_update(self, data):\n        channel_id = data['channel_id']\n\n        if not channel_id:\n            await self._destroy()\n            return\n\n        self.channel = self.client.get_channel(int(channel_id))\n\n        lavalink_data = {\n            't': 'VOICE_STATE_UPDATE',\n            'd': data\n        }\n\n        await self.lavalink.voice_update_handler(lavalink_data)\n\n    async def connect(self, *, timeout: float, reconnect: bool, self_deaf: bool = False, self_mute: bool = False) -> None:\n        self.lavalink.player_manager.create(guild_id=self.channel.guild.id)\n        await self.channel.guild.change_voice_state(channel=self.channel, self_mute=self_mute, self_deaf=self_deaf)\n\n    async def disconnect(self, *, force: bool = False) -> None:\n        player = self.lavalink.player_manager.get(self.channel.guild.id)\n\n        if not force and not player.is_connected:\n            return\n\n        await self.channel.guild.change_voice_state(channel=None)\n        player.channel_id = None\n        await self._destroy()\n\n    async def _destroy(self):\n        self.cleanup()\n\n        if self._destroyed:\n            return\n\n        self._destroyed = True\n\n        try:\n            await self.lavalink.player_manager.destroy(self.guild_id)\n        except ClientError:\n            pass\n\n\nclass Music(commands.Cog, name=\"🎵 Music\"):\n    def __init__(self, bot):\n        self.bot = bot\n\n        if not hasattr(bot, 'lavalink'):\n            bot.lavalink = lavalink.Client(bot.user.id)\n            bot.lavalink.add_node(host=host, port=port, password=password,\n                                  region=region, name=name)\n\n        self.lavalink: lavalink.Client = bot.lavalink\n        self.lavalink.add_event_hooks(self)\n\n    def cog_unload(self):\n        self.lavalink._event_hooks.clear()\n\n    async def cog_command_error(self, context, error):\n        if isinstance(error, commands.CommandInvokeError):\n            await context.send(error.original)\n\n    async def create_player(context: commands.Context):\n        if context.guild is None:\n            raise commands.NoPrivateMessage()\n\n        player = context.bot.lavalink.player_manager.create(context.guild.id)\n\n        should_connect = context.command.name in ('play',)\n\n        voice_client = context.voice_client\n\n        if not context.author.voice or not context.author.voice.channel:\n            if voice_client is not None:\n                raise commands.CommandInvokeError('You need to join my voice channel first.')\n\n            raise commands.CommandInvokeError('Join a voicechannel first.')\n\n        voice_channel = context.author.voice.channel\n\n        if voice_client is None:\n            if not should_connect:\n                raise commands.CommandInvokeError(\"I'm not playing music.\")\n\n            permissions = voice_channel.permissions_for(context.me)\n\n            if not permissions.connect or not permissions.speak:\n                raise commands.CommandInvokeError('I need the `CONNECT` and `SPEAK` permissions.')\n\n            if voice_channel.user_limit > 0:\n                if len(voice_channel.members) >= voice_channel.user_limit and not context.me.guild_permissions.move_members:\n                    raise commands.CommandInvokeError('Your voice channel is full!')\n\n            player.store('channel', context.channel.id)\n            await context.author.voice.channel.connect(cls=LavalinkVoiceClient)\n        elif voice_client.channel.id != voice_channel.id:\n            raise commands.CommandInvokeError('You need to be in my voicechannel.')\n\n        return True\n\n    @lavalink.listener(TrackStartEvent)\n    async def on_track_start(self, event: TrackStartEvent):\n        guild_id = event.player.guild_id\n        channel_id = event.player.fetch('channel')\n        guild = self.bot.get_guild(guild_id)\n\n        if not guild:\n            return await self.lavalink.player_manager.destroy(guild_id)\n\n        channel = guild.get_channel(channel_id)\n\n        if channel:\n            await channel.send(f'Now playing: {event.track.title} by {event.track.author}')\n            logger.info(f\"Now playing {event.track.title} in {guild} ({guild.id})\")\n\n\n\n    @lavalink.listener(QueueEndEvent)\n    async def on_queue_end(self, event: QueueEndEvent):\n        guild_id = event.player.guild_id\n        guild = self.bot.get_guild(guild_id)\n\n        if guild is not None:\n            await guild.voice_client.disconnect(force=True)\n\n    @commands.hybrid_command(\n        name=\"play\",\n        description=\"Searches and plays a song from a given query.\",\n        aliases=['p'],\n        usage=\"play <query or link>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @commands.check(create_player)\n    async def play(self, context, *, query: str):\n        player = self.bot.lavalink.player_manager.get(context.guild.id)\n        query = query.strip('<>')\n\n        if not url_rx.match(query):\n            query = f'ytsearch:{query}'\n\n        results = await player.node.get_tracks(query)\n\n        embed = discord.Embed(color=discord.Color.blurple())\n\n        if results.load_type == LoadType.EMPTY:\n            return await context.send(\"I couldn't find any tracks for that query.\")\n        elif results.load_type == LoadType.PLAYLIST:\n            tracks = results.tracks\n\n            for track in tracks:\n                player.add(track=track, requester=context.author.id)\n\n            embed.title = 'Playlist Enqueued!'\n            embed.description = f'{results.playlist_info.name} - {len(tracks)} tracks'\n        else:\n            track = results.tracks[0]\n            embed.title = 'Track Enqueued'\n            embed.description = f'[{track.title}]({track.uri})'\n\n            player.add(track=track, requester=context.author.id)\n\n        await context.send(embed=embed)\n\n        if not player.is_playing:\n            await player.play()\n\n    @commands.hybrid_command(\n        name=\"skip\",\n        description=\"Skip to the next song in the queue\",\n        usage=\"skip\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @commands.check(create_player)\n    async def skip(self, context):\n        await self.bot.lavalink.player_manager.get(context.guild.id).skip()\n\n    @commands.hybrid_command(\n        name=\"pause\",\n        description=\"Pauses the currently playing track\",\n        usage=\"pause\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @commands.check(create_player)\n    async def pause(self, context):\n        player = self.bot.lavalink.player_manager.get(context.guild.id)\n\n        if player.is_playing:\n            await player.set_pause(True)\n            await context.send('⏸ | Paused the player.')\n\n    @commands.hybrid_command(\n        name=\"resume\",\n        description=\"Resumes the currently paused track\",\n        usage=\"resume\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @commands.check(create_player)\n    async def resume(self, context):\n        player = self.bot.lavalink.player_manager.get(context.guild.id)\n\n        if player.paused:\n            await player.set_pause(False)\n            await context.send('▶ | Resumed the player.')\n\n    @commands.hybrid_command(\n        name=\"loop\",\n        description=\"Enables/disables the loop on the current track\",\n        aliases=['repeat'],\n        usage=\"loop\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @commands.check(create_player)\n    async def loop(self, context):\n        player = self.bot.lavalink.player_manager.get(context.guild.id)\n        player.loop = not player.loop\n\n        await context.send(f\"🔁 | {'Enabled' if player.loop else 'Disabled'} loop.\")\n\n    @commands.hybrid_group(\n        name=\"filter\",\n        description=\"Commands for managing filters.\",\n        usage=\"filter <filter> <args>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    async def filter(self, context: Context) -> None:\n        prefix = await self.bot.get_prefix(context)\n\n        cmds = \"\\n\".join([f\"{prefix}filter {cmd.name} - {cmd.description}\" for cmd in self.filter.walk_commands()])\n\n        embed = discord.Embed(\n            title=f\"Help: Filter\", description=\"List of available commands:\", color=0xBEBEFE\n        )\n        embed.add_field(\n            name=\"Commands\", value=f\"```{cmds}```\", inline=False\n        )\n\n        await context.send(embed=embed)\n\n    @filter.command(\n        name=\"lowpass\",\n        description=\"Sets the strength of the low pass filter\",\n        usage=\"filer lowpass <strength>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @commands.check(create_player)\n    async def lowpass(self, context, strength: float = 0.0):\n        player = self.bot.lavalink.player_manager.get(context.guild.id)\n\n        strength = max(0, strength)\n        strength = min(1000, strength)\n\n        if strength < 1 and strength != 0.0:\n            return await context.send('The strength must be greater than 1.')\n\n        embed = discord.Embed(color=discord.Color.blurple(), title='Low Pass Filter')\n\n        if strength == 0.0:\n            await player.remove_filter('lowpass')\n            embed.description = 'Disabled **Low Pass Filter**'\n            return await context.send(embed=embed)\n\n        low_pass = LowPass()\n        low_pass.update(smoothing=strength)\n\n        await player.set_filter(low_pass)\n\n        embed.description = f'Set **Low Pass Filter** strength to {strength}.'\n        await context.send(embed=embed)\n\n\n    @filter.command(\n        name=\"pitch\",\n        description=\"Sets the player pitch\",\n        aliases=['ptch'],\n        usage=\"filter pitch <pitch>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @commands.check(create_player)\n    async def pitch(self, context: Context, pitch: float):\n        player = self.bot.lavalink.player_manager.get(context.guild.id)\n\n        pitch = max(0.1, pitch)\n\n        timescale = Timescale()\n        timescale.pitch = pitch\n        await player.set_filter(timescale)\n\n        await context.send(f\"🎵 | Set the player pitch to {pitch}.\")\n\n\n    @filter.command(\n        name=\"speed\",\n        description=\"Sets the player speed\",\n        aliases=['spd'],\n        usage=\"filter speed <speed>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @commands.check(create_player)\n    async def speed(self, context: Context, speed: float):\n        player = self.bot.lavalink.player_manager.get(context.guild.id)\n\n        speed = max(0.1, speed)\n\n        timescale = Timescale()\n        timescale.speed = speed\n        await player.set_filter(timescale)\n\n        await context.send(f\"🏃 | Set the player speed to {speed}.\")\n\n    @commands.hybrid_command(\n        name=\"disconnect\",\n        description=\"Disconnects the player from the voice channel and clears the queue\",\n        aliases=['dc', 'leave', 'stop'],\n        usage=\"disconnect\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @commands.check(create_player)\n    async def disconnect(self, context):\n        player = self.bot.lavalink.player_manager.get(context.guild.id)\n\n        player.queue.clear()\n        await player.stop()\n        await context.voice_client.disconnect(force=True)\n        await context.send('✳ | Disconnected.')\n\n    @commands.hybrid_command(\n        name=\"volume\",\n        description=\"Sets the player volume\",\n        aliases=['vol'],\n        usage=\"volume <volume>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @commands.check(create_player)\n    async def volume(self, context: Context, volume: int):\n        player = self.bot.lavalink.player_manager.get(context.guild.id)\n\n        volume = max(1, volume)\n        volume = min(100, volume)\n\n        await player.set_volume(volume)\n        await context.send(f\"🔊 | Set the player volume to {volume}.\")\n\n\nasync def setup(bot) -> None:\n    await bot.add_cog(Music(bot))\n"
  },
  {
    "path": "cogs/owner.py",
    "content": "# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon\n\nimport discord\nimport ast\nimport os\nimport sys\nimport pymongo\nfrom datetime import datetime\n\nfrom discord import app_commands\nfrom discord.ext import commands\nfrom discord.ext.commands import Context\n\nfrom utils import CONSTANTS, DBClient, Checks, CachedDB\n\nclient = DBClient.client\ndb = client.potatobot\n\ndef insert_returns(body):\n    # insert return stmt if the last expression is a expression statement\n    if isinstance(body[-1], ast.Expr):\n        body[-1] = ast.Return(body[-1].value)\n        ast.fix_missing_locations(body[-1])\n\n    # for if statements, we insert returns into the body and the orelse\n    if isinstance(body[-1], ast.If):\n        insert_returns(body[-1].body)\n        insert_returns(body[-1].orelse)\n\n    # for with blocks, again we insert returns into the body\n    if isinstance(body[-1], ast.With):\n        insert_returns(body[-1].body)\n\nclass Owner(commands.Cog, name=\"owner\"):\n    def __init__(self, bot) -> None:\n        self.bot = bot\n\n    @commands.hybrid_group(\n        name=\"dev\",\n        description=\"Commands for devs\",\n        usage=\"dev <subcommand> [args]\",\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @app_commands.allowed_installs(guilds=True, users=True)\n    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)\n    async def dev(self, context: Context) -> None:\n        prefix = await self.bot.get_prefix(context)\n\n        cmds = \"\\n\".join([f\"{prefix}dev {cmd.name} - {cmd.description}\" for cmd in self.dev.walk_commands()])\n\n        embed = discord.Embed(\n            title=f\"Help: Dev\", description=\"List of available commands:\", color=0xBEBEFE\n        )\n        embed.add_field(\n            name=\"Commands\", value=f\"```{cmds}```\", inline=False\n        )\n\n        await context.send(embed=embed)\n\n    @dev.command(\n        name=\"sync\",\n        description=\"Sync the slash commands.\",\n        usage=\"dev sync guild/global\"\n    )\n    @app_commands.describe(scope=\"The scope of the sync. Can be `global` or `guild`\")\n    @commands.is_owner()\n    async def sync(self, context: Context, scope: str) -> None:\n        await context.defer()\n\n        if scope == \"global\":\n            await context.bot.tree.sync()\n            embed = discord.Embed(\n                description=\"Slash commands have been globally synchronized.\",\n                color=0xBEBEFE,\n            )\n            await context.send(embed=embed)\n            return\n        elif scope == \"guild\":\n            context.bot.tree.copy_global_to(guild=context.guild)\n            await context.bot.tree.sync(guild=context.guild)\n            embed = discord.Embed(\n                description=\"Slash commands have been synchronized in this guild.\",\n                color=0xBEBEFE,\n            )\n            await context.send(embed=embed)\n            return\n        embed = discord.Embed(\n            description=\"The scope must be `global` or `guild`.\", color=0xE02B2B\n        )\n        await context.send(embed=embed)\n\n    @dev.command(\n        name=\"unsync\",\n        description=\"Unsync the slash commands\",\n        usage=\"dev unsync guild/global\"\n    )\n    @commands.is_owner()\n    async def unsync(self, context: Context, scope: str) -> None:\n        await context.defer()\n\n        if scope == \"global\":\n            context.bot.tree.clear_commands(guild=None)\n            await context.bot.tree.sync()\n            embed = discord.Embed(\n                description=\"Slash commands have been globally unsynchronized.\",\n                color=0xBEBEFE,\n            )\n            await context.send(embed=embed)\n            return\n        elif scope == \"guild\":\n            context.bot.tree.clear_commands(guild=context.guild)\n            await context.bot.tree.sync(guild=context.guild)\n            embed = discord.Embed(\n                description=\"Slash commands have been unsynchronized in this guild.\",\n                color=0xBEBEFE,\n            )\n            await context.send(embed=embed)\n            return\n        embed = discord.Embed(\n            description=\"The scope must be `global` or `guild`.\", color=0xE02B2B\n        )\n        await context.send(embed=embed)\n\n    @dev.command(\n        name=\"sudo\",\n        description=\"sus\",\n        usage=\"dev sudo <user> <command> [args...]\",\n    )\n    @commands.is_owner()\n    async def sudo(self, context: Context, user: discord.Member, *, command: str) -> None:\n        message = context.message\n        message.author = user\n        message.content = context.prefix + command\n        await self.bot.process_commands(message)\n\n    @dev.command(\n        name=\"load\",\n        description=\"Load a cog\",\n        usage=\"dev load <cog>\",\n    )\n    @commands.is_owner()\n    @app_commands.allowed_installs(guilds=True, users=True)\n    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)\n    async def load(self, context: Context, cog: str) -> None:\n        try:\n            await self.bot.load_extension(f\"cogs.{cog}\")\n        except Exception:\n            embed = discord.Embed(\n                description=f\"Could not load the `{cog}` cog.\", color=0xE02B2B\n            )\n            await context.send(embed=embed)\n            return\n        embed = discord.Embed(\n            description=f\"Successfully loaded the `{cog}` cog.\", color=0xBEBEFE\n        )\n        await context.send(embed=embed)\n\n    @dev.command(\n        name=\"unload\",\n        description=\"Unloads a cog.\",\n        usage=\"dev unload <cog>\",\n    )\n    @commands.is_owner()\n    @app_commands.allowed_installs(guilds=True, users=True)\n    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)\n    async def unload(self, context: Context, cog: str) -> None:\n        try:\n            await self.bot.unload_extension(f\"cogs.{cog}\")\n        except Exception:\n            embed = discord.Embed(\n                description=f\"Could not unload the `{cog}` cog.\", color=0xE02B2B\n            )\n            await context.send(embed=embed)\n            return\n        embed = discord.Embed(\n            description=f\"Successfully unloaded the `{cog}` cog.\", color=0xBEBEFE\n        )\n        await context.send(embed=embed)\n\n    @dev.command(\n        name=\"reload\",\n        description=\"Reloads a cog\",\n        usage=\"dev reload <cog>\",\n    )\n    @app_commands.describe(cog=\"The name of the cog to reload\")\n    @app_commands.allowed_installs(guilds=True, users=True)\n    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)\n    @commands.is_owner()\n    async def reload(self, context: Context, cog: str) -> None:\n        try:\n            await self.bot.reload_extension(f\"cogs.{cog}\")\n        except Exception:\n            embed = discord.Embed(\n                description=f\"Could not reload the `{cog}` cog.\", color=0xE02B2B\n            )\n            await context.send(embed=embed)\n            return\n        embed = discord.Embed(\n            description=f\"Successfully reloaded the `{cog}` cog.\", color=0xBEBEFE\n        )\n        await context.send(embed=embed)\n\n    @dev.command(\n        name=\"shutdown\",\n        description=\"bye\",\n        usage=\"dev shutdown\"\n    )\n    @commands.is_owner()\n    async def shutdown(self, context: Context) -> None:\n        embed = discord.Embed(description=\"Shutting down. Bye! :wave:\", color=0xBEBEFE)\n        await context.send(embed=embed)\n        sys.exit(0)\n\n    @dev.command(\n        name=\"say\",\n        description=\"talk\",\n        usage=\"dev say <message>\",\n    )\n    @commands.is_owner()\n    async def say(self, context: Context, *, message: str) -> None:\n        await context.channel.send(message)\n\n    @commands.command(\n        name=\"embed\",\n        description=\"say smth in embed\",\n        usage=\"embed <title> <description> [footer]\",\n    )\n    @commands.is_owner()\n    async def embed(self, context: Context, description: str = \"\", title: str = \"\", footer: str = \"\") -> None:\n        embed = discord.Embed(\n            title=title, description=description, color=0xBEBEFE\n        )\n\n        embed.set_footer(text=footer)\n\n        await context.channel.send(embed=embed)\n\n    @dev.command(\n        name=\"reply\",\n        description=\"Reply to a message\",\n        usage=\"dev reply <message_url> <content>\",\n    )\n    @commands.is_owner()\n    async def reply(self, context: Context, message: discord.Message, *, reply: str) -> None:\n        await message.reply(reply)\n\n    @dev.command(\n        name=\"eval\",\n        description=\":D\",\n        usage=\"eval <code>\",\n    )\n    @commands.is_owner()\n    @app_commands.allowed_installs(guilds=True, users=True)\n    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)\n    async def eval(self, context, *, cmd: str):\n        fn_name = \"_eval_expr\"\n\n        cmd = cmd.strip(\"` \")\n\n        # add a layer of indentation\n        cmd = \"\\n\".join(f\"    {i}\" for i in cmd.splitlines())\n\n        # wrap in async def body\n        body = f\"async def {fn_name}():\\n{cmd}\"\n\n        parsed = ast.parse(body)\n        body = parsed.body[0].body\n\n        insert_returns(body)\n\n        env = {\n            'bot': context.bot,\n            'discord': discord,\n            'commands': commands,\n            'context': context,\n            'db': db,\n            '__import__': __import__\n        }\n        exec(compile(parsed, filename=\"<ast>\", mode=\"exec\"), env)\n\n        result = (await eval(f\"{fn_name}()\", env))\n        await context.send(result)\n\n\n    @dev.command(\n        name=\"enable-ai\",\n        description=\"Give server AI access\",\n        usage=\"dev enable-ai [optional: server id]\",\n    )\n    @commands.is_owner()\n    async def enable_ai(self, context, server: int = 0):\n        c = db[\"guilds\"]\n\n        data = c.find_one(\n            {\n                \"id\": server if server != 0 else context.guild.id\n            }\n        )\n\n        if not data:\n            data = CONSTANTS.guild_data_template(context.guild.id)\n            c.insert_one(data)\n\n        newdata = { \"$set\": { \"ai_access\": True } }\n\n        c.update_one({\"id\": context.guild.id}, newdata)\n\n        await context.send(\"AI access have been enabled in this server\")\n\n    @dev.command(\n        name=\"disable-ai\",\n        description=\"Disable server AI access\",\n        usage=\"dev disable-ai [optional: server id]\",\n    )\n    @commands.is_owner()\n    async def disable_ai(self, context, server_id: int = 0):\n        c = db[\"guilds\"]\n\n        data = c.find_one(\n            {\n                \"id\": server_id if server_id != 0 else context.guild.id\n            }\n        )\n\n        if not data:\n            data = CONSTANTS.guild_data_template(context.guild.id)\n            c.insert_one(data)\n\n        newdata = { \"$set\": { \"ai_access\": False } }\n\n        c.update_one({\"id\": context.guild.id}, newdata)\n\n        await context.send(\"AI access have been disabled in this server\")\n\n    @dev.command(\n        name=\"blacklist\",\n        description=\"Blacklist a user\",\n        usage=\"dev blacklist <user> [reason: optional]\",\n    )\n    @commands.is_owner()\n    @app_commands.allowed_installs(guilds=True, users=True)\n    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)\n    async def blacklist(self, context, user: discord.User, *, reason: str = \"No reason provided\"):\n        users_global = db[\"users_global\"]\n        user_data = users_global.find_one({\"id\": user.id})\n\n        if user is None:\n            user_data = CONSTANTS.user_global_data_template(user.id)\n            users_global.insert_one(user_data)\n\n        newdata = {\n            \"$set\": {\n                \"blacklisted\": True,\n                \"blacklist_reason\": reason\n            }\n        }\n\n        await CachedDB.update_one(users_global, {\"id\": user.id}, newdata)\n\n        await context.send(f\"{user} has been blacklisted.\")\n\n        embed = discord.Embed(\n            title=f\"You have been blacklisted from using the bot\",\n            color=0xE02B2B,\n            description=f\"Reason: {reason}\"\n        )\n\n        try:\n            await user.send(embed=embed)\n        except Exception as e:\n            await context.send(f\"Could not send message to {user.mention} due to: {e}\")\n\n    @dev.command(\n        name=\"unblacklist\",\n        description=\"Unblacklist a user\",\n        usage=\"dev unblacklist <user>\",\n    )\n    @commands.is_owner()\n    @app_commands.allowed_installs(guilds=True, users=True)\n    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)\n    async def unblacklist(self, context, user: discord.User):\n        users_global = db[\"users_global\"]\n        user_data = users_global.find_one({\"id\": user.id})\n\n        if user_data is None:\n            user_data = CONSTANTS.user_global_data_template(user.id)\n            users_global.insert_one(user_data)\n\n        newdata = {\n            \"$set\": {\n                \"blacklisted\": False,\n                \"blacklist_reason\": \"\"\n            }\n        }\n\n        await CachedDB.update_one(users_global, {\"id\": user.id}, newdata)\n\n        await context.send(f\"{user} has been unblacklisted.\")\n\n        embed = discord.Embed(\n            title=f\"You have been unblacklisted from using the bot\",\n            color=0xBEBEFE,\n        )\n\n        try:\n            await user.send(embed=embed)\n        except Exception as e:\n            await context.send(f\"Could not send message to {user.mention} due to: {e}\")\n\n    @commands.hybrid_command(\n        name=\"ai-ignore\",\n        description=\"Make the AI ignore someone\",\n        usage=\"ai_ignore <user> [reason: optional]\",\n    )\n    @commands.is_owner()\n    async def ai_ignore(self, context, user: discord.User, *, reason: str = \"No reason provided\"):\n        users_global = db[\"users_global\"]\n        user_data = users_global.find_one({\"id\": user.id})\n\n        if user_data is None:\n            user_data = CONSTANTS.user_global_data_template(user.id)\n            user_data.insert_one(user_data)\n\n        newdata = {\n            \"$set\": {\n                \"ai_ignore\": True,\n                \"ai_ignore_reason\": reason\n            }\n        }\n\n        await CachedDB.update_one(users_global, {\"id\": user.id}, newdata)\n\n        await context.send(f\"{user} will now be ignored by the AI.\")\n\n    @commands.hybrid_command(\n        name=\"ai-unignore\",\n        description=\"Make the AI not ignore someone\",\n        usage=\"ai-unignore <user>\",\n    )\n    @commands.is_owner()\n    async def ai_unignore(self, context, user: discord.User):\n        users_global = db[\"users_global\"]\n        user_data = users_global.find_one({\"id\": user.id})\n\n        if user_data is None:\n            user_data = CONSTANTS.user_global_data_template(user.id)\n            users_global.insert_one(user_data)\n\n        newdata = {\n            \"$set\": {\n                \"ai_ignore\": False,\n                \"ai_ignore_reason\": \"\"\n            }\n        }\n\n        await CachedDB.update_one(users_global, {\"id\": user.id}, newdata)\n\n        await context.send(f\"{user} will no longer be ignored by the AI\")\n\n    @commands.command(\n        name=\"inspect\",\n        description=\"Inspect a user\",\n        usage=\"inspect <user>\",\n    )\n    @commands.is_owner()\n    async def inspect(self, context, user: discord.User):\n        users_global = db[\"users_global\"]\n        user_data = users_global.find_one({\"id\": user.id})\n\n        if user_data is None:\n            user_data = CONSTANTS.user_global_data_template(user.id)\n            users_global.insert_one(user_data)\n\n        embed = discord.Embed(\n            title=f\"Inspecting {user}\",\n            color=0xBEBEFE\n        )\n\n        embed.add_field(name=\"Total Commands\", value=user_data[\"inspect\"][\"total_commands\"])\n        embed.add_field(name=\"Times Flagged\", value=user_data[\"inspect\"][\"times_flagged\"])\n        embed.add_field(name=\"NSFW Requests\", value=user_data[\"inspect\"][\"nsfw_requests\"])\n\n        # STUFF THAT MIGHT NOT BE FOUND\n        if \"ai_requests\" in user_data[\"inspect\"]:\n            embed.add_field(name=\"AI Requests\", value=user_data[\"inspect\"][\"ai_requests\"])\n\n        if user_data[\"blacklisted\"]:\n            embed.add_field(name=\"Blacklist Reason\", value=user_data[\"blacklist_reason\"])\n\n        if user_data[\"ai_ignore\"]:\n            embed.add_field(name=\"AI Ignore Reason\", value=user_data[\"ai_ignore_reason\"])\n\n        await context.send(embed=embed)\n\n    @commands.command(\n    \tname=\"inspect-clear\",\n        description=\"Clear someones inspect data\",\n        usage=\"inspect-clear <user>\",\n    )\n    @commands.is_owner()\n    async def inspect_clear(self, context: Context, user: discord.Member):\n        users_global = db[\"users_global\"]\n\n        newdata = {\n            \"$set\": {\"inspect.total_commands\": 0, \"inspect.times_flagged\": 0, \"inspect.nsfw_requests\": 0, \"inspect.ai_requests\": 0}\n        }\n\n        users_global.update_one({\"id\": user.id}, newdata)\n\n        user_new = users_global.find_one({\"id\": user.id})\n\n        await context.send(f\"Cleared inspect info for {user.mention}\")\n\n    @commands.command(\n        name=\"top-flagged\",\n        description=\"Get the top flagged users\",\n        usage=\"top-flagged\"\n    )\n    @commands.is_owner()\n    async def top_flagged(self, context):\n        users_global = db[\"users_global\"]\n        users = users_global.find().sort(\"inspect.times_flagged\", -1).limit(10)\n\n        embed = discord.Embed(\n            title=\"Top Flagged Users\",\n            color=0xBEBEFE\n        )\n\n        for user in users:\n            discord_user = self.bot.get_user(user[\"id\"])\n            if not discord_user:\n                continue\n            embed.add_field(name=f\"{str(discord_user).capitalize()} ({discord_user.id})\", value= f\"Flagged **{user['inspect']['times_flagged']}** times\", inline=False)\n\n        await context.send(embed=embed)\n\n    @commands.command(\n        name=\"top-nsfw\",\n        description=\"Get the top NSFW requesters\",\n        usage=\"top-nsfw\"\n    )\n    @commands.is_owner()\n    async def top_nsfw(self, context):\n        users_global = db[\"users_global\"]\n        users = users_global.find().sort(\"inspect.nsfw_requests\", -1).limit(10)\n\n        embed = discord.Embed(\n            title=\"Top NSFW Requesters\",\n            color=0xBEBEFE\n        )\n\n        for user in users:\n            discord_user = self.bot.get_user(user[\"id\"])\n            if not discord_user:\n                continue\n            embed.add_field(name=f\"{str(discord_user).capitalize()} ({discord_user.id})\", value= f\"**{user['inspect']['nsfw_requests']}** NSFW requests\", inline=False)\n\n        await context.send(embed=embed)\n\n    @commands.command(\n        name=\"ai-announce\",\n        description=\"Announce smth\",\n        usage=\"ai-announce <message>\"\n    )\n    @commands.is_owner()\n    async def ai_announce(self, context, *, message: str):\n        channels = db[\"ai_channels\"]\n        listOfChannels = channels.find_one({\"listOfChannels\": True})\n\n        embed = discord.Embed(description=message)\n\n        for channel_id in listOfChannels[\"ai_channels\"]:\n            channel = self.bot.get_channel(channel_id)\n            if channel:\n                if channel.permissions_for(channel.guild.me).send_messages:\n                    await channel.send(embed=embed)\n\n        await context.send(\"Announced\")\n\n    @dev.command(\n        name=\"copy-db-to-backup\",\n        description=\"Copy the database to a backup\",\n        usage=\"dev copy-db-to-backup\"\n    )\n    @commands.is_owner()\n    async def copy_db_to_backup(self, context):\n        backup_db = pymongo.MongoClient(os.getenv(\"MONGODB_BACKUP_URL\")).potatobot\n\n        message = await context.send(\"\"\"\n        Status:\n            Removing old data: :tools:\n            Copying guilds: :x:\n            Copying ai_channels: :x:\n            Copying users: :x:\n            Copying AI convos: :x:\n            Copying global user data: :x:\n            Copying starboard: :x:\n            Copying reaction roles: :x:\n        \"\"\")\n\n        backup_db[\"ai_convos\"].drop()\n        backup_db[\"guilds\"].drop()\n        backup_db[\"ai_channels\"].drop()\n        backup_db[\"users\"].drop()\n        backup_db[\"starboard\"].drop()\n        backup_db[\"users_global\"].drop()\n        backup_db[\"reactionroles\"].drop()\n\n        for guild in db[\"guilds\"].find():\n            backup_db[\"guilds\"].insert_one(guild)\n\n        await message.edit(content=\"\"\"\n        Status:\n            Removing old data: :white_check_mark:\n            Copying guilds: :tools:\n            Copying ai_channels: :x:\n            Copying users: :x:\n            Copying AI convos: :x:\n            Copying global user data: :x:\n            Copying starboard: :x:\n            Copying reaction roles: :x:\n        \"\"\")\n\n        await message.edit(content=\"\"\"\n        Status:\n            Removing old data: :white_check_mark:\n            Copying guilds: :white_check_mark:\n            Copying ai_channels: :tools:\n            Copying users: :x:\n            Copying AI convos: :x:\n            Copying global user data: :x:\n            Copying starboard: :x:\n            Copying reaction roles: :x:\n        \"\"\")\n\n        for channel in db[\"ai_channels\"].find():\n            backup_db[\"ai_channels\"].insert_one(channel)\n\n        await message.edit(content=\"\"\"\n        Status:\n            Removing old data: :white_check_mark:\n            Copying guilds: :white_check_mark:\n            Copying ai_channels: :white_check_mark:\n            Copying users: :tools:\n            Copying AI convos: :x:\n            Copying global user data: :x:\n            Copying starboard: :x:\n            Copying reaction roles: :x:\n        \"\"\")\n\n        for user in db[\"users\"].find():\n            backup_db[\"users\"].insert_one(user)\n\n        await message.edit(content=\"\"\"\n        Status:\n            Removing old data: :white_check_mark:\n            Copying guilds: :white_check_mark:\n            Copying ai_channels: :white_check_mark:\n            Copying users: :white_check_mark:\n            Copying AI convos: :tools:\n            Copying global user data: :x:\n            Copying starboard: :x:\n            Copying reaction roles: :x:\n        \"\"\")\n\n        for convo in db[\"ai_convos\"].find():\n            backup_db[\"ai_convos\"].insert_one(convo)\n\n        await message.edit(content=\"\"\"\n        Status:\n            Removing old data: :white_check_mark:\n            Copying guilds: :white_check_mark:\n            Copying ai_channels: :white_check_mark:\n            Copying users: :white_check_mark:\n            Copying AI convos: :white_check_mark:\n            Copying global user data: :tools:\n            Copying starboard: :x:\n            Copying reaction roles: :x:\n        \"\"\")\n\n        for user in db[\"users_global\"].find():\n            backup_db[\"users_global\"].insert_one(user)\n\n        await message.edit(content=\"\"\"\n        Status:\n            Removing old data: :white_check_mark:\n            Copying guilds: :white_check_mark:\n            Copying ai_channels: :white_check_mark:\n            Copying users: :white_check_mark:\n            Copying AI convos: :white_check_mark:\n            Copying global user data: :white_check_mark:\n            Copying starboard: :tools:\n            Copying reaction roles: :x:\n        \"\"\")\n\n        for starboard in db[\"starboard\"].find():\n            backup_db[\"starboard\"].insert_one(starboard)\n\n        await message.edit(content=\"\"\"\n        Status:\n            Removing old data: :white_check_mark:\n            Copying guilds: :white_check_mark:\n            Copying ai_channels: :white_check_mark:\n            Copying users: :white_check_mark:\n            Copying AI convos: :white_check_mark:\n            Copying global user data: :white_check_mark:\n            Copying starboard: :white_check_mark:\n            Copying reaction roles: :tools:\n        \"\"\")\n\n        for starboard in db[\"reactionroles\"].find():\n            backup_db[\"reactionroles\"].insert_one(starboard)\n\n        await message.edit(content=\"\"\"\n        Status:\n            Removing old data: :white_check_mark:\n            Copying guilds: :white_check_mark:\n            Copying ai_channels: :white_check_mark:\n            Copying users: :white_check_mark:\n            Copying AI convos: :white_check_mark:\n            Copying global user data: :white_check_mark:\n            Copying starboard: :white_check_mark:\n            Copying reaction roles: :white_check_mark:\n\n            **Backup Done!!!**\n        \"\"\")\n\n    @commands.command(\n        name=\"force_system_prompt\",\n        description=\"Set the system prompt for the AI\",\n    )\n    @commands.is_owner()\n    async def force_system_prompt(self, context: Context, *, prompt: str) -> None:\n        c = db[\"guilds\"]\n        data = c.find_one({\"id\": context.guild.id})\n\n        newdata = {\n                \"$set\": { \"system_prompt\": prompt }\n        }\n\n        c.update_one(\n            { \"id\": context.guild.id }, newdata\n        )\n\n        await context.send(\"System prompt set to: \" + prompt)\n\n    @commands.hybrid_group(\n        name=\"strikes\",\n        description=\"Stuff for striking users\"\n    )\n    async def strikes(self, context: Context):\n        prefix = await self.bot.get_prefix(context)\n\n        cmds = \"\\n\".join([f\"{prefix}strikes {cmd.name} - {cmd.description}\" for cmd in self.strikes.walk_commands()])\n\n        embed = discord.Embed(\n            title=f\"Help: Strikes\", description=\"List of available commands:\", color=0xBEBEFE\n        )\n        embed.add_field(\n            name=\"Commands\", value=f\"```{cmds}```\", inline=False\n        )\n\n        await context.send(embed=embed)\n\n    @strikes.command(\n        name=\"add\",\n        description=\"Strike a user\"\n    )\n    @commands.is_owner()\n    async def add(self, context: Context, user: discord.User, *, reason: str):\n        users = db[\"users_global\"]\n        user_data = users.find_one({\"id\": user.id})\n\n        if user_data is None:\n            user_data = CONSTANTS.user_global_data_template(user.id)\n            users.insert_one(user_data)\n\n        if not \"strikes\" in user_data:\n            user_data[\"strikes\"] = []\n\n        user_data[\"strikes\"].append({\"reason\": reason, \"time\": datetime.now().strftime(\"%d.%m.%Y %H:%M:%S\")})\n\n        newdata = {\"$set\": {\"strikes\": user_data[\"strikes\"]}}\n\n        users.update_one({\"id\": user.id}, newdata)\n\n        await context.send(f\"{user.mention} has been striked for **{reason}** | This is strike {len(user_data['strikes'])}\")\n\n        embed = discord.Embed(\n            title=f\"You have received a global strike\",\n            color=0xE02B2B,\n            description=f\"Reason: {reason}\"\n        )\n        embed.set_footer(text=\"Time: \" + datetime.now().strftime(\"%d.%m.%Y %H:%M:%S\"))\n\n        try:\n            await user.send(embed=embed)\n        except Exception as e:\n            await context.send(f\"Could not send message to {user.mention} due to: {e}\")\n\n    @strikes.command(\n        name=\"remove\",\n        description=\"Remove a strike from a user\"\n    )\n    @commands.is_owner()\n    async def remove(self, context: Context, user: discord.User, id: int):\n        users = db[\"users_global\"]\n        user_data = users.find_one({\"id\": user.id})\n\n        if user_data is None:\n            user_data = CONSTANTS.user_global_data_template(user.id)\n            users.insert_one(user_data)\n\n        if not \"strikes\" in user_data:\n            user_data[\"strikes\"] = []\n\n        if id > len(user_data[\"strikes\"]):\n            await context.send(\"That strike does not exist\")\n            return\n\n        reason = user_data[\"strikes\"][id][\"reason\"]\n        user_data[\"strikes\"].pop(id)\n\n        newdata = {\"$set\": {\"strikes\": user_data[\"strikes\"]}}\n\n        users.update_one({\"id\": user.id}, newdata)\n\n        await context.send(f\"Strike **{id}** has been removed from {user.mention}\")\n\n        embed = discord.Embed(\n            title=f\"Globally removed strike | ID: {id}\",\n            color=0xBEBEFE,\n            description=f\"Reason: {reason}\"\n        )\n        embed.set_footer(text=\"Time: \" + datetime.now().strftime(\"%d.%m.%Y %H:%M:%S\"))\n\n        try:\n            await user.send(embed=embed)\n        except Exception as e:\n            await context.send(f\"Could not send message to {user.mention} due to: {e}\")\n\n    @strikes.command(\n        name=\"list\",\n        description=\"Lists a users strikes\"\n    )\n    @commands.is_owner()\n    async def list(self, context: Context, user: discord.User):\n        users = db[\"users_global\"]\n        user_data = users.find_one({\"id\": user.id})\n\n        if user_data is None:\n            user_data = CONSTANTS.user_global_data_template(user.id)\n            users.insert_one(user_data)\n\n        if not \"strikes\" in user_data:\n            user_data[\"strikes\"] = []\n\n        embed = discord.Embed(\n            title=f\"Strikes for {user}\",\n            color=0xBEBEFE\n        )\n\n        for i, strike in enumerate(user_data[\"strikes\"]):\n            embed.add_field(name=f\"Strike at {strike['time']} | ID: {i}\", value=strike[\"reason\"], inline=False)\n\n        await context.send(embed=embed)\n\n    @commands.command(\n        name=\"dm\",\n        description=\"DM a user\",\n        usage=\"dev dm <user> <message>\"\n    )\n    @commands.is_owner()\n    async def dm(self, context: Context, user: discord.User, *, message: str) -> None:\n        try:\n            await user.send(message)\n            await context.send(f\"Sent message to {user.mention}\")\n        except Exception as e:\n            await context.send(f\"Could not send message to {user.mention} due to: {e}\")\n\n    @dev.command(\n        name=\"simulate-level-up\",\n        description=\"\",\n        usage=\"dev simulate-level-up\"\n    )\n    @commands.is_owner()\n    async def simulate_level_up(self, context: Context):\n        author = context.author\n\n        c = db[\"users\"]\n        data = await CachedDB.find_one(c, {\"id\": author.id, \"guild_id\": context.guild.id})\n\n        guilds = db[\"guilds\"]\n        guild_data = await CachedDB.find_one(guilds, {\"id\": context.guild.id})\n\n        if data:\n            channel = context.channel\n            if guild_data:\n                if \"level_announce_channel\" in guild_data:\n                    if guild_data[\"level_announce_channel\"] != 0:\n                        channel = context.guild.get_channel(guild_data[\"level_announce_channel\"])\n\n                if \"should_announce_levelup\" in guild_data:\n                    if guild_data[\"should_announce_levelup\"]:\n                        await channel.send(f\"{author.mention} leveled up to level {data['level']}!\")\n                else:\n                    await channel.send(f\"{author.mention} leveled up to level {data['level']}!\")\n\nasync def setup(bot) -> None:\n    await bot.add_cog(Owner(bot))\n"
  },
  {
    "path": "cogs/reactionroles.py",
    "content": "# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon\n\nimport discord\n\nfrom discord.ext import commands\nfrom discord.ext.commands import Context\n\nfrom utils import CachedDB, DBClient\n\ndb = DBClient.db\n\nfrom utils import Checks\n\nclass ReactionRoles(commands.Cog, name=\"🇺🇸 Reaction Roles\"):\n    def __init__(self, bot) -> None:\n        self.bot = bot\n\n    @commands.Cog.listener()\n    async def on_raw_reaction_add(self, payload) -> None:\n        message_data = await CachedDB.find_one(db[\"reaction_roles\"], {\"message_id\": payload.message_id})\n        if not message_data:\n            return\n\n        # Determine the emoji identifier\n        if payload.emoji.id is None:\n            # This is a Unicode emoji\n            emoji_id = str(payload.emoji)\n        else:\n            # This is a custom emoji\n            emoji_id = str(payload.emoji.id)\n\n        if emoji_id not in message_data[\"roles\"]:\n            return\n\n        guild = self.bot.get_guild(payload.guild_id)\n        if not guild:\n            return\n\n        role = guild.get_role(int(message_data[\"roles\"][emoji_id]))\n        if not role:\n            return\n\n        member = guild.get_member(payload.user_id)\n        if not member:\n            return\n\n        try:\n            await member.add_roles(role)\n            print(f\"Added role {role.name} to {member.name}\")\n        except discord.HTTPException as e:\n            print(f\"Failed to add role: {e}\")\n\n    @commands.Cog.listener()\n    async def on_raw_reaction_remove(self, payload) -> None:\n        message_data = await CachedDB.find_one(db[\"reaction_roles\"], {\"message_id\": payload.message_id})\n        if not message_data:\n            return\n\n        # Determine the emoji identifier\n        if payload.emoji.id is None:\n            # This is a Unicode emoji\n            emoji_id = str(payload.emoji)\n        else:\n            # This is a custom emoji\n            emoji_id = str(payload.emoji.id)\n\n        if emoji_id not in message_data[\"roles\"]:\n            try:\n                message = await self.bot.get_channel(payload.channel_id).fetch_message(payload.message_id)\n                await message.remove_reaction(payload.emoji, self.bot.get_user(payload.user_id))\n            except Exception as e:\n                print(e)\n                pass\n            return\n\n        guild = self.bot.get_guild(payload.guild_id)\n        if not guild:\n            return\n\n        role = guild.get_role(int(message_data[\"roles\"][emoji_id]))\n        if not role:\n            return\n\n        member = guild.get_member(payload.user_id)\n        if not member:\n            return\n\n        try:\n            await member.remove_roles(role)\n            print(f\"Removed role {role.name} from {member.name}\")\n        except discord.HTTPException as e:\n            print(f\"Failed to remove role: {e}\")\n\n    @commands.hybrid_group(\n        name=\"reactionroles\",\n        description=\"Command to manage reaction roles\",\n        usage=\"reactionroles\",\n        aliases=[\"rr\"]\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @commands.has_permissions(manage_roles=True)\n    async def reactionroles(self, context: Context) -> None:\n        subcommands = [cmd for cmd in self.reactionroles.walk_commands()]\n\n        data = []\n\n        for subcommand in subcommands:\n            description = subcommand.description.partition(\"\\n\")[0]\n            data.append(f\"{await self.bot.get_prefix(context)}reactionroles {subcommand.name} - {description}\")\n\n        help_text = \"\\n\".join(data)\n        embed = discord.Embed(\n            title=f\"Help: Reaction Roles\", description=\"List of available commands:\", color=0xBEBEFE\n        )\n        embed.add_field(\n            name=\"Commands\", value=f\"```{help_text}```\", inline=False\n        )\n\n        await context.send(embed=embed)\n\n    @reactionroles.command(\n        name=\"add\",\n        description=\"Add a reaction role to a message\",\n        usage=\"reactionroles add <message_id> <role_id> <emoji>\",\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @commands.has_permissions(manage_roles=True)\n    async def add(self, context: commands.Context, message_id: str, role: discord.Role, emoji: str):\n        try:\n            message_id = int(message_id)\n        except:\n            await context.send(\"Invalid message ID.\")\n            return\n\n        try:\n            message = await context.channel.fetch_message(message_id)\n        except discord.NotFound:\n            await context.send(\"Message not found.\")\n            return\n\n        # Convert emoji to a format we can use\n        try:\n            # Try to convert to Discord emoji\n            emoji_obj = await commands.EmojiConverter().convert(context, emoji)\n            emoji_id = str(emoji_obj.id)\n        except commands.BadArgument:\n            # If conversion fails, assume it's a Unicode emoji\n            emoji_id = emoji\n\n        try:\n            await message.add_reaction(emoji)\n        except discord.HTTPException:\n            await context.send(\"Failed to add reaction. Make sure the bot has permission to add reactions.\")\n            return\n\n        message_data = await CachedDB.find_one(db[\"reaction_roles\"], {\"message_id\": message_id})\n\n        if not message_data:\n            db[\"reaction_roles\"].insert_one({\n                \"message_id\": message_id,\n                \"roles\": {emoji_id: str(role.id)}\n            })\n            await context.send(\"Reaction role added.\")\n        else:\n            if emoji_id in message_data[\"roles\"]:\n                await context.send(\"Reaction role already exists.\")\n            else:\n                message_data[\"roles\"][emoji_id] = str(role.id)\n                await CachedDB.update_one(db[\"reaction_roles\"], {\"message_id\": message_id}, {\"$set\": {\"roles\": message_data[\"roles\"]}})\n                await context.send(\"Reaction role added.\")\n\nasync def setup(bot) -> None:\n    await bot.add_cog(ReactionRoles(bot))\n"
  },
  {
    "path": "cogs/security.py",
    "content": "# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon\n\nimport discord\nimport asyncio\nimport datetime\nimport logging\nimport os\n\nlogger = logging.getLogger(\"discord_bot\")\n\nfrom discord.ext import commands, tasks\nfrom discord.ext.commands import Context\nfrom utils import CONSTANTS, DBClient, Checks, CachedDB\n\nKICK_TRESHOLD = 5\nBAN_TRESHOLD = 3\nDELETE_TRESHOLD = 2\nPING_TRESHOLD = 12\nWEBHOOK_TRESHOLD = 40\n\nclient = DBClient.client\ndb = client.potatobot\n\nban_cache = {}\nkick_cache = {}\nping_cache = {}\nwebhook_cache = {}\ndelete_cache = {}\n\ndeleted_channels = {}\n\nclass Security(commands.Cog, name=\"🛡️ Security\"):\n    def __init__(self, bot) -> None:\n        self.bot = bot\n        self.clear_cache.start()\n\n    @tasks.loop(minutes=10)\n    async def clear_cache(self) -> None:\n        ban_cache.clear()\n        kick_cache.clear()\n        ping_cache.clear()\n        webhook_cache.clear()\n        delete_cache.clear()\n\n        deleted_channels.clear()\n\n    @commands.Cog.listener()\n    async def on_message(self, message: discord.Message) -> None:\n        if message.guild == None:\n            return\n\n        if message.author.id == self.bot.user.id:\n            return\n\n        if message.guild.owner:\n            if message.author.id == message.guild.owner.id:\n                return\n\n        if message.webhook_id:\n            try:\n                webhook = await self.bot.fetch_webhook(message.webhook_id)\n            except discord.NotFound:\n                webhook = None\n\n            if not webhook:\n                return\n\n            if message.webhook_id in webhook_cache:\n                webhook_cache[message.webhook_id] += 1\n\n                if \"@everyone\" in message.content or \"@here\" in message.content:\n                    webhook_cache[message.webhook_id] += 11\n\n                if webhook_cache[message.webhook_id] > WEBHOOK_TRESHOLD:\n                    guilds = db[\"guilds\"]\n                    data = guilds.find_one({\"id\": message.guild.id})\n\n                    if not data:\n                        data = CONSTANTS.guild_data_template(message.guild.id)\n                        guilds.insert_one(data)\n\n                    if not \"security\" in data:\n                        return\n\n                    if \"anti_webhook_spam\" not in data[\"security\"][\"antinuke\"]:\n                        return\n\n                    if not data[\"security\"][\"antinuke\"][\"anti_webhook_spam\"]:\n                        return\n\n                    await message.delete()\n\n                    log_channel = message.guild.get_channel(data[\"log_channel\"])\n\n                    try:\n                        await webhook.delete()\n\n                        embed = discord.Embed(\n                            title=\"AntiSpam Warning\",\n                            description=f\"Webhook **{message.webhook_id}** has been deleted for spamming\",\n                            color=discord.Color.green()\n                        )\n\n                        if log_channel != None:\n                            await log_channel.send(embed=embed)\n                    except:\n                        embed = discord.Embed(\n                            title=\"AntiSpam Warning\",\n                            description=f\"Unable to delete webhook **{message.webhook_id}** for spamming, please delete it manually\",\n                            color=discord.Color.red()\n                        )\n\n                        if log_channel != None:\n                            await log_channel.send(embed=embed)\n\n                    embed = discord.Embed(\n                        title=\"AntiSpam Warning\",\n                        description=f\"Webhook **{message.webhook_id}** has triggered the antispam system, last message: `{message.content}`\",\n                        color=discord.Color.orange()\n                    )\n\n                    if log_channel != None:\n                        await log_channel.send(embed=embed)\n            else:\n                webhook_cache[message.webhook_id] = 1\n\n        if message.author in ping_cache:\n            if len(message.role_mentions) > 0:\n                if message.author.guild_permissions.mention_everyone:\n                    ping_cache[message.author] += len(message.role_mentions) * 2\n\n            if len(message.mentions) > 0:\n                ping_cache[message.author] += len(message.mentions)/2\n\n                if message.author in message.mentions:\n                    ping_cache[message.author] -= 0.5\n\n            if \"@everyone\" in message.content or \"@here\" in message.content:\n                if message.author.guild_permissions.mention_everyone:\n                    ping_cache[message.author] += 11\n\n            if ping_cache[message.author] > PING_TRESHOLD:\n                logger.info(\"boom\")\n                ping_cache[message.author] = 0\n\n                users = db[\"users\"]\n                user_data = users.find_one({\"id\": message.author.id, \"guild_id\": message.guild.id})\n\n                if not user_data:\n                    user_data = CONSTANTS.user_data_template(message.author.id, message.guild.id)\n                    users.insert_one(user_data)\n\n                if \"whitelisted\" in user_data:\n                    if user_data[\"whitelisted\"]:\n                        return\n\n                guilds = db[\"guilds\"]\n                data = guilds.find_one({\"id\": message.guild.id})\n\n                if not data:\n                    data = CONSTANTS.guild_data_template(message.guild.id)\n                    guilds.insert_one(data)\n\n                if not \"security\" in data:\n                    return\n\n                if \"anti_massping\" not in data[\"security\"][\"antinuke\"]:\n                    return\n\n                if not data[\"security\"][\"antinuke\"][\"anti_massping\"]:\n                    return\n\n                await message.delete()\n\n                embed = discord.Embed(\n                    title=\"AntiSpam Warning\",\n                    description=f\"**{message.author.mention}** has triggered the antispam system, last message: `{message.content}`\",\n                    color=discord.Color.orange()\n                )\n\n                try:\n                    message.channel.send(embed=embed)\n                except:\n                    pass\n\n                log_channel = message.guild.get_channel(data[\"log_channel\"])\n\n                if log_channel != None:\n                    await log_channel.send(embed=embed)\n\n                try:\n                    try:\n                        embed = discord.Embed(\n                            title=\"You have been kicked\",\n                            description=f\"You have been kicked from **{message.guild.name}** for mass pinging\",\n                            color=discord.Color.red()\n                        )\n\n                        await message.author.send(embed=embed)\n                    except:\n                        pass\n\n                    await message.author.kick(reason=\"AntiNuke Alert - Mass pinging\")\n                    ban_cache[self.bot.user] = 0\n\n                    embed = discord.Embed(\n                        title=\"User Kicked\",\n                        description=f\"**{message.author.mention}** has been kicked for mass pinging\",\n                        color=discord.Color.red()\n                    )\n\n                    if log_channel != None:\n                        await log_channel.send(embed=embed)\n                except discord.Forbidden:\n                    embed = discord.Embed(\n                        title=\"AntiNuke Error\",\n                        description=f\"I was unable to kick the user {message.author.mention}\",\n                        color=discord.Color.red()\n                    )\n\n                    if log_channel != None:\n                        await log_channel.send(embed=embed)\n\n                    try:\n                        guild_owner = message.guild.owner\n                        await guild_owner.send(embed=embed)\n                    except discord.Forbidden:\n                        embed = discord.Embed(\n                            title=\"AntiNuke Error\",\n                            description=f\"Unable to alert the guild owner using DMs\",\n                            color=discord.Color.red()\n                        )\n\n                        if log_channel != None:\n                            await log_channel.send(embed=embed)\n        else:\n            ping_cache[message.author] = 0\n\n    @commands.Cog.listener()\n    async def on_guild_role_create(self, role: discord.Role) -> None:\n        if role.permissions.administrator:\n            guilds = db[\"guilds\"]\n            guild = guilds.find_one({\"id\": role.guild.id})\n\n            if not guild:\n                guild = CONSTANTS.guild_data_template(role.guild.id)\n                guilds.insert_one(guild)\n\n            if guild and \"security\" in guild and \"antinuke\" in guild[\"security\"]:\n                antinuke = guild[\"security\"][\"antinuke\"]\n                if antinuke.get(\"anti_danger_perms\", False):\n                    discord_guild = role.guild\n                    user = None\n\n                    async for entry in discord_guild.audit_logs(action=discord.AuditLogAction.role_create, limit=2):\n                        if entry.target == role:\n                            user = entry.user\n\n                    if user is None:\n                        return\n\n                    if user.id == discord_guild.owner.id:\n                        return\n\n                    if user.id == self.bot.user.id:\n                        return\n\n                    users = db[\"users\"]\n                    user_data = users.find_one({\"id\": user.id, \"guild_id\": role.guild.id})\n\n                    if not user_data:\n                        user_data = CONSTANTS.user_data_template(user.id, role.guild.id)\n                        users.insert_one(user_data)\n\n                    if \"whitelisted\" in user_data:\n                        if user_data[\"whitelisted\"]:\n                            embed = discord.Embed(\n                                title=\"AntiNuke Warning\",\n                                description=f\"**{user.mention}** created a dangerous role\",\n                                color=discord.Color.orange()\n                            )\n\n                            log_channel = role.guild.get_channel(guild[\"log_channel\"])\n\n                            if log_channel is None:\n                                return\n\n                            await log_channel.send(embed=embed)\n                            return\n\n                    await role.delete()\n\n                    log_channel = role.guild.get_channel(guild[\"log_channel\"])\n\n                    if log_channel is None:\n                        return\n\n                    embed = discord.Embed(\n                        title=\"AntiNuke Alert\",\n                        description=f\"**{user.mention}** tried to create a dangerous role!\",\n                        color=discord.Color.red()\n                    )\n\n                    await log_channel.send(embed=embed)\n\n    @commands.Cog.listener()\n    async def on_guild_role_update(self, before: discord.Role, after: discord.Role) -> None:\n        if after.permissions.administrator and not before.permissions.administrator:\n            guilds = db[\"guilds\"]\n            guild = guilds.find_one({\"id\": after.guild.id})\n\n            if not guild:\n                guild = CONSTANTS.guild_data_template(after.guild.id)\n                guilds.insert_one(guild)\n\n            if guild and \"security\" in guild and \"antinuke\" in guild[\"security\"]:\n                antinuke = guild[\"security\"][\"antinuke\"]\n                if antinuke.get(\"anti_danger_perms\", False):\n                    discord_guild = before.guild\n                    user = None\n\n                    async for entry in discord_guild.audit_logs(action=discord.AuditLogAction.role_update, limit=2):\n                        if entry.target == before or after:\n                            if user == discord_guild.owner:\n                                continue\n                            user = entry.user\n\n                    if user is None:\n                        pass\n\n                    if user.id == self.bot.user.id:\n                        return\n\n                    if user.id == after.guild.owner.id:\n                        return\n\n                    users = db[\"users\"]\n                    user_data = users.find_one({\"id\": user.id, \"guild_id\": after.guild.id})\n\n                    if not user_data:\n                        user_data = CONSTANTS.user_data_template(user.id, after.guild.id)\n                        users.insert_one(user_data)\n\n                    if \"whitelisted\" in user_data:\n                        if user_data[\"whitelisted\"]:\n                            embed = discord.Embed(\n                                title=\"AntiNuke Warning\",\n                                description=f\"**{user.mention}** gave **{after.mention}** dangerous permissions\",\n                                color=discord.Color.orange()\n                            )\n\n                            log_channel = after.guild.get_channel(guild[\"log_channel\"])\n\n                            if log_channel is None:\n                                return\n\n                            await log_channel.send(embed=embed)\n                            return\n\n                    await after.edit(permissions=before.permissions)\n\n                    log_channel = after.guild.get_channel(guild[\"log_channel\"])\n\n                    if log_channel is None:\n                        return\n\n                    embed = discord.Embed(\n                        title=\"AntiNuke Alert\",\n                        description=f\"**{user.mention}** tried to give **{after.mention}** dangerous permissions!\",\n                        color=discord.Color.red()\n                    )\n\n                    await log_channel.send(embed=embed)\n\n                    embed = discord.Embed(\n                        title=\"Role Changes Reverted\",\n                        description=f\"**{before.mention}** has been reverted to its previous permissions!\",\n                        color=discord.Color.green()\n                    )\n\n                    await log_channel.send(embed=embed)\n\n                    try:\n                        await discord_guild.ban(user, reason=\"AntiNuke Alert - Dangerous permissions granted\")\n                        ban_cache[self.bot.user] = 0\n\n                        embed = discord.Embed(\n                            title=\"User Banned\",\n                            description=f\"**{user.mention}** has been banned for trying to give dangerous permissions!\",\n                            color=discord.Color.red()\n                        )\n\n                        if log_channel is not None:\n                            await log_channel.send(embed=embed)\n                    except discord.Forbidden:\n                        embed = discord.Embed(\n                            title=\"AntiNuke Error\",\n                            description=f\"I was unable to ban the user {user.mention}\",\n                            color=discord.Color.red()\n                        )\n\n                        if log_channel is not None:\n                            await log_channel.send(embed=embed)\n\n                        try:\n                            guild_owner = discord_guild.owner\n                            await guild_owner.send(embed=embed)\n                        except discord.Forbidden:\n                            embed = discord.Embed(\n                                title=\"AntiNuke Error\",\n                                description=f\"Unable to alert the guild owner using DMs\",\n                                color=discord.Color.red()\n                            )\n\n                            if log_channel is not None:\n                                await log_channel.send(embed=embed)\n\n    @commands.Cog.listener()\n    async def on_member_ban(self, discord_guild: discord.Guild, banned_user: discord.User) -> None:\n        guilds = db[\"guilds\"]\n        guild = guilds.find_one({\"id\": discord_guild.id})\n\n        if not guild:\n            guild = CONSTANTS.guild_data_template(discord_guild.id)\n            guilds.insert_one(guild)\n\n        if guild and \"security\" in guild and \"antinuke\" in guild[\"security\"]:\n            antinuke = guild[\"security\"][\"antinuke\"]\n            if antinuke.get(\"anti_massban\", False):\n                user = None\n\n                await asyncio.sleep(0.5) # So audit log can update\n\n                async for entry in discord_guild.audit_logs(action=discord.AuditLogAction.ban, limit=2):\n                    if entry.target == banned_user:\n                        user = entry.user\n\n                if user is None:\n                    return\n\n                if user.id == self.bot.user.id:\n                    return\n\n                if user.id == discord_guild.owner.id:\n                    return\n\n                users = db[\"users\"]\n                user_data = users.find_one({\"id\": user.id, \"guild_id\": discord_guild.id})\n\n                if not user_data:\n                    user_data = CONSTANTS.user_data_template(user.id, discord_guild.id)\n                    users.insert_one(user_data)\n\n                if \"whitelisted\" in user_data:\n                    if user_data[\"whitelisted\"]:\n                        return\n\n                over_limit = False\n\n                if user in ban_cache:\n                    ban_cache[user] += 1\n                    if ban_cache[user] > BAN_TRESHOLD:\n                        over_limit = True\n                else:\n                    ban_cache[user] = 1\n\n                if over_limit:\n                    await discord_guild.unban(banned_user, reason=\"Mass ban detected\")\n                    ban_cache[self.bot.user] = 0\n\n                    embed = discord.Embed(\n                        title=\"AntiNuke Warning\",\n                        description=f\"**{user.mention}** has triggered the antinuke system, last banned user: **{banned_user.mention}**\",\n                        color=discord.Color.orange()\n                    )\n\n                    log_channel = discord_guild.get_channel(guild[\"log_channel\"])\n\n                    if log_channel != None:\n                        await log_channel.send(embed=embed)\n\n                    try:\n                        await discord_guild.ban(user, reason=\"AntiNuke Alert - Mass ban detected\")\n                        ban_cache[self.bot.user] = 0\n\n                        embed = discord.Embed(\n                            title=\"User Banned\",\n                            description=f\"**{user.mention}** has been banned for trying to mass ban members!\",\n                            color=discord.Color.red()\n                        )\n\n                        if log_channel != None:\n                            await log_channel.send(embed=embed)\n                    except discord.Forbidden:\n                        embed = discord.Embed(\n                            title=\"AntiNuke Error\",\n                            description=f\"I was unable to ban the user {user.mention}\",\n                            color=discord.Color.red()\n                        )\n\n                        if log_channel != None:\n                            await log_channel.send(embed=embed)\n\n                        try:\n                            guild_owner = discord_guild.owner\n                            await guild_owner.send(embed=embed)\n                        except discord.Forbidden:\n                            embed = discord.Embed(\n                                title=\"AntiNuke Error\",\n                                description=f\"Unable to alert the guild owner using DMs\",\n                                color=discord.Color.red()\n                            )\n\n                            if log_channel != None:\n                                await log_channel.send(embed=embed)\n    @commands.Cog.listener()\n    async def on_member_remove(self, member: discord.Member) -> None:\n        guilds = db[\"guilds\"]\n        guild = guilds.find_one({\"id\": member.guild.id})\n\n        if not guild:\n            guild = CONSTANTS.guild_data_template(member.guild.id)\n            guilds.insert_one(guild)\n\n        if guild and \"security\" in guild and \"antinuke\" in guild[\"security\"]:\n            antinuke = guild[\"security\"][\"antinuke\"]\n            if antinuke.get(\"anti_masskick\", False):\n                user = None\n\n                async for entry in member.guild.audit_logs(action=discord.AuditLogAction.kick, limit=2):\n                    if entry.target == member:\n                        user = entry.user\n\n                if user is None:\n                    return\n\n                if user.id == self.bot.user.id:\n                    return\n\n                if user.id == member.guild.owner.id:\n                    return\n\n                users = db[\"users\"]\n                user_data = users.find_one({\"id\": user.id, \"guild_id\": member.guild.id})\n\n                if not user_data:\n                    user_data = CONSTANTS.user_data_template(user.id, member.guild.id)\n                    users.insert_one(user_data)\n\n                if \"whitelisted\" in user_data:\n                    if user_data[\"whitelisted\"]:\n                        return\n\n                over_limit = False\n\n                if user in kick_cache:\n                    kick_cache[user] += 1\n                    if kick_cache[user] > KICK_TRESHOLD:\n                        over_limit = True\n                else:\n                    kick_cache[user] = 1\n\n                if over_limit:\n                    embed = discord.Embed(\n                        title=\"AntiNuke Warning\",\n                        description=f\"**{user.mention}** has triggered the antinuke system, last kicked user: **{member.mention}**\",\n                        color=discord.Color.orange()\n                    )\n\n                    log_channel = member.guild.get_channel(guild[\"log_channel\"])\n\n                    if log_channel != None:\n                        await log_channel.send(embed=embed)\n\n                    try:\n                        await member.guild.ban(user, reason=\"AntiNuke Alert - Mass kick detected\")\n                        ban_cache[self.bot.user] = 0\n\n                        embed = discord.Embed(\n                            title=\"User Banned\",\n                            description=f\"**{user.mention}** has been banned for trying to mass kick members!\",\n                            color=discord.Color.red()\n                        )\n\n                        if log_channel != None:\n                            await log_channel.send(embed=embed)\n                    except discord.Forbidden:\n                        embed = discord.Embed(\n                            title=\"AntiNuke Error\",\n                            description=f\"I was unable to ban the user {user.mention}\",\n                            color=discord.Color.red()\n                        )\n\n                        if log_channel != None:\n                            await log_channel.send(embed=embed)\n\n                        try:\n                            guild_owner = member.guild.owner\n                            await guild_owner.send(embed=embed)\n                        except discord.Forbidden:\n                            embed = discord.Embed(\n                                title=\"AntiNuke Error\",\n                                description=f\"Unable to alert the guild owner using DMs\",\n                                color=discord.Color.red()\n                            )\n\n                            if log_channel != None:\n                                await log_channel.send(embed=embed)\n    @commands.Cog.listener()\n    async def on_guild_channel_delete(self, channel: discord.TextChannel) -> None:\n        guilds = db[\"guilds\"]\n        guild = guilds.find_one({\"id\": channel.guild.id})\n\n        if not guild:\n            guild = CONSTANTS.guild_data_template(channel.guild.id)\n            guilds.insert_one(guild)\n\n        if guild and \"security\" in guild and \"antinuke\" in guild[\"security\"]:\n            antinuke = guild[\"security\"][\"antinuke\"]\n            if antinuke.get(\"anti_massdelete\", False):\n                user = None\n\n                async for entry in channel.guild.audit_logs(action=discord.AuditLogAction.channel_delete, limit=2):\n                    if entry.target.id == channel.id and entry.user:\n                        user = entry.user\n\n                if channel.guild in deleted_channels:\n                    deleted_channels[channel.guild].append(channel)\n                else:\n                    deleted_channels[channel.guild] = [channel]\n\n                if user is None:\n                    return\n\n                if user == self.bot.user:\n                    return\n\n                if user == channel.guild.owner:\n                    pass\n\n                users = db[\"users\"]\n                user_data = users.find_one({\"id\": user.id, \"guild_id\": channel.guild.id})\n\n                if not user_data:\n                    user_data = CONSTANTS.user_data_template(user.id, channel.guild.id)\n                    users.insert_one(user_data)\n\n\n                if \"whitelisted\" in user_data:\n                    if user_data[\"whitelisted\"]:\n                        return\n\n                over_limit = False\n\n                if user in delete_cache:\n                    delete_cache[user] += 1\n                    if delete_cache[user] > DELETE_TRESHOLD:\n                        over_limit = True\n                else:\n                    delete_cache[user] = 1\n\n                if over_limit:\n\n                    log_channel = channel.guild.get_channel(guild[\"log_channel\"])\n\n                    try:\n                        await channel.guild.ban(user, reason=\"AntiNuke Alert - Mass delete detected\")\n                        ban_cache[self.bot.user] = 0\n\n                        embed = discord.Embed(\n                            title=\"User Banned\",\n                            description=f\"**{user.mention}** has been banned for trying to mass delete channels!\",\n                            color=discord.Color.red()\n                        )\n\n                        if log_channel != None:\n                            await log_channel.send(embed=embed)\n                    except discord.Forbidden:\n                        embed = discord.Embed(\n                            title=\"AntiNuke Error\",\n                            description=f\"I was unable to ban the user {user.mention}\",\n                            color=discord.Color.red()\n                        )\n\n                        if log_channel != None:\n                            await log_channel.send(embed=embed)\n\n                        try:\n                            guild_owner = channel.guild.owner\n                            await guild_owner.send(embed=embed)\n                        except discord.Forbidden:\n                            embed = discord.Embed(\n                                title=\"AntiNuke Error\",\n                                description=f\"Unable to alert the guild owner using DMs\",\n                                color=discord.Color.red()\n                            )\n\n                            if log_channel != None:\n                                await log_channel.send(embed=embed)\n\n                    embed = discord.Embed(\n                        title=\"AntiNuke Warning\",\n                        description=f\"**{user.mention}** has triggered the antinuke system, last deleted channel: **{channel.mention}** ({channel.name})\",\n                        color=discord.Color.orange()\n                    )\n\n                    if log_channel != None:\n                        try:\n                            await log_channel.send(embed=embed)\n                        except:\n                            await channel.guild.owner.send(embed=embed)\n                    else:\n                        await channel.guild.owner.send(embed=embed)\n\n                    for del_channel in deleted_channels[channel.guild]:\n                        if not del_channel in deleted_channels[channel.guild]:\n                            return\n\n                        deleted_channels[channel.guild].remove(del_channel)\n\n                        try:\n                            new_channel = await del_channel.clone(reason=\"AntiNuke Alert - Mass delete detected\")\n                            ban_cache[self.bot.user] = 0\n\n                            embed = discord.Embed(\n                                title=\"Channel Restored\",\n                                description=f\"**{new_channel.mention}** has been restored!\",\n                                color=discord.Color.green()\n                            )\n\n                            if log_channel != None:\n                                await log_channel.send(embed=embed)\n\n                            embed = discord.Embed(\n                                title=\"This channel was nuked\",\n                                description=f\"**{new_channel.mention}** was nuked by **{user.mention}**, channel is restored but message log is gone\",\n                                color=discord.Color.red()\n                            )\n\n                            await new_channel.send(embed=embed)\n\n                            await new_channel.edit(position=del_channel.position)\n\n                        except Exception as e:\n                            embed = discord.Embed(\n                                title=\"Error\",\n                                description=f\"An error occured while trying to restore channel **{del_channel.name}**\",\n                                color=discord.Color.red()\n                            )\n\n                            embed.add_field(\n                                name=\"Error\",\n                                value=f\"```{e}```\"\n                            )\n\n                            if log_channel != None:\n                                await log_channel.send(embed=embed)\n\n                    await asyncio.sleep(60)\n                    deleted_channels[channel.guild].clear()\n\n    @commands.Cog.listener()\n    async def on_member_join(self, member: discord.Member):\n        guild = await CachedDB.find_one(db[\"guilds\"], {\"id\": member.guild.id})\n\n        if not guild:\n            return\n\n        if \"lockdown\" not in guild:\n            return\n\n        if guild[\"lockdown\"]:\n            await member.kick(reason=\"Guild is in lockdown\")\n\n    ###\n\n    @commands.hybrid_group(\n        name=\"whitelist\",\n        description=\"Whitelist users from security measures (guild owner only)\"\n    )\n    async def whitelist(self, context: Context) -> None:\n        prefix = await self.bot.get_prefix(context)\n\n        cmds = \"\\n\".join([f\"{prefix}whitelist {cmd.name} - {cmd.description}\" for cmd in self.whitelist.walk_commands()])\n\n        embed = discord.Embed(\n            title=f\"Help: Whitelist\", description=\"List of available commands:\", color=0xBEBEFE\n        )\n        embed.add_field(\n            name=\"Commands\", value=f\"```{cmds}```\", inline=False\n        )\n\n        await context.send(embed=embed)\n\n    @whitelist.command(\n        name=\"add\",\n        description=\"Whitelist a user from security measures (guild owner only)\",\n        usage=\"whitelist add <user>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    async def add(self, context: Context, user: discord.Member) -> None:\n        guild_owner = context.guild.owner\n\n        if context.author != guild_owner and context.author.id != int(os.getenv(\"OWNER_ID\")):\n            await context.send(\"You must be the guild owner to use this command!\")\n            return\n\n        users = db[\"users\"]\n        user_data = users.find_one({\"id\": user.id, \"guild_id\": context.guild.id})\n\n        if user is None:\n            user_data = CONSTANTS.user_data_template(user.id, context.guild.id)\n            users.insert_one(user_data)\n\n        newdata = {\n            \"$set\": {\n                \"whitelisted\": True\n            }\n        }\n\n        users.update_one({\"id\": user.id, \"guild_id\": context.guild.id}, newdata)\n\n        await context.send(f\"Whitelisted {user.mention}\")\n\n    @whitelist.command(\n        name=\"remove\",\n        description=\"Remove a user from the whitelist (guild owner only)\",\n        usage=\"whitelist remove <user>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    async def remove(self, context: Context, user: discord.Member) -> None:\n        guild_owner = context.guild.owner\n\n        if context.author != guild_owner:\n            await context.send(\"You must be the guild owner to use this command!\")\n            return\n\n        users = db[\"users\"]\n        user_data = users.find_one({\"id\": user.id, \"guild_id\": context.guild.id})\n\n        if user is None:\n            user_data = CONSTANTS.user_data_template(user.id, context.guild.id)\n            users.insert_one(user_data)\n\n        newdata = {\n            \"$set\": {\n                \"whitelisted\": False\n            }\n        }\n\n        users.update_one({\"id\": user.id, \"guild_id\": context.guild.id}, newdata)\n\n        await context.send(f\"Unwhitelisted {user.mention}\")\n\n    @whitelist.command(\n        name=\"list\",\n        description=\"List all whitelisted users (guild owner only)\",\n        usage=\"whitelist list\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    async def list(self, context: Context) -> None:\n        users = db[\"users\"]\n\n        whitelisted = users.find({\"guild_id\": context.guild.id, \"whitelisted\": True})\n\n        list = \"```\"\n\n        for user in whitelisted:\n            user = context.guild.get_member(user[\"id\"])\n            list += f\"{user.name}\\n\"\n\n        list += \"```\"\n\n        embed = discord.Embed(\n            title=\"Whitelisted Users\",\n            description=list\n        )\n\n        await context.send(embed=embed)\n\n    @commands.hybrid_group(\n        name=\"trusted\",\n        description=\"Trusted users can bypass security measures and change security settings\"\n    )\n    async def trusted(self, context: Context) -> None:\n        prefix = await self.bot.get_prefix(context)\n\n        cmds = \"\\n\".join([f\"{prefix}trusted {cmd.name} - {cmd.description}\" for cmd in self.trusted.walk_commands()])\n\n        embed = discord.Embed(\n            title=f\"Help: Trusted\", description=\"List of available commands:\", color=0xBEBEFE\n        )\n        embed.add_field(\n            name=\"Commands\", value=f\"```{cmds}```\", inline=False\n        )\n\n        await context.send(embed=embed)\n\n    @trusted.command(\n        name=\"add\",\n        description=\"Trust a user (guild owner only)\",\n        usage=\"trusted add <user>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    async def trusted_add(self, context: Context, user: discord.Member) -> None:\n        guild_owner = context.guild.owner\n\n        if context.author != guild_owner and context.author.id != int(os.getenv(\"OWNER_ID\")):\n            await context.send(\"You must be the guild owner to use this command!\")\n            return\n\n        users = db[\"users\"]\n        user_data = users.find_one({\"id\": user.id, \"guild_id\": context.guild.id})\n\n        if user is None:\n            user_data = CONSTANTS.user_data_template(user.id, context.guild.id)\n            users.insert_one(user_data)\n\n        newdata = {\n            \"$set\": {\n                \"trusted\": True\n            }\n        }\n\n        users.update_one({\"id\": user.id, \"guild_id\": context.guild.id}, newdata)\n\n        await context.send(f\"Trusted {user.mention}\")\n\n    @trusted.command(\n        name=\"remove\",\n        description=\"Remove a trusted user (guild owner only)\",\n        usage=\"trusted remove <user>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    async def trusted_remove(self, context: Context, user: discord.Member) -> None:\n        guild_owner = context.guild.owner\n\n        if context.author != guild_owner:\n            await context.send(\"You must be the guild owner to use this command!\")\n            return\n\n        users = db[\"users\"]\n        user_data = users.find_one({\"id\": user.id, \"guild_id\": context.guild.id})\n\n        if user is None:\n            user_data = CONSTANTS.user_data_template(user.id, context.guild.id)\n            users.insert_one(user_data)\n\n        newdata = {\n            \"$set\": {\n                \"trusted\": False\n            }\n        }\n\n        users.update_one({\"id\": user.id, \"guild_id\": context.guild.id}, newdata)\n\n        await context.send(f\"Untrusted {user.mention}\")\n\n    @trusted.command(\n        name=\"list\",\n        description=\"List all trusted users\",\n        usage=\"trusted list\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    async def trusted_list(self, context: Context) -> None:\n        users = db[\"users\"]\n\n        whitelisted = users.find({\"guild_id\": context.guild.id, \"trusted\": True})\n\n        list = \"```\"\n\n        for user in whitelisted:\n            user = context.guild.get_member(user[\"id\"])\n            list += f\"{user.name}\\n\"\n\n        list += \"```\"\n\n        embed = discord.Embed(\n            title=\"Trusted Users\",\n            description=list\n        )\n\n        await context.send(embed=embed)\n\n    @commands.hybrid_group(\n        name=\"antinuke\",\n        description=\"Commands to manage antinuke (guild owner/trusted only)\",\n        usage=\"antinuke <subcommand>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    async def antinuke(self, context: Context) -> None:\n        embed = discord.Embed(\n            title=\"Antinuke\",\n            description=\"Commands\"\n        )\n\n        # get all subcommands in group\n\n        subcommands = [cmd for cmd in self.antinuke.walk_commands()]\n\n        data = []\n\n        for subcommand in subcommands:\n            description = subcommand.description.partition(\"\\n\")[0]\n            data.append(f\"{await self.bot.get_prefix(context)}antinuke {subcommand.name} - {description}\")\n\n        help_text = \"\\n\".join(data)\n        embed = discord.Embed(\n            title=f\"Help: Antinuke\", description=\"List of available commands:\", color=0xBEBEFE\n        )\n        embed.add_field(\n            name=\"Commands\", value=f\"```{help_text}```\", inline=False\n        )\n\n        await context.send(embed=embed)\n\n    @antinuke.command(\n        name=\"anti_danger_perms\",\n        description=\"Prevent someone from giving dangerous perms to @everyone (guild owner/trusted only)\",\n        usage=\"antinuke anti_danger_perms <true/false>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    async def anti_danger_perms(self, context: Context, enabled: bool) -> None:\n        guild_owner = context.guild.owner\n\n        if context.author != guild_owner:\n            users = db[\"users\"]\n            user_data = users.find_one({\"id\": context.author.id, \"guild_id\": context.guild.id})\n\n            if not user_data:\n                user_data = CONSTANTS.user_data_template(context.author.id, context.guild.id)\n                users.insert_one(user_data)\n\n            if \"trusted\" in user_data:\n                if not user_data[\"trusted\"]:\n                    await context.send(\"You must be the guild owner or trusted to use this command!\")\n                    return\n            else:\n                return\n\n        guilds = db[\"guilds\"]\n        guild = guilds.find_one({\"id\": context.guild.id})\n\n        if not guild:\n            guild = CONSTANTS.guild_data_template(context.guild.id)\n            guilds.insert_one(guild)\n\n        if \"security\" not in guild:\n            newdata = {\n                \"$set\": {\n                    \"security\": {\n                        \"antinuke\": {\n                            \"anti_danger_perms\": enabled,\n                            \"anti_massban\": False,\n                            \"anti_masskick\": False,\n                            \"anti_masscreate\": False,\n                            \"anti_massdelete\": False,\n                            \"anti_massping\": False,\n                            \"anti_webhook_spam\": False\n\n                        }\n                    }\n                }\n            }\n\n            guilds.update_one({\"id\": context.guild.id}, newdata)\n        else:\n            newdata = {\n                \"$set\": {\n                    \"security.antinuke.anti_danger_perms\": enabled\n                }\n            }\n\n            guilds.update_one({\"id\": context.guild.id}, newdata)\n\n        await context.send(f\"Set `anti_danger_perms` to `{enabled}`\")\n\n    @antinuke.command(\n        name=\"anti_massban\",\n        description=\"Prevent someone from mass banning members (guild owner/trusted only)\",\n        usage=\"antinuke anti_massban <true/false>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    async def anti_massban(self, context: Context, enabled: bool) -> None:\n        guild_owner = context.guild.owner\n\n        if context.author != guild_owner:\n            users = db[\"users\"]\n            user_data = users.find_one({\"id\": context.author.id, \"guild_id\": context.guild.id})\n\n            if not user_data:\n                user_data = CONSTANTS.user_data_template(context.author.id, context.guild.id)\n                users.insert_one(user_data)\n\n            if \"trusted\" in user_data:\n                if not user_data[\"trusted\"]:\n                    await context.send(\"You must be the guild owner or trusted to use this command!\")\n                    return\n            else:\n                return\n\n        guilds = db[\"guilds\"]\n        guild = guilds.find_one({\"id\": context.guild.id})\n\n        if not guild:\n            guild = CONSTANTS.guild_data_template(context.guild.id)\n            guilds.insert_one(guild)\n\n        if \"security\" not in guild:\n            newdata = {\n                \"$set\": {\n                    \"security\": {\n                        \"antinuke\": {\n                            \"anti_danger_perms\": False,\n                            \"anti_massban\": enabled,\n                            \"anti_masskick\": False,\n                            \"anti_masscreate\": False,\n                            \"anti_massdelete\": False,\n                            \"anti_massping\": False,\n                            \"anti_webhook_spam\": False\n                        }\n                    }\n                }\n            }\n\n            guilds.update_one({\"id\": context.guild.id}, newdata)\n        else:\n            newdata = {\n                \"$set\": {\n                    \"security.antinuke.anti_massban\": enabled\n                }\n            }\n\n            guilds.update_one({\"id\": context.guild.id}, newdata)\n\n        await context.send(f\"Set `anti_massban` to `{enabled}`\")\n\n    @antinuke.command(\n        name=\"anti_masskick\",\n        description=\"Prevent someone from mass kicking members (guild owner/trusted only)\",\n        usage=\"antinuke anti_masskick <true/false>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    async def anti_masskick(self, context: Context, enabled: bool) -> None:\n        guild_owner = context.guild.owner\n\n        if context.author != guild_owner:\n            users = db[\"users\"]\n            user_data = users.find_one({\"id\": context.author.id, \"guild_id\": context.guild.id})\n\n            if not user_data:\n                user_data = CONSTANTS.user_data_template(context.author.id, context.guild.id)\n                users.insert_one(user_data)\n\n            if \"trusted\" in user_data:\n                if not user_data[\"trusted\"]:\n                    await context.send(\"You must be the guild owner or trusted to use this command!\")\n                    return\n            else:\n                return\n\n\n        guilds = db[\"guilds\"]\n        guild = guilds.find_one({\"id\": context.guild.id})\n\n        if not guild:\n            guild = CONSTANTS.guild_data_template(context.guild.id)\n            guilds.insert_one(guild)\n\n        if \"security\" not in guild:\n            newdata = {\n                \"$set\": {\n                    \"security\": {\n                        \"antinuke\": {\n                            \"anti_danger_perms\": False,\n                            \"anti_massban\": False,\n                            \"anti_masskick\": enabled,\n                            \"anti_masscreate\": False,\n                            \"anti_massdelete\": False,\n                            \"anti_massping\": False,\n                            \"anti_webhook_spam\": False\n                        }\n                    }\n                }\n            }\n\n            guilds.update_one({\"id\": context.guild.id}, newdata)\n        else:\n            newdata = {\n                \"$set\": {\n                    \"security.antinuke.anti_masskick\": enabled\n                }\n            }\n\n            guilds.update_one({\"id\": context.guild.id}, newdata)\n\n        await context.send(f\"Set `anti_masskick` to `{enabled}`\")\n\n    @antinuke.command(\n        name=\"anti_massdelete\",\n        description=\"Prevent someone from mass deleting channels (guild owner/trusted only)\",\n        usage=\"antinuke anti_massdelete <true/false>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    async def anti_massdelete(self, context: Context, enabled: bool) -> None:\n        guild_owner = context.guild.owner\n\n        if context.author != guild_owner:\n            users = db[\"users\"]\n            user_data = users.find_one({\"id\": context.author.id, \"guild_id\": context.guild.id})\n\n            if not user_data:\n                user_data = CONSTANTS.user_data_template(context.author.id, context.guild.id)\n                users.insert_one(user_data)\n\n            if \"trusted\" in user_data:\n                if not user_data[\"trusted\"]:\n                    await context.send(\"You must be the guild owner or trusted to use this command!\")\n                    return\n            else:\n                return\n\n        guilds = db[\"guilds\"]\n        guild = guilds.find_one({\"id\": context.guild.id})\n\n        if not guild:\n            guild = CONSTANTS.guild_data_template(context.guild.id)\n            guilds.insert_one(guild)\n\n        if \"security\" not in guild:\n            newdata = {\n                \"$set\": {\n                    \"security\": {\n                        \"antinuke\": {\n                            \"anti_danger_perms\": False,\n                            \"anti_massban\": False,\n                            \"anti_masskick\": False,\n                            \"anti_masscreate\": False,\n                            \"anti_massdelete\": enabled,\n                            \"anti_massping\": False,\n                            \"anti_webhook_spam\": False\n                        }\n                    }\n                }\n            }\n\n            guilds.update_one({\"id\": context.guild.id}, newdata)\n        else:\n            newdata = {\n                \"$set\": {\n                    \"security.antinuke.anti_massdelete\": enabled\n                }\n            }\n\n            guilds.update_one({\"id\": context.guild.id}, newdata)\n\n        await context.send(f\"Set `anti_massdelete` to `{enabled}`\")\n\n    @antinuke.command(\n        name=\"anti_massping\",\n        description=\"Prevent mass pinging (guild owner/trusted only)\",\n        usage=\"antinuke anti_massping <true/false>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    async def massping(self, context: Context, enabled: bool) -> None:\n        guild_owner = context.guild.owner\n\n        if context.author != guild_owner:\n            users = db[\"users\"]\n            user_data = users.find_one({\"id\": context.author.id, \"guild_id\": context.guild.id})\n\n            if not user_data:\n                user_data = CONSTANTS.user_data_template(context.author.id, context.guild.id)\n                users.insert_one(user_data)\n\n            if \"trusted\" in user_data:\n                if not user_data[\"trusted\"]:\n                    await context.send(\"You must be the guild owner or trusted to use this command!\")\n                    return\n            else:\n                return\n\n        guilds = db[\"guilds\"]\n        guild = guilds.find_one({\"id\": context.guild.id})\n\n        if not guild:\n            guild = CONSTANTS.guild_data_template(context.guild.id)\n            guilds.insert_one(guild)\n\n        if \"security\" not in guild:\n            newdata = {\n                \"$set\": {\n                    \"security\": {\n                        \"antinuke\": {\n                            \"anti_danger_perms\": False,\n                            \"anti_massban\": False,\n                            \"anti_masskick\": False,\n                            \"anti_masscreate\": False,\n                            \"anti_massdelete\": False,\n                            \"anti_massping\": enabled,\n                            \"anti_webhook_spam\": False\n                        }\n                    }\n                }\n            }\n\n            guilds.update_one({\"id\": context.guild.id}, newdata)\n        else:\n            newdata = {\n                \"$set\": {\n                    \"security.antinuke.anti_massping\": enabled\n                }\n            }\n\n            guilds.update_one({\"id\": context.guild.id}, newdata)\n\n        await context.send(f\"Set `anti_massping` to `{enabled}`\")\n\n    @antinuke.command(\n        name=\"anti_webhook_spam\",\n        description=\"Prevent webhook spam (guild owner/trusted only)\",\n        usage=\"antinuke anti_webhook_spam <true/false>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    async def anti_webhook_spam(self, context: Context, enabled: bool) -> None:\n        guild_owner = context.guild.owner\n\n        if context.author != guild_owner:\n            users = db[\"users\"]\n            user_data = users.find_one({\"id\": context.author.id, \"guild_id\": context.guild.id})\n\n            if not user_data:\n                user_data = CONSTANTS.user_data_template(context.author.id, context.guild.id)\n                users.insert_one(user_data)\n\n            if \"trusted\" in user_data:\n                if not user_data[\"trusted\"]:\n                    await context.send(\"You must be the guild owner or trusted to use this command!\")\n                    return\n            else:\n                return\n\n        guilds = db[\"guilds\"]\n        guild = guilds.find_one({\"id\": context.guild.id})\n\n        if not guild:\n            guild = CONSTANTS.guild_data_template(context.guild.id)\n            guilds.insert_one(guild)\n\n        if \"security\" not in guild:\n            newdata = {\n                \"$set\": {\n                    \"security\": {\n                        \"antinuke\": {\n                            \"anti_danger_perms\": False,\n                            \"anti_massban\": False,\n                            \"anti_masskick\": False,\n                            \"anti_masscreate\": False,\n                            \"anti_massdelete\": False,\n                            \"anti_massping\": False,\n                            \"anti_webhook_spam\": enabled\n                        }\n                    }\n                }\n            }\n\n            guilds.update_one({\"id\": context.guild.id}, newdata)\n        else:\n            newdata = {\n                \"$set\": {\n                    \"security.antinuke.anti_webhook_spam\": enabled\n                }\n            }\n\n            guilds.update_one({\"id\": context.guild.id}, newdata)\n\n        await context.send(f\"Set `anti_webhook_spam` to `{enabled}`\")\n\n    @commands.hybrid_command(\n        name=\"lockdown\",\n        description=\"Lockdown the server (guild owner/trusted only)\",\n        usage=\"lockdown\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    async def lockdown(self, context: Context) -> None:\n        guild_owner = context.guild.owner\n\n        if context.author != guild_owner:\n            users = db[\"users\"]\n            user_data = users.find_one({\"id\": context.author.id, \"guild_id\": context.guild.id})\n\n            if not user_data:\n                user_data = CONSTANTS.user_data_template(context.author.id, context.guild.id)\n                users.insert_one(user_data)\n\n            if \"trusted\" in user_data:\n                if not user_data[\"trusted\"]:\n                    await context.send(\"You must be the guild owner or trusted to use this command!\")\n                    return\n            else:\n                return\n\n        guilds = db[\"guilds\"]\n        guild = guilds.find_one({\"id\": context.guild.id})\n\n        if not guild:\n            guild = CONSTANTS.guild_data_template(context.guild.id)\n            guilds.insert_one(guild)\n\n        embed = discord.Embed(\n            title = \"Confirm Action\",\n            description = \"Are you sure you want to lockdown the server?\",\n            color = discord.Color.red()\n        )\n\n        await context.send(embed=embed, view=ConfirmView(\"lockdown\", context.author))\n\n    @commands.hybrid_command(\n        name=\"unlockdown\",\n        description=\"Unlockdown the server (guild owner/trusted only)\",\n        usage=\"unlockdown\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    async def unlockdown(self, context: Context) -> None:\n        guild_owner = context.guild.owner\n\n        try:\n            await context.send(\"Starting Unlockdown\")\n        except:\n            pass\n\n        if context.author != guild_owner:\n            users = db[\"users\"]\n            user_data = users.find_one({\"id\": context.author.id, \"guild_id\": context.guild.id})\n\n            if not user_data:\n                user_data = CONSTANTS.user_data_template(context.author.id, context.guild.id)\n                users.insert_one(user_data)\n\n            if \"trusted\" in user_data:\n                if not user_data[\"trusted\"]:\n                    await context.send(\"You must be the guild owner or trusted to use this command!\")\n                    return\n            else:\n                return\n\n        guilds = db[\"guilds\"]\n        guild_data = guilds.find_one({\"id\": context.guild.id})\n\n        if not guild_data:\n            guild_data = CONSTANTS.guild_data_template(context.guild.id)\n            guilds.insert_one(guild_data)\n\n        if \"oldperms\" in guild_data:\n            for channel in context.guild.text_channels:\n                try:\n                    channel_id_str = str(channel.id)\n                    if channel_id_str in guild_data[\"oldperms\"]:\n                        # Deserialize the permissions\n                        perms_dict = guild_data[\"oldperms\"][channel_id_str]\n                        overwrite = discord.PermissionOverwrite(**perms_dict)\n\n                        await channel.set_permissions(context.guild.default_role, overwrite=overwrite)\n                except:\n                    try:\n                        await context.send(\"Failed to change perms for channel \" + channel.name)\n                    except:\n                        pass\n\n            guilds.update_one({\"id\": context.guild.id}, {\"$unset\": {\"oldperms\": \"\"}})\n\n        guilds.update_one({\"id\": context.guild.id}, {\"$set\": {\"lockdown\": False}})\n        await context.send(\"Server unlockdown complete.\")\n\n\nclass ConfirmView(discord.ui.View):\n    def __init__(self, value: str, author: discord.Member):\n        super().__init__()\n\n        self.value = value\n        self.author = author\n\n    @discord.ui.button(label=\"Confirm\", style=discord.ButtonStyle.danger)\n    async def confirm(self, interaction: discord.Interaction, button: discord.ui.Button):\n        if self.author != interaction.user:\n            return interaction.response.send_message(\"no\", ephemeral=True)\n\n        await interaction.response.defer()\n\n        if self.value == \"lockdown\":\n            await interaction.message.edit(content=\"Locking down the server...\", view=None, embed=None)\n\n            oldperms = {}\n\n            for channel in interaction.guild.text_channels:\n                try:\n                    overwrite = channel.overwrites_for(interaction.guild.default_role)\n                    # Serialize the PermissionOverwrite object\n                    perms_dict = {perm: value for perm, value in overwrite}\n\n                    oldperms[str(channel.id)] = perms_dict\n\n                    overwrite.send_messages = False\n                    await channel.set_permissions(interaction.guild.default_role, overwrite=overwrite)\n                except:\n                    pass\n\n            newdata = {\n                \"$set\": {\n                    \"lockdown\": True,\n                    \"oldperms\": oldperms\n                }\n            }\n\n            guilds = db[\"guilds\"]\n            guilds.update_one({\"id\": interaction.guild.id}, newdata)\n\n            await interaction.message.edit(content=\"Server lockdown complete.\", view=None, embed=None)\n\n    @discord.ui.button(label=\"Cancel\", style=discord.ButtonStyle.primary)\n    async def cancel(self, interaction: discord.Interaction, button: discord.ui.Button):\n        if self.author != interaction.user:\n            return interaction.response.send_message(\"no\", ephemeral=True)\n\n        await interaction.response.edit_message(\"Action cancelled\", view=None)\n\nasync def setup(bot) -> None:\n    await bot.add_cog(Security(bot))\n"
  },
  {
    "path": "cogs/server.py",
    "content": "# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon\n\nimport discord\nimport os\nimport aiohttp\n\nfrom cryptography.fernet import Fernet\n\nfrom discord.ext import commands\nfrom discord.ext.commands import Context\n\nfrom utils import CachedDB, Checks, DBClient, CONSTANTS\nfrom ui.setup import StartSetupView\n\n\ndb = DBClient.db\n\nclass Server(commands.Cog, name=\"⚙️ Server\"):\n    def __init__(self, bot) -> None:\n        self.bot = bot\n        self.prefixDB = bot.prefixDB\n\n    @commands.hybrid_command(\n        name=\"setup\",\n        description=\"It's setup time!!!!!!\",\n        usage=\"testcommand\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    async def setup(self, context: Context) -> None:\n        if context.author.id != context.guild.owner.id:\n            await context.send(\"You must be the owner of the server to run this command.\")\n            return\n\n        embed = discord.Embed(\n            title=\"Setup\",\n            description=\"Let's set up your server!\",\n            color=0x2F3136\n        )\n\n        await context.send(embed=embed, view=StartSetupView(context.guild.id))\n\n    @commands.command(\n        name=\"prefix\",\n        description=\"Change the bot prefix\",\n        usage=\"prefix <symbol>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.has_permissions(manage_channels=True)\n    async def prefix(self, context: commands.Context, prefix: str = \"none\"):\n        if prefix == \"none\":\n            return await context.send(\"Current prefix is: `\" + self.prefixDB.get(str(context.guild.id)) + \"`\")\n\n        if prefix == \"/\":\n            return await context.send(\"Prefix cannot be `/`\")\n\n        guild_id = str(context.guild.id)\n        self.prefixDB.set(guild_id, prefix)\n        self.prefixDB.save()\n        await context.send(f\"Prefix set to {prefix}\")\n\n    @commands.hybrid_command(\n        name=\"groq-api-key\",\n        description=\"Set API key for AI (run in private channel please)\",\n        usage=\"groq-api-key <key>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.has_permissions(manage_channels=True)\n    async def groq_api_key(self, context: commands.Context, key: str):\n        c = db[\"guilds\"]\n        data = c.find_one({\"id\": context.guild.id})\n\n        if not data:\n            data = CONSTANTS.guild_data_template(context.guild.id)\n            c.insert_one(data)\n\n        cipher_suite = Fernet(os.getenv(\"HASHING_SECRET\"))\n        cipher_text = cipher_suite.encrypt(key.encode())\n\n        try:\n            await context.message.delete()\n        except:\n            pass\n\n        if key == \"NONE\":\n            cipher_text = \"NONE\"\n\n        newdata = { \"$set\": { \"groq_api_key\": cipher_text } }\n\n        c.update_one({\"id\": context.guild.id}, newdata)\n\n        await context.send(f\"Set groq api key\")\n\n    @commands.hybrid_command(\n        name=\"stealemoji\",\n        description=\"Steal an emoji from another server.\",\n        usage=\"stealemoji <emoji> <name>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.has_permissions(manage_emojis=True)\n    @commands.bot_has_permissions(manage_emojis=True)\n    async def stealemoji(self, context: Context, emoji: discord.PartialEmoji, name: str) -> None:\n        try:\n            emoji_bytes = await emoji.read()\n            await context.guild.create_custom_emoji(\n                name=name if name else emoji.name,\n                image=emoji_bytes,\n                reason=f\"Emoji yoinked by {context.author} VIA {context.guild.me.name}\",\n            )\n            await context.send(\n                embed=discord.Embed(\n                    description=f\"Emoji Stolen\",\n                    color=discord.Color.random(),\n                ).set_image(url=emoji.url)\n            )\n        except Exception as e:\n            await context.send(str(e))\n\n    @commands.hybrid_command(\n        name=\"emojifromurl\",\n        description=\"Add an emoji from a URL.\",\n        usage=\"emojifromurl <url> <name>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.has_permissions(manage_emojis=True)\n    @commands.bot_has_permissions(manage_emojis=True)\n    async def emojifromurl(self, context: Context, url: str, name: str) -> None:\n        async with aiohttp.ClientSession() as session:\n            async with session.get(url) as response:\n                if response.status == 200:\n                    emoji_bytes = await response.read()\n                    await context.guild.create_custom_emoji(\n                        name=name,\n                        image=emoji_bytes,\n                        reason=f\"Emoji added by {context.author} VIA {context.guild.me.name}\",\n                    )\n                    await context.send(\n                        embed=discord.Embed(\n                            description=f\"Emoji added\",\n                            color=discord.Color.random(),\n                        ).set_image(url=url)\n                    )\n                else:\n                    await context.send(\"Failed to download the emoji\")\n\n    @commands.hybrid_group(\n        name=\"settings\",\n        description=\"Command to change server settings\",\n        aliases=[\"setting\"],\n        usage=\"settings <subcommand> [args]\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.has_permissions(manage_channels=True)\n    async def settings(self, context: Context) -> None:\n        subcommands = [cmd for cmd in self.settings.walk_commands()]\n\n        data = []\n\n        for subcommand in subcommands:\n            description = subcommand.description.partition(\"\\n\")[0]\n            data.append(f\"{await self.bot.get_prefix(context)}settings {subcommand.name} - {description}\")\n\n        help_text = \"\\n\".join(data)\n        embed = discord.Embed(\n            title=f\"Help: Settings\", description=\"List of available commands:\", color=0xBEBEFE\n        )\n        embed.add_field(\n            name=\"Commands\", value=f\"```{help_text}```\", inline=False\n        )\n\n        await context.send(embed=embed)\n\n    @settings.command(\n        name=\"show\",\n        description=\"Show server settings\",\n        usage=\"settings show\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.has_permissions(manage_channels=True)\n    async def show(self, context: Context) -> None:\n        c = db[\"guilds\"]\n        data = c.find_one({\"id\": context.guild.id})\n\n        if not data:\n            data = CONSTANTS.guild_data_template(context.guild.id)\n            c.insert_one(data)\n\n        embed = discord.Embed(\n            title=\"Server Settings\",\n            color=discord.Color.blue()\n        )\n\n        embed.add_field( name=\"Daily Cash\", value=data[\"daily_cash\"] )\n        embed.add_field( name=\"Tickets Category\",\n                        value=context.guild.get_channel(data[\"tickets_category\"]).name.capitalize() if data[\"tickets_category\"] else \"None\" )\n        embed.add_field( name=\"Tickets Support Role\",\n                        value=context.guild.get_role(data[\"tickets_support_role\"]).mention if data[\"tickets_support_role\"] else \"None\" )\n        embed.add_field( name=\"Log Channel\", value=context.guild.get_channel(data[\"log_channel\"]).mention if data[\"log_channel\"] else \"None\" )\n        embed.add_field( name=\"Level Roles\", value=\"`/setting level_roles show`\")\n        embed.add_field( name=\"Level Announce Channel\",\n                        value=context.guild.get_channel( data[\"level_announce_channel\"]).mention if (\n                                \"level_announce_channel\" in data and context.guild.get_channel(data[\"level_announce_channel\"]) != None\n                            ) else \"None\"\n                        )\n        embed.add_field( name=\"Should announce levelup\", value=data[\"should_announce_levelup\"] if \"should_announce_levelup\" in data else \"idk\")\n\n        await context.send(embed=embed)\n\n    @settings.command(\n        name=\"announce-levelup\",\n        description=\"Should levelups be announced?\",\n        usage=\"settings announce-levelup <enabled>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.has_permissions(manage_roles=True)\n    async def should_announce_levelup(self, context: Context, enabled: bool) -> None:\n        c = db[\"guilds\"]\n        data = c.find_one({\"id\": context.guild.id})\n\n        if not data:\n            data = CONSTANTS.guild_data_template(context.guild.id)\n            c.insert_one(data)\n\n        newdata = { \"$set\": { \"should_announce_levelup\": enabled } }\n\n        c.update_one({\"id\": context.guild.id}, newdata)\n\n        await context.send(f\"Set should announce levelup to {enabled}\")\n\n    @settings.command(\n        name=\"daily-cash\",\n        description=\"Set daily cash amount\",\n        usage=\"settings daily-cash <amount>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.has_permissions(administrator=True)\n    async def daily_cash(self, context: Context, amount: int) -> None:\n        c = db[\"guilds\"]\n\n        data = c.find_one({\"id\": context.guild.id})\n\n        if not data:\n            data = CONSTANTS.guild_data_template(context.guild.id)\n            c.insert_one(data)\n\n        newdata = { \"$set\": { \"daily_cash\": amount } }\n\n        c.update_one({\"id\": context.guild.id}, newdata)\n\n        await context.send(f\"Set daily cash to {amount}\")\n\n    @settings.command(\n        name=\"tickets-category\",\n        description=\"Set category where tickets are created\",\n        usage=\"settings tickets-category <category>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.has_permissions(administrator=True)\n    async def tickets_category(self, context: Context, category: discord.CategoryChannel) -> None:\n        c = db[\"guilds\"]\n\n        data = c.find_one({\"id\": context.guild.id})\n\n        if not data:\n            data = CONSTANTS.guild_data_template(context.guild.id)\n            c.insert_one(data)\n\n        newdata = { \"$set\": { \"tickets_category\": category.id } }\n\n        c.update_one({\"id\": context.guild.id}, newdata)\n\n        await context.send(f\"Set tickets category to {category.mention}\")\n\n    @settings.command(\n        name=\"level-up-channel\",\n        description=\"Set level up announce channel\",\n        usage=\"settings level-up-channel <channel>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.has_permissions(manage_channels=True)\n    async def level_up_channel(self, context: Context, channel: discord.TextChannel) -> None:\n        c = db[\"guilds\"]\n\n        data = c.find_one({\"id\": context.guild.id})\n\n        if not data:\n            data = CONSTANTS.guild_data_template(context.guild.id)\n            c.insert_one(data)\n\n        newdata = { \"$set\": { \"level_announce_channel\": channel.id } }\n\n        c.update_one({\"id\": context.guild.id}, newdata)\n\n        await context.send(f\"Set level announce channel to {channel.mention}\")\n\n    @settings.command(\n        name=\"tickets-support-role\",\n        description=\"Set ticket support role\",\n        usage=\"settings tickets-support-role <role>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.has_permissions(manage_roles=True)\n    async def tickets_support_role(self, context: Context, role: discord.Role) -> None:\n        c = db[\"guilds\"]\n\n        data = c.find_one({\"id\": context.guild.id})\n\n        if not data:\n            data = CONSTANTS.guild_data_template(context.guild.id)\n            c.insert_one(data)\n\n        newdata = { \"$set\": { \"tickets_support_role\": role.id } }\n\n        c.update_one({\"id\": context.guild.id}, newdata)\n\n        await context.send(f\"Set tickets support role to {role.mention}\")\n\n    @settings.command(\n        name=\"log-channel\",\n        description=\"Set log channel\",\n        usage=\"settings log-channel <channel>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.has_permissions(manage_channels=True)\n    async def log_channel(self, context: Context, channel: discord.TextChannel) -> None:\n        c = db[\"guilds\"]\n\n        data = c.find_one({\"id\": context.guild.id})\n\n        if not data:\n            data = CONSTANTS.guild_data_template(context.guild.id)\n            c.insert_one(data)\n\n        newdata = { \"$set\": { \"log_channel\": channel.id } }\n\n        c.update_one({\"id\": context.guild.id}, newdata)\n\n        await context.send(f\"Set log channel to {channel.mention}\")\n\n    @settings.command(\n        name=\"default-role\",\n        description=\"Set default role to be given to new members\",\n        usage=\"settings default-role <role>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.has_permissions(manage_roles=True)\n    async def default_role(self, context: Context, role: discord.Role) -> None:\n        c = db[\"guilds\"]\n\n        data = c.find_one({\"id\": context.guild.id})\n\n        if not data:\n            data = CONSTANTS.guild_data_template(context.guild.id)\n            c.insert_one(data)\n\n        dangerous_permissions = [\n            \"administrator\",\n            \"manage_guild\",\n            \"manage_roles\",\n            \"manage_channels\",\n            \"manage_messages\",\n            \"kick_members\",\n            \"ban_members\",\n            \"manage_webhooks\",\n            \"manage_emojis\",\n            \"manage_nicknames\",\n        ]\n\n        for permission in dangerous_permissions:\n            if getattr(role.permissions, permission):\n                return await context.send(\"The role has dangerous permissions. Please choose a role without dangerous permissions.\")\n\n        newdata = { \"$set\": { \"default_role\": role.id } }\n\n        c.update_one({\"id\": context.guild.id}, newdata)\n\n        await context.send(f\"Set default role to {role.name}\")\n\n    @settings.group(\n        name=\"level-roles\",\n        description=\"Commands to set up level roles\",\n        usage=\"settings level-roles\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.has_permissions(manage_roles=True)\n    async def level_roles(self, context: Context) -> None:\n        c = db[\"guilds\"]\n        data = c.find_one({\"id\": context.guild.id})\n\n        if not data:\n            data = CONSTANTS.guild_data_template(context.guild.id)\n            c.insert_one(data)\n\n        embed = discord.Embed(\n            title=\"Level Roles\",\n            color=discord.Color.blue()\n        )\n\n\n        for r in data[\"level_roles\"]:\n            embed.add_field(\n                name=r,\n                value=context.guild.get_role(data[\"level_roles\"][r]).mention\n            )\n\n        await context.send(embed=embed)\n\n    @level_roles.command(\n        name=\"show\",\n        description=\"Show level roles\",\n        usage=\"settings level-roles show\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.has_permissions(manage_roles=True)\n    async def show_level_roles(self, context: Context) -> None:\n        c = db[\"guilds\"]\n        data = c.find_one({\"id\": context.guild.id})\n\n        if not data:\n            data = CONSTANTS.guild_data_template(context.guild.id)\n            c.insert_one(data)\n\n        embed = discord.Embed(\n            title=\"Level Roles\",\n            color=discord.Color.blue()\n        )\n\n        for r in data[\"level_roles\"]:\n            embed.add_field(\n                name=r,\n                value=context.guild.get_role(data[\"level_roles\"][r]).mention\n            )\n\n        await context.send(embed=embed)\n\n    @level_roles.command(\n        name=\"set\",\n        description=\"Set level roles\",\n        usage=\"settings level-roles set <level> <role>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.has_permissions(manage_roles=True)\n    async def set(self, context: Context, level: int, role: discord.Role) -> None:\n        c = db[\"guilds\"]\n        data = c.find_one({\"id\": context.guild.id})\n\n        if not data:\n            data = CONSTANTS.guild_data_template(context.guild.id)\n            c.insert_one(data)\n\n        level_roles = data[\"level_roles\"]\n        level_roles[str(level)] = role.id\n\n        newdata = { \"$set\": { \"level_roles\": level_roles } }\n        c.update_one({\"id\": context.guild.id}, newdata)\n\n        await context.send(f\"Set level {level} role to {role.name}\")\n\n    @commands.hybrid_group(\n        name=\"command\",\n        description=\"Commands to re-enable/disable commands\",\n        aliases=[\"cmd\"],\n        usage=\"Command <subcommand> [args]\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.has_permissions(manage_channels=True)\n    async def cmd(self, context: Context) -> None:\n        prefix = await self.bot.get_prefix(context)\n\n        cmds = \"\\n\".join([f\"{prefix}cmd {cmd.name} - {cmd.description}\" for cmd in self.cmd.walk_commands()])\n\n        embed = discord.Embed(\n            title=f\"Help: Command\", description=\"List of available commands:\", color=0xBEBEFE\n        )\n        embed.add_field(\n            name=\"Commands\", value=f\"```{cmds}```\", inline=False\n        )\n\n        await context.send(embed=embed)\n\n    @cmd.command(\n        name=\"disable\",\n        description=\"Disable a command\",\n        usage=\"cmd disable <command>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.has_permissions(administrator=True)\n    async def disable(self, context: Context, *, command: str) -> None:\n        cmd = self.bot.get_command(command)\n\n        if not cmd:\n            return await context.send(\"Command not found\")\n\n        if cmd.qualified_name.startswith(\"command\") or cmd.qualified_name.startswith(\"cmd\"):\n            return await context.send(\"You cannot disable this command\")\n\n        guild = await CachedDB.find_one(db[\"guilds\"], {\"id\": context.guild.id})\n\n        if not guild:\n            guild = CONSTANTS.guild_data_template(context.guild.id)\n            db[\"guilds\"].insert_one(guild)\n\n        if cmd.qualified_name in guild[\"disabled_commands\"]:\n            return await context.send(f\"The command `{cmd.qualified_name}` is already disabled\")\n\n        guild[\"disabled_commands\"].append(cmd.qualified_name)\n\n        await CachedDB.update_one(db[\"guilds\"], {\"id\": context.guild.id}, {\"$set\": {\"disabled_commands\": guild[\"disabled_commands\"]}})\n\n        await context.send(f\"Disabled the command `{cmd.qualified_name}`\")\n\n    @cmd.command(\n        name=\"enable\",\n        description=\"Re-enable a command\",\n        usage=\"cmd enable <command>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.has_permissions(administrator=True)\n    async def cmd_enable(self, context: Context, *, command: str) -> None:\n        cmd = self.bot.get_command(command)\n\n        if not cmd:\n            return await context.send(\"Command not found\")\n\n        guild = await CachedDB.find_one(db[\"guilds\"], {\"id\": context.guild.id})\n\n        if not guild:\n            guild = CONSTANTS.guild_data_template(context.guild.id)\n            db[\"guilds\"].insert_one(guild)\n\n        if command not in guild[\"disabled_commands\"]:\n            return await context.send(f\"The command `{cmd.qualified_name}` is not disabled\")\n\n        guild[\"disabled_commands\"].remove(cmd.qualified_name)\n\n        await CachedDB.update_one(db[\"guilds\"], {\"id\": context.guild.id}, {\"$set\": {\"disabled_commands\": guild[\"disabled_commands\"]}})\n\n        await context.send(f\"Re-enabled the command `{cmd.qualified_name}`\")\n\n\nasync def setup(bot) -> None:\n    await bot.add_cog(Server(bot))\n"
  },
  {
    "path": "cogs/staff.py",
    "content": "# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon\n\nimport os\n\nimport re\nfrom datetime import datetime, timedelta\n\nimport discord\nfrom discord import app_commands\nfrom discord.ext import commands\nfrom discord.ext.commands import Context\n\nfrom utils import DBClient, CONSTANTS, Checks, CachedDB\n\nfrom ui.recreate import deleteconfirm\n\nclient = DBClient.client\ndb = client.potatobot\n\nclass Staff(commands.Cog, name=\"👮‍♂️ Staff\"):\n    def __init__(self, bot) -> None:\n        self.bot = bot\n        self.prefixDB = bot.prefixDB\n\n    @commands.Cog.listener()\n    async def on_message_delete(self, message: discord.Message) -> None:\n        if message.author == self.bot.user or message.author.bot:\n            return\n\n        if message.author.guild_permissions.administrator:\n            return\n\n        c = db[\"guilds\"]\n        data = await CachedDB.find_one(c, {\"id\": message.guild.id})\n\n        if not data:\n            data = CONSTANTS.guild_data_template(message.guild.id)\n            c.insert_one(data)\n\n        if not data[\"log_channel\"]:\n            return\n\n        log_channel = message.guild.get_channel(data[\"log_channel\"])\n\n        if not log_channel:\n            return\n\n        embed = discord.Embed(\n            title=\"Message Deleted\",\n            description=f\"Message sent by {message.author.mention} deleted in {message.channel.mention}\",\n            color=0xff6961\n        )\n\n        embed.add_field(\n            name=\"Content\",\n            value=message.content\n        )\n\n        await log_channel.send(embed=embed)\n\n    @commands.Cog.listener()\n    async def on_message_edit(self, before: discord.Message, after: discord.Message) -> None:\n        if before.author == self.bot.user or before.author.bot:\n            return\n\n        if before.author.guild_permissions.administrator:\n            return\n\n        if before.content == after.content:\n            return\n\n        c = db[\"guilds\"]\n        data = await CachedDB.find_one(c, {\"id\": before.guild.id})\n\n        if not data:\n            data = CONSTANTS.guild_data_template(before.guild.id)\n            c.insert_one(data)\n\n        if not data[\"log_channel\"]:\n            return\n\n        log_channel = before.guild.get_channel(data[\"log_channel\"])\n\n        if not log_channel:\n            return\n\n        embed = discord.Embed(\n            title=\"Message Edited\",\n            description=f\"Message sent by {before.author.mention} edited in {before.channel.mention}\",\n            color=0xfdfd96\n        )\n\n        embed.add_field(\n            name=\"Before\",\n            value=before.content\n        )\n\n        embed.add_field(\n            name=\"After\",\n            value=after.content\n        )\n\n        await log_channel.send(embed=embed)\n\n    @commands.Cog.listener()\n    async def on_member_remove(self, user: discord.User) -> None:\n        c = db[\"guilds\"]\n        guild = user.guild\n\n        data = await CachedDB.find_one(c, {\"id\": guild.id})\n\n        if not data:\n            data = CONSTANTS.guild_data_template(guild.id)\n            c.insert_one(data)\n\n        if not data[\"log_channel\"]:\n            return\n\n        log_channel = guild.get_channel(data[\"log_channel\"])\n\n        if not log_channel:\n            return\n\n        embed = discord.Embed(\n            title=\"Member Left\",\n            description=f\"{user.mention} ({user}) left the server\",\n            color=0xff6961\n        )\n\n        await log_channel.send(embed=embed)\n\n    @commands.Cog.listener()\n    async def on_member_ban(self, guild: discord.Guild, user: discord.User) -> None:\n        c = db[\"guilds\"]\n\n        data = await CachedDB.find_one(c, {\"id\": guild.id})\n\n        if not data:\n            data = CONSTANTS.guild_data_template(guild.id)\n            c.insert_one(data)\n\n        if not data[\"log_channel\"]:\n            return\n\n        log_channel = guild.get_channel(data[\"log_channel\"])\n\n        if not log_channel:\n            return\n\n        embed = discord.Embed(\n            title=\"Member Banned\",\n            description=f\"{user.mention} was banned\",\n            color=0xff6961\n        )\n\n        await log_channel.send(embed=embed)\n\n    @commands.Cog.listener()\n    async def on_member_unban(self, guild: discord.Guild, user: discord.User) -> None:\n        c = db[\"guilds\"]\n\n        data = await CachedDB.find_one(c, {\"id\": guild.id})\n\n        if not data:\n            data = CONSTANTS.guild_data_template(guild.id)\n            c.insert_one(data)\n\n        if not data[\"log_channel\"]:\n            return\n\n        log_channel = guild.get_channel(data[\"log_channel\"])\n\n        if not log_channel:\n            return\n\n        embed = discord.Embed(\n            title=\"Member Unbanned\",\n            description=f\"{user.mention} was unbanned\",\n            color=discord.Color.green()\n        )\n\n        await log_channel.send(embed=embed)\n\n    @commands.Cog.listener()\n    async def on_member_kick(self, guild: discord.Guild, user: discord.User) -> None:\n        c = db[\"guilds\"]\n\n        data = await CachedDB.find_one(c, {\"id\": guild.id})\n\n        if not data:\n            data = CONSTANTS.guild_data_template(guild.id)\n            c.insert_one(data)\n\n        if not data[\"log_channel\"]:\n            return\n\n        log_channel = guild.get_channel(data[\"log_channel\"])\n\n        if not log_channel:\n            return\n\n        embed = discord.Embed(\n            title=\"Member Kicked\",\n            description=f\"{user.mention} was kicked\",\n            color=0xff6961\n        )\n\n        await log_channel.send(embed=embed)\n\n    @commands.Cog.listener()\n    async def on_member_join(self, user: discord.User) -> None:\n        if user.bot:\n            return\n\n        users = db[\"users\"]\n        user_data = await CachedDB.find_one(users, {\"id\": user.id})\n\n        guilds = db[\"guilds\"]\n\n        data = await CachedDB.find_one(guilds, {\"id\": user.guild.id})\n\n\n        if not data:\n            data = CONSTANTS.guild_data_template(user.guild.id)\n            guilds.insert_one(data)\n\n        if user_data:\n            if \"jailed\" in user_data:\n                if user_data[\"jailed\"]:\n                    if \"jail_role\" in data:\n                        role = None\n                        jail_channel = None\n\n                        if data[\"jail_role\"] == 0:\n                            role = await user.guild.create_role(name=\"Jailed\", reason=\"Jail role created by PotatoBot\")\n                            data[\"jail_role\"] = role.id\n\n                            newdata = {\"$set\": {\"jail_role\": role.id}}\n                            guilds.update_one({\"id\": user.guild.id}, newdata)\n                        else:\n                            role = user.guild.get_role(data[\"jail_role\"])\n\n                        for old_role in user.roles:\n                            if old_role == user.guild.default_role:\n                                continue\n\n                            await user.remove_roles(old_role)\n\n                        await user.add_roles(role, reason=\"User is jailed and tried to rejoin\")\n\n                        return\n\n        if not \"default_role\" in data:\n            return\n\n        default_role = user.guild.get_role(data[\"default_role\"])\n\n        if default_role:\n            await user.add_roles(default_role)\n\n\n    @commands.Cog.listener()\n    async def on_bulk_message_delete(self, messages) -> None:\n        embed = discord.Embed(\n            title=\"Bulk Message Delete\",\n            description=f\"{len(messages)} messages were deleted\",\n            color=0xff6961\n        )\n\n        c = db[\"guilds\"]\n        data = await CachedDB.find_one(c, {\"id\": messages[0].guild.id})\n\n        if not data:\n            data = CONSTANTS.guild_data_template(messages[0].guild.id)\n            c.insert_one(data)\n\n        if not data[\"log_channel\"]:\n            return\n\n        log_channel = messages[0].guild.get_channel(data[\"log_channel\"])\n\n        if not log_channel:\n            return\n\n        await log_channel.send(embed=embed)\n\n    @commands.Cog.listener()\n    async def on_guild_channel_create(self, channel: discord.TextChannel):\n        embed = discord.Embed(\n            title = \"Channel Created\",\n            description = f\"Channel {channel.mention} was created\",\n            color = discord.Color.green()\n        )\n\n        c = db[\"guilds\"]\n        data = c.find_one({\"id\": channel.guild.id})\n\n        if not data:\n            data = CONSTANTS.guild_data_template(channel.guild.id)\n            c.insert_one(data)\n\n        if not data[\"log_channel\"]:\n            return\n\n        log_channel = channel.guild.get_channel(data[\"log_channel\"])\n\n        if not log_channel:\n            return\n\n        await log_channel.send(embed=embed)\n\n    @commands.Cog.listener()\n    async def on_guild_channel_delete(self, channel: discord.TextChannel):\n        embed = discord.Embed(\n            title = \"Channel Deleted\",\n            description = f\"Channel {channel.mention} ({channel.name}) was deleted\",\n            color = 0xff6961\n        )\n\n        c = db[\"guilds\"]\n        data = c.find_one({\"id\": channel.guild.id})\n\n        if not data:\n            data = CONSTANTS.guild_data_template(channel.guild.id)\n            c.insert_one(data)\n\n        if not data[\"log_channel\"]:\n            return\n\n        log_channel = channel.guild.get_channel(data[\"log_channel\"])\n\n        if not log_channel:\n            return\n\n        try:\n            await log_channel.send(embed=embed)\n        except:\n            pass\n\n    ###\n\n    @commands.hybrid_command(\n        name=\"kick\",\n        aliases=[\"k\", \"yeet\"],\n        description=\"Kick a user out of the server.\",\n        usage=\"kick <user> [reason]\",\n        extras={\"example\":\"kick @user advertising\"}\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @Checks.has_perm(kick_members=True)\n    @commands.bot_has_permissions(kick_members=True)\n    async def kick(\n        self, context: Context, member: discord.Member, *, reason: str = \"Not specified\"\n    ) -> None:\n        if context.author.top_role.position <= member.top_role.position:\n            embed = discord.Embed(\n                description=\"You cannot kick a user with a higher or equal role than you.\",\n                color=0xE02B2B,\n            )\n            return await context.send(embed=embed)\n\n        if member == self.bot.user:\n            return await context.send(\"what did i do :C\")\n\n        if member.guild_permissions.administrator:\n            embed = discord.Embed(\n                description=\"User has administrator permissions.\", color=0xE02B2B\n            )\n            await context.send(embed=embed)\n        else:\n            try:\n                messaged = False\n\n                try:\n                    await member.send(f\"You were kicked by **{context.author}** from **{context.guild.name}**!\\nReason: {reason}\")\n                    messaged = True\n                except:\n                    pass\n                await member.kick(reason=reason)\n\n                embed = discord.Embed(\n                    description=f\"**{member}** was kicked by **{context.author}**!\",\n                    color=0xBEBEFE,\n                )\n                embed.add_field(name=\"Reason:\", value=reason)\n                embed.add_field(name=\"Messaged User:\", value=\"Yes\" if messaged else \"No\")\n                await context.send(embed=embed)\n\n                guilds = db[\"guilds\"]\n                data = guilds.find_one({\"id\": context.guild.id})\n\n                if not data:\n                    data = CONSTANTS.guild_data_template(context.guild.id)\n                    guilds.insert_one(data)\n\n                if \"log_channel\" in data:\n                    log_channel = context.guild.get_channel(data[\"log_channel\"])\n\n                    if log_channel:\n                        embed = discord.Embed(\n                            title=\"Member Kicked\",\n                            description=f\"{member.mention} was kicked by {context.author.mention}\",\n                            color=0xff6961\n                        )\n\n                        embed.add_field(\n                            name=\"Reason\",\n                            value=reason\n                        )\n\n                        await log_channel.send(embed=embed)\n            except:\n                embed = discord.Embed(\n                    description=\"An error occurred while trying to kick the user. Make sure my role is above the role of the user you want to kick.\",\n                    color=0xE02B2B,\n                )\n                await context.send(embed=embed)\n\n    @commands.hybrid_command(\n        name=\"nick\",\n        aliases=[\"n\"],\n        description=\"Change the nickname of a user on a server.\",\n        usage=\"nick <user> <nickname>\",\n        extras={\"example\":\"nick @user new nickname\"}\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @Checks.has_perm(manage_nicknames=True)\n    @commands.bot_has_permissions(manage_nicknames=True)\n    async def nick(\n        self, context: Context, member: discord.Member, *, nickname: str = None\n    ) -> None:\n        try:\n            await member.edit(nick=nickname)\n            embed = discord.Embed(\n                description=f\"**{member}'s** new nickname is **{nickname}**!\",\n                color=0xBEBEFE,\n            )\n            await context.send(embed=embed)\n        except:\n            embed = discord.Embed(\n                description=\"An error occurred while trying to change the nickname of the user. Make sure my role is above the role of the user you want to change the nickname.\",\n                color=0xE02B2B,\n            )\n            await context.send(embed=embed)\n\n    @commands.hybrid_command(\n        name=\"ban\",\n        aliases=[\"b\"],\n        description=\"Bans a user from the server.\",\n        usage=\"ban <user> [reason]\",\n        extras={\"example\": \"ban @user spamming\"},\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @Checks.has_perm(ban_members=True)\n    @commands.bot_has_permissions(ban_members=True)\n    async def ban(\n        self, context: Context, member: discord.Member, *, reason: str = \"Not specified\"\n    ) -> None:\n        if context.author.top_role.position <= member.top_role.position:\n            embed = discord.Embed(\n                description=\"You cannot kick a user with a higher or equal role than you.\",\n                color=0xE02B2B,\n            )\n            return await context.send(embed=embed)\n\n        if member == self.bot.user:\n            return await context.send(\"what did i do :C\")\n\n        try:\n            if member.guild_permissions.administrator:\n                embed = discord.Embed(\n                    description=\"User has administrator permissions.\", color=0xE02B2B\n                )\n                await context.send(embed=embed)\n            else:\n                messaged = False\n                try:\n                    embed = discord.Embed(\n                        title=\"You were banned!\",\n                        description=f\"You were banned from **{context.guild.name}**\",\n                        color=0xff6961\n                    )\n\n                    embed.add_field(name=\"Reason\", value=reason)\n\n                    await member.send(embed=embed)\n                    messaged = True\n                except:\n                    pass\n\n                await member.ban(reason=reason, delete_message_days=0)\n\n                embed = discord.Embed(\n                    description=f\"**{member}** was banned by **{context.author}**!\",\n                    color=0xBEBEFE,\n                )\n                embed.add_field(name=\"Reason:\", value=reason)\n                embed.add_field(name=\"Messaged User:\", value=\"Yes\" if messaged else \"No\")\n                await context.send(embed=embed)\n\n                guilds = db[\"guilds\"]\n                data = guilds.find_one({\"id\": context.guild.id})\n\n                if not data:\n                    data = CONSTANTS.guild_data_template(context.guild.id)\n                    guilds.insert_one(data)\n\n                if \"log_channel\" in data:\n                    log_channel = context.guild.get_channel(data[\"log_channel\"])\n\n                    if log_channel:\n                        embed = discord.Embed(\n                            title=\"Member Banned\",\n                            description=f\"{member.mention} was banned by {context.author.mention}\",\n                            color=0xff6961\n                        )\n\n                        embed.add_field(\n                            name=\"Reason\",\n                            value=reason\n                        )\n\n                        await log_channel.send(embed=embed)\n        except:\n            embed = discord.Embed(\n                title=\"Error!\",\n                description=\"An error occurred while trying to ban the user. Make sure my role is above the role of the user you want to ban.\",\n                color=0xE02B2B,\n            )\n            await context.send(embed=embed)\n\n    @commands.hybrid_command(\n        name=\"hackban\",\n        description=\"Ban a user that is not in the server\",\n        usage=\"hackban <user> [reason]\",\n        extras={\"example\": \"hackban 1226487228914602005 spamming\"}\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @Checks.has_perm(ban_members=True)\n    @commands.bot_has_permissions(ban_members=True)\n    async def hackban(self, context: Context, user: discord.User, *, reason: str = \"Not specified\"):\n        if user == self.bot.user:\n            return await context.send(\"what did i do :C\")\n\n        member = await context.guild.fetch_member(user.id)\n\n        if member:\n            return await context.send(\"User is already in the server! Use the `ban` command instead.\")\n\n        try:\n            await context.guild.ban(user, reason=reason, delete_message_days=0)\n\n            embed = discord.Embed(\n                title=\"User Hackbanned\",\n                description=f\"**{user}** was hackbanned by **{context.author}**!\",\n                color=0xBEBEFE,\n            )\n\n            embed.add_field(name=\"Reason:\", value=reason)\n\n            guilds = db[\"guilds\"]\n            data = guilds.find_one({\"id\": context.guild.id})\n\n            if not data:\n                data = CONSTANTS.guild_data_template(context.guild.id)\n                guilds.insert_one(data)\n\n            if \"log_channel\" in data:\n                log_channel = context.guild.get_channel(data[\"log_channel\"])\n\n                if log_channel:\n                    await log_channel.send(embed=embed)\n\n            await context.send(f\"Banned **{user}**!\")\n        except:\n            embed = discord.Embed(\n                title=\"Error!\",\n                description=\"An error occurred while trying to ban the user.\",\n                color=0xE02B2B,\n            )\n\n            await context.send(embed=embed)\n\n    @commands.hybrid_command(\n        name=\"softban\",\n        description=\"Bans and unbans a user from the server to delete messages\",\n        usage=\"softban <user>\",\n        extras={\"example\": \"softban @user\"}\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @Checks.has_perm(ban_members=True)\n    @commands.bot_has_permissions(ban_members=True)\n    async def softban(self, context: Context, user: discord.Member):\n        if context.author.top_role.position <= user.top_role.position:\n            embed = discord.Embed(\n                description=\"You cannot kick a user with a higher or equal role than you.\",\n                color=0xE02B2B,\n            )\n            return await context.send(embed=embed)\n\n        if user == self.bot.user:\n            return await context.send(\"what did i do :C\")\n\n        try:\n            if user.guild_permissions.administrator:\n                embed = discord.Embed(\n                    description=\"User has administrator permissions.\", color=0xE02B2B\n                )\n                return await context.send(embed=embed)\n\n            await context.guild.ban(user, reason=\"Softban\", delete_message_days=7)\n            await context.guild.unban(user, reason=\"Softban\")\n\n            embed = discord.Embed(\n                description=f\"**{user}** was softbanned by **{context.author}**!\",\n                color=0xBEBEFE,\n            )\n            await context.send(embed=embed)\n\n        except Exception as e:\n            embed = discord.Embed(\n                description=\"An error occurred while trying to softban the user, \" + str(e),\n                color=0xE02B2B,\n            )\n            await context.send(embed=embed)\n\n\n    @commands.hybrid_command(\n        name=\"unban\",\n        description=\"Unban a user from the server.\",\n        usage=\"unban <user>\",\n        extras={\"example\": \"unban 1226487228914602005\"}\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @Checks.has_perm(ban_members=True)\n    @commands.bot_has_permissions(ban_members=True)\n    async def unban(self, context: Context, user: discord.User):\n        try:\n            banned_users = context.guild.bans()\n            async for ban_entry in banned_users:\n                if ban_entry.user.id == user.id:\n                    await context.guild.unban(user)\n                    embed = discord.Embed(\n                        description=f\"**{user}** was unbanned by **{context.author}**!\",\n                        color=0xBEBEFE,\n                    )\n                    await context.send(embed=embed)\n\n                    try:\n                        embed = discord.Embed(\n                            title=\"You were unbanned!\",\n                            description=f\"You were unbanned from **{context.guild.name}**\",\n                            color=discord.Color.green()\n                        )\n\n                        await user.send(embed=embed)\n                    except:\n                        pass\n\n                    guilds = db[\"guilds\"]\n                    guild = guilds.find_one({\"id\": context.guild.id})\n\n                    if not guild:\n                        guild = CONSTANTS.guild_data_template(context.guild.id)\n                        guilds.insert_one(guild)\n\n                    if \"log_channel\" in guild:\n                        log_channel = context.guild.get_channel(guild[\"log_channel\"])\n\n                        if log_channel:\n                            embed = discord.Embed(\n                                title=\"Member Unbanned\",\n                                description=f\"{user.mention} was unbanned by {context.author.mention}\",\n                                color=discord.Color.green()\n                            )\n\n                            await log_channel.send(embed=embed)\n\n                    return\n            embed = discord.Embed(\n                description=\"User is not banned.\", color=0xE02B2B\n            )\n            await context.send(embed=embed)\n        except Exception as e:\n            embed = discord.Embed(\n                description=\"An error occurred while trying to unban the user: \" + str(e),\n                color=0xE02B2B,\n            )\n            await context.send(embed=embed)\n\n    @commands.hybrid_command(\n        name=\"purge\",\n        aliases=[\"clear\"],\n        description=\"Delete a number of messages.\",\n        usage=\"purge <amount>\",\n        extras={\"example\": \"purge 10\"}\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @Checks.has_perm(manage_messages=True)\n    @commands.bot_has_permissions(manage_messages=True)\n    @app_commands.describe(amount=\"The amount of messages that should be deleted.\")\n    async def purge(self, context: Context, amount: int) -> None:\n        await context.defer()\n        purged_messages = await context.channel.purge(limit=amount + 1)\n        embed = discord.Embed(\n            description=f\"**{context.author}** cleared **{len(purged_messages)-1}** messages!\",\n            color=0xBEBEFE,\n        )\n        await context.channel.send(embed=embed)\n\n    @commands.hybrid_command(\n        name=\"archive\",\n        description=\"Archives in a text file the last messages with a chosen limit of messages.\",\n        usage=\"archive <limit>\",\n        extras={\"example\": \"archive 10\"}\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @Checks.has_perm(manage_messages=True)\n    async def archive(self, context: Context, limit: int = 10) -> None:\n        os.makedirs(\"logs\", exist_ok=True)\n        log_file = f\"logs/{context.channel.id}.log\"\n        with open(log_file, \"w\", encoding=\"UTF-8\") as f:\n            f.write(\n                f'Archived messages from: #{context.channel} ({context.channel.id}) in the guild \"{context.guild}\" ({context.guild.id}) at {datetime.now().strftime(\"%d.%m.%Y %H:%M:%S\")}\\n'\n            )\n            async for message in context.channel.history(\n                limit=limit, before=context.message\n            ):\n                attachments = []\n                for attachment in message.attachments:\n                    attachments.append(attachment.url)\n                attachments_text = (\n                    f\"[Attached File{'s' if len(attachments) >= 2 else ''}: {', '.join(attachments)}]\"\n                    if len(attachments) >= 1\n                    else \"\"\n                )\n                f.write(\n                    f\"{message.created_at.strftime('%d.%m.%Y %H:%M:%S')} {message.author} {message.id}: {message.clean_content} {attachments_text}\\n\"\n                )\n        f = discord.File(log_file)\n        await context.send(file=f)\n        os.remove(log_file)\n\n    @commands.hybrid_command(\n        name=\"mute\",\n        aliases=[\"timeout\"],\n        description=\"Mute a user in the server.\",\n        usage=\"mute <user> <time> [reason]\",\n        extras={\"example\": \"mute @user 1d spamming in #general\"}\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @Checks.has_perm(moderate_members=True)\n    @commands.bot_has_permissions(moderate_members=True)\n    async def mute(self, context: Context, user: discord.Member, time: str, *, reason: str = \"Not specified\") -> None:\n        if context.author.top_role.position <= user.top_role.position:\n            embed = discord.Embed(\n                description=\"You cannot mute a user with a higher or equal role than you.\",\n                color=0xE02B2B,\n            )\n            return await context.send(embed=embed)\n\n        if user == self.bot.user:\n            return await context.send(\"what did i do :C\")\n        try:\n            # Try to parse the string as a datetime\n            dt = datetime.fromisoformat(time)\n            return dt\n        except ValueError:\n            pass\n\n        # If the string is not a valid datetime, try to parse it as a duration\n        pattern = r'^(\\d+)([ydhmsw])$'\n        match = re.match(pattern, time)\n\n        if not match:\n            return await context.send(f\"Invalid duration string: {time}\")\n\n        value, unit = int(match.group(1)), match.group(2)\n        duration = {\n            'y': timedelta(days=365*value),\n            'w': timedelta(days=7*value),\n            'month': timedelta(days=30*value),\n            'd': timedelta(days=value),\n            'h': timedelta(hours=value),\n            'm': timedelta(minutes=value),\n            's': timedelta(seconds=value),\n        }\n\n        delta = duration[unit]\n\n        await user.timeout(delta, reason=reason)\n        await context.send(f\"{user.mention} has been muted for {delta}\")\n\n        try:\n            await user.send(f\"You have been muted in {context.guild.name} for {delta} for the following reason: {reason}\")\n        except:\n            pass\n\n    @commands.hybrid_command(\n        name=\"unmute\",\n        aliases=[\"untimeout\"],\n        description=\"Unmute a user in the server.\",\n        usage=\"unmute <user> [reason]\",\n        extras={\"example\": \"unmute @user spamming in #general\"}\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @Checks.has_perm(moderate_members=True)\n    @commands.bot_has_permissions(moderate_members=True)\n    async def unmute(self, context: Context, user: discord.Member, *, reason: str = \"Not specified\") -> None:\n        await user.timeout(None, reason=reason)\n        await context.send(f\"{user.mention} has been unmuted\")\n\n        try:\n            await user.send(f\"You have been unmuted in {context.guild.name} for the following reason: {reason}\")\n        except:\n            pass\n\n    @commands.hybrid_command(\n        name=\"lock\",\n        description=\"Lock a channel.\",\n        usage=\"lock [optional: channel]\",\n        extras={\"example\": \"lock #general\"}\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @Checks.has_perm(manage_channels=True)\n    @commands.bot_has_permissions(manage_channels=True)\n    async def lockdown(self, context: Context, channel: discord.TextChannel = None) -> None:\n        if not channel:\n            channel = context.channel\n\n        overwrite = discord.PermissionOverwrite()\n        overwrite = channel.overwrites_for(context.guild.default_role)\n        overwrite.send_messages = False\n\n        await channel.set_permissions(context.guild.default_role, overwrite=overwrite)\n\n        await context.send(f\"{channel.mention} has been locked down\")\n\n        await channel.send(f\"# 🔒 This channel has been locked by staff\")\n\n    @commands.hybrid_command(\n        name=\"unlock\",\n        description=\"Unlock a channel.\",\n        usage=\"unlock [channel]\",\n        extras={\"example\": \"unlock #general\"}\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @Checks.has_perm(manage_channels=True)\n    @commands.bot_has_permissions(manage_channels=True)\n    async def unlock(self, context: Context, channel: discord.TextChannel = None) -> None:\n        if not channel:\n            channel = context.channel\n\n        overwrite = discord.PermissionOverwrite()\n        overwrite = channel.overwrites_for(context.guild.default_role)\n        overwrite.send_messages = None\n\n        await channel.set_permissions(context.guild.default_role, overwrite=overwrite)\n\n        await context.send(f\"{channel.mention} has been unlocked\")\n\n        await channel.send(f\"# 🔓 This channel has been unlocked by staff\")\n\n    @commands.hybrid_command(\n        name=\"jail\",\n        description=\"Jail a user.\",\n        usage=\"jail <user> [reason]\",\n        aliases=[\"quarantine\"],\n        extras={\"example\": \"jail @user admin abusing\"}\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @Checks.has_perm(moderate_members=True)\n    @commands.bot_has_permissions(manage_roles=True, manage_channels=True, manage_messages=True)\n    async def jail(self, context: Context, user: discord.Member, *, reason: str = \"Not specified\") -> None:\n        if context.author.top_role.position <= user.top_role.position:\n            embed = discord.Embed(\n                description=\"You cannot jail a user with a higher or equal role than you.\",\n                color=0xE02B2B,\n            )\n            return await context.send(embed=embed)\n\n        await context.send(\"Jailing user... please wait\")\n        guilds = db[\"guilds\"]\n        data = await CachedDB.find_one(guilds, {\"id\": context.guild.id})\n\n        if not data:\n            data = CONSTANTS.guild_data_template(context.guild.id)\n            guilds.insert_one(data)\n\n        role = None\n        jail_channel = None\n\n        if \"jail_role\" in data:\n            if data[\"jail_role\"] == 0:\n                role = await context.guild.create_role(name=\"Jailed\", reason=\"Jail role created by PotatoBot\")\n                data[\"jail_role\"] = role.id\n\n                newdata = {\"$set\": {\"jail_role\": role.id}}\n                guilds.update_one({\"id\": context.guild.id}, newdata)\n            else:\n                role = context.guild.get_role(data[\"jail_role\"])\n        else:\n            role = await context.guild.create_role(name=\"Jailed\", reason=\"Jail role created by PotatoBot\")\n            data[\"jail_role\"] = role.id\n\n            newdata = {\"$set\": {\"jail_role\": role.id}}\n            guilds.update_one({\"id\": context.guild.id}, newdata)\n\n\n        if \"jail_channel\" in data:\n            if data[\"jail_channel\"] == 0:\n                jail_channel = await context.guild.create_text_channel(name=\"jail\", reason=\"Jail channel created by PotatoBot\")\n                data[\"jail_channel\"] = jail_channel.id\n\n                newdata = {\"$set\": {\"jail_channel\": jail_channel.id}}\n                guilds.update_one({\"id\": context.guild.id}, newdata)\n            else:\n                jail_channel = context.guild.get_channel(data[\"jail_channel\"])\n        else:\n            jail_channel = await context.guild.create_text_channel(name=\"jail\", reason=\"Jail channel created by PotatoBot\")\n            data[\"jail_channel\"] = jail_channel.id\n\n            newdata = {\"$set\": {\"jail_channel\": jail_channel.id}}\n            guilds.update_one({\"id\": context.guild.id}, newdata)\n\n        for old_role in user.roles:\n            if old_role == context.guild.default_role:\n                continue\n\n            await user.remove_roles(old_role)\n\n        await user.add_roles(role, reason=reason)\n\n        for channel in context.guild.channels:\n            if channel == jail_channel:\n                continue\n\n            await channel.set_permissions(role, view_channel=False)\n\n        if not jail_channel:\n            jail_channel = await context.guild.create_text_channel(name=\"jail\", reason=\"Jail channel created by PotatoBot\")\n            data[\"jail_channel\"] = jail_channel.id\n\n            newdata = {\"$set\": {\"jail_channel\": jail_channel.id}}\n            guilds.update_one({\"id\": context.guild.id}, newdata)\n\n        await jail_channel.set_permissions(context.guild.default_role, view_channel=False)\n        await jail_channel.set_permissions(role, view_channel=True)\n\n        users = db[\"users\"]\n        user_data = await CachedDB.find_one(users, {\"id\": user.id})\n\n        if not user_data:\n            user_data = CONSTANTS.user_data_template(context.guild.id, user.id)\n            users.insert_one(user_data)\n\n        newdata = {\n            \"$set\": { \"jailed\": True }\n        }\n\n        await CachedDB.update_one(users, {\"id\": user.id}, newdata)\n\n        await context.send(f\"{user.mention} has been jailed\")\n\n        embed = discord.Embed(\n            description = \"You have been jailed for reason: **\" + reason + \"**\",\n            color = 0xBEBEFE\n        )\n        await jail_channel.send(user.mention, embed=embed)\n\n    @commands.hybrid_command(\n        name=\"unjail\",\n        description=\"Unjail a user.\",\n        usage=\"unjail <user>\",\n        aliases=[\"unquarantine\"],\n        extras={\"example\": \"unjail @user\"}\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @Checks.has_perm(moderate_members=True)\n    @commands.bot_has_permissions(manage_roles=True, manage_channels=True, manage_messages=True)\n    async def unjail(self, context: Context, user: discord.Member):\n\n\n        guilds = db[\"guilds\"]\n        data = guilds.find_one({\"id\": context.guild.id})\n\n        await user.remove_roles(context.guild.get_role(data[\"jail_role\"]))\n\n        users = db[\"users\"]\n        user_data = await CachedDB.find_one(users, {\"id\": user.id})\n\n        if not user_data:\n            user_data = CONSTANTS.user_data_template(context.guild.id, user.id)\n            users.insert_one(user_data)\n\n        newdata = {\n            \"$set\": { \"jailed\": False }\n        }\n\n        await CachedDB.update_one(users, {\"id\": user.id}, newdata)\n\n        await context.send(f\"{user.mention} has been unjailed\")\n\n    @commands.hybrid_group(\n        name=\"warnings\",\n        description=\"Commands to warn users\",\n        usage=\"warnings\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    async def warnings(self, context: Context) -> None:\n        subcommands = [cmd for cmd in self.warnings.walk_commands()]\n\n        data = []\n\n        for subcommand in subcommands:\n            description = subcommand.description.partition(\"\\n\")[0]\n            data.append(f\"{await self.bot.get_prefix(context)}warnings {subcommand.name} - {description}\")\n\n        help_text = \"\\n\".join(data)\n        embed = discord.Embed(\n            title=f\"Help: Warnings\", description=\"List of available commands:\", color=0xBEBEFE\n        )\n        embed.add_field(\n            name=\"Commands\", value=f\"```{help_text}```\", inline=False\n        )\n\n        await context.send(embed=embed)\n\n    @warnings.command(\n        name=\"add\",\n        description=\"Warn a user.\",\n        usage=\"warnings add <user> <reason>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @Checks.has_perm(manage_messages=True)\n    async def warn(self, context: Context, user: discord.Member, *, reason: str = \"Not specified\") -> None:\n        users = db[\"users\"]\n        data = users.find_one({\"id\": user.id, \"guild_id\": context.guild.id})\n\n        if not data:\n            data = CONSTANTS.user_data_template(user.id, context.guild.id)\n            users.insert_one(data)\n\n        if not \"warnings\" in data:\n            data[\"warnings\"] = []\n\n        data[\"warnings\"].append({\"reason\": reason, \"time\": datetime.now().strftime(\"%d.%m.%Y %H:%M:%S\")})\n\n        newdata = {\"$set\": {\"warnings\": data[\"warnings\"]}}\n\n        users.update_one({\"id\": user.id, \"guild_id\": context.guild.id}, newdata)\n\n        await context.send(f\"{user.mention} has been warned for {reason}\")\n\n    @warnings.command(\n        name=\"list\",\n        description=\"Get a user's warnings.\",\n        usage=\"warnings list <user>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @Checks.has_perm(manage_messages=True)\n    async def listwarnings(self, context: Context, user: discord.Member) -> None:\n        users = db[\"users\"]\n        data = users.find_one({\"id\": user.id, \"guild_id\": context.guild.id})\n\n        if not data:\n            data = CONSTANTS.user_data_template(user.id, context.guild.id)\n            users.insert_one(data)\n\n\n        embed = discord.Embed(\n            title=f\"Warnings for {user}\",\n            color=0xff6961\n        )\n\n        for w in data[\"warnings\"]:\n            embed.add_field(\n                name=w[\"time\"],\n                value=w[\"reason\"],\n                inline=False\n            )\n\n        await context.send(embed=embed)\n\n    @warnings.command(\n        name=\"clear\",\n        description=\"Clear a user's warnings.\",\n        usage=\"warnings clear <user>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @Checks.has_perm(manage_messages=True)\n    async def clearwarnings(self, context: Context, user: discord.Member) -> None:\n        users = db[\"users\"]\n        data = users.find_one({\"id\": user.id, \"guild_id\": context.guild.id})\n\n        if not data:\n            data = CONSTANTS.user_data_template(user.id, context.guild.id)\n            users.insert_one(data)\n\n        newdata = {\"$set\": {\"warnings\": []}}\n\n        users.update_one({\"id\": user.id, \"guild_id\": context.guild.id}, newdata)\n\n        await context.send(f\"Cleared warnings for {user.mention}\")\n\n    @commands.hybrid_command(\n        name=\"recreate\",\n        description=\"Recreates channel with same settings\",\n        usage=\"recreate [optional: channel]\",\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @Checks.has_perm(manage_channels=True)\n    @commands.bot_has_permissions(manage_channels=True)\n    async def recreate(self, context: Context, channel: discord.TextChannel = None) -> None:\n        if not channel:\n            channel = context.channel\n\n        await context.send(f\"Are you sure you want to recreate {channel.mention}\", view=deleteconfirm(context.author, channel))\n\nasync def setup(bot) -> None:\n    await bot.add_cog(Staff(bot))\n"
  },
  {
    "path": "cogs/starboard.py",
    "content": "# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon\n\nimport discord\nfrom discord.ext import commands\nfrom discord.ext.commands import Context\nfrom utils import CONSTANTS, DBClient, Checks, CachedDB\n\nfrom ui.starboard import JumpToMessageView\n\nclient = DBClient.client\ndb = client.potatobot\n\nclass Starboard(commands.Cog, name=\"⭐ Starboard\"):\n    def __init__(self, bot) -> None:\n        self.bot = bot\n\n    @commands.Cog.listener()\n    async def on_raw_reaction_add(self, payload) -> None:\n        channel = self.bot.get_channel(payload.channel_id)\n        message = await channel.fetch_message(payload.message_id)\n\n        if message.author.bot:\n            return\n\n        col = db[\"guilds\"]\n        guild = await CachedDB.find_one(col, {\"id\": payload.guild_id})\n\n        if not guild:\n            return\n\n        if \"starboard\" not in guild:\n            return\n\n        if guild[\"starboard\"][\"channel\"] == 0:\n            return\n\n        if \"enabled\" in guild[\"starboard\"]:\n            if not guild[\"starboard\"][\"enabled\"]:\n                return\n\n        starboard_col = db[\"starboard\"]\n        starboard_message = await CachedDB.find_one(starboard_col, {\"message_id\": message.id})\n        starboard_channel = self.bot.get_channel(guild[\"starboard\"][\"channel\"])\n\n        star_reactions = 0\n        for r in message.reactions:\n            if r.emoji == \"⭐\":\n                star_reactions = r.count\n\n        if payload.emoji.name == \"⭐\":\n            if star_reactions >= guild[\"starboard\"][\"threshold\"]:\n                if not starboard_message:\n                    embed = discord.Embed(\n                        description=message.content,\n                        color=0xFFD700,\n                        timestamp=message.created_at\n                    )\n\n                    embed.set_author(name=message.author, icon_url=message.author.display_avatar.url)\n\n                    if message.attachments:\n                        embed.set_image(url=message.attachments[0].url)\n\n                    label = \"⭐ \" + str(star_reactions)\n\n                    msg = await starboard_channel.send(label, embed=embed, view=JumpToMessageView(message))\n\n                    newdata = {\n                        \"message_id\": message.id,\n                        \"starboard_id\": msg.id\n                    }\n\n                    starboard_col.insert_one(newdata)\n                else:\n                    embed = discord.Embed(\n                        description=message.content,\n                        color=0xFFD700,\n                        timestamp=message.created_at\n                    )\n\n                    embed.set_author(name=message.author, icon_url=message.author.display_avatar.url)\n\n                    if message.attachments:\n                        embed.set_image(url=message.attachments[0].url)\n\n                    label = \"⭐ \" + str(star_reactions)\n\n                    starboard_message = await starboard_channel.fetch_message(starboard_message[\"starboard_id\"])\n\n                    await starboard_message.edit(content=label, embed=embed, view=JumpToMessageView(message))\n\n    @commands.Cog.listener()\n    async def on_raw_reaction_remove(self, payload) -> None:\n        channel = self.bot.get_channel(payload.channel_id)\n        message = await channel.fetch_message(payload.message_id)\n\n        if message.author.bot:\n            return\n\n        col = db[\"guilds\"]\n        guild = await CachedDB.find_one(col, {\"id\": payload.guild_id})\n\n        if not guild:\n            return\n\n        if \"starboard\" not in guild:\n            return\n\n        if guild[\"starboard\"][\"channel\"] == 0:\n            return\n\n        if \"enabled\" in guild[\"starboard\"]:\n            if not guild[\"starboard\"][\"enabled\"]:\n                return\n\n        star_reactions = 0\n        for r in message.reactions:\n            if r.emoji == \"⭐\":\n                star_reactions = r.count\n\n        starboard_col = db[\"starboard\"]\n        starboard_message = await CachedDB.find_one(starboard_col, {\"message_id\": message.id})\n        starboard_channel = self.bot.get_channel(guild[\"starboard\"][\"channel\"])\n\n        if not starboard_channel:\n            return\n\n        if payload.emoji.name == \"⭐\":\n            embed = discord.Embed(\n                description=message.content,\n                color=0xFFD700,\n                timestamp=message.created_at\n            )\n\n            embed.set_author(name=message.author, icon_url=message.author.display_avatar.url)\n\n            label = \"⭐ \" + str(star_reactions)\n\n            if message.attachments:\n                embed.set_image(url=message.attachments[0].url)\n\n            starboard_message = await starboard_channel.fetch_message(starboard_message[\"starboard_id\"])\n\n            await starboard_message.edit(content=label, embed=embed, view=JumpToMessageView(message))\n\n    @commands.hybrid_group(\n        name=\"starboard\",\n        description=\"Commands for managing the starboard.\",\n        usage=\"starboard <subcommand>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    async def starboard(self, context: Context) -> None:\n        subcommands = [cmd for cmd in self.starboard.walk_commands()]\n\n        data = []\n\n        for subcommand in subcommands:\n            print(subcommand)\n            description = subcommand.description.partition(\"\\n\")[0]\n            data.append(f\"{await self.bot.get_prefix(context)}starboard {subcommand.name} - {description}\")\n\n        help_text = \"\\n\".join(data)\n        embed = discord.Embed(\n            title=f\"Help: Starboard\", description=\"List of available commands:\", color=0xBEBEFE\n        )\n        embed.add_field(\n            name=\"Commands\", value=f\"```{help_text}```\", inline=False\n        )\n\n        await context.send(embed=embed)\n\n    @starboard.command(\n        name=\"channel\",\n        description=\"Set the starboard channel.\",\n        usage=\"starboard channel <channel>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @commands.has_permissions(manage_channels=True)\n    async def set_starboard(self, context: Context, channel: discord.TextChannel) -> None:\n        col = db[\"guilds\"]\n        guild = await CachedDB.find_one(col, {\"id\": context.guild.id})\n\n        if not guild:\n            guild = CONSTANTS.guild_data_template(context.guild.id)\n            await col.insert_one(CONSTANTS.guild_data_template(context.guild.id))\n\n        newdata = {\n            \"$set\": {\n                \"starboard.channel\": channel.id\n            }\n        }\n\n        await CachedDB.update_one(col, {\"id\": context.guild.id}, newdata)\n        await context.send(f\"Starboard channel set to {channel.mention}.\")\n\n    @starboard.command(\n        name=\"threshold\",\n        description=\"Set the starboard threshold required to show in starboard channel\",\n        usage=\"starboard threshold <threshold>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @commands.has_permissions(manage_channels=True)\n    async def set_threshold(self, context: Context, threshold: int) -> None:\n        col = db[\"guilds\"]\n        guild = await CachedDB.find_one(col, {\"id\": context.guild.id})\n\n        if not guild:\n            guild = CONSTANTS.guild_data_template(context.guild.id)\n            await col.insert_one(guild)\n\n        newdata = {\n            \"$set\": {\n                \"starboard.threshold\": threshold\n            }\n        }\n\n        await CachedDB.update_one(col, {\"id\": context.guild.id}, newdata)\n        await context.send(f\"Starboard threshold set to {threshold}.\")\n\n    @starboard.command(\n        name=\"disable\",\n        description=\"Disable the starboard.\",\n        usage=\"starboard disable\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @commands.has_permissions(manage_channels=True)\n    async def disable_starboard(self, context: Context) -> None:\n        col = db[\"guilds\"]\n        guild = await CachedDB.find_one(col, {\"id\": context.guild.id})\n\n        if not guild:\n            guild = CONSTANTS.guild_data_template(context.guild.id)\n            await col.insert_one(guild)\n\n        newdata = {\n            \"$set\": {\n                \"starboard.enabled\": False\n            }\n        }\n\n        await CachedDB.update_one(col, {\"id\": context.guild.id}, newdata)\n        await context.send(\"Starboard disabled.\")\n\n    @starboard.command(\n        name=\"enable\",\n        description=\"Enable the starboard.\",\n        usage=\"starboard enable\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n\n    @commands.has_permissions(manage_channels=True)\n    async def enable_starboard(self, context: Context) -> None:\n        col = db[\"guilds\"]\n        guild = await CachedDB.find_one(col, {\"id\": context.guild.id})\n\n        if not guild:\n            guild = CONSTANTS.guild_data_template(context.guild.id)\n            await col.insert_one(guild)\n\n        newdata = {\n            \"$set\": {\n                \"starboard.enabled\": True\n            }\n        }\n\n        await CachedDB.update_one(col, {\"id\": context.guild.id}, newdata)\n        await context.send(\"Starboard enabled.\")\n\nasync def setup(bot) -> None:\n    await bot.add_cog(Starboard(bot))\n"
  },
  {
    "path": "cogs/stats.py",
    "content": "# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon\n\nimport discord\nimport os\nfrom discord.ext import commands\nfrom discord.ext.commands import Context\nfrom datetime import datetime\n\nfrom easy_pil import Font\n\nfrom PIL import Image, ImageDraw\nfrom pickledb import PickleDB\n\nfrom utils import Checks\n\ndb = PickleDB('pickle/charts.db')\n\ndef textangle(draw, text, xy, angle, fill, font):\n    img = Image.new('RGBA', font.getsize(text))\n    d = ImageDraw.Draw(img)\n    d.text((0, 0), text, font=font, fill=fill)\n    w = img.rotate(angle, expand=1)\n    draw.bitmap(xy, w, fill=fill)\n\nclass Stats(commands.Cog, name=\"📈 Stats\"):\n    def __init__(self, bot) -> None:\n        self.bot = bot\n\n    os.makedirs(\"graphs\", exist_ok=True)\n\n    @commands.Cog.listener()\n    async def on_message(self, message: discord.Message):\n        if message.guild == None:\n            return\n\n        if message.author == self.bot.user:\n            return\n\n        guild_id = str(message.guild.id)\n        current_date = datetime.utcnow().date()\n\n        if not db.get(guild_id):\n            db.set(guild_id, {})\n\n        if str(current_date) not in db.get(guild_id):\n            db.get(guild_id)[str(current_date)] = {\"messages\": 0}\n\n        db.get(guild_id)[str(current_date)][\"messages\"] += 1\n\n        current_users = message.guild.member_count\n\n        db.get(guild_id)[str(current_date)][\"users\"] = current_users\n\n        guild_data = db.get(guild_id)\n        for date_str in list(guild_data.keys()):\n            date = datetime.fromisoformat(date_str).date()\n            if (current_date - date).days > 30:\n                del guild_data[date_str]\n\n        db.save()\n\n    @commands.hybrid_group(\n        name=\"chart\",\n        description=\"Show chart of ... activity\",\n        usage=\"chart\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    async def chart(self, context: Context) -> None:\n        subcommands = [cmd for cmd in self.chart.walk_commands()]\n\n        data = []\n\n        for subcommand in subcommands:\n            description = subcommand.description.partition(\"\\n\")[0]\n            data.append(f\"{await self.bot.get_prefix(context)}chart {subcommand.name} - {description}\")\n\n        help_text = \"\\n\".join(data)\n        embed = discord.Embed(\n            title=f\"Help: Chart\", description=\"List of available commands:\", color=0xBEBEFE\n        )\n        embed.add_field(\n            name=\"Commands\", value=f\"```{help_text}```\", inline=False\n        )\n\n        await context.send(embed=embed)\n\n    @chart.command(\n        name=\"messages\",\n        description=\"Show chart of message activity\",\n        usage=\"chart messages\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    async def messages(self, context: Context) -> None:\n        guild_id = str(context.guild.id)\n        if not db.get(guild_id):\n            await context.send(\"No data available for this server.\")\n            return\n\n        guild_data = db.get(guild_id)\n        dates = sorted([datetime.fromisoformat(date_str).date() for date_str in guild_data.keys()])\n        message_counts = [guild_data[str(date)][\"messages\"] for date in dates]\n\n        total_messages = sum(message_counts)\n\n        img = Image.new('RGB', (1600, 800), color=(32, 34, 38))\n        draw = ImageDraw.Draw(img)\n        font = Font.poppins(size=20)\n\n        max_count = max(message_counts) if message_counts else 1\n        max_count = max_count if max_count != 0 else 1  # Ensure max_count is never zero\n        y_step = 100\n        for y in range(100, 701, y_step):\n            draw.line((100, y, 1500, y), fill=(64, 68, 75), width=2)\n            number = (max_count - (y - 100) * max_count // 600) / 60 * 60\n            number = int(str(number).split('.')[0])\n            draw.text((20, y - 10), str(number), font=font, fill=(255, 255, 255))\n\n        bar_color = (128, 128, 128)\n        line_color = (0, 255, 255)\n        previous_point = None\n\n        for i in range(len(dates)):\n            x = 200 + i * 40\n            y = 700 - (message_counts[i] * 600 // max_count)\n            draw.line((x, 700, x, y), fill=bar_color, width=20)\n            if previous_point:\n                draw.line((previous_point, (x, y)), fill=line_color, width=5)\n            draw.ellipse((x - 5, y - 5, x + 5, y + 5), fill=line_color)\n            previous_point = (x, y)\n            textangle(draw, dates[i].strftime('%d %b'), (x - 40, 720), 45, (255, 255, 255), font)\n\n        label_text = f'Messages - Last 30 days'\n        total_text = f'Total Messages: {total_messages}'\n        label_width, _ = draw.textsize(label_text, font=font)\n        total_width, _ = draw.textsize(total_text, font=font)\n        draw.text((20, 20), label_text, font=font, fill=(255, 255, 255))\n        draw.text((1600 - total_width - 20, 20), total_text, font=font, fill=(255, 255, 255))\n\n        img.save(f'graphs/graph-msgs-{context.channel.id}.png')\n        await context.send(file=discord.File(f'graphs/graph-msgs-{context.channel.id}.png'))\n\n        os.remove(f'graphs/graph-msgs-{context.channel.id}.png')\n\n    @chart.command(\n        name=\"members\",\n        description=\"Show chart of member count\",\n        usage=\"chart members\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    async def members(self, context: Context) -> None:\n        guild_id = str(context.guild.id)\n        if not db.get(guild_id):\n            await context.send(\"No data available for this server.\")\n            return\n\n        guild_data = db.get(guild_id)\n        dates = sorted([datetime.fromisoformat(date_str).date() for date_str in guild_data.keys()])\n        user_counts = [((guild_data[str(date)][\"users\"]) if \"users\" in guild_data[str(date)] else 0) for date in dates]\n\n        img = Image.new('RGB', (1600, 800), color=(32, 34, 38))\n        draw = ImageDraw.Draw(img)\n        font = Font.poppins(size=20)\n\n        max_count = max(user_counts) if user_counts else 1\n        max_count = max_count if max_count != 0 else 1\n\n        y_step = 100\n\n        for y in range(100, 701, y_step):\n            draw.line((100, y, 1500, y), fill=(64, 68, 75), width=2)\n            number = (max_count - (y - 100) * max_count // 600) / 60 * 60\n            number = int(str(number).split('.')[0])\n            draw.text((20, y - 10), str(number), font=font, fill=(255, 255, 255))\n\n        bar_color = (128, 128, 128)\n        line_color = (0, 255, 255)\n        previous_point = None\n\n        for i in range(len(dates)):\n            x = 200 + i * 40\n            y = 700 - (user_counts[i] * 600 // max_count)\n            draw.line((x, 700, x, y), fill=bar_color, width=20)\n            if previous_point:\n                draw.line((previous_point, (x, y)), fill=line_color, width=5)\n            draw.ellipse((x - 5, y - 5, x + 5, y + 5), fill=line_color)\n            previous_point = (x, y)\n            textangle(draw, dates[i].strftime('%d %b'), (x - 40, 720), 45, (255, 255, 255), font)\n\n        label_text = f'Member Count - Last 30 days'\n\n        label_width, _ = draw.textsize(label_text, font=font)\n        draw.text((20, 20), label_text, font=font, fill=(255, 255, 255))\n\n        img.save(f'graphs/graph-members-{context.channel.id}.png')\n        await context.send(file=discord.File(f'graphs/graph-members-{context.channel.id}.png'))\n\n        os.remove(f'graphs/graph-members-{context.channel.id}.png')\n\nasync def setup(bot) -> None:\n    await bot.add_cog(Stats(bot))\n"
  },
  {
    "path": "cogs/ticket.py",
    "content": "# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon\n\nimport discord\nimport os\nfrom datetime import datetime\nfrom discord.ext import commands\nfrom discord.ext.commands import Context\n\nfrom utils import ServerLogger, DBClient, Checks\nfrom ui.ticket import CreateButton, CloseButton, TrashButton\n\nclient = DBClient.client\ndb = client.potatobot\n\nclass Ticket(commands.Cog, name=\"🎫 Ticket\"):\n    def __init__(self, bot) -> None:\n        self.bot = bot\n\n    @commands.hybrid_command(\n        name=\"ticketembed\",\n        description=\"Command to make a embed for making tickets\",\n        usage=\"ticketembed\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @commands.has_permissions(administrator=True)\n    async def ticketembed(self, context):\n        await context.send(\n            embed = discord.Embed(\n                description=\"Press the button to create a new ticket!\",\n                color=discord.Color.blue()\n            ),\n            view = CreateButton()\n        )\n\n    @commands.hybrid_command(\n        name=\"open\",\n        description=\"Open a ticket\",\n        usage=\"open\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    async def open(self, context: Context):\n        c = db[\"guilds\"]\n\n        data = c.find_one({\"id\": context.guild.id})\n\n        if not data:\n            await context.send(\"**Tickets info not found! If you are an admin use `/setting` for more info**\")\n            return\n\n        if not data[\"tickets_category\"]:\n            await context.send(\"**Tickets info not found! If you are an admin use `/setting` for more info**\")\n            return\n\n        category: discord.CategoryChannel = discord.utils.get(context.guild.categories, id=data[\"tickets_category\"])\n        for ch in category.text_channels:\n            if ch.topic == f\"{context.author.id} DO NOT CHANGE THE TOPIC OF THIS CHANNEL!\":\n                await context.send(\"You already have a ticket in {0}\".format(ch.mention))\n                return\n        r1 = None\n\n        if data[\"tickets_support_role\"]:\n            r1 : discord.Role = context.guild.get_role(data[\"tickets_support_role\"])\n        else:\n            r1 = context.guild.default_role\n        overwrites = {\n            context.guild.default_role: discord.PermissionOverwrite(read_messages=False),\n            r1: discord.PermissionOverwrite(read_messages=True, send_messages=True, manage_messages=True),\n            context.author: discord.PermissionOverwrite(read_messages = True, send_messages=True),\n            context.guild.me: discord.PermissionOverwrite(read_messages=True, send_messages=True)\n        }\n        channel = await category.create_text_channel(\n            name=str(context.author),\n            topic=f\"{context.author.id} DO NOT CHANGE THE TOPIC OF THIS CHANNEL!\",\n            overwrites=overwrites\n        )\n        await channel.send(\"{0} a ticket has been created!\".format(r1.mention))\n        await channel.send(\n            embed=discord.Embed(\n                title=f\"Ticket Created!\",\n                description=\"Don't ping a staff member, they will be here soon.\",\n                color = discord.Color.green()\n            ),\n            view = CloseButton()\n        )\n        await channel.send(\"Please describe your issue\")\n\n        await context.send(\n            embed= discord.Embed(\n                description = \"Created your ticket in {0}\".format(channel.mention),\n                color = discord.Color.blurple()\n            )\n        )\n\n        await ServerLogger.send_log(\n            title=\"Ticket Created\",\n            description=\"Created by {0}\".format(context.author.mention),\n            color=discord.Color.green(),\n            guild=context.guild,\n            channel=context.channel\n        )\n\n    @commands.hybrid_group(\n        name=\"ticket\",\n        description=\"Commands to manage a ticket\",\n        usage=\"ticket\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    async def ticket(self, context: Context):\n        subcommands = [cmd for cmd in self.ticket.walk_commands()]\n\n        data = []\n\n        for subcommand in subcommands:\n            description = subcommand.description.partition(\"\\n\")[0]\n            data.append(f\"{await self.bot.get_prefix(context)}ticket {subcommand.name} - {description}\")\n\n        help_text = \"\\n\".join(data)\n        embed = discord.Embed(\n            title=f\"Help: Ticket\", description=\"List of available commands:\", color=0xBEBEFE\n        )\n        embed.add_field(\n            name=\"Commands\", value=f\"```{help_text}```\", inline=False\n        )\n\n        await context.send(embed=embed)\n\n    @ticket.command(\n        name=\"upgrade\",\n        description=\"Remove support role access from the ticket\",\n        usage=\"ticket upgrade\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @commands.has_permissions(manage_channels=True)\n    async def upgrade(self, context: Context):\n        try:\n            int(context.channel.topic.split()[0])\n        except:\n            return await context.send(\"This is not a ticket channel.\")\n\n        c = db[\"guilds\"]\n        guild = c.find_one({\"id\": context.guild.id})\n\n        if not guild or not guild.get(\"tickets_support_role\"):\n            return await context.send(\"Support role not configured for this server.\")\n\n        support_role = context.guild.get_role(guild[\"tickets_support_role\"])\n        if not support_role:\n            return await context.send(\"Support role not found.\")\n\n        if support_role not in context.channel.overwrites:\n            return await context.send(\"This ticket is already upgraded.\")\n\n        await context.channel.set_permissions(support_role, overwrite=None)\n        await context.send(\"Support role access has been removed from this ticket.\")\n\n        await ServerLogger.send_log(\n            title=\"Ticket Upgraded\",\n            description=f\"{context.author.mention} upgraded ticket {context.channel.name}\",\n            color=discord.Color.purple(),\n            guild=context.guild,\n            channel=context.channel\n        )\n\n    @ticket.command(name=\"downgrade\", description=\"Restore support role access to the ticket\", usage=\"ticket downgrade\")\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @commands.has_permissions(manage_channels=True)\n    async def downgrade(self, context: Context):\n        try:\n            int(context.channel.topic.split()[0])\n        except:\n            return await context.send(\"This is not a ticket channel.\")\n\n        c = db[\"guilds\"]\n        guild = c.find_one({\"id\": context.guild.id})\n\n        if not guild or not guild.get(\"tickets_support_role\"):\n            return await context.send(\"Support role not configured for this server.\")\n\n        support_role = context.guild.get_role(guild[\"tickets_support_role\"])\n        if not support_role:\n            return await context.send(\"Support role not found.\")\n\n        if support_role in context.channel.overwrites:\n            return await context.send(\"This ticket is already accessible to the support role.\")\n\n        await context.channel.set_permissions(support_role, read_messages=True, send_messages=True)\n        await context.send(\"Support role access has been restored to this ticket.\")\n\n        await ServerLogger.send_log(\n            title=\"Ticket Downgraded\",\n            description=f\"{context.author.mention} downgraded ticket {context.channel.name}\",\n            color=discord.Color.green(),\n            guild=context.guild,\n            channel=context.channel\n        )\n\n    @ticket.command(\n        name=\"add\",\n        description=\"Add a user to the ticket\",\n        usage=\"ticket add <user>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    async def add(self, context: Context, user: discord.Member):\n        try:\n            int(context.channel.topic.split()[0])\n        except:\n            return await context.send(\"This is not a ticket channel.\")\n\n        member = context.guild.get_member(int(context.channel.topic.split(\" \")[0]))\n\n        if not context.author == member and not context.author.guild_permissions.manage_channels:\n            return await context.send(\"You don't have permission to add users to this ticket.\")\n\n        if user in context.channel.members:\n            return await context.send(f\"{user.mention} is already in this ticket.\")\n\n        await context.channel.set_permissions(user, read_messages=True, send_messages=True)\n        await context.send(f\"Added {user.mention} to the ticket.\")\n\n        await ServerLogger.send_log(\n            title=\"User Added to Ticket\",\n            description=f\"{context.author.mention} added {user.mention} to ticket {context.channel.name}\",\n            color=discord.Color.blue(),\n            guild=context.guild,\n            channel=context.channel\n        )\n\n    @ticket.command(\n        name=\"remove\",\n        description=\"Remove a user from the ticket\",\n        usage=\"ticket remove <user>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    async def remove(self, context: Context, user: discord.Member):\n        try:\n            int(context.channel.topic.split()[0])\n        except:\n            return await context.send(\"This is not a ticket channel.\")\n\n        member = context.guild.get_member(int(context.channel.topic.split(\" \")[0]))\n\n        if not context.author == member and not context.author.guild_permissions.manage_channels:\n            return await context.send(\"You don't have permission to remove users from this ticket.\")\n\n        if user not in context.channel.members:\n            return await context.send(f\"{user.mention} is not in this ticket.\")\n\n        if user == context.channel.guild.get_member(int(context.channel.topic.split(\" \")[0])):\n            return await context.send(\"You can't remove the ticket creator.\")\n\n        await context.channel.set_permissions(user, overwrite=None)\n        await context.send(f\"Removed {user.mention} from the ticket.\")\n\n        await ServerLogger.send_log(\n            title=\"User Removed from Ticket\",\n            description=f\"{context.author.mention} removed {user.mention} from ticket {context.channel.name}\",\n            color=discord.Color.orange(),\n            guild=context.guild,\n            channel=context.channel\n        )\n\n    @ticket.command(\n        name=\"claim\",\n        description=\"Claim the ticket\",\n        usage=\"ticket claim\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    async def claim(self, context: Context):\n        try:\n            int(context.channel.topic.split()[0])\n        except:\n            return await context.send(\"This is not a ticket channel.\")\n\n        member = context.guild.get_member(int(context.channel.topic.split(\" \")[0]))\n\n        if context.author == member:\n            return await context.send(\"This is your ticket.\")\n\n        guilds = db[\"guilds\"]\n        guild = guilds.find_one({\"id\": context.guild.id})\n\n        if guild and guild.get(\"tickets_support_role\"):\n            support_role = context.guild.get_role(guild[\"tickets_support_role\"])\n\n            await context.channel.set_permissions(member, overwrite=None)\n            await context.channel.set_permissions(support_role, read_messages=True, send_messages=False)\n            await context.channel.set_permissions(context.author, read_messages=True, send_messages=True)\n\n            embed = discord.Embed(\n                title=\"Ticket Claimed\",\n                description=f\"{context.author.mention} will now handle this ticket.\",\n            )\n\n            await context.send(embed=embed)\n\n            await ServerLogger.send_log(\n                title=\"Ticket Claimed\",\n                description=f\"{context.author.mention} claimed ticket {context.channel.name}\",\n                color=discord.Color.green(),\n                guild=context.guild,\n                channel=context.channel\n            )\n\n    @ticket.command(\n        name=\"unclaim\",\n        description=\"Unclaim the ticket\",\n        usage=\"ticket unclaim\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    async def unclaim(self, context: Context):\n        try:\n            int(context.channel.topic.split()[0])\n        except:\n            return await context.send(\"This is not a ticket channel.\")\n\n        member = context.guild.get_member(int(context.channel.topic.split(\" \")[0]))\n\n        if context.author == member:\n            return await context.send(\"This is your ticket.\")\n\n        guilds = db[\"guilds\"]\n        guild = guilds.find_one({\"id\": context.guild.id})\n\n        if guild and guild.get(\"tickets_support_role\"):\n            support_role = context.guild.get_role(guild[\"tickets_support_role\"])\n\n            await context.channel.set_permissions(member, read_messages=True, send_messages=True)\n            await context.channel.set_permissions(support_role, read_messages=True, send_messages=True)\n            await context.channel.set_permissions(context.author, overwrite=None)\n\n            embed = discord.Embed(\n                title=\"Ticket Unclaimed\",\n                description=f\"{context.author.mention} has unclaimed this ticket.\",\n            )\n\n            await context.send(embed=embed)\n\n\n    @ticket.command(\n        name=\"close\",\n        description=\"Close the ticket\",\n        usage=\"ticket close\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    async def close(self, context: Context):\n        try:\n            int(context.channel.topic.split()[0])\n        except:\n            return await context.send(\"This is not a ticket channel.\")\n\n        member = context.guild.get_member(int(context.channel.topic.split(\" \")[0]))\n\n        if not context.author == member and not context.author.guild_permissions.manage_channels:\n            return await context.send(\"You don't have permission to close this ticket.\")\n\n        await context.send(\"Starting ticket closing, dont run command again\")\n\n        os.makedirs(\"logs\", exist_ok=True)\n        log_file = f\"logs/{context.channel.id}.log\"\n        with open(log_file, \"w\", encoding=\"UTF-8\") as f:\n            f.write(\n                f'Ticket log from: #{context.channel} ({context.channel.id}) in the guild \"{context.guild}\" ({context.guild.id}) at {datetime.now().strftime(\"%d.%m.%Y %H:%M:%S\")}\\n'\n            )\n            async for message in context.channel.history(\n                limit=None, oldest_first=True\n            ):\n                attachments = []\n                for attachment in message.attachments:\n                    attachments.append(attachment.url)\n                attachments_text = (\n                    f\"[Attached File{'s' if len(attachments) >= 2 else ''}: {', '.join(attachments)}]\"\n                    if len(attachments) >= 1\n                    else \"\"\n                )\n                f.write(\n                    f\"{message.created_at.strftime('%d.%m.%Y %H:%M:%S')} {message.author} {message.id}: {message.clean_content} {attachments_text}\\n\"\n                )\n\n        guilds = DBClient.client.potatobot[\"guilds\"]\n        data = guilds.find_one({\"id\": context.guild.id})\n\n        if data[\"log_channel\"]:\n            log_channel = context.guild.get_channel(data[\"log_channel\"])\n\n            if log_channel:\n                try:\n                    await log_channel.send(file=discord.File(log_file))\n\n                    embed = discord.Embed(\n                        title=\"Ticket Closed\",\n                        description=f\"Ticket {context.channel.name} closed by {context.author.mention}\",\n                        color=discord.Color.orange()\n                    )\n\n                    await log_channel.send(embed=embed)\n                except Exception as e:\n                    return await context.send(\"An error occurred, \" + str(e))\n\n        try:\n            with open (log_file, \"rb\") as f:\n                await member.send(f\"Your ticket in {context.guild} has been closed. Transcript: \", file=discord.File(f))\n        except Exception as e:\n            await context.channel.send(\n                f\"Couldn't send the log file to {member.mention}, \" + str(e)\n            )\n\n        await context.channel.set_permissions(member, overwrite=None)\n        await context.channel.edit(name=f\"closed-{context.channel.name}\")\n\n        os.remove(log_file)\n\n        await context.channel.send(\n            embed= discord.Embed(\n                description=\"Ticket Closed!\",\n                color = discord.Color.red()\n            ),\n            view = TrashButton()\n        )\n\nasync def setup(bot) -> None:\n    await bot.add_cog(Ticket(bot))\n    bot.add_view(CreateButton())\n    bot.add_view(CloseButton())\n    bot.add_view(TrashButton())\n"
  },
  {
    "path": "cogs/utility.py",
    "content": "# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon\n\nimport io\n\nfrom asteval import Interpreter\naeval = Interpreter()\n\nimport discord\nfrom discord import app_commands\nfrom discord.ext import commands\nfrom discord.ext.commands import Context\nfrom deep_translator import GoogleTranslator\n\nfrom utils import Checks\n\nfrom PIL import ImageColor, Image\n\nclass Utility(commands.Cog, name=\"⚡ Utility\"):\n    def __init__(self, bot) -> None:\n        self.bot = bot\n\n    @commands.hybrid_group(\n        name=\"convert\",\n        description=\"Commands to convert stuff\",\n        usage=\"convert <subcommand>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @app_commands.allowed_installs(guilds=True, users=True)\n    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)\n    async def convert(self, context: Context) -> None:\n        prefix = await self.bot.get_prefix(context)\n\n        cmds = \"\\n\".join([f\"{prefix}convert {cmd.name} - {cmd.description}\" for cmd in self.convert.walk_commands()])\n\n        embed = discord.Embed(\n            title=f\"Help: Convert\", description=\"List of available commands:\", color=0xBEBEFE\n        )\n        embed.add_field(\n            name=\"Commands\", value=f\"```{cmds}```\", inline=False\n        )\n\n        await context.send(embed=embed)\n\n    @convert.command(\n        name=\"mb-gb\",\n        aliases=[\"mbgb\", \"mb-to-gb\", \"mb2gb\"],\n        description=\"Convert megabytes to gigabytes\",\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    async def convert_mb_gb(self, context: Context, mb: float, binary: bool = True) -> None:\n        if binary:\n            gb = mb / 1024\n        else:\n            gb = mb / 1000\n\n        await context.send(f\"{mb}MB is equal to {gb}GB\")\n\n    @convert.command(\n        name=\"gb-mb\",\n        aliases=[\"gbmb\", \"gb-to-mb\", \"gb2mb\"],\n        description=\"Convert gigabytes to megabytes\",\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    async def convert_gb_mb(self, context: Context, gb: float, binary: bool = True) -> None:\n        if binary:\n            mb = gb * 1024\n        else:\n            mb = gb * 1000\n\n        await context.send(f\"{gb}GB is equal to {mb}MB\")\n\n    @convert.command(\n        name=\"gb-tb\",\n        aliases=[\"gbtb\", \"gb-to-tb\", \"gb2tb\"],\n        description=\"Convert gigabytes to terabytes\",\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    async def convert_gb_tb(self, context: Context, gb: float, binary: bool = True) -> None:\n        if binary:\n            tb = gb / 1024\n        else:\n            tb = gb / 1000\n\n        await context.send(f\"{gb}GB is equal to {tb}TB\")\n\n    @convert.command(\n        name=\"tb-gb\",\n        aliases=[\"tbg\", \"tb-to-gb\", \"tb2gb\"],\n        description=\"Convert terabytes to gigabytes\",\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    async def convert_tb_gb(self, context: Context, tb: float, binary: bool = True) -> None:\n        if binary:\n            gb = tb * 1024\n        else:\n            gb = tb * 1000\n\n        await context.send(f\"{tb}TB is equal to {gb}GB\")\n\n    @commands.hybrid_command(\n        name=\"calc\",\n        description=\"Calculate a math expression.\",\n        aliases=[\"calculate\"],\n        usage=\"calc <expression>\",\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @app_commands.allowed_installs(guilds=True, users=True)\n    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)\n    async def calc(self, context: Context, *, expression: str) -> None:\n        try:\n            result = aeval(expression)\n\n            embed = discord.Embed(\n                title=\"Calculator\",\n                description=f\"**Input:**\\n```{expression}```\\n**Output:**\\n```{result}```\",\n                color=0xBEBEFE\n            )\n\n            await context.send(embed=embed)\n        except Exception as e:\n            await context.send(f\"An error occurred: {e}\")\n\n    @commands.hybrid_command(\n        name=\"translate\",\n        description=\"Translate text to a specified language example: ,translate en hola\",\n        usage=\"translate <text> <language>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @app_commands.describe(text=\"The text you want to translate.\")\n    @app_commands.describe(language=\"The language you want to translate the text to.\")\n    @app_commands.allowed_installs(guilds=True, users=True)\n    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)\n    async def translate(self, context: Context, language, *, text: str) -> None:\n        translated = GoogleTranslator(source='auto', target=language).translate(text)\n\n        embed = discord.Embed(\n            title=\"Translation\",\n            description=f\"**Original text:**\\n{text}\\n\\n**Translated text:**\\n{translated}\",\n            color=0xBEBEFE,\n        )\n        embed.set_footer(text=f\"Translated to {language}\")\n        await context.send(embed=embed)\n\n    @commands.hybrid_command(\n        name=\"color\",\n        description=\"Get information about a color.\",\n        aliases=[\"colour\"],\n        usage=\"color <color>\"\n    )\n    @commands.check(Checks.is_not_blacklisted)\n    @commands.check(Checks.command_not_disabled)\n    @app_commands.allowed_installs(guilds=True, users=True)\n    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)\n    async def color(self, context: Context, color: str) -> None:\n        try:\n            rgb = ImageColor.getrgb(color)\n            rgba = ImageColor.getcolor(color, \"RGBA\")\n            grayscale = ImageColor.getcolor(color, \"L\")\n            hex = hex_value = \"#{:02x}{:02x}{:02x}\".format(*rgb)\n\n\n            embed = discord.Embed(\n                title=\"Color Information\",\n                description=\"\\n\".join(\n                    [\n                        f\"Color: **{color}**\",\n                        f\"Hex: **{hex}**\",\n                        f\"RGB: **RGB{rgb}**\",\n                        f\"RGBA: **RGBA{rgba}**\",\n                        f\"Grayscale: **{grayscale}**\",\n                    ]\n                ),\n                color=0xBEBEFE,\n            )\n\n            img = Image.new(\"RGB\", (100, 100), rgb)\n\n            with io.BytesIO() as image_binary:\n                img.save(image_binary, \"PNG\")\n                image_binary.seek(0)\n\n                file = discord.File(fp=image_binary, filename=\"color.png\")\n                embed.set_image(url=\"attachment://color.png\")\n\n                await context.send(embed=embed, file=file)\n        except ValueError:\n            await context.send(\"Invalid color\")\n            return\n\nasync def setup(bot) -> None:\n    await bot.add_cog(Utility(bot))\n"
  },
  {
    "path": "config.example.json",
    "content": "{\n  \"prefix\": \",\",\n  \"invite_link\": \"https://discord.com/oauth2/authorize?client_id=1226487228914602005&scope=bot&permissions=8\",\n  \"command_error_webhook\": \"\",\n  \"error_webhooks\": \"\",\n  \"join_leave_webhook\": \"\",\n  \"bug_channel\": \"1244584577989873684\",\n  \"origins\": [\"http://localhost\", \"http://localhost:3000\"],\n  \"ssl_keyfile\": \"./ssl/example.com.key\",\n  \"ssl_certfile\": \"./ssl/example.com.pem\",\n  \"use_ssl\": false,\n  \"port\": 80,\n  \"fully_ignore\": []\n}\n"
  },
  {
    "path": "main.py",
    "content": "# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon\n\nimport os\nimport threading\nimport uvicorn\nimport json\nimport sys\nfrom bson import ObjectId\nfrom dotenv import load_dotenv\nfrom typing import Optional\n\nimport ssl\n\nfrom fastapi import FastAPI\nfrom fastapi.middleware.cors import CORSMiddleware\n\nfrom bot import DiscordBot\n\nfrom utils import DBClient, CONSTANTS, CachedDB\n\ndb = DBClient.db\n\n# Load environment variables\nload_dotenv()\n\n# Instantiate the bot and FastAPI app\nbot = DiscordBot()\napp = FastAPI()\n\nif not os.path.isfile(f\"{os.path.realpath(os.path.dirname(__file__))}/config.json\"):\n    sys.exit(\"'config.json' not found! Please add it and try again.\")\nelse:\n    with open(f\"{os.path.realpath(os.path.dirname(__file__))}/config.json\") as file:\n        config = json.load(file)\n\norigins = config[\"origins\"]\n\napp.add_middleware(\n    CORSMiddleware,\n    allow_origins=origins,\n    allow_credentials=True,\n    allow_methods=[\"*\"],\n    allow_headers=[\"*\"],\n)\n\nclass JSONEncoder(json.JSONEncoder):\n    def default(self, obj):\n        if isinstance(obj, ObjectId):\n            return str(obj)\n        elif isinstance(obj, bytes):\n            return None  # Skip binary data\n        return json.JSONEncoder.default(self, obj)\n\n@app.get(\"/\")\nasync def read_root():\n    return {\"message\": \"User: \" + bot.user.name + \" is online! \"}\n\n@app.get(\"/api\")\nasync def read_api_root():\n    return {\"message\": \"OK\"}\n\n@app.get(\"/api/commands/{cog}\")\nasync def get_commands(cog: Optional[str] = \"all\"):\n    if cog == \"all\":\n        all_commands = [\n            {\n                \"name\": (cmd.parent.name + \" \" if cmd.parent else \"\") + cmd.name,\n                \"description\": cmd.description,\n                \"cog\": cmd.cog_name,\n                \"usage\": cmd.usage, \"aliases\": cmd.aliases,\n                \"subcommand\": cmd.parent != None,\n                \"extras\": cmd.extras\n            } for cmd in bot.walk_commands() if not \"owner\" in cmd.cog_name\n        ]\n        return all_commands\n    else:\n        if cog not in bot.cogs:\n            return {\"message\": \"Cog not found.\", \"status\": 404}\n\n        if \"owner\" in cog:\n            return {\"message\": \"Cog not found.\", \"status\": 404}\n\n        commands = [\n            {\n                \"name\": (cmd.parent.name + \" \" if cmd.parent else \"\") + cmd.name,\n                \"description\": cmd.description,\n                \"usage\": cmd.usage, \"aliases\": cmd.aliases,\n                \"subcommand\": cmd.parent != None,\n                \"extras\": cmd.extras\n            } for cmd in bot.get_cog(cog).walk_commands()\n        ]\n\n        return commands\n\n@app.get(\"/api/cogs\")\nasync def get_cogs():\n    cogs = list(bot.cogs.keys())\n    if 'owner' in cogs:\n        cogs.remove('owner')\n    return cogs\n\n@app.get(\"/api/guild/{id}\")\nasync def get_guild(id: int):\n    guild = bot.get_guild(id)\n\n    if guild is None:\n        return {\"message\": \"Guild not found.\", \"status\": 404}\n\n    guilds = db[\"guilds\"]\n    guild_data = guilds.find_one({\"id\": guild.id})\n\n    if guild_data is None:\n        guild_data = CONSTANTS.guild_data_template(id)\n        guilds.insert_one(guild_data)\n\n    guild = {\n        \"name\": guild.name,\n        \"id\": guild.id,\n        \"dbdata\": str(JSONEncoder().encode(guild_data)),\n        \"members\": len(guild.members),\n        \"channels\": len(guild.channels),\n        \"roles\": len(guild.roles),\n    }\n\n    return guild\n\n\n@app.get(\"/api/user/{id}\")\nasync def get_user(id: int):\n    user = bot.get_user(id)\n\n    if user is None:\n        return {\"message\": \"User not found.\", \"status\": 404}\n\n    users = db[\"global_users\"]\n    user_data = await CachedDB.find_one(users, {\"id\": user.id})\n\n    if user_data is None:\n        user_data = CONSTANTS.user_global_data_template(id)\n        users.insert_one(user_data)\n\n    if user_data[\"blacklisted\"]:\n        return {\"message\": \"User is blacklisted.\", \"status\": 403, \"reason\": user_data[\"blacklist_reason\"]}\n\n    mutals = user.mutual_guilds\n\n    guilds = []\n\n    for guild in mutals:\n        if guild.get_member(user.id).guild_permissions.administrator:\n            guilds.append({\n                \"name\": guild.name,\n                \"id\": str(guild.id),\n                \"members\": len(guild.members),\n            })\n\n    return {\n        \"name\": user.name,\n        \"id\": user.id,\n        \"guilds\": guilds\n    }\n\n@app.get(\"/api/stats\")\nasync def get_stats():\n    return {\n        \"commands_ran\": bot.statsDB.get(\"commands_ran\"),\n        \"users\": len(set(bot.get_all_members())),\n        \"ai_requests\": bot.statsDB.get(\"ai_requests\"),\n    }\n\ndef run_fastapi():\n    if config[\"use_ssl\"]:\n        uvicorn.run(\n            app, host=\"0.0.0.0\",\n            port=config[\"port\"],\n            ssl_keyfile=config[\"ssl_keyfile\"],\n            ssl_certfile=config[\"ssl_certfile\"],\n            ssl_version=ssl.PROTOCOL_TLS\n        )\n    else:\n        uvicorn.run(\n            app, host=\"0.0.0.0\",\n            port=config[\"port\"],\n        )\n\nthread = threading.Thread(target=run_fastapi)\nthread.start()\n\nTOKEN = os.getenv(\"TOKEN\")\nbot.run(TOKEN)\n"
  },
  {
    "path": "requirements.txt",
    "content": "aiohttp\nasteval\nasyncpraw\nbetter_profanity\ncryptography\ndeep_translator\ndiscord.py\neasy_pil\nfastapi\ngroq\nlavalink\npickleDB\npymongo\npython-dotenv\nredis\nuvicorn\npillow\n"
  },
  {
    "path": "ui/code.py",
    "content": "import discord\nimport aiohttp\nfrom discord import ui\n\nclass CodeModal(ui.Modal, title = \"Run Code\"):\n    language = ui.TextInput(label = \"Language\", placeholder = \"Enter the language of your code\", style=discord.TextStyle.short, min_length = 1, max_length = 50)\n    code = ui.TextInput(label = \"Code\", placeholder = \"Enter your code here\", style=discord.TextStyle.long, min_length = 1, max_length = 2000)\n\n    async def on_submit(self, interaction: discord.Interaction) -> None:\n        async with aiohttp.ClientSession() as session:\n            embed = discord.Embed(title=f\"Running your {self.language.value} code...\", color=0xFFFFFF)\n\n            code = self.code.value[:1000].strip()\n            shortened = len(code) > 1000\n            lines = code.splitlines()\n            shortened = shortened or (len(lines) > 40)\n            code = \"\\n\".join(lines[:40])\n            code += shortened * \"\\n\\n**Code shortened**\"\n            embed.add_field(name=\"Code\", value=f\"```{self.language.value}\\n{code}```\", inline=False)\n\n            await interaction.response.send_message(embed=embed)\n\n            response = await session.post(\n                \"https://emkc.org/api/v1/piston/execute\",\n                json={\"language\": self.language.value, \"source\": self.code.value},\n            )\n\n            json = await response.json()\n\n            output = None\n            try:\n                output = json[\"output\"]\n            except KeyError:\n                await interaction.response.send_message(\"An error occurred while running your code: \\n\\n\" + json.get(\"message\", \"Unknown error\"))\n                return\n\n            embed = discord.Embed(title=f\"Ran your {json['language']} code\", color=0xFFFFFF)\n            output = output[:500].strip()\n            shortened = len(output) > 500\n            lines = output.splitlines()\n            shortened = shortened or (len(lines) > 15)\n            output = \"\\n\".join(lines[:15])\n            output += shortened * \"\\n\\n**Output shortened**\"\n            embed.add_field(name=\"Output\", value=f\"```{self.language.value}\\n{output}\\n```\" or \"**<No output>**\")\n\n            await interaction.followup.send(embed=embed)\n"
  },
  {
    "path": "ui/farm.py",
    "content": "import discord\nimport time\n\nfrom discord import ui\nfrom discord.ui import button, View, Modal\n\nfrom utils import DBClient, CachedDB\n\ndb = DBClient.db\n\nclass FarmModal(Modal, title = \"Buy Saplings (5$ per sapling)\"):\n    def __init__(self, message):\n        super().__init__(timeout = 60)\n\n        self.message = message\n\n    amount = ui.TextInput(label = \"Amount of Sapling\", placeholder = \"Type max to buy for all your money\", style=discord.TextStyle.short, min_length = 1, max_length = 50)\n\n    async def on_submit(self, interaction: discord.Interaction) -> None:\n        users = db[\"users\"]\n        data = await CachedDB.find_one(users, {\"id\": interaction.user.id, \"guild_id\": interaction.guild.id})\n\n        value = self.amount.value\n\n        if value == \"max\":\n            value = data[\"wallet\"] // 5\n        else:\n            if not value.isdigit():\n                await interaction.response.send_message(\"Please enter a valid number\", ephemeral=True)\n                return\n\n        price = 5 * int(value)\n\n        if data[\"wallet\"] < price:\n            await interaction.response.send_message(f\"You cant afford {value} sapling(s) for ${price}\", ephemeral=True)\n            return\n\n        data[\"wallet\"] -= price\n        data[\"farm\"][\"saplings\"] += int(value)\n\n        new_data = {\n            \"$set\": {\"farm\": data[\"farm\"], \"wallet\": data[\"wallet\"]}\n        }\n\n        await CachedDB.update_one(users, {\"id\": interaction.user.id, \"guild_id\": interaction.guild.id}, new_data)\n\n        await interaction.response.send_message(f\"Bought {value} sapling(s) for ${price}\", ephemeral=True)\n\n        c = db[\"users\"]\n        data = c.find_one({\"id\": interaction.user.id, \"guild_id\": interaction.guild.id})\n\n        farmData = data[\"farm\"]\n\n        embed = discord.Embed(\n            title=\"Farm\",\n            description=\"Buy saplings to farm potatoes\",\n            color=0x77dd77,\n        )\n\n        embed.add_field(\n            name=\"Saplings\",\n            value=farmData[\"saplings\"],\n            inline=False,\n        )\n\n        embed.add_field(\n            name=\"Crops\",\n            value=farmData[\"crops\"],\n            inline=False,\n        )\n\n        embed.add_field(\n            name=\"Harvestable\",\n            value=farmData[\"harvestable\"],\n            inline=False,\n        )\n\n        embed.add_field(\n            name=\"Ready\",\n            value=f\"<t:{int(farmData['ready_in'])}:R>\",\n            inline=False,\n        )\n\n        embed.set_footer(text=f\"Wallet: ${data['wallet']}\")\n\n        await interaction.message.edit(embed=embed, view=FarmButton(interaction.user.id))\n\nclass FarmButton(View):\n    def __init__(self, authorid):\n        super().__init__(timeout=None)\n        self.saplings = 0\n        self.authorid = authorid\n\n    @button(label=\"Buy Saplings (show menu)\", style=discord.ButtonStyle.primary, custom_id=\"farm\",emoji=\"🌱\")\n    async def farm(self, interaction: discord.Interaction, button: discord.ui.Button):\n        if interaction.user.id != self.authorid:\n            return await interaction.response.send_message(\"You can't farm someone else's farm\", ephemeral=True)\n\n        await interaction.response.send_modal(FarmModal(interaction.message))\n\n\n    @button(label=\"Plant Crops\", style=discord.ButtonStyle.primary, custom_id=\"plant\",emoji=\"🌾\", row=1)\n    async def plant(self, interaction: discord.Interaction, button: discord.ui.Button):\n        if interaction.user.id != self.authorid:\n            return await interaction.response.send_message(\"You can't plant someone else's crops\", ephemeral=True)\n\n        c = db[\"users\"]\n        data = c.find_one({\"id\": interaction.user.id, \"guild_id\": interaction.guild.id})\n\n\n        farmData = data[\"farm\"]\n\n        if not farmData[\"saplings\"] > 0:\n            await interaction.response.send_message(\"You don't have any saplings to plant\", ephemeral=True)\n            return\n\n        if farmData[\"crops\"] > 0:\n            await interaction.response.send_message(\"You already have crops growing\", ephemeral=True)\n            return\n\n        farmData[\"crops\"] = farmData[\"saplings\"]\n        farmData[\"ready_in\"] = time.time() + 86400\n        farmData[\"saplings\"] = 0\n\n        newdata = {\n            \"$set\": {\n                \"farm.saplings\": farmData[\"saplings\"],\n                \"farm.crops\": farmData[\"crops\"],\n                \"farm.ready_in\": farmData[\"ready_in\"],\n                }\n        }\n        c.update_one(\n            {\"id\": interaction.user.id, \"guild_id\": interaction.guild.id}, newdata\n        )\n\n        await interaction.response.send_message(\"You planted your crops\", ephemeral=True)\n\n        farmData = data[\"farm\"]\n\n        embed = discord.Embed(\n            title=\"Farm\",\n            description=\"Buy saplings to farm potatoes\",\n            color=0x77dd77,\n        )\n\n        embed.add_field(\n            name=\"Saplings\",\n            value=farmData[\"saplings\"],\n            inline=False,\n        )\n\n        embed.add_field(\n            name=\"Crops\",\n            value=farmData[\"crops\"],\n            inline=False,\n        )\n\n        embed.add_field(\n            name=\"Harvestable\",\n            value=farmData[\"harvestable\"],\n            inline=False,\n        )\n\n        embed.add_field(\n            name=\"Ready\",\n            value=f\"<t:{int(farmData['ready_in'])}:R>\",\n            inline=False,\n        )\n\n        embed.set_footer(text=f\"Wallet: ${data['wallet']}\")\n\n        await interaction.message.edit(embed=embed, view=FarmButton(self.authorid))\n\n    @button(label=\"Harvest Crops\", style=discord.ButtonStyle.primary, custom_id=\"harvest\",emoji=\"🥔\", row=1)\n    async def harvest(self, interaction: discord.Interaction, button: discord.ui.Button):\n        if interaction.user.id != self.authorid:\n            return await interaction.response.send_message(\"You can't harvest someone else's crops\", ephemeral=True)\n\n        c = db[\"users\"]\n        data = c.find_one({\"id\": interaction.user.id, \"guild_id\": interaction.guild.id})\n\n        farmData = data[\"farm\"]\n\n        if not farmData[\"harvestable\"] > 0:\n            await interaction.response.send_message(\"You don't have any crops to harvest\", ephemeral=True)\n            return\n\n        await interaction.response.send_message(\"You harvested your crops for $\" + str(farmData[\"harvestable\"]*10), ephemeral=True)\n\n        data[\"wallet\"] += farmData[\"harvestable\"]*10\n\n        if farmData[\"ready_in\"] < time.time():\n            farmData[\"harvestable\"] = 0\n            farmData[\"ready_in\"] = time.time() + 86400\n\n        newdata = {\n            \"$set\": {\n                \"wallet\": data[\"wallet\"],\n                \"farm.harvestable\": 0,\n                \"farm.ready_in\": farmData[\"ready_in\"],\n                }\n        }\n        c.update_one(\n            {\"id\": interaction.user.id, \"guild_id\": interaction.guild.id}, newdata\n        )\n\n\n        farmData = data[\"farm\"]\n\n        embed = discord.Embed(\n            title=\"Farm\",\n            description=\"Buy saplings to farm potatoes\",\n            color=0x77dd77,\n        )\n\n        embed.add_field(\n            name=\"Saplings\",\n            value=farmData[\"saplings\"],\n            inline=False,\n        )\n\n        embed.add_field(\n            name=\"Crops\",\n            value=farmData[\"crops\"],\n            inline=False,\n        )\n\n        embed.add_field(\n            name=\"Harvestable\",\n            value=farmData[\"harvestable\"],\n            inline=False,\n        )\n\n        embed.add_field(\n            name=\"Ready\",\n            value=f\"<t:{int(farmData['ready_in'])}:R>\",\n            inline=False,\n        )\n\n        embed.set_footer(text=f\"Wallet: ${data['wallet']}\")\n\n        await interaction.message.edit(embed=embed, view=FarmButton(self.authorid))\n"
  },
  {
    "path": "ui/gambling.py",
    "content": "import discord\nimport asyncio\nimport random\n\nfrom discord import ui\nfrom discord.ui import Button, button, View\n\nfrom utils import DBClient\n\ndb = DBClient.db\n\nclass GamblingButton(View):\n    def __init__(self, amount, authorid):\n        super().__init__(timeout=None)\n        self.amount = amount\n        self.authorid = authorid\n\n    @button(label=\"Coin Flip\", style=discord.ButtonStyle.primary, custom_id=\"coin_flip\", emoji=\"🪙\")\n    async def coinflip(self, interaction: discord.Interaction, button: discord.ui.Button):\n        if interaction.user.id != self.authorid:\n            return await interaction.response.send_message(\"Nuh uh :D\", ephemeral=True)\n\n        await interaction.response.edit_message(content=\"Heads or tails?\", view=HeadsOrTailsButton(self.amount, self.authorid))\n\n    @button(label=\"Dice Roll\", style=discord.ButtonStyle.primary, custom_id=\"roll_dice\", emoji=\"🎲\")\n    async def diceroll(self, interaction: discord.Interaction, button: discord.ui.Button):\n        if interaction.user.id != self.authorid:\n            return await interaction.response.send_message(\"Nuh uh :D\", ephemeral=True)\n\n        await interaction.response.edit_message(content=\"Choose a number between 1 and 6\", view=RollButton(self.amount, self.authorid))\n\n    @button(label=\"Blackjack\", style=discord.ButtonStyle.primary, custom_id=\"blackjack\", emoji=\"🃏\")\n    async def blackjack(self, interaction: discord.Interaction, button: discord.ui.Button):\n        if interaction.user.id != self.authorid:\n            return await interaction.response.send_message(\"Nuh uh :D\", ephemeral=True)\n\n        view = BlackjackView(self.amount, self.authorid)\n        await view.start_game(interaction)\n\n    @button(label=\"Slots\", style=discord.ButtonStyle.primary, custom_id=\"slots\", emoji=\"🎰\")\n    async def slots(self, interaction: discord.Interaction, button: discord.ui.Button):\n        if interaction.user.id != self.authorid:\n            return await interaction.response.send_message(\"Nuh uh :D\", ephemeral=True)\n        await interaction.response.edit_message(content=\"LETS GO GAMBLING!!!\", view=SlotsButton(self.amount, 1, self.authorid))\n\n\nclass BlackjackView(View):\n    def __init__(self, amount, authorid):\n        super().__init__(timeout=None)\n        self.amount = amount\n        self.authorid = authorid\n        self.deck = self.create_deck()\n        self.player_hand = [self.deck.pop(), self.deck.pop()]\n        self.dealer_hand = [self.deck.pop(), self.deck.pop()]\n        self.player_score = self.calculate_score(self.player_hand)\n        self.dealer_score = self.calculate_score(self.dealer_hand)\n        self.game_over = False\n\n    def create_deck(self):\n        deck = []\n        for _ in range(4):\n            for value in range(1, 14):\n                deck.append(value)\n        random.shuffle(deck)\n        return deck\n\n    def calculate_score(self, hand):\n        score = 0\n        aces = 0\n        for card in hand:\n            if card == 1:\n                aces += 1\n            elif card > 10:\n                score += 10\n            else:\n                score += card\n        for _ in range(aces):\n            if score + 11 <= 21:\n                score += 11\n            else:\n                score += 1\n        return score\n\n    def update_embed(self):\n        embed = discord.Embed(title=\"Blackjack\", color=0x77dd77)\n        embed.add_field(name=\"Your hand\", value=f\"{self.player_hand} ({self.player_score})\", inline=False)\n        embed.add_field(name=\"Dealer's hand\", value=f\"{self.dealer_hand[0]} and hidden\", inline=False)  # Show one dealer card\n        return embed\n\n    @button(label=\"Hit\", style=discord.ButtonStyle.primary, custom_id=\"hit\", emoji=\"👊\")\n    async def hit(self, interaction: discord.Interaction, button: discord.ui.Button):\n        if interaction.user.id != self.authorid:\n            return await interaction.response.send_message(\"Nuh uh :D\", ephemeral=True)\n\n        if self.game_over:\n            return await interaction.response.send_message(\"The game is over\", ephemeral=True)\n\n        c = db[\"users\"]\n        user = c.find_one({\"id\": interaction.user.id, \"guild_id\": interaction.guild.id})\n\n        self.player_hand.append(self.deck.pop())\n        self.player_score = self.calculate_score(self.player_hand)\n\n        if self.player_score > 21:\n            self.game_over = True\n            user[\"wallet\"] -= self.amount\n\n            newdata = {\"$set\": {\"wallet\": user[\"wallet\"]}}\n            c.update_one({\"id\": interaction.user.id, \"guild_id\": interaction.guild.id}, newdata)\n\n            embed = self.update_embed()\n            return await interaction.response.edit_message(content=\"You went over 21! You lost\", embed=embed, view=self)\n\n        if self.player_score == 21:\n            self.game_over = True\n            user[\"wallet\"] += self.amount\n\n            newdata = {\"$set\": {\"wallet\": user[\"wallet\"]}}\n            c.update_one({\"id\": interaction.user.id, \"guild_id\": interaction.guild.id}, newdata)\n\n            embed = self.update_embed()\n            return await interaction.response.edit_message(content=\"You got 21! You won\", embed=embed, view=self)\n\n        embed = self.update_embed()\n        await interaction.response.edit_message(embed=embed, view=self)\n\n    @button(label=\"Stand\", style=discord.ButtonStyle.primary, custom_id=\"stand\", emoji=\"🛑\")\n    async def stand(self, interaction: discord.Interaction, button: discord.ui.Button):\n        if interaction.user.id != self.authorid:\n            return await interaction.response.send_message(\"Nuh uh :D\", ephemeral=True)\n\n        if self.game_over:\n            return await interaction.response.send_message(\"The game is over\", ephemeral=True)\n\n        c = db[\"users\"]\n        user = c.find_one({\"id\": interaction.user.id, \"guild_id\": interaction.guild.id})\n\n        while self.dealer_score < 17:\n            self.dealer_hand.append(self.deck.pop())\n            self.dealer_score = self.calculate_score(self.dealer_hand)\n\n        if self.dealer_score > 21:\n            self.game_over = True\n            user[\"wallet\"] += self.amount\n\n            newdata = {\"$set\": {\"wallet\": user[\"wallet\"]}}\n            c.update_one({\"id\": interaction.user.id, \"guild_id\": interaction.guild.id}, newdata)\n\n            embed = self.update_embed()\n            return await interaction.response.edit_message(content=\"Dealer went over 21! You won\", embed=embed, view=self)\n\n        if self.dealer_score > self.player_score:\n            self.game_over = True\n            user[\"wallet\"] -= self.amount\n\n            newdata = {\"$set\": {\"wallet\": user[\"wallet\"]}}\n            c.update_one({\"id\": interaction.user.id, \"guild_id\": interaction.guild.id}, newdata)\n\n            embed = self.update_embed()\n            return await interaction.response.edit_message(content=\"Dealer won\", embed=embed, view=self)\n\n        if self.dealer_score == self.player_score:\n            self.game_over = True\n            embed = self.update_embed()\n            return await interaction.response.edit_message(content=\"It's a tie\", embed=embed, view=self)\n\n        self.game_over = True\n        embed = self.update_embed()\n        await interaction.response.edit_message(content=\"Game is over\", embed=embed, view=self)\n\n    async def interaction_check(self, interaction: discord.Interaction) -> bool:\n        return interaction.user.id == self.authorid\n\n    async def on_timeout(self):\n        self.clear_items()\n        self.stop()\n\n    async def start_game(self, interaction: discord.Interaction):\n        embed = self.update_embed()\n        await interaction.response.send_message(embed=embed, view=self)\n\nclass HeadsOrTailsButton(View):\n    def __init__(self, amount, authorid):\n        super().__init__(timeout=None)\n        self.amount = amount\n        self.authorid = authorid\n\n    @button(label=\"Heads\", style=discord.ButtonStyle.primary, custom_id=\"heads\",emoji=\"🪙\")\n    async def heads(self, interaction: discord.Interaction, button: Button):\n        if interaction.user.id != self.authorid:\n            return\n\n        await interaction.response.defer()\n        await interaction.message.edit(content=\"Flipping the coin...\", view=None)\n        await asyncio.sleep(1)\n        coin = random.choice([\"heads\", \"tails\"])\n\n        c = db[\"users\"]\n        data = c.find_one({\"id\": interaction.user.id, \"guild_id\": interaction.guild.id})\n\n        if coin == \"heads\":\n            await interaction.message.edit(content=f\"The coin landed on {coin}! You won {self.amount * 2}$\")\n\n            data[\"wallet\"] += self.amount * 2\n        else:\n            await interaction.message.edit(content=f\"The coin landed on {coin}! You lost {self.amount}$\")\n\n            data[\"wallet\"] -= self.amount\n\n        newdata = {\n            \"$set\": {\"wallet\": data[\"wallet\"]}\n        }\n        c.update_one(\n            {\"id\": interaction.user.id, \"guild_id\": interaction.guild.id}, newdata\n        )\n\n    @button(label=\"Tails\", style=discord.ButtonStyle.primary, custom_id=\"tails\",emoji=\"🪙\")\n    async def tails(self, interaction: discord.Interaction, button: Button):\n        if interaction.user.id != self.authorid:\n            return\n\n        await interaction.response.defer()\n        await interaction.message.edit(content=\"Flipping the coin...\", view=None)\n        await asyncio.sleep(1)\n        coin = random.choice([\"heads\", \"tails\"])\n\n        c = db[\"users\"]\n        data = c.find_one({\"id\": interaction.user.id, \"guild_id\": interaction.guild.id})\n\n        if coin == \"tails\":\n            await interaction.message.edit(content=f\"The coin landed on {coin}! You won {self.amount * 2}$\")\n\n            data[\"wallet\"] += self.amount * 2\n        else:\n            await interaction.message.edit(content=f\"The coin landed on {coin}! You lost {self.amount}$\")\n\n            data[\"wallet\"] -= self.amount\n\n        newdata = {\n            \"$set\": {\"wallet\": data[\"wallet\"]}\n        }\n        c.update_one(\n            {\"id\": interaction.user .id, \"guild_id\": interaction.guild.id}, newdata\n        )\n\n# roll 1 - 6\nclass RollButton(View):\n    def __init__(self, amount, authorid):\n        super().__init__(timeout=None)\n        self.amount = amount\n        self.authorid = authorid\n\n    @button(label=\"\", style=discord.ButtonStyle.primary, custom_id=\"roll_1\",emoji=\"1️⃣\")\n    async def one(self, interaction: discord.Interaction, button: button):\n        if interaction.user.id != self.authorid:\n            return\n\n        await interaction.message.edit(content=\"Rolling the dice...\", view=None)\n        await asyncio.sleep(1)\n        number = random.randrange(1, 6)\n\n        c = db[\"users\"]\n        data = c.find_one({\"id\": interaction.user.id, \"guild_id\": interaction.guild.id})\n\n        if number == 1:\n            await interaction.message.edit(content=f\"The dice landed on {number}! You won {self.amount * 5}$\")\n\n            data[\"wallet\"] += self.amount * 5\n        else:\n            await interaction.message.edit(content=f\"The dice landed on {number}! You lost {self.amount}$\")\n\n            data[\"wallet\"] -= self.amount\n\n        newdata = {\n            \"$set\": {\"wallet\": data[\"wallet\"]}\n        }\n        c.update_one(\n            {\"id\": interaction.user.id, \"guild_id\": interaction.guild.id}, newdata\n        )\n\n    @button(label=\"\", style=discord.ButtonStyle.primary, custom_id=\"roll_2\",emoji=\"2️⃣\")\n    async def two(self, interaction: discord.Interaction, button: button):\n        if interaction.user.id != self.authorid:\n            return\n\n        await interaction.message.edit(content=\"Rolling the dice...\", view=None)\n        await asyncio.sleep(1)\n        number = random.randrange(1, 6)\n\n        c = db[\"users\"]\n        data = c.find_one({\"id\": interaction.user.id, \"guild_id\": interaction.guild.id})\n\n        if number == 2:\n            await interaction.message.edit(content=f\"The dice landed on {number}! You won {self.amount * 5}$\")\n\n            data[\"wallet\"] += self.amount * 5\n        else:\n            await interaction.message.edit(content=f\"The dice landed on {number}! You lost {self.amount}$\")\n\n            data[\"wallet\"] -= self.amount\n\n        newdata = {\n            \"$set\": {\"wallet\": data[\"wallet\"]}\n        }\n        c.update_one(\n            {\"id\": interaction.user.id, \"guild_id\": interaction.guild.id}, newdata\n        )\n\n    @button(label=\"\", style=discord.ButtonStyle.primary, custom_id=\"roll_3\",emoji=\"3️⃣\")\n    async def three(self, interaction: discord.Interaction, button: button):\n        if interaction.user.id != self.authorid:\n            return\n\n        await interaction.message.edit(content=\"Rolling the dice...\", view=None)\n        await asyncio.sleep(1)\n        number = random.randrange(1, 6)\n\n        c = db[\"users\"]\n        data = c.find_one({\"id\": interaction.user.id, \"guild_id\": interaction.guild.id})\n\n        if number == 3:\n            await interaction.message.edit(content=f\"The dice landed on {number}! You won {self.amount * 5}$\")\n\n            data[\"wallet\"] += self.amount * 5\n        else:\n            await interaction.message.edit(content=f\"The dice landed on {number}! You lost {self.amount}$\")\n\n            data[\"wallet\"] -= self.amount\n\n        newdata = {\n            \"$set\": {\"wallet\": data[\"wallet\"]}\n        }\n\n        c.update_one(\n            {\"id\": interaction.user.id, \"guild_id\": interaction.guild.id}, newdata\n        )\n\n    @button(label=\"\", style=discord.ButtonStyle.primary, custom_id=\"roll_4\",emoji=\"4️⃣\")\n    async def four(self, interaction: discord.Interaction, button: button):\n        if interaction.user.id != self.authorid:\n            return\n\n        await interaction.message.edit(content=\"Rolling the dice...\", view=None)\n        await asyncio.sleep(1)\n        number = random.randrange(1, 6)\n\n        c = db[\"users\"]\n        data = c.find_one({\"id\": interaction.user.id, \"guild_id\": interaction.guild.id})\n\n        if number == 4:\n            await interaction.message.edit(content=f\"The dice landed on {number}! You won {self.amount * 5}$\")\n\n            data[\"wallet\"] += self.amount * 5\n        else:\n            await interaction.message.edit(content=f\"The dice landed on {number}! You lost {self.amount}$\")\n\n            data[\"wallet\"] -= self.amount\n\n        newdata = {\n            \"$set\": {\"wallet\": data[\"wallet\"]}\n        }\n\n        c.update_one(\n            {\"id\": interaction.user.id, \"guild_id\": interaction.guild.id}, newdata\n        )\n\n    @button(label=\"\", style=discord.ButtonStyle.primary, custom_id=\"roll_5\",emoji=\"5️⃣\")\n    async def five(self, interaction: discord.Interaction, button: button):\n        if interaction.user.id != self.authorid:\n            return\n\n        await interaction.message.edit(content=\"Rolling the dice...\", view=None)\n        await asyncio.sleep(1)\n        number = random.randrange(1, 6)\n\n        c = db[\"users\"]\n        data = c.find_one({\"id\": interaction.user.id, \"guild_id\": interaction.guild.id})\n\n        if number == 5:\n            await interaction.message.edit(content=f\"The dice landed on {number}! You won {self.amount * 5}$\")\n\n            data[\"wallet\"] += self.amount * 5\n        else:\n            await interaction.message.edit(content=f\"The dice landed on {number}! You lost {self.amount}$\")\n\n            data[\"wallet\"] -= self.amount\n\n        newdata = {\n            \"$set\": {\"wallet\": data[\"wallet\"]}\n        }\n        c.update_one(\n            {\"id\": interaction.user.id, \"guild_id\": interaction.guild.id}, newdata\n        )\n\n    @button(label=\"\", style=discord.ButtonStyle.primary, custom_id=\"roll_6\",emoji=\"6️⃣\")\n    async def six(self, interaction: discord.Interaction, button: button):\n\n        if interaction.user.id != self.authorid:\n            return\n\n        await interaction.message.edit(content=\"Rolling the dice...\", view=None)\n        await asyncio.sleep(1)\n        number = random.randrange(1, 6)\n\n        c = db[\"users\"]\n        data = c.find_one({\"id\": interaction.user.id, \"guild_id\": interaction.guild.id})\n\n        if number == 6:\n            await interaction.message.edit(content=f\"The dice landed on {number}! You won {self.amount * 5}$\")\n\n            data[\"wallet\"] += self.amount * 5\n        else:\n            await interaction.message.edit(content=f\"The dice landed on {number}! You lost {self.amount}$\")\n\n            data[\"wallet\"] -= self.amount\n\n        newdata = {\n            \"$set\": {\"wallet\": data[\"wallet\"]}\n        }\n        c.update_one(\n            {\"id\": interaction.user.id, \"guild_id\": interaction.guild.id}, newdata\n        )\n\n        # TODO: make sure my ass code actually w̶o̶r̶k̶s looks good\n\nclass SlotsButton(View):\n    def __init__(self, amount, multii, authorid):\n        super().__init__(timeout=None)\n        self.amount = amount\n        self.multii = multii\n        self.authorid = authorid\n        self.result = \"❌ ❌ ❌\"\n        self.outcome_message = \"Spin first!\"\n\n    def getEmbed(self):\n        embed = discord.Embed(title=\"Slots\", description=f\"# `{self.result}`\", color=0xe86e30)\n        embed.add_field(name=\"Result:\", value=f\"```{self.outcome_message}```\", inline=False)\n        embed.add_field(name=\"Multiplier:\", value=f\"```x{self.multii}```\", inline=False)\n        return embed\n\n    @button(label=\"Spin\", style=discord.ButtonStyle.primary, custom_id=\"spin\", emoji=\"🎰\")\n    async def spin(self, interaction: discord.Interaction, button: discord.ui.Button):\n        if interaction.user.id != self.authorid:\n            return await interaction.response.send_message(\"Nuh uh :D\", ephemeral=True)\n\n        result, outcome_message, amount_won = play_slots(self.amount, self.multii)\n        self.result = result\n        self.outcome_message = outcome_message\n\n        # Update user wallet in database\n        c = db[\"users\"]\n        user = c.find_one({\"id\": interaction.user.id, \"guild_id\": interaction.guild.id})\n        user[\"wallet\"] += amount_won\n        newdata = {\"$set\": {\"wallet\": user[\"wallet\"]}}\n        c.update_one({\"id\": interaction.user.id, \"guild_id\": interaction.guild.id}, newdata)\n\n        await interaction.response.edit_message(embed=self.getEmbed(), view=self)\n\n    @button(label=\"\", style=discord.ButtonStyle.primary, custom_id=\"incmulti\", emoji=\"➕\")\n    async def increment_multiplier(self, interaction: discord.Interaction, button: discord.ui.Button):\n        if interaction.user.id != self.authorid:\n            return await interaction.response.send_message(\"Nuh uh :D\", ephemeral=True)\n\n        self.multii += 1\n        await interaction.response.edit_message(embed=self.getEmbed(), view=self)\n\n    @button(label=\"\", style=discord.ButtonStyle.primary, custom_id=\"decmulti\", emoji=\"➖\")\n    async def decrement_multiplier(self, interaction: discord.Interaction, button: discord.ui.Button):\n        if interaction.user.id != self.authorid:\n            return await interaction.response.send_message(\"Nuh uh :D\", ephemeral=True)\n\n        if self.multii > 1:  # Prevents multiplier from going below 1\n            self.multii -= 1\n        await interaction.response.edit_message(embed=self.getEmbed(), view=self)\n\ndef play_slots(amount, multii):\n    symbols = [\"🍒\", \"🍋\", \"🍉\", \"⭐\", \"🔔\", \"🍇\", \"🍍\", \"🍎\", \"🍓\", \"🥭\"]\n    reel = [random.choice(symbols) for _ in range(3)]\n    result = f\"{reel[0]} {reel[1]} {reel[2]}\"\n\n    if reel[0] == reel[1] == reel[2]:\n        amount_won = (amount * 5) * multii\n        outcome_message = f\"Jackpot! You won {amount_won}$!\"\n    elif reel[0] == reel[1] or reel[1] == reel[2] or reel[0] == reel[2]:\n        amount_won = (amount * 2) * multii\n        outcome_message = f\"You got a match! You won {amount_won}$!\"\n    else:\n        amount_won = (-amount) * multii\n        outcome_message = f\"Unlucky! You lost {amount}$.\"\n\n    return result, outcome_message, amount_won\n"
  },
  {
    "path": "ui/papertrading.py",
    "content": "import discord\r\nimport asyncio\r\nimport aiohttp\r\nimport json\r\nimport os\r\nfrom datetime import datetime\r\nfrom discord import ui\r\nfrom discord.ui import Button, button, View\r\n\r\nfrom utils import DBClient\r\n\r\ndb = DBClient.db\r\n\r\n# Configuration Constants\r\n# TODO: put this in a config file\r\nALPHA_VANTAGE_API_KEY = os.getenv('ALPHA_VANTAGE_API_KEY')\r\nMIN_TRADE_AMOUNT = 1\r\nMAX_TRADE_AMOUNT = 100000\r\nTRADE_COOLDOWN = 5\r\nDEMO_MODE = False\r\nMOCK_PRICES = {\r\n    \"AAPL\": 175.50,\r\n    \"GOOGL\": 140.25,\r\n    \"MSFT\": 380.75,\r\n    \"AMZN\": 145.30,\r\n    \"TSLA\": 240.45,\r\n    \"META\": 485.60,\r\n    \"NVDA\": 820.30,\r\n    \"AMD\": 175.25\r\n}\r\n\r\nclass StockPortfolioView(View):\r\n    def __init__(self, authorid):\r\n        super().__init__(timeout=None)\r\n        self.authorid = authorid\r\n        self.last_trade_time = {}\r\n\r\n    @button(label=\"Buy Stocks\", style=discord.ButtonStyle.primary, custom_id=\"buy_stocks\", emoji=\"📈\")\r\n    async def buy_stocks(self, interaction: discord.Interaction, button: discord.ui.Button):\r\n        if interaction.user.id != self.authorid:\r\n            return await interaction.response.send_message(\"This isn't your trading session!\", ephemeral=True)\r\n\r\n        current_time = datetime.now().timestamp()\r\n        if self.authorid in self.last_trade_time:\r\n            time_diff = current_time - self.last_trade_time[self.authorid]\r\n            if time_diff < TRADE_COOLDOWN:\r\n                return await interaction.response.send_message(\r\n                    f\"Please wait {TRADE_COOLDOWN - int(time_diff)} seconds before trading again!\",\r\n                    ephemeral=True\r\n                )\r\n\r\n        self.last_trade_time[self.authorid] = current_time\r\n        await interaction.response.send_modal(BuyStocksModal(self.authorid))\r\n\r\n    @button(label=\"Sell Stocks\", style=discord.ButtonStyle.danger, custom_id=\"sell_stocks\", emoji=\"📉\")\r\n    async def sell_stocks(self, interaction: discord.Interaction, button: discord.ui.Button):\r\n        if interaction.user.id != self.authorid:\r\n            return await interaction.response.send_message(\"This isn't your trading session!\", ephemeral=True)\r\n\r\n        current_time = datetime.now().timestamp()\r\n        if self.authorid in self.last_trade_time:\r\n            time_diff = current_time - self.last_trade_time[self.authorid]\r\n            if time_diff < TRADE_COOLDOWN:\r\n                return await interaction.response.send_message(\r\n                    f\"Please wait {TRADE_COOLDOWN - int(time_diff)} seconds before trading again!\",\r\n                    ephemeral=True\r\n                )\r\n\r\n        self.last_trade_time[self.authorid] = current_time\r\n        await interaction.response.send_modal(SellStocksModal(self.authorid))\r\n\r\n    @button(label=\"View Portfolio\", style=discord.ButtonStyle.secondary, custom_id=\"view_portfolio\", emoji=\"📊\")\r\n    async def view_portfolio(self, interaction: discord.Interaction, button: discord.ui.Button):\r\n        if interaction.user.id != self.authorid:\r\n            return await interaction.response.send_message(\"This isn't your trading session!\", ephemeral=True)\r\n\r\n        c = db[\"trading\"]\r\n        portfolio = c.find_one({\"user_id\": interaction.user.id, \"guild_id\": interaction.guild.id})\r\n\r\n        if not portfolio or not portfolio.get(\"positions\", {}):\r\n            return await interaction.response.send_message(\"You don't have any positions yet!\", ephemeral=True)\r\n\r\n        c_users = db[\"users\"]\r\n        user = c_users.find_one({\"id\": interaction.user.id, \"guild_id\": interaction.guild.id})\r\n\r\n        embed = discord.Embed(title=\"Your Portfolio\", color=0x00ff00)\r\n        embed.add_field(name=\"Available Balance\", value=f\"${user['wallet']:,.2f}\", inline=False)\r\n\r\n        total_value = 0\r\n\r\n        for symbol, position in portfolio[\"positions\"].items():\r\n            price = await get_stock_price(symbol)\r\n            if price:\r\n                current_value = position[\"shares\"] * price\r\n                total_value += current_value\r\n                profit_loss = current_value - (position[\"shares\"] * position[\"average_price\"])\r\n\r\n                embed.add_field(\r\n                    name=f\"{symbol}\",\r\n                    value=f\"Shares: {position['shares']}\\n\"\r\n                          f\"Avg Price: ${position['average_price']:.2f}\\n\"\r\n                          f\"Current Price: ${price:.2f}\\n\"\r\n                          f\"P/L: ${profit_loss:.2f} ({(profit_loss/current_value)*100:.1f}%)\",\r\n                    inline=False\r\n                )\r\n\r\n        embed.add_field(name=\"Total Portfolio Value\", value=f\"${total_value:.2f}\", inline=False)\r\n        embed.add_field(name=\"Total Account Value\", value=f\"${(total_value + user['wallet']):.2f}\", inline=False)\r\n        await interaction.response.send_message(embed=embed, ephemeral=True)\r\n\r\nclass BuyStocksModal(ui.Modal, title=\"Buy Stocks\"):\r\n    def __init__(self, authorid):\r\n        super().__init__()\r\n        self.authorid = authorid\r\n\r\n    symbol = ui.TextInput(label=\"Stock Symbol\", placeholder=\"e.g. AAPL\", min_length=1, max_length=5)\r\n    shares = ui.TextInput(label=\"Number of Shares\", placeholder=\"e.g. 10\")\r\n\r\n    async def on_submit(self, interaction: discord.Interaction):\r\n        if interaction.user.id != self.authorid:\r\n            return await interaction.response.send_message(\"This isn't your trading session!\", ephemeral=True)\r\n\r\n        symbol = self.symbol.value.upper()\r\n        try:\r\n            shares = float(self.shares.value)\r\n            if not MIN_TRADE_AMOUNT <= shares <= MAX_TRADE_AMOUNT:\r\n                return await interaction.response.send_message(\r\n                    f\"Please enter between {MIN_TRADE_AMOUNT} and {MAX_TRADE_AMOUNT} shares!\",\r\n                    ephemeral=True\r\n                )\r\n        except ValueError:\r\n            return await interaction.response.send_message(\"Please enter a valid number of shares!\", ephemeral=True)\r\n\r\n        price = await get_stock_price(symbol)\r\n        if not price:\r\n            return await interaction.response.send_message(\"Invalid stock symbol or API error!\", ephemeral=True)\r\n\r\n        total_cost = price * shares\r\n\r\n        c = db[\"users\"]\r\n        user = c.find_one({\"id\": interaction.user.id, \"guild_id\": interaction.guild.id})\r\n        if not user or user[\"wallet\"] < total_cost:\r\n            return await interaction.response.send_message(\r\n                f\"Insufficient funds! You need ${total_cost:,.2f} but have ${user['wallet']:,.2f}\",\r\n                ephemeral=True\r\n            )\r\n\r\n        c = db[\"trading\"]\r\n        portfolio = c.find_one({\"user_id\": interaction.user.id, \"guild_id\": interaction.guild.id})\r\n\r\n        if not portfolio:\r\n            portfolio = {\r\n                \"user_id\": interaction.user.id,\r\n                \"guild_id\": interaction.guild.id,\r\n                \"positions\": {}\r\n            }\r\n            c.insert_one(portfolio)\r\n\r\n        if symbol in portfolio[\"positions\"]:\r\n            current_position = portfolio[\"positions\"][symbol]\r\n            new_shares = current_position[\"shares\"] + shares\r\n            new_average_price = ((current_position[\"shares\"] * current_position[\"average_price\"]) + total_cost) / new_shares\r\n            portfolio[\"positions\"][symbol] = {\r\n                \"shares\": new_shares,\r\n                \"average_price\": new_average_price\r\n            }\r\n        else:\r\n            portfolio[\"positions\"][symbol] = {\r\n                \"shares\": shares,\r\n                \"average_price\": price\r\n            }\r\n\r\n        c.update_one(\r\n            {\"user_id\": interaction.user.id, \"guild_id\": interaction.guild.id},\r\n            {\"$set\": {\"positions\": portfolio[\"positions\"]}}\r\n        )\r\n\r\n        user[\"wallet\"] -= total_cost\r\n        c = db[\"users\"]\r\n        c.update_one(\r\n            {\"id\": interaction.user.id, \"guild_id\": interaction.guild.id},\r\n            {\"$set\": {\"wallet\": user[\"wallet\"]}}\r\n        )\r\n\r\n        await interaction.response.send_message(\r\n            f\"Successfully bought {shares} shares of {symbol} at ${price:.2f} per share.\\n\"\r\n            f\"Total cost: ${total_cost:.2f}\\n\"\r\n            f\"Remaining balance: ${user['wallet']:,.2f}\",\r\n            ephemeral=True\r\n        )\r\n\r\nclass SellStocksModal(ui.Modal, title=\"Sell Stocks\"):\r\n    def __init__(self, authorid):\r\n        super().__init__()\r\n        self.authorid = authorid\r\n\r\n    symbol = ui.TextInput(label=\"Stock Symbol\", placeholder=\"e.g. AAPL\", min_length=1, max_length=5)\r\n    shares = ui.TextInput(label=\"Number of Shares\", placeholder=\"e.g. 10\")\r\n\r\n    async def on_submit(self, interaction: discord.Interaction):\r\n        if interaction.user.id != self.authorid:\r\n            return await interaction.response.send_message(\"This isn't your trading session!\", ephemeral=True)\r\n\r\n        symbol = self.symbol.value.upper()\r\n        try:\r\n            shares = float(self.shares.value)\r\n            if shares <= 0:\r\n                raise ValueError(\"Shares must be positive\")\r\n        except ValueError:\r\n            return await interaction.response.send_message(\"Please enter a valid number of shares!\", ephemeral=True)\r\n\r\n        c = db[\"trading\"]\r\n        portfolio = c.find_one({\"user_id\": interaction.user.id, \"guild_id\": interaction.guild.id})\r\n\r\n        if not portfolio or symbol not in portfolio[\"positions\"]:\r\n            return await interaction.response.send_message(\"You don't own this stock!\", ephemeral=True)\r\n\r\n        current_position = portfolio[\"positions\"][symbol]\r\n        if current_position[\"shares\"] < shares:\r\n            return await interaction.response.send_message(\r\n                f\"You don't have enough shares! You own {current_position['shares']} shares.\",\r\n                ephemeral=True\r\n            )\r\n\r\n        price = await get_stock_price(symbol)\r\n        if not price:\r\n            return await interaction.response.send_message(\"Invalid stock symbol or API error!\", ephemeral=True)\r\n\r\n        total_value = price * shares\r\n\r\n        new_shares = current_position[\"shares\"] - shares\r\n        if new_shares == 0:\r\n            del portfolio[\"positions\"][symbol]\r\n        else:\r\n            portfolio[\"positions\"][symbol][\"shares\"] = new_shares\r\n\r\n        c.update_one(\r\n            {\"user_id\": interaction.user.id, \"guild_id\": interaction.guild.id},\r\n            {\"$set\": {\"positions\": portfolio[\"positions\"]}}\r\n        )\r\n\r\n        c = db[\"users\"]\r\n        user = c.find_one({\"id\": interaction.user.id, \"guild_id\": interaction.guild.id})\r\n        user[\"wallet\"] += total_value\r\n        c.update_one(\r\n            {\"id\": interaction.user.id, \"guild_id\": interaction.guild.id},\r\n            {\"$set\": {\"wallet\": user[\"wallet\"]}}\r\n        )\r\n\r\n        profit_loss = (price - current_position[\"average_price\"]) * shares\r\n\r\n        await interaction.response.send_message(\r\n            f\"Successfully sold {shares} shares of {symbol} at ${price:.2f} per share.\\n\"\r\n            f\"Total value: ${total_value:.2f}\\n\"\r\n            f\"Profit/Loss: ${profit_loss:.2f}\\n\"\r\n            f\"New balance: ${user['wallet']:,.2f}\",\r\n            ephemeral=True\r\n        )\r\n\r\nasync def get_stock_price(symbol):\r\n    \"\"\"Get current stock price using Alpha Vantage API or mock data\"\"\"\r\n    if DEMO_MODE and symbol in MOCK_PRICES:\r\n        return MOCK_PRICES[symbol]\r\n\r\n    url = f\"https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol={symbol}&apikey={ALPHA_VANTAGE_API_KEY}\"\r\n\r\n    async with aiohttp.ClientSession() as session:\r\n        try:\r\n            async with session.get(url) as response:\r\n                data = await response.json()\r\n                if \"Global Quote\" in data and \"05. price\" in data[\"Global Quote\"]:\r\n                    return float(data[\"Global Quote\"][\"05. price\"])\r\n                return None\r\n        except:\r\n            return None\r\n\r\nasync def start_paper_trading(ctx):\r\n    \"\"\"\r\n    Command to start paper trading session\r\n    Usage: !trade or /trade\r\n    \"\"\"\r\n    c = db[\"users\"]\r\n    user = c.find_one({\"id\": ctx.author.id, \"guild_id\": ctx.guild.id})\r\n\r\n    if not user:\r\n        return await ctx.send(\"get outa here brokie\")\r\n\r\n    embed = discord.Embed(\r\n        title=\"Paper Trading\",\r\n        description=\"Welcome to paper trading! Trade stocks with your existing balance.\\n\"\r\n                   \"Use the buttons below to buy/sell stocks and view your portfolio.\",\r\n        color=0x00ff00\r\n    )\r\n    embed.add_field(\r\n        name=\"Available Balance\",\r\n        value=f\"${user['wallet']:,.2f}\",\r\n        inline=False\r\n    )\r\n    if DEMO_MODE:\r\n        embed.add_field(\r\n            name=\"Available Demo Stocks\",\r\n            value=\"\\n\".join([f\"{symbol}: ${price:.2f}\" for symbol, price in MOCK_PRICES.items()]),\r\n            inline=False\r\n        )\r\n\r\n    view = StockPortfolioView(ctx.author.id)\r\n    await ctx.send(embed=embed, view=view)\r\n"
  },
  {
    "path": "ui/recreate.py",
    "content": "import discord\n\nclass deleteconfirm(discord.ui.View):\n    def __init__(self, user, channel):\n        super().__init__(timeout=None)\n        self.user = user\n        self.channel = channel\n\n    @discord.ui.button(label=\"Confirm\", style=discord.ButtonStyle.red)\n    async def yes(self, interaction: discord.Interaction, button: discord.ui.Button):\n        if interaction.user != self.user:\n            return\n\n        old_channel = self.channel\n\n        await self.channel.delete()\n\n        new_channel = await old_channel.clone()\n\n        await new_channel.edit(position=old_channel.position)\n\n        await new_channel.send(\"Channel has been recreated\")\n\n    @discord.ui.button(label=\"Cancel\", style=discord.ButtonStyle.green)\n    async def no(self, interaction: discord.Interaction, button: discord.ui.Button):\n        await interaction.message.delete()\n"
  },
  {
    "path": "ui/setup.py",
    "content": "import discord\nimport asyncio\n\nfrom utils import DBClient\n\ndb = DBClient.db\n\nclass StartSetupView(discord.ui.View):\n    def __init__(self, server_id) -> None:\n        super().__init__()\n        self.server_id = server_id\n\n    @discord.ui.button(label=\"Start Setup\", style=discord.ButtonStyle.primary)\n    async def start_setup(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:\n        if interaction.user != interaction.guild.owner:\n            await interaction.response.send_message(\"You can't interact with this :D\", ephemeral=True)\n            return\n\n        embed = discord.Embed(\n            title=\"Would you like to set up the ticket system?\",\n            description=\"This will allow people to create tickets for support.\",\n            color=0x2F3136\n        )\n\n        await interaction.response.edit_message(embed=embed, view=TicketSetupView(self.server_id))\n\nclass TicketSetupView(discord.ui.View):\n    def __init__(self, server_id) -> None:\n        super().__init__()\n        self.server_id = server_id\n\n    @discord.ui.button(label=\"Yes\", style=discord.ButtonStyle.primary)\n    async def yes(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:\n        if interaction.user != interaction.guild.owner:\n            await interaction.response.send_message(\"You can't interact with this :D\", ephemeral=True)\n            return\n\n        embed = discord.Embed(\n            title=\"What category should the tickets be created in?\",\n            description=\"Select the category where the tickets should be created.\",\n            color=0x2F3136\n        )\n\n        categories = [discord.SelectOption(label=category.name, value=category.id) for category in interaction.guild.categories]\n\n        await interaction.response.edit_message(embed=embed, view=TicketCategoryView(self.server_id, categories))\n\n    @discord.ui.button(label=\"Skip\", style=discord.ButtonStyle.secondary)\n    async def skip(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:\n        embed = discord.Embed(\n            title=\"Change leveling system settings\",\n            description=\"Would you like to change the leveling system settings for your server?\",\n            color=0x2F3136\n        )\n\n        await interaction.response.edit_message(embed=embed, view=LevelingSetupView(self.server_id))\n\nclass TicketCategorySelect(discord.ui.Select):\n    def __init__(self, server_id, categories) -> None:\n        super().__init__(placeholder=\"Choose a category...\", options=categories)\n        self.server_id = server_id\n\n    async def callback(self, interaction: discord.Interaction) -> None:\n        if interaction.user != interaction.guild.owner:\n            await interaction.response.send_message(\"You can't interact with this :D\", ephemeral=True)\n            return\n\n        category_id = self.values[0]\n        db.guilds.update_one({\"id\": self.server_id}, {\"$set\": {\"tickets_category\": int(category_id)}})\n\n        embed = discord.Embed(\n            title=\"What role should be given access to the tickets and pinged?\",\n            description=\"This can be a role like `Support` or `Staff`. You can mention the role to select it.\",\n            color=0x2F3136\n        )\n\n        await interaction.response.edit_message(embed=embed, view=None)\n\n        while True:\n            try:\n                message = await interaction.client.wait_for(\"message\", check=lambda m: m.author == interaction.user, timeout=30)\n            except asyncio.TimeoutError:\n                await interaction.followup.send(\"You took too long to respond.\", ephemeral=True)\n                return\n\n            try:\n                role_id = int(message.content.replace(\"<@&\", \"\").replace(\">\", \"\"))\n                role = interaction.guild.get_role(role_id)\n\n                if role is None:\n                    await interaction.followup.send(\"You must mention a role.\", ephemeral=True)\n                    continue\n                break\n            except:\n                await interaction.followup.send(\"You must mention a role.\", ephemeral=True)\n\n        await message.delete()\n        db.guilds.update_one({\"id\": self.server_id}, {\"$set\": {\"tickets_support_role\": role_id}})\n\n        embed = discord.Embed(\n            title=\"Change leveling system settings\",\n            description=\"Would you like to change the leveling system settings for your server?\",\n            color=0x2F3136\n        )\n\n        await interaction.message.edit(embed=embed, view=LevelingSetupView(self.server_id))\n\nclass TicketCategoryView(discord.ui.View):\n    def __init__(self, server_id, categories) -> None:\n        super().__init__()\n        self.server_id = server_id\n        self.categories = categories\n\n        self.add_item(TicketCategorySelect(self.server_id, self.categories))\n\nclass TicketSupportRoleSelect(discord.ui.Select):\n    def __init__(self, server_id, roles) -> None:\n        super().__init__(placeholder=\"Choose a role...\", options=roles)\n        self.server_id = server_id\n\n    async def callback(self, interaction: discord.Interaction) -> None:\n        if interaction.user != interaction.guild.owner:\n            await interaction.response.send_message(\"You can't interact with this :D\", ephemeral=True)\n            return\n\n        role_id = self.values[0]\n        db.guilds.update_one({\"id\": self.server_id}, {\"$set\": {\"tickets_support_role\": role_id}})\n\n        embed = discord.Embed(\n            title=\"Change leveling system settings\",\n            description=\"Would you like to change the leveling system settings for your server?\",\n            color=0x2F3136\n        )\n\n        await interaction.response.edit_message(embed=embed, view=LevelingSetupView(self.server_id))\n\nclass TicketSupportRoleView(discord.ui.View):\n    def __init__(self, server_id, roles) -> None:\n        super().__init__()\n        self.server_id = server_id\n\n        self.add_item(TicketSupportRoleSelect(self.server_id, roles))\n\nclass LevelingSetupView(discord.ui.View):\n    def __init__(self, server_id) -> None:\n        super().__init__()\n        self.server_id = server_id\n\n    @discord.ui.button(label=\"Yes\", style=discord.ButtonStyle.primary)\n    async def yes(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:\n        if interaction.user != interaction.guild.owner:\n            await interaction.response.send_message(\"You can't interact with this :D\", ephemeral=True)\n            return\n\n        embed = discord.Embed(\n            title=\"Should levelups be announced?\",\n            description=\"Tell when someone levels up\",\n            color=0x2F3136\n        )\n\n        await interaction.response.edit_message(embed=embed, view=LevelingShouldAnnounceLevelUp(self.server_id))\n\n    @discord.ui.button(label=\"No\", style=discord.ButtonStyle.secondary)\n    async def no(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:\n        db.guilds.update_one({\"id\": self.server_id}, {\"$set\": {\"should_announce_levelup\": False}})\n\n        embed = discord.Embed(\n            title=\"Setup starboard?\",\n            description=\"Would you like to setup the starboard?\",\n            color=0x2F3136\n        )\n\n        await interaction.response.edit_message(embed=embed, view=StarboardSetupView(self.server_id))\n\nclass LevelingShouldAnnounceLevelUp(discord.ui.View):\n    def __init__(self, server_id) -> None:\n        super().__init__()\n        self.server_id = server_id\n\n    @discord.ui.button(label=\"Yes\", style=discord.ButtonStyle.primary)\n    async def yes(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:\n        if interaction.user != interaction.guild.owner:\n            await interaction.response.send_message(\"You can't interact with this :D\", ephemeral=True)\n            return\n\n        db.guilds.update_one({\"id\": self.server_id}, {\"$set\": {\"should_announce_levelup\": True}})\n\n        embed = discord.Embed(\n            title=\"Would you like to set a channel for levelups?\",\n            description=\"Which channel to send levelup messages, will be sent in the channel where the user leveled up if not set. Mention the channel to select it.\",\n            color=0x2F3136\n        )\n\n        channels = [discord.SelectOption(label=channel.name, value=channel.id) for channel in interaction.guild.text_channels]\n\n        await interaction.response.edit_message(embed=embed, view=LevelingChannelSelectView(self.server_id, channels))\n\n    @discord.ui.button(label=\"No\", style=discord.ButtonStyle.secondary)\n    async def no(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:\n        db.guilds.update_one({\"id\": self.server_id}, {\"$set\": {\"should_announce_levelup\": False}})\n\n        embed = discord.Embed(\n            title=\"Setup starboard?\",\n            description=\"Would you like to setup the starboard?\",\n            color=0x2F3136\n        )\n\n        await interaction.response.edit_message(embed=embed, view=StarboardSetupView(self.server_id))\n\nclass LevelingChannelSelectView(discord.ui.View):\n    def __init__(self, server_id, channels) -> None:\n        super().__init__()\n        self.server_id = server_id\n\n    @discord.ui.button(label=\"Yes\", style=discord.ButtonStyle.primary)\n    async def yes(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:\n        if interaction.user != interaction.guild.owner:\n            await interaction.response.send_message(\"You can't interact with this :D\", ephemeral=True)\n            return\n\n        embed = discord.Embed(\n            title=\"Mention the channel for levelups\",\n            description=\"Which channel to send levelup messages, will be sent in the channel where the user leveled up if not set. Mention the channel.\",\n            color=0x2F3136\n        )\n\n        await interaction.response.edit_message(embed=embed, view=None)\n\n        while True:\n            try:\n                message = await interaction.client.wait_for(\"message\", check=lambda m: m.author == interaction.user, timeout=30)\n            except asyncio.TimeoutError:\n                await interaction.followup.send(\"You took too long to respond.\", ephemeral=True)\n                return\n\n            try:\n                channel_id = int(message.content.replace(\"<#\", \"\").replace(\">\", \"\"))\n                channel = interaction.guild.get_channel(channel_id)\n\n                if channel is None:\n                    await interaction.followup.send(\"You must mention a channel.\", ephemeral=True)\n                    continue\n                break\n            except:\n                await interaction.followup.send(\"You must mention a channel.\", ephemeral=True)\n\n        await message.delete()\n        db.guilds.update_one({\"id\": self.server_id}, {\"$set\": {\"level_announce_channel\": channel_id}})\n\n        embed = discord.Embed(\n            title=\"Setup starboard?\",\n            description=\"Would you like to setup the starboard?\",\n            color=0x2F3136\n        )\n\n        await interaction.message.edit(embed=embed, view=StarboardSetupView(self.server_id))\n\n    @discord.ui.button(label=\"No\", style=discord.ButtonStyle.secondary)\n    async def no(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:\n        embed = discord.Embed(\n            title=\"Setup starboard?\",\n            description=\"Would you like to setup the starboard?\",\n            color=0x2F3136\n        )\n\n        await interaction.response.edit_message(embed=embed, view=StarboardSetupView(self.server_id))\n\nclass StarboardSetupView(discord.ui.View):\n    def __init__(self, server_id) -> None:\n        super().__init__()\n        self.server_id = server_id\n\n    @discord.ui.button(label=\"Yes\", style=discord.ButtonStyle.primary)\n    async def yes(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:\n        if interaction.user != interaction.guild.owner:\n            await interaction.response.send_message(\"You can't interact with this :D\", ephemeral=True)\n            return\n\n        db.guilds.update_one({\"id\": self.server_id}, {\"$set\": {\"starboard.enabled\": True}})\n\n        embed = discord.Embed(\n            title=\"Mention the channel for the starboard\",\n            description=\"Send a message containing the channel where the starboard should be created\",\n            color=0x2F3136\n        )\n\n        await interaction.response.edit_message(embed=embed, view=None)\n\n        while True:\n            try:\n                message = await interaction.client.wait_for(\"message\", check=lambda m: m.author == interaction.user, timeout=30)\n            except asyncio.TimeoutError:\n                await interaction.followup.send(\"You took too long to respond.\", ephemeral=True)\n                return\n\n            try:\n                channel_id = int(message.content.replace(\"<#\", \"\").replace(\">\", \"\"))\n                channel = interaction.guild.get_channel(channel_id)\n\n                if channel is None:\n                    await interaction.followup.send(\"You must mention a channel.\", ephemeral=True)\n                    continue\n                break\n            except:\n                await interaction.followup.send(\"You must mention a channel.\", ephemeral=True)\n\n        await message.delete()\n        db.guilds.update_one({\"id\": self.server_id}, {\"$set\": {\"starboard.channel\": channel_id}})\n\n        embed = discord.Embed(\n            title=\"Select the starboard threshold\",\n            description=\"Send a message containing the threshold for the starboard.\",\n            color=0x2F3136\n        )\n\n        await interaction.message.edit(embed=embed, view=None)\n\n        while True:\n            try:\n                message = await interaction.client.wait_for(\"message\", check=lambda m: m.author == interaction.user, timeout=30)\n            except asyncio.TimeoutError:\n                await interaction.followup.send(\"You took too long to respond.\", ephemeral=True)\n                return\n\n            if not message.content.isdigit():\n                await interaction.followup.send(\"You must send a number.\", ephemeral=True)\n                continue\n\n            break\n\n        threshold = int(message.content)\n\n        await message.delete()\n        db.guilds.update_one({\"id\": self.server_id}, {\"$set\": {\"starboard.threshold\": threshold}})\n\n        embed = discord.Embed(\n            title = \"Do you want to set a logging channel?\",\n            description = \"Would you like to set a logging channel for mod/admin actions?\",\n            color = 0x2F3136\n        )\n\n        await interaction.message.edit(embed=embed, view=LoggingSetupView(self.server_id))\n\n    @discord.ui.button(label=\"No\", style=discord.ButtonStyle.secondary)\n    async def no(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:\n        db.guilds.update_one({\"id\": self.server_id}, {\"$set\": {\"starboard.enabled\": False}})\n\n        embed = discord.Embed(\n            title = \"Do you want to set a logging channel?\",\n            description = \"Would you like to set a logging channel for mod/admin actions?\",\n            color = 0x2F3136\n        )\n\n        await interaction.response.edit_message(embed=embed, view=LoggingSetupView(self.server_id))\n\nclass LoggingSetupView(discord.ui.View):\n    def __init__(self, server_id) -> None:\n        super().__init__()\n        self.server_id = server_id\n\n    @discord.ui.button(label=\"Yes\", style=discord.ButtonStyle.primary)\n    async def yes(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:\n        if interaction.user != interaction.guild.owner:\n            await interaction.response.send_message(\"You can't interact with this :D\", ephemeral=True)\n            return\n\n        embed = discord.Embed(\n            title=\"Mention the logging channel\",\n            description=\"Send a message containing the channel where logs should be sent\",\n            color=0x2F3136\n        )\n\n        await interaction.response.edit_message(embed=embed, view=None)\n\n        while True:\n            try:\n                message = await interaction.client.wait_for(\"message\", check=lambda m: m.author == interaction.user, timeout=30)\n            except asyncio.TimeoutError:\n                await interaction.followup.send(\"You took too long to respond.\", ephemeral=True)\n                return\n\n            try:\n                channel_id = int(message.content.replace(\"<#\", \"\").replace(\">\", \"\"))\n                channel = interaction.guild.get_channel(channel_id)\n\n                if channel is None:\n                    await interaction.followup.send(\"You must mention a channel.\", ephemeral=True)\n                    continue\n                break\n            except:\n                await interaction.followup.send(\"You must mention a channel.\", ephemeral=True)\n\n        await message.delete()\n        db.guilds.update_one({\"id\": self.server_id}, {\"$set\": {\"log_channel\": channel_id}})\n\n        embed = discord.Embed(\n            title=\"Setup complete!\",\n            description=\"We recommend you move the role 'Potato Bot' high up on the role list to make sure all features works properly\",\n            color=0x2F3136\n        )\n\n        await interaction.followup.send(embed=embed)\n\n    @discord.ui.button(label=\"No\", style=discord.ButtonStyle.secondary)\n    async def no(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:\n        embed = discord.Embed(\n            title=\"Setup complete!\",\n            description=\"We recommend you move the role 'Potato Bot' high up on the role list to make sure all features works properly\",\n            color=0x2F3136\n        )\n\n        await interaction.response.edit_message(embed=embed)\n"
  },
  {
    "path": "ui/starboard.py",
    "content": "import discord\n\nclass JumpToMessageButton(discord.ui.Button):\n    def __init__(self, message: discord.message) -> None:\n        super().__init__(\n            style=discord.ButtonStyle.link,\n            label=\"Jump to message\",\n            url=f\"https://discord.com/channels/{message.guild.id}/{message.channel.id}/{message.id}\"\n        )\n\n    async def callback(self, interaction: discord.Interaction) -> None:\n        pass\n\nclass JumpToMessageView(discord.ui.View):\n    def __init__(self, message: discord.message) -> None:\n        super().__init__()\n        self.add_item(JumpToMessageButton(message))\n"
  },
  {
    "path": "ui/ticket.py",
    "content": "import discord\nimport asyncio\nimport os\nfrom datetime import datetime\n\nfrom discord.ui import Button, button, View\n\nfrom utils import ServerLogger, DBClient\n\ndb = DBClient.db\n\nclass CreateButton(View):\n    def __init__(self):\n        super().__init__(timeout=None)\n\n    @button(label=\"Create Ticket\",style=discord.ButtonStyle.blurple, emoji=\"🎫\",custom_id=\"ticketopen\")\n    async def ticket(self, interaction: discord.Interaction, button: Button):\n        c = db[\"guilds\"]\n\n        data = c.find_one({\"id\": interaction.guild.id})\n\n        if not data:\n            await interaction.channel.send(\"**Tickets info not found! If you are an admin use `/setting` for more info**\")\n            return\n\n        if not data[\"tickets_category\"] or not data[\"tickets_support_role\"]:\n            await interaction.channel.send(\"**Tickets info not found! If you are an admin use `/setting` for more info**\")\n            return\n\n\n        await interaction.response.defer(ephemeral=True)\n        category: discord.CategoryChannel = discord.utils.get(interaction.guild.categories, id=data[\"tickets_category\"])\n        for ch in category.text_channels:\n            if ch.topic == f\"{interaction.user.id} DO NOT CHANGE THE TOPIC OF THIS CHANNEL!\":\n                await interaction.followup.send(\"You already have a ticket in {0}\".format(ch.mention), ephemeral=True)\n                return\n\n        r1 : discord.Role = interaction.guild.get_role(data[\"tickets_support_role\"])\n        overwrites = {\n            interaction.guild.default_role: discord.PermissionOverwrite(read_messages=False),\n            r1: discord.PermissionOverwrite(read_messages=True, send_messages=True, manage_messages=True),\n            interaction.user: discord.PermissionOverwrite(read_messages = True, send_messages=True),\n            interaction.guild.me: discord.PermissionOverwrite(read_messages=True, send_messages=True)\n        }\n        channel = await category.create_text_channel(\n            name=str(interaction.user),\n            topic=f\"{interaction.user.id} DO NOT CHANGE THE TOPIC OF THIS CHANNEL!\",\n            overwrites=overwrites\n        )\n        await channel.send(\"{0} a ticket has been created!\".format(r1.mention))\n        await channel.send(\n            embed=discord.Embed(\n                title=f\"Ticket Created!\",\n                description=\"Don't ping a staff member, they will be here soon.\",\n                color = discord.Color.green()\n            ),\n            view = CloseButton()\n        )\n        await channel.send(\"Please describe your issue\")\n\n        await interaction.followup.send(\n            embed= discord.Embed(\n                description = \"Created your ticket in {0}\".format(channel.mention),\n                color = discord.Color.blurple()\n            ),\n            ephemeral=True\n        )\n\n        await ServerLogger.send_log(\n            title=\"Ticket Created\",\n            description=\"Created by {0}\".format(interaction.user.mention),\n            color=discord.Color.green(),\n            guild=interaction.guild,\n            channel=interaction.channel\n        )\n\n\nclass CloseButton(View):\n    def __init__(self):\n        super().__init__(timeout=None)\n\n    @button(label=\"Close the ticket\",style=discord.ButtonStyle.red,custom_id=\"closeticket\",emoji=\"🔒\")\n    async def close(self, interaction: discord.Interaction, button: Button):\n        c = db[\"guilds\"]\n\n        data = c.find_one({\"id\": interaction.guild.id})\n\n        if not data:\n            await interaction.channel.send(\"**Tickets info not found! If you are an admin use `/setting` for more info**\")\n            return\n\n        if not data[\"tickets_category\"] or not data[\"tickets_support_role\"]:\n            await interaction.channel.send(\"**Tickets info not found! If you are an admin use `/setting` for more info**\")\n            return\n\n        await interaction.response.defer(ephemeral=True)\n\n        await interaction.channel.send(\"Closing this ticket in 3 seconds!\")\n\n        await asyncio.sleep(3)\n\n        category: discord.CategoryChannel = discord.utils.get(interaction.guild.categories, id = data[\"tickets_category\"])\n        r1 : discord.Role = interaction.guild.get_role(data[\"tickets_support_role\"])\n        overwrites = {\n            interaction.guild.default_role: discord.PermissionOverwrite(read_messages=False),\n            r1: discord.PermissionOverwrite(read_messages=True, send_messages=True, manage_messages=True),\n            interaction.guild.me: discord.PermissionOverwrite(read_messages=True, send_messages=True)\n        }\n        await interaction.channel.edit(category=category, overwrites=overwrites)\n        await interaction.channel.send(\n            embed= discord.Embed(\n                description=\"Ticket Closed!\",\n                color = discord.Color.red()\n            ),\n            view = TrashButton()\n        )\n\n        member = interaction.guild.get_member(int(interaction.channel.topic.split(\" \")[0]))\n\n        os.makedirs(\"logs\", exist_ok=True)\n        log_file = f\"logs/{interaction.channel.id}.log\"\n        with open(log_file, \"w\", encoding=\"UTF-8\") as f:\n            f.write(\n                f'Ticket log from: #{interaction.channel} ({interaction.channel.id}) in the guild \"{interaction.guild}\" ({interaction.guild.id}) at {datetime.now().strftime(\"%d.%m.%Y %H:%M:%S\")}\\n'\n            )\n            async for message in interaction.channel.history(\n                limit=None, oldest_first=True\n            ):\n                attachments = []\n                for attachment in message.attachments:\n                    attachments.append(attachment.url)\n                attachments_text = (\n                    f\"[Attached File{'s' if len(attachments) >= 2 else ''}: {', '.join(attachments)}]\"\n                    if len(attachments) >= 1\n                    else \"\"\n                )\n                f.write(\n                    f\"{message.created_at.strftime('%d.%m.%Y %H:%M:%S')} {message.author} {message.id}: {message.clean_content} {attachments_text}\\n\"\n                )\n\n        guilds = DBClient.client.potatobot[\"guilds\"]\n        data = guilds.find_one({\"id\": interaction.guild.id})\n\n        if data[\"log_channel\"]:\n            log_channel = interaction.guild.get_channel(data[\"log_channel\"])\n\n            if log_channel:\n                try:\n                    await log_channel.send(file=discord.File(log_file))\n\n                    embed = discord.Embed(\n                        title=\"Ticket Closed\",\n                        description=f\"Ticket {interaction.channel.name} closed by {interaction.user.mention}\",\n                        color=discord.Color.orange()\n                    )\n\n                    await log_channel.send(embed=embed)\n                except:\n                    pass\n\n        try:\n            with open (log_file, \"rb\") as f:\n                await member.send(f\"Your ticket in {interaction.guild} has been closed. Transcript: \", file=discord.File(f))\n        except Exception as e:\n            await interaction.channel.send(\n                f\"Couldn't send the log file to {member.mention}, \" + str(e)\n            )\n\n        os.remove(log_file)\n\n\nclass TrashButton(View):\n    def __init__(self):\n        super().__init__(timeout=None)\n\n    @button(label=\"Delete the ticket\", style=discord.ButtonStyle.red, emoji=\"🚮\", custom_id=\"trash\")\n    async def trash(self, interaction: discord.Interaction, button: Button):\n        await interaction.response.defer()\n        await interaction.channel.send(\"Deleting the ticket in 3 seconds\")\n        await asyncio.sleep(3)\n\n        await interaction.channel.delete()\n        await ServerLogger.send_log(\n            title=\"Ticket Deleted\",\n            description=f\"Deleted by {interaction.user.mention}, ticket: {interaction.channel.name}\",\n            color=discord.Color.red(),\n            guild=interaction.guild,\n            channel=interaction.channel\n        )\n"
  },
  {
    "path": "ui/translate.py",
    "content": "import discord\nimport aiohttp\nfrom discord import ui\n\nfrom deep_translator import GoogleTranslator\n\nclass TranslateModal(ui.Modal, title = \"Translate\"):\n    def __init__(self, message: discord.Message):\n        super().__init__(timeout = 60)\n        self.message = message\n\n    language = ui.TextInput(label = \"Language\", placeholder = \"Enter the language to translate this message to\", style=discord.TextStyle.short, min_length = 1, max_length = 50)\n\n    async def on_submit(self, interaction: discord.Interaction) -> None:\n        try:\n            translated = GoogleTranslator(source='auto', target=self.language.value.lower()).translate(self.message.content)\n\n            embed = discord.Embed(title = \"Translation\", description = translated, color = discord.Color.blurple())\n            embed.set_footer(text = f\"Original: \\\"{self.message.content}\\\"\")\n\n            await interaction.response.send_message(embed = embed, ephemeral = True)\n        except:\n            await interaction.response.send_message(content = \"Failed to translate message\", ephemeral = True)\n"
  },
  {
    "path": "utils/CONSTANTS.py",
    "content": "# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon\n\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\n\nfrom typing import Final\n\ndef guild_data_template(guild_id):\n    return {\n        \"id\": guild_id,\n        \"level_roles\": {},\n        \"daily_cash\": 50,\n        \"tickets_category\": 0,\n        \"tickets_support_role\": 0,\n        \"log_channel\": 0,\n        \"ai_access\": False,\n        \"should_announce_levelup\": False,\n        \"groq_api_key\": \"NONE\",\n        \"level_announce_channel\": 0,\n        \"jail_role\": 0,\n        \"jail_channel\": 0,\n        \"default_role\": 0,\n        \"lockdown\": False,\n        \"oldperms\": {},\n        \"fakeperms\": {},\n        \"authorized_bots\": [],\n        \"disabled_commands\": [],\n        \"starboard\": {\n            \"channel\": 0,\n            \"threshold\": 5,\n            \"enabled\": False\n        },\n        \"security\": {\n            \"antinuke\": {\n                \"anti_danger_perms\": False,\n                \"anti_massban\": False,\n                \"anti_masskick\": False,\n                \"anti_massdelete\": False,\n                \"anti_massping\": False,\n                \"anti_webhook_spam\": False,\n                \"anti_unauthorized_bot\": False,\n            }\n        }\n    }\n\ndef user_data_template(user_id, guild_id):\n    return {\n        \"id\": user_id,\n        \"guild_id\": guild_id,\n        \"wallet\": 0,\n        \"xp\": 0,\n        \"level\": 0,\n        \"last_daily\": 0,\n        \"last_robbed_at\": 0,\n        \"jailed\": False,\n        \"farm\": {\n            \"saplings\": 0,\n            \"crops\": 0,\n            \"harvestable\": 0,\n            \"ready_in\": 0\n        },\n        \"warnings\": [],\n        \"whitelisted\": False,\n        \"trusted\": False\n    }\n\ndef user_global_data_template(user_id):\n    return {\n        \"id\": user_id,\n        \"blacklisted\": False,\n        \"blacklist_reason\": \"\",\n        \"ai_ignore\": False,\n        \"ai_ignore_reason\": \"\",\n        \"inspect\": {\n            \"total_commands\": 0,\n            \"times_flagged\": 0,\n            \"nsfw_requests\": 0,\n            \"ai_requests\": 0,\n        },\n        \"strikes\": {}\n    }\n\nLEVELS_AND_XP: Final = {  # credit's for this goes to the mee6 developers as we use the same xp values as them\n    0: 0,\n    1: 100,\n    2: 255,\n    3: 475,\n    4: 770,\n    5: 1_150,\n    6: 1_625,\n    7: 2_205,\n    8: 2_900,\n    9: 3_720,\n    10: 4_675,\n    11: 5_775,\n    12: 7_030,\n    13: 8_450,\n    14: 10_045,\n    15: 11_825,\n    16: 13_800,\n    17: 15_980,\n    18: 18_375,\n    19: 20_995,\n    20: 23_850,\n    21: 26_950,\n    22: 30_305,\n    23: 33_925,\n    24: 37_820,\n    25: 42_000,\n    26: 46_475,\n    27: 51_255,\n    28: 56_350,\n    29: 61_770,\n    30: 67_525,\n    31: 73_625,\n    32: 80_080,\n    33: 86_900,\n    34: 94_095,\n    35: 101_675,\n    36: 109_650,\n    37: 118_030,\n    38: 126_825,\n    39: 136_045,\n    40: 145_700,\n    41: 155_800,\n    42: 166_355,\n    43: 177_375,\n    44: 188_870,\n    45: 200_850,\n    46: 213_325,\n    47: 226_305,\n    48: 239_800,\n    49: 253_820,\n    50: 268_375,\n    51: 283_475,\n    52: 299_130,\n    53: 315_350,\n    54: 332_145,\n    55: 349_525,\n    56: 367_500,\n    57: 386_080,\n    58: 405_275,\n    59: 425_095,\n    60: 445_550,\n    61: 466_650,\n    62: 488_405,\n    63: 510_825,\n    64: 533_920,\n    65: 557_700,\n    66: 582_175,\n    67: 607_355,\n    68: 633_250,\n    69: 659_870,\n    70: 687_225,\n    71: 715_325,\n    72: 744_180,\n    73: 773_800,\n    74: 804_195,\n    75: 835_375,\n    76: 867_350,\n    77: 900_130,\n    78: 933_725,\n    79: 968_145,\n    80: 1_003_400,\n    81: 1_039_500,\n    82: 1_076_455,\n    83: 1_114_275,\n    84: 1_152_970,\n    85: 1_192_550,\n    86: 1_233_025,\n    87: 1_274_405,\n    88: 1_316_700,\n    89: 1_359_920,\n    90: 1_404_075,\n    91: 1_449_175,\n    92: 1_495_230,\n    93: 1_542_250,\n    94: 1_590_245,\n    95: 1_639_225,\n    96: 1_689_200,\n    97: 1_740_180,\n    98: 1_792_175,\n    99: 1_845_195,\n    100: 1_899_250,\n    101: 1_954_350,\n    102: 2_010_505,\n    103: 2_067_725,\n    104: 2_126_020,\n    105: 2_185_400,\n    106: 2_245_875,\n    107: 2_307_455,\n    108: 2_370_150,\n    109: 2_433_970,\n    110: 2_498_925,\n    111: 2_565_025,\n    112: 2_632_280,\n    113: 2_700_700,\n    114: 2_770_295,\n    115: 2_841_075,\n    116: 2_913_050,\n    117: 2_986_230,\n    118: 3_060_625,\n    119: 3_136_245,\n    120: 3_213_100,\n    121: 3_291_200,\n    122: 3_370_555,\n    123: 3_451_175,\n    124: 3_533_070,\n    125: 3_616_250,\n    126: 3_700_725,\n    127: 3_786_505,\n    128: 3_873_600,\n    129: 3_962_020,\n    130: 4_051_775,\n    131: 4_142_875,\n    132: 4_235_330,\n    133: 4_329_150,\n    134: 4_424_345,\n    135: 4_520_925,\n    136: 4_618_900,\n    137: 4_718_280,\n    138: 4_819_075,\n    139: 4_921_295,\n    140: 5_024_950,\n    141: 5_130_050,\n    142: 5_236_605,\n    143: 5_344_625,\n    144: 5_454_120,\n    145: 5_565_100,\n    146: 5_677_575,\n    147: 5_791_555,\n    148: 5_907_050,\n    149: 6_024_070,\n    150: 6_142_625,\n}\nMAX_LEVEL: Final = len(LEVELS_AND_XP) - 1\nMAX_XP: Final = LEVELS_AND_XP[MAX_LEVEL]\n"
  },
  {
    "path": "utils/CachedDB.py",
    "content": "# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon\n\nimport pymongo\nimport redis\nimport json\nimport logging\nimport time\nimport os\nfrom bson import ObjectId\n\nlogger = logging.getLogger(\"discord_bot\")\n\nmongo_client_pool = pymongo.MongoClient(os.getenv(\"MONGODB_URL\"), maxPoolSize=50)\nmongo_db = mongo_client_pool.potatobot\n\nredis_pool = redis.ConnectionPool.from_url(os.getenv(\"REDIS_URL\"), max_connections=100)\nredis_client = redis.Redis(connection_pool=redis_pool)\n\nprint(\"Connected to MongoDB at: \", mongo_client_pool.host)\nprint(\"Connected to Redis at: \", redis_client.connection_pool.connection_kwargs[\"host\"])\n\nclass JSONEncoder(json.JSONEncoder):\n    def default(self, obj):\n        if isinstance(obj, ObjectId):\n            return str(obj)\n        elif isinstance(obj, bytes):\n            return None  # Skip binary data\n        return json.JSONEncoder.default(self, obj)\n\nasync def find_one(collection, query, ex=30):\n    start_time = time.time() * 1000\n\n    cache_key = f\"{collection.name}:{json.dumps(query, cls=JSONEncoder)}\"\n    cached_result = redis_client.get(cache_key)\n\n    if cached_result:\n        logger.info(f\"Cache hit for query {cache_key} - took {time.time() * 1000 - start_time:.2f}ms\")\n        return json.loads(cached_result)\n    else:\n        result = collection.find_one(query)\n\n        if result:\n            result = json.loads(JSONEncoder().encode(result))\n            redis_client.set(cache_key, json.dumps(result), ex=ex)\n\n        logger.info(f\"Cache miss for query {cache_key} - took {time.time() * 1000 - start_time:.2f}ms\")\n        return result\n\nasync def update_one(collection, filter, update, upsert=False):\n    result = collection.update_one(filter, update, upsert=upsert)\n\n    cache_key = f\"{collection.name}:{json.dumps(filter, cls=JSONEncoder)}\"\n    redis_client.delete(cache_key)\n\n    return result\n\ndef sync_find_one(collection, query, ex=30):\n    start_time = time.time() * 1000\n\n    cache_key = f\"{collection.name}:{json.dumps(query, cls=JSONEncoder)}\"\n    cached_result = redis_client.get(cache_key)\n\n    if cached_result:\n        logger.info(f\"Cache hit for query {cache_key} - took {time.time() * 1000 - start_time:.2f}ms\")\n        return json.loads(cached_result)\n    else:\n        result = collection.find_one(query)\n\n        if result:\n            result = json.loads(JSONEncoder().encode(result))\n            redis_client.set(cache_key, json.dumps(result), ex=ex)\n\n        logger.info(f\"Cache miss for query {cache_key} - took {time.time() * 1000 - start_time:.2f}ms\")\n        return result\n\ndef sync_update_one(collection, filter, update, upsert=False):\n    result = collection.update_one(filter, update, upsert=upsert)\n\n    cache_key = f\"{collection.name}:{json.dumps(filter, cls=JSONEncoder)}\"\n    redis_client.delete(cache_key)\n\n    return result\n"
  },
  {
    "path": "utils/Checks.py",
    "content": "# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon\n\nimport discord\n\nfrom utils import DBClient, CONSTANTS, CachedDB, Errors\n\nfrom discord.ext import commands\nfrom discord.ext.commands import Context\n\ndb = DBClient.db\n\nasync def is_not_blacklisted(context: Context):\n    users_global = db[\"users_global\"]\n    user = await CachedDB.find_one(users_global, {\"id\": context.author.id})\n\n    if user is None:\n        user = CONSTANTS.user_global_data_template(context.author.id)\n        users_global.insert_one(user)\n\n    if user[\"blacklisted\"]:\n        raise Errors.UserBlacklisted(\"You are blacklisted from using the bot, reason: **\" + (user[\"blacklist_reason\"] if user[\"blacklist_reason\"] else \"Not Specified\") + \"**\")\n    else:\n        return True\n\n# TODO: Add fakeperms\ndef has_perm(**perms):\n    def predicate(context: commands.Context):\n        author_permissions = context.channel.permissions_for(context.author)\n\n        for perm, value in perms.items():\n            if getattr(author_permissions, perm, None) != value:\n                raise discord.ext.commands.MissingPermissions([perm])\n        return True\n\n    return commands.check(predicate)\n\nasync def command_not_disabled(context: Context):\n    if context.guild:\n        guild = await CachedDB.find_one(db[\"guilds\"], {\"id\": context.guild.id})\n\n        if guild is None:\n            guild = CONSTANTS.guild_data_template(context.guild.id)\n            db[\"guilds\"].insert_one(guild)\n\n        if context.command.qualified_name in guild[\"disabled_commands\"] or context.command.qualified_name.split(\" \")[0] in guild[\"disabled_commands\"]:\n            raise Errors.CommandDisabled(\"This command is disabled in this server.\")\n        else:\n            return True\n    else:\n        return True\n"
  },
  {
    "path": "utils/DBClient.py",
    "content": "# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon\n\nimport pymongo\nimport os\n\nclient = pymongo.MongoClient(os.getenv(\"MONGODB_URL\"))\ndb = client.potatobot\n"
  },
  {
    "path": "utils/ErrorLogger.py",
    "content": "# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon\n\nimport os\nimport sys\nimport json\n\nimport discord\nfrom discord import Webhook\nimport aiohttp\nimport traceback\n\nif not os.path.isfile(f\"./config.json\"):\n    sys.exit(\"'config.json' not found! Please add it and try again.\")\nelse:\n    with open(f\"./config.json\") as file:\n        config = json.load(file)\n\ndef apply_context_errors(embed, context, ignore_message=False):\n    embed.add_field(\n        name=\"Author\",\n        value=f\"{context.author.mention}\",\n        inline=True\n    )\n\n    if context.guild:\n        embed.add_field(\n            name=\"Guild\",\n            value=f\"`{context.guild.name}` (`{context.guild.id}`)\",\n            inline=True\n        )\n\n    if context.command:\n        embed.add_field(\n            name=\"Command\",\n            value=f\"`{context.command.name}`\",\n            inline=True\n        )\n\n    if context.message.content != \"\" and not ignore_message:\n        embed.add_field(\n            name=\"Message\",\n            value=f\"```{context.message.content}```\",\n            inline=True\n        )\n\n    if context.interaction:\n        options = context.interaction.data[\"options\"]\n        options = json.dumps(options, indent=2)\n\n        embed.add_field(\n            name=\"Interaction Options\",\n            value=f\"```{options}```\",\n            inline=True\n        )\n\nasync def command_error(error, context):\n    async with aiohttp.ClientSession() as session:\n        command_error_webhook = Webhook.from_url(config[\"command_error_webhook\"], session=session)\n\n        embed = discord.Embed(\n            title=\"An error occurred!\",\n            description=f\"```{error}```\",\n            color=discord.Color.red()\n        )\n\n        apply_context_errors(embed, context)\n\n        await command_error_webhook.send(embed=embed, username = \"PotatoBot - Error Logger\")\n\nasync def error(self, event_method, *args, **kwargs):\n    async with aiohttp.ClientSession() as session:\n        error_webhook = Webhook.from_url(config[\"error_webhooks\"], session=session)\n\n        embed = discord.Embed(\n            title=\"An error occurred!\",\n            description=f\"```{traceback.format_exc().replace('```', '``')}```\",\n            color=discord.Color.red()\n        )\n\n        embed.add_field(\n            name=\"Event Method\",\n            value=f\"`{event_method}`\",\n            inline=False\n        )\n\n        if args:\n            if isinstance(args[0], discord.ext.commands.Context):\n                apply_context_errors(embed, args[0], ignore_message=True)\n            else:\n                embed.add_field(\n                    name=\"Args\",\n                    value=f\"```{args}```\",\n                    inline=False\n                )\n\n        embed.add_field(\n            name=\"Kwargs\",\n            value=f\"```{kwargs}```\",\n            inline=False\n        )\n\n        await error_webhook.send(embed=embed, username=\"PotatoBot - Error Logger\")\n"
  },
  {
    "path": "utils/Errors.py",
    "content": "from discord.ext.commands import CommandError\n\nclass CommandDisabled(CommandError):\n    pass\n\nclass UserBlacklisted(CommandError):\n    pass\n"
  },
  {
    "path": "utils/ServerLogger.py",
    "content": "# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon\n\nimport discord\n\nfrom utils import DBClient\nclient = DBClient.client\ndb = client.potatobot\n\nasync def send_log(title: str, guild: discord.Guild, description: str, color: discord.Color, channel: discord.TextChannel) -> None:\n    c = db[\"guilds\"]\n\n    g = c.find_one({\"id\": guild.id})\n\n    if not g:\n        await channel.send(\"**Log channel not found! If you are an admin use `/setting log_channel #channel`**\")\n        return\n\n    if not g[\"log_channel\"]:\n        await channel.send(\"**Log channel not found! If you are an admin use `/setting log_channel #channel`**\")\n        return\n\n    log_channel = g[\"log_channel\"]\n    log_channel = guild.get_channel(log_channel)\n\n    embed = discord.Embed(\n        title=title,\n        description=description,\n        color=color\n    )\n    await log_channel.send(embed=embed)\n"
  }
]