Full Code of Cyteon/potatobot for AI

main dbf734e910b1 cached
43 files
464.5 KB
103.8k tokens
497 symbols
1 requests
Download .txt
Showing preview only (483K chars total). Download the full file or copy to clipboard to get everything.
Repository: Cyteon/potatobot
Branch: main
Commit: dbf734e910b1
Files: 43
Total size: 464.5 KB

Directory structure:
gitextract_qm_y2xv1/

├── .gitignore
├── Dockerfile
├── LICENSE
├── README.md
├── bot.py
├── cogs/
│   ├── ai.py
│   ├── api.py
│   ├── code.py
│   ├── economy.py
│   ├── fun.py
│   ├── general.py
│   ├── github.py
│   ├── giveaway.py
│   ├── level.py
│   ├── music.py
│   ├── owner.py
│   ├── reactionroles.py
│   ├── security.py
│   ├── server.py
│   ├── staff.py
│   ├── starboard.py
│   ├── stats.py
│   ├── ticket.py
│   └── utility.py
├── config.example.json
├── main.py
├── requirements.txt
├── ui/
│   ├── code.py
│   ├── farm.py
│   ├── gambling.py
│   ├── papertrading.py
│   ├── recreate.py
│   ├── setup.py
│   ├── starboard.py
│   ├── ticket.py
│   └── translate.py
└── utils/
    ├── CONSTANTS.py
    ├── CachedDB.py
    ├── Checks.py
    ├── DBClient.py
    ├── ErrorLogger.py
    ├── Errors.py
    └── ServerLogger.py

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
#  Usually these files are written by a python script from a template
#  before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
#   For a library or package, you might want to ignore these files since the code is
#   intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
#   According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
#   However, in case of collaboration, if having platform-specific dependencies or dependencies
#   having no cross-platform support, pipenv may install dependencies that don't work, or not
#   install all needed dependencies.
#Pipfile.lock

# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/

# PyCharm IDEA
.idea/*

# SQLITE database
*.db

# Log file
discord.log

graphs/
logs/
ssl/
pickle/

.pem
.key
config.json

*.out


================================================
FILE: Dockerfile
================================================
# Use an official Python runtime as a parent image
FROM python:3.9-slim-buster

# Set the working directory in the container to /app
WORKDIR /app

# Add the current directory contents into the container at /app
ADD . /app

# Install any needed packages specified in requirements.txt
RUN pip install --no-cache-dir -r requirements.txt

# Make port 443 available to the world outside this container
EXPOSE 443

# Run app.py when the container launches
CMD ["python", "main.py"]


================================================
FILE: LICENSE
================================================
                    GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU General Public License is a free, copyleft license for
software and other kinds of works.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.  We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors.  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights.  Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received.  You must make sure that they, too, receive
or can get the source code.  And you must show them these terms so they
know their rights.

  Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.

  For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software.  For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.

  Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so.  This is fundamentally incompatible with the aim of
protecting users' freedom to change the software.  The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable.  Therefore, we
have designed this version of the GPL to prohibit the practice for those
products.  If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.

  Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary.  To prevent this, the GPL assures that
patents cannot be used to render the program non-free.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Use with the GNU Affero General Public License.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:

    <program>  Copyright (C) <year>  <name of author>
    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.

  The GNU General Public License does not permit incorporating your program
into proprietary programs.  If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library.  If this is what you want to do, use the GNU Lesser General
Public License instead of this License.  But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.


================================================
FILE: README.md
================================================
# PotatoBot
> The best AIO bot on Discord.

top.gg: https://top.gg/bot/1226487228914602005 \
Invite: https://discord.com/oauth2/authorize?client_id=1226487228914602005


## Run Locally

1. Clone the project:

```bash
  git clone https://github.com/Cyteon/potatobot
```

2. Go to the project directory:

```bash
  cd potatobot
```

3. Install the required Python dependencies:

```bash
  pip install -r requirements.txt
```

4. Rename `.env.example` to `.env`, and populate the required values.
5. Rename `config.example.json` to `config.json` and populate the required values.

6. Run the bot:

```bash
  python main.py
```

7. Profit.


================================================
FILE: bot.py
================================================
# pylint: disable-all

# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon

import json
import logging
import os
import platform
import random
import sys
import time
import aiohttp

from pickledb import PickleDB
import pymongo

import discord
from discord import Webhook
from discord.ext import commands, tasks

from dotenv import load_dotenv
load_dotenv()

from utils import ErrorLogger, Errors

if not os.path.isfile(f"{os.path.realpath(os.path.dirname(__file__))}/config.json"):
    sys.exit("'config.json' not found! Please add it and try again.")
else:
    with open(f"{os.path.realpath(os.path.dirname(__file__))}/config.json") as file:
        config = json.load(file)

intents = discord.Intents.default()
intents.message_content = True
intents.members = True

client = pymongo.MongoClient(os.getenv("MONGODB_URL"))
db = client.potatobot

os.makedirs("pickle", exist_ok=True)
prefixDB = PickleDB("pickle/prefix.db")
statsDB = PickleDB("pickle/stats.db")

cant_react_in = []

class LoggingFormatter(logging.Formatter):
    black = "\x1b[30m"
    red = "\x1b[31m"
    green = "\x1b[32m"
    yellow = "\x1b[33m"
    blue = "\x1b[34m"
    gray = "\x1b[38m"
    reset = "\x1b[0m"
    bold = "\x1b[1m"

    COLORS = {
        logging.DEBUG: gray + bold,
        logging.INFO: blue + bold,
        logging.WARNING: yellow + bold,
        logging.ERROR: red,
        logging.CRITICAL: red + bold,
    }

    def format(self, record):
        log_color = self.COLORS[record.levelno]
        format = "(black){asctime}(reset) (levelcolor){levelname:<8}(reset) \x1b[32m{name}(reset) {message}"
        format = format.replace("(black)", self.black + self.bold)
        format = format.replace("(reset)", self.reset)
        format = format.replace("(levelcolor)", log_color)
        formatter = logging.Formatter(format, "%Y-%m-%d %H:%M:%S", style="{")
        return formatter.format(record)

logger = logging.getLogger("discord_bot")
logger.setLevel(logging.INFO)

console_handler = logging.StreamHandler()
console_handler.setFormatter(LoggingFormatter())
file_handler = logging.FileHandler(filename="discord.log", encoding="utf-8", mode="w")
file_handler_formatter = logging.Formatter(
    "[{asctime}] [{levelname:<8}] {name}: {message}", "%Y-%m-%d %H:%M:%S", style="{"
)
file_handler.setFormatter(file_handler_formatter)

logger.addHandler(console_handler)
logger.addHandler(file_handler)

class DiscordBot(commands.AutoShardedBot):
    def __init__(self) -> None:
        super().__init__(
            command_prefix=self.get_prefix,
            intents=intents,
            help_command=None,
            owner_ids=set([int(os.getenv("OWNER_ID"))]),
        )
        self.logger = logger
        self.config = config
        self.version = "2.1.8"
        self.start_time = time.time()
        self.prefixDB = prefixDB
        self.statsDB = statsDB

    async def get_prefix(self, message):
        if message.guild:
            guild_id = str(message.guild.id)
            if prefixDB.get(guild_id):
                return prefixDB.get(guild_id)
            else:
                return config["prefix"]
        else:
            return config["prefix"]

    async def load_cogs(self) -> None:
        for file in os.listdir(f"{os.path.realpath(os.path.dirname(__file__))}/cogs"):
            if file.endswith(".py"):
                extension = file[:-3]
                try:
                    await self.load_extension(f"cogs.{extension}")
                    self.logger.info(f"Loaded extension '{extension}'")
                except Exception as e:
                    exception = f"{type(e).__name__}: {e}"
                    self.logger.error(
                        f"Failed to load extension {extension}\n{exception}"
                    )

    @tasks.loop(minutes=1.0)
    async def status_task(self) -> None:
        statuses = ["youtube", "netflix"]
        await self.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=random.choice(statuses)))

    @status_task.before_loop
    async def before_status_task(self) -> None:
        await self.wait_until_ready()


    async def setup_hook(self) -> None:
        self.logger.info(f"Logged in as {self.user.name}")
        self.logger.info(f"discord.py API version: {discord.__version__}")
        self.logger.info(f"Python version: {platform.python_version()}")
        self.logger.info(
            f"Running on: {platform.system()} {platform.release()} ({os.name})"
        )

        self.logger.info("-------------------")

        self.logger.info(f"Connection to db successful: {client.address}")

        self.logger.info("-------------------")

        await self.load_cogs()

        self.logger.info("-------------------")

        self.logger.info(f"Command count (slash+chat): {len([x for x in self.walk_commands() if isinstance(x, commands.HybridCommand)])}")
        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)])}")
        self.logger.info(f"Total command count: {len([x for x in self.walk_commands()])}")

        self.logger.info(
            f"Command groups: {len([x for x in self.walk_commands() if isinstance(x, commands.HybridGroup) or isinstance(x, commands.Group)])}"
        )
        self.logger.info(f"Cog count: {len([x for x in self.cogs])}")

        self.logger.info(
            f"Discord slash command limit: {len([x for x in self.commands if isinstance(x, commands.HybridCommand) or isinstance(x, commands.HybridGroup)])}/100"
        )
        self.logger.info("(Dosent include subcommands)")

        self.logger.info("-------------------")

        self.status_task.start()

    async def on_guild_remove(self, guild: discord.Guild):
        async with aiohttp.ClientSession() as session:
            to_send = Webhook.from_url(config["join_leave_webhook"], session=session)

            embed = discord.Embed(
                title="Bot left a guild!",
                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}",
                color=0xE02B2B
            )

            await to_send.send(embed=embed, username="PotatoBot - Guild Logger")

        self.logger.info("Bot left guild " + guild.name)

    async def on_guild_join(self, guild: discord.Guild):
        async with aiohttp.ClientSession() as session:
            to_send = Webhook.from_url(config["join_leave_webhook"], session=session)

            embed = discord.Embed(
                title="Bot joined a guild!",
                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}",
                color=0x57F287
            )

            await to_send.send(embed=embed, username="PotatoBot - Guild Logger")

        self.logger.info("Bot joined guild: " + guild.name)

    async def on_error(self, event_method, *args, **kwargs):
        await ErrorLogger.error(self, event_method, *args, **kwargs)

    async def on_message(self, message: discord.Message) -> None:
        if message.author.id in config["fully_ignore"]:
            return

        if message.author == self.user or message.author.bot:
            return

        arr = message.content.split(" ")

        arr[0] = arr[0].lower()

        message.content = " ".join(arr)

        ctx = await self.get_context(message)
        if ctx.command is not None:
            self.dispatch('command', ctx)
            try:
                if await self.can_run(ctx, call_once=True):
                    await ctx.command.invoke(ctx)
                else:
                    raise commands.errors.CheckFailure('The global check once functions failed.')
            except commands.errors.CommandError as exc:
                await ctx.command.dispatch_error(ctx, exc)
            else:
                self.dispatch('command_completion', ctx)
        elif ctx.invoked_with:
            exc = commands.errors.CommandNotFound(f'Command "{ctx.invoked_with}" is not found')
            self.dispatch('command_error', ctx, exc)
        else:
            if f"<@{str(self.user.id)}>" in message.content:
                await message.reply(f"> My prefix is `{await self.get_prefix(message)}`")


    async def on_command_completion(self, context: commands.Context) -> None:
        full_command_name = context.command.qualified_name
        split = full_command_name.split(" ")
        executed_command = str(split[0])

        if context.guild is not None:
            self.logger.info(
                f"Executed {executed_command} command in {context.guild.name} (ID: {context.guild.id}) by {context.author} (ID: {context.author.id})"
            )
        else:
            self.logger.info(
                f"Executed {executed_command} command by {context.author} (ID: {context.author.id}) in DMs"
            )

        commands_ran = (statsDB.get("commands_ran") if statsDB.get("commands_ran") else 0) + 1
        statsDB.set("commands_ran", commands_ran)
        statsDB.save()

    async def on_command_error(self, context: commands.Context, error) -> None:
        if isinstance(error, commands.CommandOnCooldown):
            minutes, seconds = divmod(error.retry_after, 60)
            hours, minutes = divmod(minutes, 60)
            hours = hours % 24
            embed = discord.Embed(
                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 ''}.",
                color=0xE02B2B,
            )
            await context.send(embed=embed)
        elif isinstance(error, commands.NotOwner):
            embed = discord.Embed(
                description="You are not the owner of the bot!", color=0xE02B2B
            )
            await context.send(embed=embed)
            if context.guild:
                self.logger.warning(
                    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."
                )
            else:
                self.logger.warning(
                    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."
                )
        elif isinstance(error, commands.MissingPermissions):
            embed = discord.Embed(
                description="You are missing the permission(s) `"
                + ", ".join(error.missing_permissions)
                + "` to execute this command!",
                color=0xE02B2B,
            )
            await context.send(embed=embed)
        elif isinstance(error, commands.BotMissingPermissions):
            embed = discord.Embed(
                description="I am missing the permission(s) `"
                + ", ".join(error.missing_permissions)
                + "` to fully perform this command!",
                color=0xE02B2B,
            )
            await context.send(embed=embed)
        elif isinstance(error, commands.MissingRequiredArgument):
            embed = discord.Embed(
                title="Error!",
                description=str(error).capitalize(),
                color=0xE02B2B,
            )
            await context.send(embed=embed)
        elif isinstance(error, commands.CheckFailure):
            embed = discord.Embed(
                title="Error!",
                description=str(error).capitalize(),
                color=0xE02B2B,
            )
            await context.send(embed=embed)
        elif isinstance(error, commands.CommandNotFound):
            if not context.channel in cant_react_in:
                try:
                    await context.message.add_reaction("❓")
                except discord.errors.Forbidden:
                    cant_react_in.append(context.channel)
                    logger.warning(
                        f"Couldn't react to a message in {context.channel.name} (ID: {context.channel.id}) in {context.guild.name} (ID: {context.guild.id})"
                    )
        elif isinstance(error, Errors.CommandDisabled):
            embed = discord.Embed(
                title="Error!",
                description=str(error).capitalize(),
                color=0xE02B2B,
            )
            await context.send(embed=embed)
        elif isinstance(error, Errors.UserBlacklisted):
            embed = discord.Embed(
                title="Error!",
                description=str(error).capitalize(),
                color=0xE02B2B,
            )
            await context.send(embed=embed)
        elif isinstance(error, commands.CommandError):
            embed = discord.Embed(
                title="Error!",
                description=str(error).capitalize(),
                color=0xE02B2B,
            )
            await context.send(embed=embed)

            await ErrorLogger.command_error(error, context)
        else:
            if "not found" in str(error):
                embed = discord.Embed(
                    title="Error!",
                    description=str(error).capitalize(),
                    color=0xE02B2B,
                )
                await context.send(embed=embed)
            else:
                embed = discord.Embed(
                    title="Error!",
                    description=str(error).capitalize(),
                    color=0xE02B2B,
                )
                await context.send(embed=embed)
                await ErrorLogger.command_error(error, context)
                raise error


================================================
FILE: cogs/ai.py
================================================
# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon

FILTERS = [
    {
        "old": "@everyone",
        "new": "@​everyone"
    },
    {
        "old": "@here",
        "new": "@​here"
    },
    {
        "old": "<@&",
        "new": "<@&​"
    },
    {
        "old": "discord.gg",
        "new": "[filtered]"
    },
    {
        "old": "discord.com/invite",
        "new": "[filtered]"
    }
]

WORD_BLACKLIST = ["nigger", "nigga", "n i g g e r"]

import discord
import requests
import io
import os
import re
import time
import asyncio
import functools
import http.client
import aiohttp
import base64
import aiohttp
import logging
import json

from io import BytesIO
from datetime import datetime

from better_profanity import profanity
from groq import Groq

from discord import app_commands, Webhook
from discord.ext import commands, tasks
from discord.ext.commands import Context
from utils import CONSTANTS, DBClient, Checks, CachedDB

from cryptography.fernet import Fernet

client = DBClient.client
db = client.potatobot

logger = logging.getLogger("discord_bot")

if not os.path.isfile(f"./config.json"):
    sys.exit("'config.json' not found! Please add it and try again.")
else:
    with open(f"./config.json") as file:
        config = json.load(file)

models = [
    "llama-3.3-70b-versatile",
    "llama-3.2-11b-text-preview",
    "llama-3.1-8b-instant",
    "llama3-groq-70b-8192-tool-use-preview",
    "llama3-groq-8b-8192-tool-use-preview",
]

api_key = os.getenv('FUSION_API_KEY')
secret_key = os.getenv('FUSION_SECRET_KEY')

ai_temp_disabled = False

ai_channels = []
c = db["ai_channels"]
data = c.find_one({ "listOfChannels": True })
logger.info("Initing AI channels")

if data:
    ai_channels = data["ai_channels"]
    logger.info("AI Channels data Found")
else:
    logger.info("Creating AI Channels data")
    data = {
    	"listOfChannels": True,
         "ai_channels": []
    }
    c.insert_one(data)

last_api_key = 1
total_api_keys = os.getenv("GROQ_API_KEY_COUNT")

def get_api_key():
    global last_api_key
    global total_api_keys

    if str(last_api_key) == total_api_keys:
        last_api_key = 1
    else:
        last_api_key += 1

    return os.getenv("GROQ_API_KEY_" + str(last_api_key))

def prompt_ai(
        prompt="Hello",
        image_url=None,
        authorId = 0,
        channelId = 0,
        userInfo="",
        groq_client=Groq(api_key=get_api_key()),
        systemPrompt="none"
    ):
    c = db["ai_convos"]
    data = {}

    messageArray = []

    if channelId != 0:
        data = CachedDB.sync_find_one(c, { "isChannel": True, "id": channelId })

        if data:
            messageArray = data["messageArray"]
        else:
            data = { "isChannel": True, "id": channelId, "messageArray": [], "expiresAt": time.time()+604800 }

            c.insert_one(data)
    elif authorId != 0:
        data = CachedDB.sync_find_one(c, { "isChannel": False, "id": authorId })

        if data:
            messageArray = data["messageArray"]
        else:
            data = { "isChannel": False, "id": authorId, "messageArray": [], "expiresAt": time.time()+604800 }

            c.insert_one(data)

    image_interpretation = ""

    if image_url and image_url.split("?")[0].endswith((".png", ".jpg", ".jpeg", ".gif", ".webp")):
        image = requests.get(image_url)

        if image.status_code == 200:
            response = requests.post(
                "https://api-inference.huggingface.co/models/Salesforce/blip-image-captioning-large",
                headers={
                    "Authorization": f"Bearer {os.getenv('HF_API_KEY')}"
                },
                data=image.content
            )

            if response.status_code == 200:
                prompt += f" | Image Interpretation: {response.json()[0]['generated_text']}"
                image_interpretation = response.json()[0]['generated_text']
            else:
                logger.info(f"Failed to get image interpretation: {response.status_code}")

    messageArray.append(
        {
            "role": "user",
            "content": prompt,
        }
    )

    newMessageArray = messageArray.copy()

    systemInfo = {
        "datetime": datetime.now(),
        "timezone": time.tzname,
        "ai_models": models,
        "ai_image_model": "Kandinsky 3.0",
        "owner/dev": "Cyteon",
        "instance owner/dev ID": os.getenv("OWNER_ID"),
        "support_server": "https://discord.gg/df8eCZDvxB",
        "website": "https://potato.cyteon.tech",
        "bot_invite": config["invite_link"],
        "source_code": "https://github.com/cyteon/potatobot",
        "special_emojis": "<:joos:1254878760218529873>",
        "notes": {
            1: "Sending just an emoji with no text makes it big, discord has markdown",
        },
        "rules": {
            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",
            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",
            3: "Never start a message with username:, where username is everything",
        },
        "self-data": {
        	"name": "PotatoBot"
    	}
    }

    newMessageArray.append(
    	{
            "role": "system",
            "content": f"{systemPrompt} | SystemInfo: {systemInfo} | UserInfo: {userInfo}"
        }
    )

    ai_response = ""

    for msg in newMessageArray:
        # To remove _id (appears from the rewrite in js using same db ig)
        newMessageArray[newMessageArray.index(msg)] = {
            "role": msg["role"],
            "content": msg["content"]
        }

    for model in models:
        try:
            ai_response = groq_client.chat.completions.create(
                messages=newMessageArray,
                model=model,
                temperature=0.7,
            ).choices[0].message.content

            break
        except Exception as e:
            logger.info(f"Error: {e}")
            ai_response = f"Error: {e}"

    messageArray.append(
        {
            "role": "assistant",
            "content": ai_response
        }
    )

    if len(messageArray) >= 24 :
        newdata = {
                "$set": { "messageArray": messageArray[2::],  }
        }
    else:
        newdata = {
                "$set": { "messageArray": messageArray, "expiresAt": time.time()+604800  }
        }

    if channelId != 0:
        CachedDB.sync_update_one(
            c, { "isChannel": True, "id": channelId}, newdata
        )
    elif authorId != 0:
        CachedDB.sync_update_one(
            c, { "isChannel": False, "id": authorId}, newdata
        )

    ai_response = ai_response.replace("</s>", " ") # It kept sending this somtimes

    for word in WORD_BLACKLIST:
        if word.lower() in ai_response.lower():
            logger.error(f"AI Response contains blacklisted word: {word}")
            return "The AIs response has been identified as containing blacklisted words, we are sorry for this inconvenience"

    for filter in FILTERS:
        if filter["old"] == "discord.gg":
            # TODO: Fix where if someone makes ai say support server invite and another invite it dosent get filtered
            if systemInfo["support_server"] in ai_response:
                continue
        ai_response =  ai_response.replace(filter["old"], filter["new"])

    if image_interpretation:
        ai_response += f"\n-# Image Interpretation: {image_interpretation}"

    return ai_response

class Text2ImageAPI:
    def __init__(self, url):
        self.URL = url

    global AUTH_HEADERS
    AUTH_HEADERS = {
        'X-Key': f'Key {api_key}',
        'X-Secret': f'Secret {secret_key}',
    }

    def get_model(self):
        response = requests.get(self.URL + 'key/api/v1/models', headers=AUTH_HEADERS)
        data = response.json()
        return data[0]['id']

    def generate(self, prompt, model, images=1, width=1024, height=1024, style="DEFAULT", negative_prompt=""):
        params = {
            "type": "GENERATE",
            "stype": style,
            "numImages": images,
            "width": width,
            "height": height,
            "negativePromptUnclip": negative_prompt,
            "generateParams": {
                "query": f"{prompt}"
            }
        }
        data = {
            'model_id': (None, model),
            'params': (None, json.dumps(params), 'application/json')
        }
        response = requests.post(self.URL + 'key/api/v1/text2image/run', headers=AUTH_HEADERS, files=data)
        data = response.json()
        return data['uuid']

    def check_generation(self, request_id, attempts=10, delay=10):
        while attempts > 0:
            response = requests.get(self.URL + 'key/api/v1/text2image/status/' + request_id, headers=AUTH_HEADERS)
            data = response.json()

            logger.info(data)

            if data['status'] == 'DONE':
                return data['images']
            attempts -= 1
            time.sleep(delay)

        raise Exception("An error occured while generating the image")

class Ai(commands.Cog, name="🤖 AI"):
    def __init__(self, bot) -> None:
        self.bot = bot
        self.purge_conversations.start()
        self.ai_temp_disabled = False
        self.get_prefix = bot.get_prefix
        self.statsDB = bot.statsDB
        self.cooldown = commands.CooldownMapping.from_cooldown(5, 10, commands.BucketType.user)
        self.too_many_violations = commands.CooldownMapping.from_cooldown(3, 10, commands.BucketType.user)

    @commands.Cog.listener()
    async def on_message(self, message: discord.Message) -> None:
        if message.author == self.bot or message.author.bot:
            return

        if not message.channel.id in ai_channels:
            return

        if message.content.startswith("-"):
            return

        if message.content.startswith(await self.bot.get_prefix(message)):
            return

        if self.ai_temp_disabled:
            await message.reply("AI is temporarily disabled due to techincal difficulties")
            return

        bucket = self.cooldown.get_bucket(message)
        retry_after = bucket.update_rate_limit()

        users_global = db["users_global"]

        user_data = await CachedDB.find_one(users_global, {"id": message.author.id})

        if not user_data:
            user_data = CONSTANTS.user_global_data_template(message.author.id)
            users_global.insert_one(user_data)

        if user_data:
            if user_data["ai_ignore"]:
                await message.reply("**You are being ignored by the AI, reason: " + user_data["ai_ignore_reason"] + "**")
                return

            if user_data["blacklisted"]:
                await message.reply("**You are blacklisted from using the bot, reason: " + user_data["blacklist_reason"] + "**")
                return

        if retry_after:
            embed = discord.Embed(
                title="Slow Down! Ratelimit hit",
                description=f"Try again <t:{(time.time() + int(retry_after)):.0f}:R>",
                color=discord.Color.red()
            )
            embed.set_footer(text="Further violations may result in a mute or blacklist.")

            await message.reply(embed=embed)

            bucket = self.too_many_violations.get_bucket(message)
            retry_after = bucket.update_rate_limit()

            if retry_after:
                embed = discord.Embed(
                    title="Too many violations! Max ratelimit hit",
                    description=f"You have been blacklisted from using the AI.",
                    color=discord.Color.red()
                )
                embed.set_footer(text=" If you believe this is a mistake, please contact the support server.")

                newdata = {
                    "$set": { "ai_ignore": True, "ai_ignore_reason": "Too many violations, max ratelimit hit."}
                }

                users_global.update_one(
                    { "id": message.author.id }, newdata
                )

                await message.reply(embed=embed)

            return

        if profanity.contains_profanity(message.content):
            newdata ={
                "$inc": { "inspect.nsfw_requests": 1}
            }

            users_global.update_one(
                { "id": message.author.id }, newdata
            )

        for word in WORD_BLACKLIST:
            if word.lower() in message.content.lower():
                newdata = {
                    "$inc": { "inspect.times_flagged": 1}
                }

                users_global.update_one(
                    { "id": message.author.id }, newdata
                )

                return await message.reply("Your message contains a blacklisted word, please refrain from using it.")

        if not "ai_requests" in user_data["inspect"]:
            newdata = {
                "$set": { "inspect.ai_requests": 0}
            }
            users_global.update_one(
                { "id": message.author.id }, newdata
            )

        if user_data["inspect"]["ai_requests"] == 0:
            embed = discord.Embed(
                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."
            )
            await message.reply(embed=embed)

        newdata ={
            "$inc": { "inspect.ai_requests": 1}
        }

        users_global.update_one(
            { "id": message.author.id }, newdata
        )

        c = db["guilds"]
        data = c.find_one({"id": message.guild.id})

        if not data:
            data = CONSTANTS.guild_data_template(message.guild.id)
            c.insert_one(data)

        if data["groq_api_key"] == "NONE":
            if not data["ai_access"]:
                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>**")
                logger.info(f"{message.author} tried to ask AI in {message.guild.name} ({message.guild.id}): AI Disabled!")
                return
            client = Groq(api_key=get_api_key())
        else:
            cipher_suite = Fernet(os.getenv("HASHING_SECRET"))
            key = cipher_suite.decrypt(data["groq_api_key"]).decode()
            client = Groq(api_key=key)

        c = db["users"]
        userInfo = await CachedDB.find_one(c, {"id": message.author.id, "guild_id": message.guild.id})

        if not userInfo:
            userInfo = {}
        else:
            userInfo["whitelisted"] = "[REDACTED]"
            userInfo["trusted"] = "[REDACTED]"
            userInfo["jailed"] = "[REDACTED]"
            userInfo["warnings"] = "[REDACTED]"

        userInfo["user"] = message.author
        userInfo["channel"] = message.channel

        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}"

        if "system_prompt" in data:
            if data["system_prompt"] != "NONE":
                systemPrompt = data["system_prompt"]

            if profanity.contains_profanity(systemPrompt):
                if hasattr(message.channel, "is_nsfw"):
                    if not message.channel.is_nsfw():
                        await message.reply("The system prompt contains profanity and this channel is not marked as NSFW. **Using default system prompt**")
                        systemPrompt = "NONE"

        image_url = None

        if message.attachments:
            image_url = message.attachments[0].url
        else:
            if message.content:
                urls = re.findall(r'(https?://[^\s]+)', message.content)
                if urls:
                    image_url = urls[0]

        loop = asyncio.get_running_loop()
        try:
            async with message.channel.typing():
                data = await loop.run_in_executor(
                    None,
                    functools.partial(
                        prompt_ai,
                        message.author.name + ": " + message.content,
                        image_url,
                        0,
                        message.channel.id, str(userInfo),
                        groq_client=client,
                        systemPrompt=systemPrompt)
                    )

                if len(data) > 2000:
                    file = discord.File(io.BytesIO(data.encode()), filename="ai_response.txt")

                    await message.reply("-# Response was too long for a normal message", file=file)
                else:
                    await message.reply(data)

                ai_requests = (self.statsDB.get("ai_requests") if self.statsDB.get("ai_requests") else 0) + 1
                self.statsDB.set("ai_requests", ai_requests)
                self.statsDB.save()

        except Exception as e:
            logger.error(f"Error in AI: {e}")
            await message.reply("An error in the AI has occured")

        logger.info(f"AI replied to {message.author} in {message.guild.name} ({message.guild.id})")

    @tasks.loop(hours=1)
    async def purge_conversations(self):
        convos = db["ai_convos"]
        result = convos.delete_many({"expiresAt": {"$lt": time.time()}})

    @commands.hybrid_command(
        name="ai",
        description="Ask an AI for something",
        usage="ai <prompt>"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @app_commands.allowed_installs(guilds=True, users=True)
    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
    @commands.cooldown(10, 60, commands.BucketType.default)
    async def ai(self, context: Context, *, prompt: str) -> None:
        if self.ai_temp_disabled:
            await context.send("AI is temporarily disabled due to techincal difficulties")
            return

        await context.defer()

        users_global = db["users_global"]
        user_data = users_global.find_one({"id": context.author.id})

        if not user_data:
            user_data = CONSTANTS.user_global_data_template(context.author.id)
            users_global.insert_one(user_data)

        if user_data:
            if user_data["ai_ignore"]:
                await context.reply("**You are being ignored by the AI, reason: " + user_data["ai_ignore_reason"] + "**")
                return

        if profanity.contains_profanity(context.message.content):
            newdata ={
                "$inc": { "inspect.nsfw_requests": 1}
            }

            users_global.update_one(
                { "id": context.author.id }, newdata
            )

        if user_data["inspect"]["ai_requests"] == 0:
            embed = discord.Embed(
                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."
            )
            await context.send(embed=embed)

        if not "ai_requests" in user_data["inspect"]:
            newdata = {
                "$set": { "inspect.ai_requests": 0}
            }
            users_global.update_one(
                { "id": context.author.id }, newdata
            )

        newdata ={
            "$inc": { "inspect.ai_requests": 1}
        }

        users_global.update_one(
            { "id": context.author.id }, newdata
        )

        client = Groq(api_key=get_api_key())

        userInfo = { "user": context.author }

        c = db["users"]
        userData = c.find_one({"id": context.author.id, "guild_id": context.guild.id}) if context.guild else {}

        if userData:
            userData["whitelisted"] = "[REDACTED]"
            userData["trusted"] = "[REDACTED]"
            userData["jailed"] = "[REDACTED]"
            userData["warnings"] = "[REDACTED]"

        userInfo["data"] = userData

        loop = asyncio.get_running_loop()
        try:
            data = await loop.run_in_executor(
                None,
                functools.partial(
                    prompt_ai,
                    prompt,
                    None,
                    context.author.id,
                    0,
                    str(userInfo),
                    groq_client=client
                )
            )

            if len(data) > 2000:
                file = discord.File(io.BytesIO(data.encode()), filename="ai_response.txt")

                await context.reply("-# Response was too long for a normal message", file=file)
            else:
                await context.reply(data)

            ai_requests = (self.statsDB.get("ai_requests") if self.statsDB.get("ai_requests") else 0) + 1
            self.statsDB.set("ai_requests", ai_requests)
            self.statsDB.save()
        except Exception as e:
            logger.error(f"Error in AI: {e}")
            await context.reply("An error in the AI has occured")

    @commands.hybrid_command(
        name="set-ai-channel",
        description="Set current channel as an AI channel",
        usage="set-ai-channel"
    )
    @commands.has_permissions(manage_channels=True)
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    async def set_ai_channel(self, context: Context):
        c = db["guilds"]
        data = c.find_one({"id": context.guild.id})

        if not data:
            data = CONSTANTS.guild_data_template(context.guild.id)
            c.insert_one(data)

        if data["groq_api_key"] == "NONE":
            if not data["ai_access"]:
                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>**")
                logger.info(f"{context.author} tried to set AI channel in {context.guild.name} ({context.guild.id}): AI Disabled!")
                return

            client = Groq(api_key=get_api_key())
        else:
            cipher_suite = Fernet(os.getenv("HASHING_SECRET"))
            key = cipher_suite.decrypt(data["groq_api_key"]).decode()
            client = Groq(api_key=key)

        await context.send("Setting channel...")

        loop = asyncio.get_running_loop()
        data = await loop.run_in_executor(None, functools.partial(prompt_ai, "Hello", groq_client=client))

        try:
             await context.channel.edit(slowmode_delay=5)
        except:
             pass

        await context.send(data)

        ai_channels.append(context.channel.id)

        c = db["ai_channels"]
        data = c.find_one({ "listOfChannels": True })

        newdata = {
                "$set": { "ai_channels": ai_channels }
        }

        c.update_one(
            { "listOfChannels": True }, newdata
        )

    @commands.hybrid_command(
        name="unset-ai-channel",
        description="Unset current channel as an AI channel",
        usage="unset-ai-channel"
    )
    @commands.has_permissions(manage_channels=True)
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    async def unset_ai_channel(self, context: Context):
        c = db["ai_channels"]

        ai_channels.remove(context.channel.id)

        await context.channel.edit(slowmode_delay=0)

        newdata = {
                "$set": { "ai_channels": ai_channels }
        }

        c.update_one(
            { "listOfChannels": True }, newdata
        )

        await context.send("Channel unset as AI channel")

    @commands.cooldown(1, 30, commands.BucketType.user)
    @commands.hybrid_command(
        name="create-ai-thread",
        description="Create AI thread so u dont have to do !ai",
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    async def create_ai_thread(self, context: Context, *, prompt = "Hello") -> None:
        c = db["guilds"]
        data = c.find_one({"id": context.guild.id})

        if not data:
            data = CONSTANTS.guild_data_template(context.guild.id)
            c.insert_one(data)

        if data["groq_api_key"] == "NONE":
            if not data["ai_access"]:
                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>**")
                logger.info(f"{context.author} tried to create AI thread in {context.guild.name} ({context.guild.id}): AI Disabled!")
                return

            client = Groq(api_key=get_api_key())
        else:
            cipher_suite = Fernet(os.getenv("HASHING_SECRET"))
            key = cipher_suite.decrypt(data["groq_api_key"]).decode()

            client = Groq(api_key=key)

        msg = await context.send("Creating, please wait")

        loop = asyncio.get_running_loop()
        data = await loop.run_in_executor(None, functools.partial(prompt_ai, prompt, groq_client=client))

        ai_requests = (self.statsDB.get("ai_requests") if self.statsDB.get("ai_requests") else 0) + 1
        self.statsDB.set("ai_requests", ai_requests)
        self.statsDB.save()

        newChannel = await context.channel.create_thread(
            name=f"AI Convo - {context.author}",
            type=discord.ChannelType.public_thread,
            slowmode_delay=5
        )

        await newChannel.send(data)
        await msg.delete()

        ai_channels.append(newChannel.id)

        c = db["ai_channels"]
        data = c.find_one({ "listOfChannels": True })

        newdata = {
                "$set": { "ai_channels": ai_channels }
        }

        c.update_one(
            { "listOfChannels": True }, newdata
        )

        await context.send("Thread created: " + newChannel.mention)

    @commands.hybrid_command(
        name="ai-image",
        description="Generate an ai image",
        usage="ai-image <prompt>",
        aliases=["image"]
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @app_commands.allowed_installs(guilds=True, users=True)
    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
    async def ai_image(self, context: commands.Context, prompt: str) -> None:
        users_global = db["users_global"]
        user_data = users_global.find_one({"id": context.author.id})

        if not user_data:
            user_data = CONSTANTS.user_global_data_template(context.author.id)
            users_global.insert_one(user_data)

        if user_data:
            if user_data["ai_ignore"]:
                await context.reply("**You are being ignored by the AI, reason: " + user_data["ai_ignore_reason"] + "**")
                return

        if profanity.contains_profanity(prompt):
            newdata ={
                "$inc": { "inspect.nsfw_requests": 1}
            }

            users_global.update_one(
                { "id": context.author.id }, newdata
            )

            if hasattr(context.channel, "is_nsfw"):
                if not context.channel.is_nsfw():
                    return await context.send(f"NSFW requests are not allowed in non nsfw channels!", ephemeral=True)

        if not "ai_requests" in user_data["inspect"]:
            newdata = {
                "$set": { "inspect.ai_requests": 0}
            }
            users_global.update_one(
                { "id": context.author.id }, newdata
            )

        if user_data["inspect"]["ai_requests"] == 0:
            embed = discord.Embed(
                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."
            )
            await context.reply(embed=embed)

        newdata ={
            "$inc": { "inspect.ai_requests": 1}
        }

        users_global.update_one(
            { "id": context.author.id }, newdata
        )

        eta = int(time.time() + 20)

        msg = await context.send(f"Generating image... ETA: <t:{eta}:R>")

        attachments = []

        loop = asyncio.get_running_loop()
        try:
            data = await loop.run_in_executor(None, functools.partial(self.generate_image, context, prompt))
        except Exception as e:
            await msg.edit(content="An error occurred while generating the image")
            raise e

        logger.info(data)

        for image in data:
            attachments.append(discord.File(BytesIO(base64.b64decode(image)), "ai_image.png"))

        await msg.edit(content="Here you go!", attachments=attachments)

    @commands.hybrid_command(
        name="imagine",
        description="Generate an ai image, where you can change the model",
        usage="imagine <model (run command with no arguments for list)> <prompt>"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @app_commands.allowed_installs(guilds=True, users=True)
    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
    async def imagine(self, context: commands.Context, model: str = "none", *, prompt: str = "potato") -> None:
        options = {
            "openjourney": "prompthero/openjourney-v4",
            "realistic-vision": "SG161222/Realistic_Vision_V4.0_noVAE",
            "ssd-1b": "segmind/SSD-1B",
            "dreamshaper": "Lykon/dreamshaper-xl-v2-turbo",
            "mobius": "Corcelio/mobius",
            "dalle": "ehristoforu/dalle-3-xl-v2",
            "sdxl": "stabilityai/stable-diffusion-xl-base-1.0",
        }

        nsfw_options = []

        users_global = db["users_global"]
        user_data = users_global.find_one({"id": context.author.id})

        if not user_data:
            user_data = CONSTANTS.user_global_data_template(context.author.id)
            users_global.insert_one(user_data)

        if model not in options:
            return await context.send("Invalid model. Available models: " + ", ".join(options.keys()))

        if model in nsfw_options:
            if hasattr(context.channel, "is_nsfw"):
                if not context.channel.is_nsfw():
                    return await context.send(f"NSFW models are not allowed in non NSFW channels!", ephemeral=True)

        if user_data:
            if user_data["ai_ignore"]:
                await context.reply("**You are being ignored by the AI, reason: " + user_data["ai_ignore_reason"] + "**")
                return

        users_global = db["users_global"]

        user_data = users_global.find_one({"id": context.author.id})

        if not user_data:
            user_data = CONSTANTS.user_global_data_template(context.author.id)
            users_global.insert_one(user_data)

        if profanity.contains_profanity(prompt):
            newdata ={
                "$inc": { "inspect.nsfw_requests": 1}
            }

            users_global.update_one(
                { "id": context.author.id }, newdata
            )

            if hasattr(context.channel, "is_nsfw"):
                if not context.channel.is_nsfw():
                    return await context.send(f"NSFW requests are not allowed in non NSFW channels!", ephemeral=True)

        if not "ai_requests" in user_data["inspect"]:
            newdata = {
                "$set": { "inspect.ai_requests": 0}
            }
            users_global.update_one(
                { "id": context.author.id }, newdata
            )

        if user_data["inspect"]["ai_requests"] == 0:
            embed = discord.Embed(
                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."
            )
            await context.reply(embed=embed)
        newdata ={
            "$inc": { "inspect.ai_requests": 1}
        }

        users_global.update_one(
            { "id": context.author.id }, newdata
        )

        ETA = int(time.time() + 15)
        msg = await context.send(
            f"This might take a bit of time... ETA: <t:{ETA}:R>"
        )

        async with aiohttp.ClientSession() as session:
            api_key = os.getenv("HF_API_KEY")

            response = await session.post(
                "https://api-inference.huggingface.co/models/" + options[model],
                json={"inputs": prompt},
                headers={"Authorization": f"Bearer {api_key}"},
            )

            if response.status != 200:
                return await msg.edit(content="An error occurred while generating the image: " + http.client.responses[response.status])

            images = [discord.File(BytesIO(await response.read()), "ai_image.png")]

            await msg.edit(attachments=images, content="Here you go!")

    def generate_image(self, context: commands.Context, prompt: str, width=1024, height=1024, style="DEFAULT", negative_prompt="", number_of_images=1) -> None:
        api_key = os.environ.get('FUSION_API_KEY')
        secret_key = os.environ.get('FUSION_SECRET_KEY')

        if not api_key or not secret_key:
            context.send("API keys are missing. Please set the FUSION_API_KEY and FUSION_SECRET_KEY environment variables.")
            return

        api = Text2ImageAPI('https://api-key.fusionbrain.ai/')
        model_id = api.get_model()
        uuid = api.generate(prompt, model_id, images=number_of_images, width=width, height=height, style=style, negative_prompt=negative_prompt)
        images_data = api.check_generation(uuid)

        return images_data

    @commands.hybrid_command(
        name="system-prompt",
        description="Set the system prompt for the AI",
        usage="system-prompt <prompt>"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @commands.has_permissions(manage_messages=True)
    async def system_prompt(self, context: Context, *, prompt: str = "") -> None:
        c = db["guilds"]
        data = c.find_one({"id": context.guild.id})

        if prompt == "":
            if data:
                if "system_prompt" in data:
                    return await context.send("Current system prompt: " + data["system_prompt"])
                else:
                    return await context.send("No system prompt set.")

        if profanity.contains_profanity(prompt):
            if not context.channel.is_nsfw():
                prompt = "NONE"
                await context.send("The system prompt contains profanity and this channel is not marked as NSFW. Please use an NSFW channel for NSFW prompts.")

        newdata = {
                "$set": { "system_prompt": prompt }
        }

        c.update_one(
            { "id": context.guild.id }, newdata
        )

        await context.send("System prompt set to: " + prompt)

    @commands.hybrid_command(
        name="reset-ai",
        description="Reset AI data",
        usage="reset-ai"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @commands.has_permissions(manage_messages=True)
    async def reset_ai(self, context: Context) -> None:
        c = db["ai_convos"]
        c.delete_one({"id": context.channel.id})
        await context.send("AI data reset for " + context.channel.mention)

    @commands.command(
        name="toggle-ai",
        description="Reset AI data (owner only)",
    )
    @commands.is_owner()
    async def toggle_ai(self, context: Context) -> None:
        self.ai_temp_disabled = not self.ai_temp_disabled

        if self.ai_temp_disabled:
            await context.send("AI is now disabled globally")
        else:
            await context.send("AI is now enabled globally")

async def setup(bot) -> None:
    await bot.add_cog(Ai(bot))


================================================
FILE: cogs/api.py
================================================
# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon

import discord
import aiohttp

from discord import app_commands
from discord.ext import commands
from discord.ext.commands import Context

from utils import Checks

class Api(commands.Cog, name="🌐 API"):
    def __init__(self, bot) -> None:
        self.bot = bot

    @commands.hybrid_group(
        name="api",
        description="Commands for diffrent APIs",
        usage="api <subcommand> [args]",
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @app_commands.allowed_installs(guilds=True, users=True)
    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
    async def api(self, context: Context) -> None:
        prefix = await self.bot.get_prefix(context)

        cmds = "\n".join([f"{prefix}api {cmd.name} - {cmd.description}" for cmd in self.api.walk_commands()])

        embed = discord.Embed(
            title=f"Help: Api", description="List of available commands:", color=0xBEBEFE
        )
        embed.add_field(
            name="Commands", value=f"```{cmds}```", inline=False
        )

        await context.send(embed=embed)

    @api.command(
        name="minecraft",
        aliases=["mc"],
        description="Get someones minecraft character",
        usage="api minecraft <username>"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    async def api_minecraft(self, context: Context, *, username: str) -> None:
        embed = discord.Embed(title=f"Minecraft character for {username}", color=0xBEBEFE)
        embed.set_image(url=f"https://mc-heads.net/body/{username}")

        await context.send(embed=embed)

    @api.command(
        name="mc-server",
        aliases=["mcserver", "mc-srv", "mcs"],
        description="Get info on a minecraft server",
        usage="api mc-server <username>"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    async def api_mc_server(self, context: Context, *, host: str) -> None:
        async with aiohttp.ClientSession() as session:
            async with session.get(f"https://api.mcsrvstat.us/3/{host}") as response:
                data = await response.json()

                if data["online"]:
                    embed = discord.Embed(
                        title=f"Server info for {host}", color=0xBEBEFE
                    )
                    embed.add_field(
                        name="Players", value=f"```{data['players']['online']}/{data['players']['max']}```", inline=False
                    )

                    if "software" in data:
                        embed.add_field(
                            name="Version", value=f"```{data['version']} ({data['software']})```", inline=False
                        )
                    else:
                        embed.add_field(
                            name="Version", value=f"```{data['version']}```", inline=False
                        )

                    embed.add_field(
                        name="MOTD", value=f"```{data['motd']['clean'][0]}```", inline=False
                    )

                    if "list" in data["players"]:
                        players = [p["name"] for p in data["players"]["list"]]
                        players = ", ".join(players)


                        embed.add_field(
                            name="Online players", value=f"```{players}```", inline=False
                        )

                    if "plugins" in data:
                        plugins = [p["name"] for p in data["plugins"]]
                        plugins = ", ".join(plugins)

                        embed.add_field(
                            name="Plugins", value=f"```{plugins}```", inline=False
                        )

                    if "mods" in data:
                        mods = [m["name"] for m in data["mods"]]
                        mods = ", ".join(mods)

                        embed.add_field(
                            name="Mods", value=f"```{mods}```", inline=False
                        )

                    await context.send(embed=embed)
                else:
                    await context.send("The server is offline")

async def setup(bot) -> None:
    await bot.add_cog(Api(bot))


================================================
FILE: cogs/code.py
================================================
"""
The MIT License (MIT)

Copyright (c) 2022 Ogiroid Development Team

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
"""

from discord import app_commands
from discord.ext import commands
from discord.ext.commands import Context

from utils import Checks
from ui.code import CodeModal

class Code(commands.Cog, name="💻 Code"):
    def __init__(self, bot) -> None:
        self.bot = bot

    @commands.hybrid_command(
        name="code",
        description="Run code in (almost) any language, a modal will pop up",
        usage="code"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @app_commands.allowed_installs(guilds=True, users=True)
    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
    async def code(self, context: Context) -> None:
        if not context.interaction:
            await context.send("This command can only be used as a slash command.")
            return
        await context.interaction.response.send_modal(CodeModal())

async def setup(bot) -> None:
    await bot.add_cog(Code(bot))


================================================
FILE: cogs/economy.py
================================================
# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon

import random
import discord
import time

from discord import ui
from discord.ext import commands
from discord.ext.commands import Context

from utils import CONSTANTS, DBClient, CachedDB, Checks
from ui.farm import FarmButton
from ui.gambling import GamblingButton

from ui.papertrading import start_paper_trading

db = DBClient.db

class Economy(commands.Cog, name="🪙 Economy"):
    def __init__(self, bot) -> None:
        self.bot = bot

    @commands.hybrid_command(
        name="balance",
        aliases=["wallet", "bal"],
        description="See yours or someone else's wallet",
        usage="balance [optional: user]"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @commands.cooldown(3, 10, commands.BucketType.user)
    async def wallet(self, context: Context, user: discord.Member = None) -> None:
        if not user:
            user = context.author

        c = db["users"]
        data = c.find_one({"id": user.id, "guild_id": context.guild.id})

        if not data:
            data = CONSTANTS.user_data_template(user.id, context.guild.id)
            c.insert_one(data)
        await context.send(f"**{user}** has ${data['wallet']} in their wallet")

    @commands.hybrid_command(
        name="daily",
        description="Get your daily cash",
        usage="daily"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    async def daily(self, context: Context) -> None:
        c = db["users"]
        data = await CachedDB.find_one(c, {"id": context.author.id, "guild_id": context.guild.id})

        if not data:
            data = CONSTANTS.user_data_template(context.author.id, context.guild.id)
            c.insert_one(data)
        if time.time() - data["last_daily"] < 86400:
            eta = data["last_daily"] + 86400
            await context.send(
                f"You can claim your daily cash <t:{int(eta)}:R>"
            )
            return

        guild = db["guilds"]
        guild_data = await CachedDB.find_one(guild, {"id": context.guild.id})

        if not guild_data:
            guild_data = CONSTANTS.guild_data_template(context.guild.id)
            guild.insert_one(guild_data)

        data["wallet"] += guild_data["daily_cash"]
        newdata = {
            "$set": {"wallet": data["wallet"], "last_daily": time.time()}
        }

        await CachedDB.update_one(c, {"id": context.author.id, "guild_id": context.guild.id}, newdata)

        await context.send(f"Added {guild_data['daily_cash']}$ to wallet")

    @commands.hybrid_command(
        name="beg",
        description="Beg for money",
        usage="beg"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @commands.cooldown(1, 600, commands.BucketType.user)
    async def beg(self, context: Context) -> None:
        c = db["users"]
        data = await CachedDB.find_one(c, {"id": context.author.id, "guild_id": context.guild.id})

        if not data:
            data = CONSTANTS.user_data_template(context.author.id, context.guild.id)
            c.insert_one(data)

        amount = random.randint(5, 200)
        data["wallet"] += amount

        newdata = {
            "$set": {"wallet": data["wallet"]}
        }

        await CachedDB.update_one(c, {"id": context.author.id, "guild_id": context.guild.id}, newdata)

        await context.send(f"Someone gave you {amount}$!")

    @commands.hybrid_command(
        name="rob",
        description="Rob someone's wallet",
        usage="rob <user>"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @commands.cooldown(1, 3600, commands.BucketType.user)
    async def rob(self, context: Context, user: discord.Member) -> None:
        if user == context.author:
            await context.send("You can't rob yourself")
            return

        c = db["users"]

        target_data = await CachedDB.find_one(c, {"id": user.id, "guild_id": context.guild.id})

        if not target_data:
            return await context.send("User has no money")

        if target_data["wallet"] == 0:
            return await context.send("User has no money")

        author_data = await CachedDB.find_one(c, {"id": context.author.id, "guild_id": context.guild.id})

        if not author_data:
            author_data = CONSTANTS.user_data_template(context.author.id, context.guild.id)
            c.insert_one(author_data)

        max_payout = target_data["wallet"] // 5

        if target_data["last_robbed_at"] > time.time() - 10800:
            eta = target_data["last_robbed_at"] + 10800
            await context.send(
                f"This user can be robbed again <t:{int(eta)}:R>"
            )
            return

        result = random.randint(0, 2)
        if result == 0:
            payout = random.randint(1, max_payout)
            author_data["wallet"] += payout
            target_data["wallet"] -= payout

            newdata = {
                "$set": {
                    "wallet": author_data["wallet"],
                }
            }

            newdata2 = {
                "$set": {
                    "wallet": target_data["wallet"],
                    "last_robbed_at": time.time()
                }
            }

            await CachedDB.update_one(c, {"id": context.author.id, "guild_id": context.guild.id}, newdata)
            await CachedDB.update_one(c, {"id": user.id, "guild_id": context.guild.id}, newdata2)

            await context.send(f"You successfully robbed {user} and got {payout}$")
        elif result == 1:
            payout = min(random.randint(1, max_payout//2), author_data["wallet"]//3, 10000)
            author_data["wallet"] -= payout
            target_data["wallet"] += payout

            newdata = {
                "$set": {
                    "wallet": author_data["wallet"],
                }
            }

            newdata2 = {
                "$set": {"wallet": target_data["wallet"], "last_robbed_at": time.time()}
            }

            await CachedDB.update_one(c, {"id": context.author.id, "guild_id": context.guild.id}, newdata)
            await CachedDB.update_one(c, {"id": user.id, "guild_id": context.guild.id}, newdata2)

            await context.send(f"You got caught by {user} and they took {payout}$")
        else:
            await context.send(f"You failed to rob {user}, but lost nothing")

    @commands.hybrid_command(
        name="baltop",
        description="See the top 10 richest users",
        usage="baltop"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    async def baltop(self, context: Context) -> None:
        c = db["users"]
        data = c.find({"guild_id": context.guild.id}).sort("wallet", -1).limit(10)

        embed = discord.Embed(
            title="Top Balances",
            description="",
            color=discord.Color.gold(),
        )

        i = 1
        for _, user in enumerate(data, start=1):
            member = context.guild.get_member(user["id"])
            if member != None:
                if member.bot:
                    continue
                embed.add_field(
                    name=f"{i}. {member.nick if member.nick else member.display_name if member.display_name else member.name}",
                    value=f"${user['wallet']}",
                    inline=False,
                )
                i += 1

        await context.send(embed=embed)

    @commands.hybrid_command(
        name="pay",
        description="Pay someone from your wallet",
        usage="pay <user> <amount>"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    async def pay(self, context: Context, user: discord.Member, amount: int) -> None:
        if amount < 0:
            await context.send("You can't pay a negative amount")
            return

        if user == context.author:
            await context.send("You can't pay yourself")
            return

        c = db["users"]
        data = await CachedDB.find_one(c, {"id": context.author.id, "guild_id": context.guild.id})

        if not data:
            data = CONSTANTS.user_data_template(context.author.id, context.guild.id)
            c.insert_one(data)
        if data["wallet"] < amount:
            await context.send("You don't have enough money")
            return

        target_user_data = c.find_one({"id": user.id, "guild_id": context.guild.id})
        if not target_user_data:
            target_user_data = CONSTANTS.user_data_template(user.id, context.guild.id)

            c.insert_one(target_user_data)
        data["wallet"] -= amount
        target_user_data["wallet"] += amount
        newdata = {
            "$set": {"wallet": data["wallet"]}
        }
        newdata2 = {
            "$set": {"wallet": target_user_data["wallet"]}
        }

        await CachedDB.update_one(c, {"id": context.author.id, "guild_id": context.guild.id}, newdata)
        await CachedDB.update_one(c, {"id": user.id, "guild_id": context.guild.id}, newdata2)

        await context.send(f"Paid {amount}$ to {user.mention}")

    @commands.hybrid_command(
        name="set",
        description="Set someones wallet (admin only)",
        usage="set <user> <amount>"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @commands.has_permissions(manage_messages=True)
    async def set(self, context: Context, user: discord.Member, amount: int) -> None:
        c = db["users"]

        target_user_data = await CachedDB.find_one(c, {"id": user.id, "guild_id": context.guild.id})

        if not target_user_data:
            target_user_data = CONSTANTS.user_data_template(context.author.id, context.guild.id)

            c.insert_one(target_user_data)

        newdata = {
            "$set": {"wallet": amount}
        }

        await CachedDB.update_one(c, {"id": user.id, "guild_id": context.guild.id}, newdata)

        await context.send(f"Set {user.mention}'s wallet to {amount}$")

    @commands.hybrid_command(
        name="gamble",
        description="Gamble your money",
        usage="gamble <amount>"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    async def gamble(self, context: Context, amount: int) -> None:
        if amount < 0:
            await context.send("You can't gamble a negative amount")
            return

        c = db["users"]
        data = await CachedDB.find_one(c, {"id": context.author.id, "guild_id": context.guild.id})

        if not data:
            data = CONSTANTS.user_data_template(context.author.id, context.guild.id)
            c.insert_one(data)
        if data["wallet"] < amount:
            await context.send("You don't have enough money")
            return

        if amount < 1:
            await context.send("You can't gamble less than 1$")
            return

        await context.send(
            "How would you like to gamble?",
            view=GamblingButton(amount, context.author.id),
        )

    @commands.hybrid_command(
        name="stockmarket",
        description="Gamble your money(but like irl but like fake fr)",
        usage="stockmarket"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    async def stockmarket(self, context: Context) -> None:
        await start_paper_trading(context)

    # TODO: MORE CACHING AFTER THIS POINT

    @commands.hybrid_command(
        name="farm",
        description="Farm some potatoes",
        usage="farm"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    async def farm(self, context: Context) -> None:

        c = db["users"]
        data = await CachedDB.find_one(c, {"id": context.author.id, "guild_id": context.guild.id})

        if not data:
            data = CONSTANTS.user_data_template(context.author.id, context.guild.id)
            c.insert_one(data)

        if not "farm" in data:
            data["farm"] = {
                "saplings": 0,
                "crops": 0,
                "harvestable": 0,
                "ready_in": 0
            }
            newdata = {
                "$set": {"farm": data["farm"]}
            }
            c.update_one(
                {"id": context.author.id, "guild_id": context.guild.id}, newdata
            )

        farmData = data["farm"]

        if farmData["ready_in"] < time.time():
            farmData["harvestable"] += farmData["crops"]
            farmData["crops"] = 0

        embed = discord.Embed(
            title="Farm",
            description="Buy saplings to farm potatoes",
            color=0x77dd77,
        )

        embed.add_field(
            name="Saplings",
            value=farmData["saplings"],
            inline=False,
        )

        embed.add_field(
            name="Crops",
            value=farmData["crops"],
            inline=False,
        )

        embed.add_field(
            name="Harvestable",
            value=farmData["harvestable"],
            inline=False,
        )

        embed.add_field(
            name="Ready",
            value=f"<t:{int(farmData['ready_in'])}:R>",
            inline=False,
        )

        embed.set_footer(text=f"Wallet: ${data['wallet']}")

        await context.send(embed=embed, view=FarmButton(context.author.id))

        new_data = {
            "$set": {"farm": farmData}
        }
        c.update_one(
            {"id": context.author.id, "guild_id": context.guild.id}, new_data
        )

async def setup(bot) -> None:
    await bot.add_cog(Economy(bot))


================================================
FILE: cogs/fun.py
================================================
# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon

import random
import discord
import os
import aiohttp
import json
import requests
import io
from PIL import Image

from io import BytesIO
from discord.ui import Button, View

from discord import app_commands
from discord.ext import commands
from discord.ext.commands import Context

from utils import Checks

TENOR_API_KEY = os.getenv("TENOR_API_KEY")

class TicTacToeButton(Button):
    def __init__(self, x: int, y: int, player_x: discord.Member, player_o: discord.Member):
        super().__init__(style=discord.ButtonStyle.secondary, label="\u200b", row=y)
        self.x = x
        self.y = y
        self.player_x = player_x
        self.player_o = player_o

    async def callback(self, interaction: discord.Interaction):
        view: TicTacToeView = self.view
        if interaction.user != view.current_player:
            await interaction.response.send_message("It's not your turn!", ephemeral=True)
            return

        if self.label == "\u200b":
            self.label = "X" if view.current_player == self.player_x else "O"
            self.style = discord.ButtonStyle.danger if view.current_player == self.player_x else discord.ButtonStyle.primary
            self.disabled = True

            view.board[self.x][self.y] = 1 if view.current_player == self.player_x else -1
            view.current_player = self.player_o if view.current_player == self.player_x else self.player_x

            await interaction.response.edit_message(content=f"{view.current_player.mention}, your turn.", view=view)

            winner = view.check_winner()
            if winner:
                await interaction.followup.send(f"{winner.mention} wins!", ephemeral=False)
                view.stop()
            elif all(cell != 0 for row in view.board for cell in row):
                await interaction.followup.send("It's a tie!", ephemeral=False)
                view.stop()
        else:
            await interaction.response.send_message("This button is already clicked!", ephemeral=True)

class TicTacToeView(View):
    def __init__(self, player_x: discord.Member, player_o: discord.Member):
        super().__init__(timeout=None)
        self.player_x = player_x
        self.player_o = player_o
        self.current_player = player_x
        self.board = [[0 for _ in range(3)] for _ in range(3)]

        for x in range(3):
            for y in range(3):
                self.add_item(TicTacToeButton(x, y, player_x, player_o))

    def check_winner(self):
        for row in self.board:
            if sum(row) == 3:
                return self.player_x
            elif sum(row) == -3:
                return self.player_o

        for col in range(3):
            if self.board[0][col] + self.board[1][col] + self.board[2][col] == 3:
                return self.player_x
            elif self.board[0][col] + self.board[1][col] + self.board[2][col] == -3:
                return self.player_o

        if self.board[0][0] + self.board[1][1] + self.board[2][2] == 3:
            return self.player_x
        elif self.board[0][0] + self.board[1][1] + self.board[2][2] == -3:
            return self.player_o

        if self.board[0][2] + self.board[1][1] + self.board[2][0] == 3:
            return self.player_x
        elif self.board[0][2] + self.board[1][1] + self.board[2][0] == -3:
            return self.player_o

        return None

class Fun(commands.Cog, name="🎉 Fun"):
    def __init__(self, bot) -> None:
        self.bot = bot

    @commands.command(
        name="joos",
        description="joos",
        usage="joos",
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    async def joos(self, context: Context) -> None:
        await context.send("<:joos:1254878760218529873>")

    @commands.hybrid_group(
        name="http",
        description="Commands for http cat/dog/fish images.",
        usage="http <subcommand>"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @app_commands.allowed_installs(guilds=True, users=True)
    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
    async def http(self, context: Context) -> None:
        prefix = await self.bot.get_prefix(context)

        cmds = "\n".join([f"{prefix}http {cmd.name} - {cmd.description}" for cmd in self.http.walk_commands()])

        embed = discord.Embed(
            title=f"Help: Http", description="List of available commands:", color=0xBEBEFE
        )
        embed.add_field(
            name="Commands", value=f"```{cmds}```", inline=False
        )

        await context.send(embed=embed)

    @http.command(
        name="cat",
        description="Get a cat image representing a http status code.",
        usage="http cat <code>"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    async def http_cat(self, context: Context, code) -> None:
        await context.send(f"https://http.cat/{code}.jpg")

    @http.command(
        name="dog",
        description="Get a dog image representing a http status code.",
        usage="http dog <code>"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    async def http_dog(self, context: Context, code) -> None:
        await context.send(f"https://http.dog/{code}.jpg")

    @http.command(
        name="fish",
        description="Get a fish image representing a http status code.",
        usage="http fish <code>"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    async def http_fish(self, context: Context, code) -> None:
        await context.send(f"https://http.fish/{code}.jpg")

    @http.command(
        name="goat",
        description="Get a goat image representing a http status code.",
        usage="http goat <code>"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    async def http_goat(self, context: Context, code) -> None:
        await context.send(f"https://httpgoats.com/{code}.jpg")

    @commands.hybrid_command( # TODO: fix this crap
        name="bored",
        description="Get an activity if you are bored"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @app_commands.allowed_installs(guilds=True, users=True)
    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
    async def bored(self, context: Context) -> None:
        async with aiohttp.ClientSession() as session:
            url="https://bored-api.appbrewery.com/random"

            async with session.get(url) as r:
                if r.status == 200:
                    data = await r.json()

                    embed = discord.Embed()

                    if "error" in data:
                        embed = discord.Embed(title=data["error"], color=discord.Color.brand_red())
                    else:
                        embed = discord.Embed(title=data["activity"], color=discord.Color.teal())

                        embed.add_field(name = "Type", value = data["type"].capitalize())
                        embed.add_field(name = "Participants", value = data["participants"])
                        embed.add_field(name = "Price", value = data["price"])

                    await context.send(embed=embed)
                elif r.status == 404:
                    embed = discord.Embed(title="No activities found", color=discord.Color.brand_red())

                    await context.send(embed=embed)
                else:
                    await context.send(f"BoredAPI is currently experiencing issues: Status " + str(r.status))

    @commands.hybrid_command(
        name="advice",
        description="Get some advice",
        usage="advice"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @app_commands.allowed_installs(guilds=True, users=True)
    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
    async def advice(self, context: Context) -> None:
        async with aiohttp.ClientSession() as session:
            r = requests.get("https://api.adviceslip.com/advice")
            data = json.loads(r.text)

            await context.send(data["slip"]["advice"])

    @commands.hybrid_command(
        name="insult",
        description="Get an insult"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @app_commands.allowed_installs(guilds=True, users=True)
    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
    async def insult(self, context: Context) -> None:
        async with aiohttp.ClientSession() as session:
            async with session.get(f"https://evilinsult.com/generate_insult.php?lang=en&type=json") as r:
                if r.status == 200:
                    data = await r.json()

                    await context.send(data["insult"])

    @commands.hybrid_command(
        name="gif",
        description="Get a random gif, unless query is specified",
        usage="gif [optional: query]"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @app_commands.allowed_installs(guilds=True, users=True)
    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
    async def gif(self, context: Context, *, query="NONE") -> None:
        rand = False
        if query == "NONE":
            query = random.choice(
                [
                    "bored",
                    "exited",
                    "happy",
                    "sad",
                    "angry",
                    "confused",
                    "crying",
                    "cat",
                    "dog",
                    "slap",
                    "animal",
                    "building",
                    "car",
                    "technology",
                    "random",
                    "plane"
                ]
            )
            rand = True

        async with aiohttp.ClientSession() as session:
            data = await session.get(
                f"https://tenor.googleapis.com/v2/search?random={rand}&q={query}&key=" + TENOR_API_KEY
            )

            data = await data.json()

            img = await session.get(
                data["results"][0]["media_formats"]["gif"]["url"]
            )

            imageData = io.BytesIO(await img.read())
            await context.send(file=discord.File(imageData, "gif.gif"))

    @commands.hybrid_group(
        name="avatar",
        description="Commands for avatar manipulation",
        aliases=["av", "pfp"],
        usage="avatar <subcommand>"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @app_commands.allowed_installs(guilds=True, users=True)
    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
    async def avatar(self, context: Context) -> None:
        prefix = await self.bot.get_prefix(context)

        cmds = "\n".join([f"{prefix}avatar {cmd.name} - {cmd.description}" for cmd in self.avatar.walk_commands()])

        embed = discord.Embed(
            title=f"Help: Avatar", description="List of available commands:", color=0xBEBEFE
        )
        embed.add_field(
            name="Commands", value=f"```{cmds}```", inline=False
        )

        await context.send(embed=embed)

    @avatar.command(
        name="get",
        description="Get someone's avatar",
        usage="avatar get [optional: user]"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    async def get(self, context: Context, user: discord.User = None) -> None:
        if not user:
            user = context.author

        embed = discord.Embed(
            title=f"{user.name}'s Avatar",
            color=discord.Color.blurple()
        )

        embed.set_image(url=user.display_avatar.url)

        await context.send(embed=embed)

    @avatar.command(
        name="blur",
        description="Blur someone",
        usage="avatar blur [optional: user]"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    async def blur(self, context: Context, user: discord.User = None) -> None:
        if not user:
            user = context.author

        async with aiohttp.ClientSession() as session:
            img = await session.get(
                f"https://some-random-api.com/canvas/misc/blur?avatar={user.display_avatar.url}"
            )

            imageData = io.BytesIO(await img.read())
            await context.send(file=discord.File(imageData, "blur.png"))

    @avatar.command(
        name="pixelate",
        description="Pixelate someone",
        usage="avatar pixelate [optional: user]"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    async def pixelate(self, context: Context, user: discord.User = None) -> None:
        if not user:
            user = context.author

        async with aiohttp.ClientSession() as session:
            img = await session.get(
                f"https://some-random-api.com/canvas/misc/pixelate?avatar={user.display_avatar.url}"
            )

            imageData = io.BytesIO(await img.read())
            await context.send(file=discord.File(imageData, "pixelate.png"))

    @avatar.command(
        name="trigger",
        description="Trigger someone",
        usage="avatar trigger [optional: user]"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    async def trigger(self, context: Context, user: discord.User = None) -> None:
        if not user:
            user = context.author

        async with aiohttp.ClientSession() as session:
            img = await session.get(
                f"https://some-random-api.com/canvas/overlay/triggered?avatar={user.display_avatar.url}"
            )

            imageData = io.BytesIO(await img.read())
            await context.send(file=discord.File(imageData, "triggered.gif"))

    @avatar.command(
        name="jail",
        description="Put someone in jail",
        usage="avatar jail [optional: user]"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    async def jail(self, context: Context, user: discord.User = None) -> None:
        if not user:
            user = context.author

        async with aiohttp.ClientSession() as session:
            img = await session.get(
                f"https://some-random-api.com/canvas/overlay/jail?avatar={user.display_avatar.url}"
            )

            imageData = io.BytesIO(await img.read())
            await context.send(file=discord.File(imageData, "jail.png"))

    @avatar.command(
        name="wasted",
        description="Wasted",
        usage="avatar wasted [optional: user]"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    async def wasted(self, context: Context, user: discord.User = None) -> None:
        if not user:
            user = context.author

        async with aiohttp.ClientSession() as session:
            img = await session.get(
                f"https://some-random-api.com/canvas/overlay/wasted?avatar={user.display_avatar.url}"
            )

            imageData = io.BytesIO(await img.read())
            await context.send(file=discord.File(imageData, "wasted.png"))

    @avatar.command(
        name="passed",
        description="Passed",
        usage="avatar passed [optional: user]"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    async def passed(self, context: Context, user: discord.User = None) -> None:
        if not user:
            user = context.author

        async with aiohttp.ClientSession() as session:
            img = await session.get(
                f"https://some-random-api.com/canvas/overlay/passed?avatar={user.display_avatar.url}"
            )

            imageData = io.BytesIO(await img.read())
            await context.send(file=discord.File(imageData, "passed.png"))

    @avatar.command(
        name="trans",
        description="Trans border around pfp",
        usage="avatar trans [optional: user]"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    async def trans(self, context: Context, user: discord.User = None) -> None:
        if not user:
            user = context.author

        async with aiohttp.ClientSession() as session:
            img = await session.get(
                f"https://some-random-api.com/canvas/misc/transgender?avatar={user.display_avatar.url}"
            )

            imageData = io.BytesIO(await img.read())
            await context.send(file=discord.File(imageData, "transgender.png"))

    @commands.hybrid_group(
        name="random",
        description="Commands for random stuff",
        usage="random <subcommand>"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @app_commands.allowed_installs(guilds=True, users=True)
    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
    async def random(self, context: Context) -> None:
        prefix = await self.bot.get_prefix(context)

        cmds = "\n".join([f"{prefix}random {cmd.name} - {cmd.description}" for cmd in self.random.walk_commands()])

        embed = discord.Embed(
            title=f"Help: Random", description="List of available commands:", color=0xBEBEFE
        )
        embed.add_field(
            name="Commands", value=f"```{cmds}```", inline=False
        )

        await context.send(embed=embed)

    @random.command(
        name="boykisser",
        description="Get a random boykisser image",
        usage="boykisser"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @app_commands.allowed_installs(guilds=True, users=True)
    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
    async def boykisser(self, context: Context) -> None:
        async with aiohttp.ClientSession() as session:
            data = await session.get(
                "https://api.gizzy.is-a.dev/api/random?redirect=0"
            )

            data = await data.json()

            await context.send(data['url'])

    @random.command(
        name="gayrate",
        description="Get your gay rate",
        usage="random gayrate <user>"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @app_commands.allowed_installs(guilds=True, users=True)
    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
    async def gayrate(self, context: Context, user: discord.User = None) -> None:
        if not user:
            user = context.author

        percentage = random.randint(0, 100)
        emojis = ["😳", "😳", "😳", "😳", "😳", "😳", "😳", "😳", "😳", "😳", "🏳️‍🌈", "🔥"]

        if percentage > 90:
            emoji = "🌈"
        elif percentage < 10:
            emoji = "🔥"
        else:
            emoji = random.choice(emojis)

        await context.send(f"**{user}** is {percentage}% gay {emoji}")


    @random.command(
        name="coffee",
        description="Get a random coffee image",
        usage="random coffee"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @app_commands.allowed_installs(guilds=True, users=True)
    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
    async def random_cat(self, context: Context) -> None:
        async with aiohttp.ClientSession() as session:

            img = await session.get(
                "https://coffee.alexflipnote.dev/random"
            )

            imageData = io.BytesIO(await img.read())
            await context.send(file=discord.File(imageData, "coffee.png"))

    @random.command(
        name="cat",
        description="Get a random cat image",
        usage="random cat"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @app_commands.allowed_installs(guilds=True, users=True)
    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
    async def random_cat(self, context: Context) -> None:

        async with aiohttp.ClientSession() as session:
            data = await session.get(
                "https://some-random-api.com/animal/cat"
            )

            data = await data.json()

            await context.send(data["image"])

    @random.command(
        name="dog",
        description="Get a random dog image",
        usage="random dog"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @app_commands.allowed_installs(guilds=True, users=True)
    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
    async def random_dog(self, context: Context) -> None:
        async with aiohttp.ClientSession() as session:
            data = await session.get(
                "https://some-random-api.com/animal/dog"
            )

            data = await data.json()

            await context.send(data["image"])

    @random.command(
        name="bird",
        description="Get a random bird image",
        usage="random bird"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @app_commands.allowed_installs(guilds=True, users=True)
    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
    async def random_bird(self, context: Context) -> None:

        async with aiohttp.ClientSession() as session:
            data = await session.get(
                "https://some-random-api.com/animal/bird"
            )

            data = await data.json()

            await context.send(data["image"])

    @random.command(
        name="fox",
        description="Get a random fox image",
        usage="random fox"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @app_commands.allowed_installs(guilds=True, users=True)
    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
    async def random_fox(self, context: Context) -> None:

        async with aiohttp.ClientSession() as session:
            data = await session.get(
                "https://some-random-api.com/animal/fox"
            )

            data = await data.json()

            await context.send(data["image"])

    @random.command(
        name="kangaroo",
        description="Get a random kangaroo image",
        usage="random kangaroo"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @app_commands.allowed_installs(guilds=True, users=True)
    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
    async def random_kangaroo(self, context: Context) -> None:
        async with aiohttp.ClientSession() as session:
            data = await session.get(
                "https://some-random-api.com/animal/kangaroo"
            )

            data = await data.json()

            await context.send(data["image"])

    @random.command(
        name="koala",
        description="Get a random koala image",
        usage="random koala"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @app_commands.allowed_installs(guilds=True, users=True)
    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
    async def random_koala(self, context: Context) -> None:
        async with aiohttp.ClientSession() as session:
            data = await session.get(
                "https://some-random-api.com/animal/koala"
            )

            data = await data.json()

            await context.send(data["image"])

    @random.command(
        name="panda",
        description="Get a random panda image",
        usage="random panda"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @app_commands.allowed_installs(guilds=True, users=True)
    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
    async def random_panda(self, context: Context) -> None:

        async with aiohttp.ClientSession() as session:
            data = await session.get(
                "https://some-random-api.com/animal/panda"
            )

            data = await data.json()

            await context.send(data["image"])

    @random.command(
        name="raccoon",
        description="Get a random raccoon image",
        usage="random raccoon"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @app_commands.allowed_installs(guilds=True, users=True)
    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
    async def random_raccoon(self, context: Context) -> None:

        async with aiohttp.ClientSession() as session:
            data = await session.get(
                "https://some-random-api.com/animal/raccoon"
            )

            data = await data.json()

            await context.send(data["image"])

    @random.command(
        name="red-panda",
        description="Get a random raccoon image",
        usage="random red-panda"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @app_commands.allowed_installs(guilds=True, users=True)
    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
    async def random_red_panda(self, context: Context) -> None:

        async with aiohttp.ClientSession() as session:
            data = await session.get(
                "https://some-random-api.com/animal/red_panda"
            )

            data = await data.json()

            await context.send(data["image"])

    @commands.hybrid_group(
        name="img",
        description="Commands for image creation",
        usage="img <subcommand>"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @app_commands.allowed_installs(guilds=True, users=True)
    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
    async def image(self, context: Context) -> None:
        prefix = await self.bot.get_prefix(context)

        cmds = "\n".join([f"{prefix}image {cmd.name} - {cmd.description}" for cmd in self.image.walk_commands()])

        embed = discord.Embed(
            title=f"Help: Image", description="List of available commands:", color=0xBEBEFE
        )
        embed.add_field(
            name="Commands", value=f"```{cmds}```", inline=False
        )

        await context.send(embed=embed)

    @image.command(
        name="youtube",
        description="Youtube comment",
        usage="image youtube <user> <text>"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    async def youtube(self, context: Context, user: discord.User, *, text: str) -> None:
        if not user:
            user = context.author

        async with aiohttp.ClientSession() as session:
            img = await session.get(
                f"https://some-random-api.com/canvas/misc/youtube-comment?avatar={user.display_avatar.url}&username={user.display_name}&comment={text}"
            )

            imageData = io.BytesIO(await img.read())
            await context.send(file=discord.File(imageData, "youtube.png"))

    @image.command(
        name="tweet",
        description="Tweet",
        usage="image tweet <user> <text>"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    async def tweet(self, context: Context, user: discord.User, *, tweet: str) -> None:
        async with aiohttp.ClientSession() as session:
            nick = user.nick if hasattr(user, 'nick') else user.display_name
            if nick == None:
                nick = user.display_name

            img = await session.get(
                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"
            )

            imageData = io.BytesIO(await img.read())
            await context.send(file=discord.File(imageData, "tweet.png"))

    @commands.hybrid_command(
        name="ttt",
        aliases=["tictactoe"],
        description="Play a game of Tic-Tac-Toe",
        usage="ttt <opponent>"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @app_commands.allowed_installs(guilds=True, users=True)
    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
    async def tictactoe(self, context: Context, opponent: discord.User) -> None:
        """Start a game of Tic-Tac-Toe with the specified opponent."""

        if opponent == context.author:
            await context.send("You cannot play against yourself!")
            return

        if opponent.bot:
            await context.send("You cannot play against bots!")
            return

        await context.send(f"{context.author.mention} vs {opponent.mention}!", view=TicTacToeView(context.author, opponent))

    @commands.hybrid_command(
        name="togif",
        description="Convert an uploaded image (PNG/JPG) into a GIF",
        usage="togif [upload image]"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @app_commands.allowed_installs(guilds=True, users=True)
    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
    async def togif(self, context: Context, attachment: discord.Attachment) -> None:
        if not attachment.content_type or not attachment.content_type.startswith("image"):
            await context.send("Please upload a valid image file!")
            return

        if attachment.size > 20 * 1024 * 1024:
            await context.send("The image is too large! Please upload a file smaller than 20MB.")
            return

        async with context.typing():
            image_bytes = await attachment.read()
            img_input = io.BytesIO(image_bytes)
            
            try:
                with Image.open(img_input) as img:
                    if img.mode in ("RGBA", "P"):
                        img = img.convert("RGB")
                    
                    output_buffer = io.BytesIO()
                    img.save(output_buffer, format="GIF")
                    output_buffer.seek(0)
                    
                    await context.send(
                        file=discord.File(fp=output_buffer, filename="converted.gif")
                    )
            except Exception as e:
                self.bot.logger.error(f"Error in togif command: {e}")
                await context.send("Failed to convert image to GIF. Ensure the file is a valid image.")

async def setup(bot) -> None:
    await bot.add_cog(Fun(bot))


================================================
FILE: cogs/general.py
================================================
# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon

import random
import os
import aiohttp
import time
import asyncpraw
import inspect
import json
import sys

import logging
logger = logging.getLogger("discord_bot")

import discord
from discord import app_commands
from discord.ext import commands
from discord.ext.commands import Context

from utils import DBClient, Checks
from ui import translate

db = DBClient.db

reddit = asyncpraw.Reddit(
    client_id=os.getenv("REDDIT_CLIENT_ID"),
    client_secret=os.getenv("REDDIT_CLIENT_SECRET"),
    user_agent="PotatoBot",
)

if not os.path.isfile(f"./config.json"):
    sys.exit("'config.json' not found! Please add it and try again.")
else:
    with open(f"./config.json") as file:
        config = json.load(file)

class General(commands.Cog, name="⬜ General"):
    def __init__(self, bot) -> None:
        self.bot = bot
        self.context_menu_message = app_commands.ContextMenu(
            name="Remove spoilers", callback=self.ctx_remove_spoilers
        )
        self.context_menu_message = app_commands.ContextMenu(
            name="Translate",
            callback=self.ctx_translate,
            allowed_contexts=app_commands.AppCommandContext(guild=True, dm_channel=True, private_channel=True),
            allowed_installs=app_commands.AppInstallationType(guild=True, user=True)
        )
        self.bot.tree.add_command(self.context_menu_message)
        self.get_prefix = bot.get_prefix

    # Message context menu command
    async def ctx_remove_spoilers(
        self, interaction: discord.Interaction, message: discord.Message
    ) -> None:
        spoiler_attachment = None
        for attachment in message.attachments:
            if attachment.is_spoiler():
                spoiler_attachment = attachment
                break
        embed = discord.Embed(
            title="Message without spoilers",
            description=message.content.replace("||", ""),
            color=0xBEBEFE,
        )
        if spoiler_attachment is not None:
            embed.set_image(url=attachment.url)
        await interaction.response.send_message(embed=embed, ephemeral=True)

    async def ctx_translate(
        self, interaction: discord.Interaction, message: discord.Message
    ) -> None:
        if message.content:
            await interaction.response.send_modal(translate.TranslateModal(message))
        else:
            await interaction.response.send_message("No text to translate", ephemeral=True)

    @commands.hybrid_command(
        name="help",
        aliases=["h", "commands", "cmds"],
        description="Get help with commands",
        usage="help [optional: command]"
    )
    @commands.check(Checks.is_not_blacklisted)
    @app_commands.allowed_installs(guilds=True, users=True)
    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
    async def help(self, context: Context, *, command: str = "none") -> None:
        if command != "none":
            cmd = self.bot.get_command(command)
            if cmd is None:
                await context.send("Command not found")
                return

            if cmd.cog_name == "owner" and not context.author.id in self.bot.owner_ids:
                await context.send("Command not found")
                return

            embed = discord.Embed(
                title=f"Command: {cmd.name}",
                description=cmd.description,
                color=0xBEBEFE
            )

            usage = cmd.usage if cmd.usage else "Not Found"
            example = cmd.extras["example"] if "example" in cmd.extras else "Not Found"
            embed.add_field(
                name="Usage",
                value=f"```Syntax: {usage}\nExample: {example}```",
                inline=False
            )

            aliases = ", ".join(cmd.aliases) if cmd.aliases else "None"
            embed.add_field(
                name="Aliases",
                value=f"```{aliases}```",
                inline=True
            )

            embed.add_field(
                name="Category",
                value=f"```{cmd.cog_name}```",
                inline=True
            )

            cmd_type = ""

            if isinstance(cmd, commands.HybridGroup):
                cmd_type = "Command Group"
            elif isinstance(cmd, commands.HybridCommand):
                cmd_type = "Chat+Slash Command"
            elif isinstance(cmd, commands.Command):
                cmd_type = "Chat Only Command"


            embed.add_field(
                name="Type",
                value=f"```{cmd_type}```",
                inline=True
            )

            params = inspect.signature(cmd.callback).parameters
            param_list = []
            for name, param in params.items():
                if name not in ["self", "context"]:
                    if param.default == inspect.Parameter.empty:
                        param_list.append(f"{name}: <Required>")
                    else:
                        param_list.append(f"{name}: [Optional, default: '{param.default}']")

            params_str = "\n".join(param_list) if param_list else "None"
            embed.add_field(
                name="Parameters",
                value=f"```{params_str}```",
                inline=False
            )

            if isinstance(cmd, commands.HybridGroup):
                    subcommands = ", ".join([sub.name for sub in cmd.commands])
                    embed.add_field(
                        name="Subcommands",
                        value=f"```{subcommands}```",
                        inline=False
                    )

            return await context.send(embed=embed)

        cogs = []

        for cog in self.bot.cogs:
            if cog.startswith("-"):
                continue

            if "owner" in cog and context.author.id != int(os.getenv("OWNER_ID")):
                continue

            if "staff" in cog:
                author_permissions = context.author.guild_permissions

            cogs.append(cog)

        view = CogSelectView(cogs, context.author)

        await context.send('Pick a cog:', view=view)

    @commands.command(
        name="uptime",
        description="Get the bot's uptime",
        usage="uptime"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    async def uptime(self, context: Context):
        uptime = time.time() - self.bot.start_time
        str = time.strftime("%H:%M:%S", time.gmtime(uptime))
        await context.send("Uptime: " + str)

    @commands.hybrid_command(
        name="botinfo",
        description="See bot info",
        usage="botinfo"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @app_commands.allowed_installs(guilds=True, users=True)
    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
    async def botinfo(self, context: Context) -> None:
        dpyVersion = discord.__version__
        serverCount = len(self.bot.guilds)
        memberCount = len(set(self.bot.get_all_members()))

        shard_id = context.guild.shard_id if context.guild else None
        shard = self.bot.get_shard(shard_id) if shard_id is not None else self.bot.shards[0]
        shard_ping = shard.latency
        shard_servers = len([guild for guild in self.bot.guilds if guild.shard_id == shard_id])
        shard_count = len(self.bot.shards)

        embed = discord.Embed(title=f'{self.bot.user.name} - Stats', color = discord.Color.blurple())

        command_count = len([command for command in self.bot.walk_commands()])

        embed.add_field(name="Bot Version:", value=self.bot.version)
        embed.add_field(name="Discord.Py Version:", value=dpyVersion)
        embed.add_field(name="Ping:", value=f"{round(self.bot.latency * 1000)}ms")
        embed.add_field(name="Total Guilds:", value=serverCount)
        embed.add_field(name="Total Users:", value=memberCount)
        embed.add_field(name="Total Commands:", value=command_count)
        embed.add_field(name="Shard ID:", value=shard_id)
        embed.add_field(name="Shard Ping:", value=f"{round(shard_ping * 1000)}ms")
        embed.add_field(name="Shard Servers:", value=shard_servers)
        embed.add_field(name="Shard Count:", value=shard_count)

        embed.set_footer(text="Bot made by Cyteon @ https://github.com/cyteon")
        await context.send(embed=embed)

    @commands.hybrid_command(
        name="ping",
        description="Check if the bot is alive.",
        usage="ping"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @app_commands.allowed_installs(guilds=True, users=True)
    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
    async def ping(self, context: Context) -> None:
        embed = discord.Embed(
            title="🏓 Pong!",
            description=f"The bot latency is {round(self.bot.latency * 1000)}ms.",
            color=0xBEBEFE,
        )
        await context.send(embed=embed)

    @commands.hybrid_command(
        name="bug",
        description="Send a bug report",
        usage="bug <bug>"
    )
    @commands.check(Checks.is_not_blacklisted)
    @app_commands.allowed_installs(guilds=True, users=True)
    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
    @commands.cooldown(5, 3600, commands.BucketType.user)
    async def bug(self, context: Context, *, bug: str) -> None:
        id = int(config["bug_channel"])
        channel = self.bot.get_channel(id)
        embed = discord.Embed(
        	title="Bug Report",
            description=bug,
            color=0xFF0000
        )

        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'})")

        await channel.send(embed=embed)
        await context.send("Bug Reported")

    @commands.hybrid_command(
        name="8ball",
        description="Ask any question to the bot.",
        usage="8ball <question>"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @app_commands.describe(question="The question you want to ask.")
    @app_commands.allowed_installs(guilds=True, users=True)
    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
    async def eight_ball(self, context: Context, *, question: str) -> None:
        answers = [
            "It is certain.",
            "It is decidedly so.",
            "You may rely on it.",
            "Without a doubt.",
            "As I see, yes.",
            "Most likely.",
            "Outlook good.",
            "Yes.",
            "Signs point to yes.",
            "Reply hazy, try again.",
            "Ask again later.",
            "Better not tell you now.",
            "Concentrate and ask again later.",
            "Don't count on it.",
            "My reply is no.",
            "My sources say no.",
            "Outlook not so good.",
            "Very doubtful.",
            "Potato"
        ]
        embed = discord.Embed(
            title="**My Answer:**",
            description=f"{random.choice(answers)}",
            color=0xBEBEFE,
        )
        embed.set_footer(text=f"The question was: {question}")
        await context.send(embed=embed)

    @commands.command(
        name="support",
        description="Support Server.",
        usage="support"
    )
    @commands.check(Checks.command_not_disabled)
    async def support(self, context: commands.Context) -> None:
        message = await context.send("https://discord.gg/wtur9j8uVP")

    @commands.hybrid_command(
        name="define",
        description="Get the definition of a word.",
        usage="define <word>",
        aliases=["dictionary", "dict", "word"]
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @app_commands.allowed_installs(guilds=True, users=True)
    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
    async def define(self, context: Context, *, word: str) -> None:
        async with aiohttp.ClientSession() as session:
            async with session.get(f"https://api.dictionaryapi.dev/api/v2/entries/en/{word}") as response:
                if response.status != 200:
                    return await context.send("No results found.")

                data = await response.json()
                data = data[0]

                embed = discord.Embed(title=f"Definition of {data['word']}", description=data.get("phonetic", "N/A"), color=0xBEBEFE)

                def truncate_text(text, limit=1024):
                    if len(text) > limit:
                        return text[:limit-3] + "..."
                    return text

                definitions = "\n".join(f"{i+1}. {definition['definition']}" for i, meaning in enumerate(data["meanings"]) for definition in meaning["definitions"])

                synonyms = ", ".join(synonym for meaning in data["meanings"] for synonym in meaning.get("synonyms", []))
                antonyms = ", ".join(antonym for meaning in data["meanings"] for antonym in meaning.get("antonyms", []))

                embed.add_field(name="Definition(s)", value=truncate_text(definitions), inline=False)
                embed.add_field(name="Synonym(s)", value=truncate_text(synonyms) if synonyms else "None", inline=False)
                embed.add_field(name="Antonym(s)", value=truncate_text(antonyms) if antonyms else "None", inline=False)

                await context.send(embed=embed)

    @commands.hybrid_command(
        name="urban-dictionary",
        description="Get the definition of a word from Urban Dictionary.",
        usage="urban-dictionary <word>",
        aliases=["urban", "ud"]
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @app_commands.allowed_installs(guilds=True, users=True)
    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
    async def urban_dict(self, context: Context, *, term: str):
        async with aiohttp.ClientSession() as session:
            async with session.get(f"https://api.urbandictionary.com/v0/define?term={term}") as response:
                data = await response.json()

                if not data["list"]:
                    return await context.send("No results found.")

                definition = data["list"][0]["definition"]

                embed = discord.Embed(
                    title=f"Definition of {term}",
                    description=definition,
                    color=0xBEBEFE
                )

                await context.send(embed=embed)

    @commands.hybrid_command(
        name="reddit",
        description="Returns a random post from reddit, or from a subreddit",
        usage="reddit [optional: subreddit]"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @app_commands.allowed_installs(guilds=True, users=True)
    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
    async def reddit(self, context: Context, subreddit: str = "") -> None:
        if subreddit == "":
            subreddit = await reddit.subreddit("random")
        else:
            subreddit = await reddit.subreddit(subreddit)

        #check if NSFW
        loaded_sub = subreddit
        await loaded_sub.load()

        if hasattr(context.channel, "over18"):
            if loaded_sub.over18 and not context.channel.is_nsfw() and not context.channel.id == context.author.id:
                await context.send("This subreddit is NSFW, please use this command in a NSFW channel or dms.")
                return

        posts = []
        async for post in subreddit.hot(limit=25):
            posts.append(post)

        random_post = None

        if len(posts) == 0:
            return await context.send("No posts found")

        while True:
            if len(posts) == 0:
                await context.send("No posts that are not NSFW found, try again or run command in an NSFW channel or dms.")
                return

            random_post = random.choice(posts)
            posts.remove(random_post)

            loaded_post = random_post
            await loaded_post.load()

            if not context.guild:
                if loaded_post.over_18 and not context.channel.is_nsfw() and not context.channel.id == context.author.id:
                    continue

            if loaded_post.stickied:
                continue

            break

        logger.info(f"Reddit post: {random_post.url}")

        title = random_post.title
        url = random_post.url
        author = random_post.author

        embed = discord.Embed(
            title=title,
            description=random_post.selftext,
            url=url,
            color=0xBEBEFE,
        )

        if random_post.url.endswith(('.jpg', '.jpeg', '.png', '.gif')):
            embed.set_image(url=random_post.url)

        await context.send(embed=embed)

    @commands.hybrid_command(
        name="vote",
        description="Vote for the bot on top.gg",
        usage="vote"
    )
    @commands.check(Checks.command_not_disabled)
    @app_commands.allowed_installs(guilds=True, users=True)
    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
    async def vote(self, context: Context):
        embed = discord.Embed(
            title="Vote on top.gg",
            description="Help out the bot by voting now!",
            url="https://top.gg/bot/1226487228914602005/vote",
            color=0xBEBEFE
        )

        await context.send(embed=embed, view=VoteView())

class VoteButton(discord.ui.Button):
    def __init__(self):
        super().__init__(style=discord.ButtonStyle.link, label="Vote on top.gg", url="https://top.gg/bot/1226487228914602005/vote")

    async def callback(self, interaction: discord.Interaction):
        await interaction.response.send_message("Thank you for voting!", ephemeral=True)

class VoteView(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)
        self.add_item(VoteButton())

class CogSelect(discord.ui.Select):
    def __init__(self, cogs, author):
        options = [
            discord.SelectOption(label=cog, description=f"Show commands for {cog}")
            for cog in cogs
        ]
        super().__init__(placeholder='Choose a cog...', min_values=1, max_values=1, options=options)
        self.author = author

    async def callback(self, interaction: discord.Interaction):
        if interaction.user != self.author:
            await interaction.response.send_message("You cannot use this select.", ephemeral=True)
            return

        await interaction.response.defer()

        cog_name = self.values[0]
        cog = interaction.client.get_cog(cog_name)
        commands = cog.get_commands()
        data = []
        for command in commands:
            description = command.description.partition("\n")[0]
            data.append(f"{await interaction.client.get_prefix(interaction)}{command.name} - {description}")
        help_text = "\n".join(data)
        embed = discord.Embed(
            title=f"Help: {cog_name}", description="List of available commands:", color=0xBEBEFE
        )
        embed.add_field(
            name=cog_name.capitalize(), value=f"```{help_text}```", inline=False
        )
        embed.set_footer(text=f"To get more info on a command, use {await interaction.client.get_prefix(interaction)}help <command>")

        await interaction.message.edit(embed=embed)

class CogSelectView(discord.ui.View):
    def __init__(self, cogs, author):
        super().__init__(timeout=None)
        self.add_item(CogSelect(cogs, author))

async def setup(bot) -> None:
    await bot.add_cog(General(bot))
    bot.add_view(VoteView())


================================================
FILE: cogs/github.py
================================================
"""
The MIT License (MIT)

Copyright (c) 2022 Ogiroid Development Team

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
"""


import aiohttp
import discord
from discord import app_commands
from discord.ext import commands
from discord.ext.commands import Context

from utils import Checks


class Github(commands.Cog, name="🖧 Github"):
    def __init__(self, bot) -> None:
        self.bot = bot

    @commands.hybrid_group(
        name="github",
        description="Commands related to GitHub",
        usage="github <subcommand> [args]",
        aliases=["gh"],
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @app_commands.allowed_installs(guilds=True, users=True)
    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
    async def github(self, context: Context) -> None:
        prefix = await self.bot.get_prefix(context)

        cmds = "\n".join([f"{prefix}github {cmd.name} - {cmd.description}" for cmd in self.github.walk_commands()])

        embed = discord.Embed(
            title=f"Help: Github", description="List of available commands:", color=0xBEBEFE
        )
        embed.add_field(
            name="Commands", value=f"```{cmds}```", inline=False
        )

        await context.send(embed=embed)

    # Command to get information about a GitHub user
    @github.command(
        name="user",
        description="Gets the Profile of the github person.",
        usage="github user <username>"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    async def ghuser(self, context, user: str):
        async with aiohttp.ClientSession() as session:
            person_raw = await session.get(
                f"https://api.github.com/users/{user}"
            )
            if person_raw.status != 200:
                return await context.send("User not found!")
            else:
                person = await person_raw.json()
            # Returning an Embed containing all the information:
            embed = discord.Embed(
                title=f"GitHub Profile: {person['login']}",
                description=f"**Bio:** {person['bio']}",
                color=0xFFFFFF,
            )
            embed.set_thumbnail(url=f"{person['avatar_url']}")
            embed.add_field(
                name="Username 📛: ", value=f"{person['name']}", inline=True
            )
            # embed.add_field(name="Email ✉: ", value=f"{person['email']}", inline=True) Commented due to GitHub not responding with the correct email
            embed.add_field(
                name="Repos 📁: ", value=f"{person['public_repos']}", inline=True
            )
            embed.add_field(
                name="Location 📍: ", value=f"{person['location']}", inline=True
            )
            embed.add_field(
                name="Company 🏢: ", value=f"{person['company']}", inline=True
            )
            embed.add_field(
                name="Followers 👥: ", value=f"{person['followers']}", inline=True
            )
            embed.add_field(
                name="Website 🖥️: ", value=f"{person['blog']}", inline=True
            )

            await context.send(embed=embed, view=ProfileButton(url=person["html_url"]))

    # Command to get search for GitHub repositories:
    @github.command(
        name="repo",
        description="Searches for the specified repo.",
        usage="github repo <repo>"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    async def ghsearchrepo(self, context, query: str):
        pages = 1
        url = f"https://api.github.com/search/repositories?q={query}&{pages}"
        async with aiohttp.ClientSession() as session:
            repos_raw = await session.get(url)
            if repos_raw.status != 200:
                return await context.send("Repo not found!")
            else:
                repos = (
                    await repos_raw.json()
                )  # Getting first repository from the query
            repo = repos["items"][0]
            # Returning an Embed containing all the information:
            embed = discord.Embed(
                title=f"GitHub Repository: {repo['name']}",
                description=f"**Description:** {repo['description']}",
                color=0xFFFFFF,
            )
            embed.set_thumbnail(url=f"{repo['owner']['avatar_url']}")
            embed.add_field(
                name="Author 🖊:",
                value=f"__[{repo['owner']['login']}]({repo['owner']['html_url']})__",
                inline=True,
            )
            embed.add_field(
                name="Stars ⭐:", value=f"{repo['stargazers_count']}", inline=True
            )
            embed.add_field(
                name="Forks 🍴:", value=f"{repo['forks_count']}", inline=True
            )
            embed.add_field(
                name="Language 💻:", value=f"{repo['language']}", inline=True
            )
            embed.add_field(
                name="Size 🗃️:",
                value=f"{round(repo['size'] / 1000, 2)} MB",
                inline=True,
            )
            if repo["license"]:
                spdx_id = repo["license"]["spdx_id"]
                embed.add_field(
                    name="License name 📃:",
                    value=f"{spdx_id if spdx_id != 'NOASSERTION' else repo['license']['name']}",
                    inline=True,
                )
            else:
                embed.add_field(
                    name="License name 📃:",
                    value="This Repo doesn't have a license",
                    inline=True,
                )

            await context.send(embed=embed, view=RepoButton(url=repo["html_url"]))

class ProfileButton(discord.ui.View):
    def __init__(self, url: str):
        super().__init__()

        self.add_item(discord.ui.Button(label="GitHub Profile", style=discord.ButtonStyle.url, url=url))

class RepoButton(discord.ui.View):
    def __init__(self, url: str):
        super().__init__()

        self.add_item(discord.ui.Button(label="GitHub Repository", style=discord.ButtonStyle.url, url=url))

async def setup(bot) -> None:
    await bot.add_cog(Github(bot))


================================================
FILE: cogs/giveaway.py
================================================
# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon

import discord
import random

from discord.ext import commands
from discord.ext.commands import Context

from utils import Checks

class Giveaway(commands.Cog, name="🎁 Giveaway"):
    def __init__(self, bot) -> None:
        self.bot = bot

    @commands.hybrid_group(
        name="giveaway",
        description="Command to start or end giveaways",
        usage="giveaway"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @commands.has_permissions(manage_messages=True)
    async def giveaway(self, context: Context) -> None:
        prefix = await self.bot.get_prefix(context)

        cmds = "\n".join([f"{prefix}giveaway {cmd.name} - {cmd.description}" for cmd in self.giveaway.walk_commands()])

        embed = discord.Embed(
            title=f"Help: Giveaway", description="List of available commands:", color=0xBEBEFE
        )
        embed.add_field(
            name="Commands", value=f"```{cmds}```", inline=False
        )

        await context.send(embed=embed)

    @giveaway.command(
        name="start",
        description="Start a giveaway!",
        usage="giveaway start <reward>"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @commands.has_permissions(manage_messages=True)
    async def giveaway_start(self, context: Context, *, reward: str) -> None:
        embed = discord.Embed(title="Giveaway!", description=reward, color=0xBEBEFE)

        message = await context.send(embed=embed)

        await message.add_reaction("🎁")

    @giveaway.command(
        name = "end",
        description = "Ends a poll using message id",
        usage = "giveaway end <message_id>"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @commands.has_permissions(manage_messages=True)
    async def giveaway_end(self, context: Context, message_id) -> None:
        message_id = int(message_id)

        message = await context.fetch_message(message_id)

        users = []

        async for u in message.reactions[0].users():
            users.append(u)

        users.pop(users.index(self.bot.user))
        winner = random.choice(users)

        embed = discord.Embed(title="Giveaway ended!", description="The winner is: {0} 🎉🎉🎉".format(winner.mention), color=0xBEBEFE)

        await message.reply(winner.mention, embed=embed)

async def setup(bot) -> None:
    await bot.add_cog(Giveaway(bot))


================================================
FILE: cogs/level.py
================================================
# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon

import random
import pymongo

import discord
from discord.ext import commands
from discord.ext.commands import Context

from easy_pil import *

from utils import CONSTANTS, DBClient, Checks, CachedDB

db = DBClient.db

class Level(commands.Cog, name="🚀 Level"):
    def __init__(self, bot) -> None:
        self.bot = bot

    @commands.hybrid_command(
        name="level",
        description="See yours or someone elses current level and xp",
        usage="level [optional: user]"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @commands.cooldown(3, 10, commands.BucketType.user)
    async def level(self, context: Context, user: discord.Member = None) -> None:
        if not user:
            user = context.author

        c = db["users"]
        data = await CachedDB.find_one(c, {"id": user.id, "guild_id": context.guild.id})

        if data:
            xp_for_next_level = CONSTANTS.LEVELS_AND_XP[data["level"] + 1]

            percentage = round(data["xp"] / xp_for_next_level * 100, 1)

            background = Editor(Canvas((900, 300), color="#141414"))
            profile_picture = await load_image_async(str(user.avatar.url))
            profile = Editor(profile_picture).resize((150, 150)).circle_image()

            poppins = Font.poppins(size=40)
            poppins_small = Font.poppins(size=30)

            card_right_shape = [(600, 0), (750, 300), (900, 300), (900, 0)]

            background.polygon(card_right_shape, color="#FFFFFF")
            background.paste(profile, (30, 30))

            background.rectangle((30, 220), width=650, height=40, color="#FFFFFF", radius=20)
            background.bar((30, 220), max_width=650, height=40, percentage=percentage, color="orange", radius=20)
            background.text((200, 40), user.name, font=poppins, color="#FFFFFF")

            background.rectangle((200, 100), width=350, height=2, fill="#FFFFFF")
            background.text((200, 130), f"Level {data['level']} - {data['xp']}/{xp_for_next_level} XP", font=poppins_small, color="#FFFFFF")

            file = discord.File(fp=background.image_bytes, filename="level_card.png")
            await context.send(file=file)

        else:
            await context.send("Start chatting to gain a level")

    @commands.hybrid_command(
        name="leaderboard",
        description="See the top 10 users with the most xp in this server",
        aliases=["lb"],
        usage="leaderboard"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @commands.cooldown(1, 10, commands.BucketType.user)
    async def leaderboard(self, context: Context) -> None:
        c = db["users"]
        data = c.find({"guild_id": context.guild.id}).sort([("level", pymongo.DESCENDING), ("xp", pymongo.DESCENDING)]).limit(10)

        embed = discord.Embed(
            title="Leaderboard",
            description="",
            color=discord.Color.gold()
        )

        for index, user in enumerate(data, start=1):
            member = context.guild.get_member(user["id"])

            if member != None:
                if not member.bot:
                    embed.add_field(
                        name=f"{index}. {member.nick if member.nick else member.display_name if member.display_name else member.name}",
                        value=f"Level: {user['level']} - XP: {user['xp']}",
                        inline=False
                    )
            else:
                fetched = await self.bot.fetch_user(user["id"])

                if fetched == None:
                    embed.add_field(
                        name=f"{index}. Unknown User",
                        value=f"Level: {user['level']} - XP: {user['xp']}",
                        inline=False
                    )

                if not fetched.bot:
                    embed.add_field(
                        name=f"{index}. {fetched.name}",
                        value=f"Level: {user['level']} - XP: {user['xp']}",
                        inline=False
                    )

        await context.send(embed=embed)

    @commands.Cog.listener()
    async def on_message(self, message: discord.Message) -> None:
        if message.guild == None:
            return

        if message.author == self.bot or message.author.bot:
            return

        author = message.author

        c = db["users"]
        data = await CachedDB.find_one(c, {"id": author.id, "guild_id": message.guild.id})

        if not data:
            data = CONSTANTS.user_data_template(author.id, message.guild.id)
            c.insert_one(data)

        if data["level"] >= CONSTANTS.MAX_LEVEL:
            return

        if data["xp"] >= CONSTANTS.MAX_XP:
            return

        data["xp"] += random.randint(1, 3)

        if data["xp"] >= CONSTANTS.LEVELS_AND_XP[data["level"] + 1]:
            guilds = db["guilds"]
            guild_data = await CachedDB.find_one(guilds, {"id": message.guild.id})

            if not guild_data:
                guild_data = CONSTANTS.guild_data_template(message.guild.id)
                guilds.insert_one(guild_data)

            data["level"] += 1
            data["xp"] = 0

            if str(data["level"]) in guild_data["level_roles"]:
                role = message.guild.get_role(guild_data["level_roles"][str(data["level"])])
                await message.author.add_roles(role)

            channel = message.channel
            if guild_data:
                if "level_announce_channel" in guild_data:
                    if guild_data["level_announce_channel"] != 0:
                        channel = message.guild.get_channel(guild_data["level_announce_channel"])

                if "should_announce_levelup" in guild_data:
                    if guild_data["should_announce_levelup"]:
                        await channel.send(f"{author.mention} leveled up to level {data['level']}!")
                else:
                    await channel.send(f"{author.mention} leveled up to level {data['level']}!")

        newdata = {"$set": {"xp": data["xp"], "level": data["level"]}}

        await CachedDB.update_one(c, {"id": author.id, "guild_id": message.guild.id}, newdata)

    @commands.hybrid_command(
        name="create-level-roles",
        description="Create roles for levels (manage_roles permission)",
        usage="create-level-roles"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @commands.has_permissions(manage_roles=True)
    async def create_level_roles(self, context: Context):
        # create role for level 1/3/5/10/15/20

        guilds = db["guilds"]
        guild_data = await CachedDB.find_one(guilds, {"id": context.guild.id})

        if not guild_data:
            guild_data = CONSTANTS.guild_data_template(context.guild.id)
            guilds.insert_one(guild_data)

        for level in [1, 3, 5, 10, 15, 20]:
            if str(level) not in guild_data["level_roles"]:
                role = await context.guild.create_role(name=f"Level {level}")
                guild_data["level_roles"][str(level)] = role.id

        newdata = {"$set": {"level_roles": guild_data["level_roles"]}}

        await CachedDB.update_one(guilds, {"id": context.guild.id}, newdata)
        await context.send("Roles created!")

    @commands.hybrid_command(
        name="delete-level-roles",
        description="Delete roles for levels",
        usage="delete-level-roles"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @commands.has_permissions(manage_roles=True)
    async def delete_level_roles(self, context: Context):
        guilds = db["guilds"]
        guild_data = await CachedDB.find_one(guilds, {"id": context.guild.id})

        if not guild_data:
            guild_data = CONSTANTS.guild_data_template(context.guild.id)
            guilds.insert_one(guild_data)

        for level in guild_data["level_roles"]:
            role = context.guild.get_role(guild_data["level_roles"][level])
            if role:
                try:
                    await role.delete()
                except:
                    pass

        newdata = {"$set": {"level_roles": {}}}

        await CachedDB.update_one(guilds, {"id": context.guild.id}, newdata)
        await context.send("Roles deleted!")

async def setup(bot) -> None:
    await bot.add_cog(Level(bot))


================================================
FILE: cogs/music.py
================================================
# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon

import re
import os
import logging

import discord
import lavalink
from discord.ext import commands
from discord.ext.commands import Context
from lavalink.events import TrackStartEvent, QueueEndEvent
from lavalink.errors import ClientError
from lavalink.filters import LowPass, Timescale
from lavalink.server import LoadType

url_rx = re.compile(r'https?://(?:www\.)?.+')

from utils import Checks

logger = logging.getLogger("discord_bot")


host = os.getenv("LAVALINK_HOST")
port = os.getenv("LAVALINK_PORT")
password = os.getenv("LAVALINK_PASSWORD")
region = os.getenv("LAVALINK_REGION")
name = os.getenv("LAVALINK_NAME")

class LavalinkVoiceClient(discord.VoiceProtocol):
    def __init__(self, client: discord.Client, channel: discord.abc.Connectable):
        self.client = client
        self.channel = channel
        self.guild_id = channel.guild.id
        self._destroyed = False

        if not hasattr(self.client, 'lavalink'):
            self.client.lavalink = lavalink.Client(client.user.id)
            self.client.lavalink.add_node(host=host, port=port, password=password,
                                          region=region, name=name)

        self.lavalink = self.client.lavalink

    async def on_voice_server_update(self, data):
        lavalink_data = {
            't': 'VOICE_SERVER_UPDATE',
            'd': data
        }
        await self.lavalink.voice_update_handler(lavalink_data)

    async def on_voice_state_update(self, data):
        channel_id = data['channel_id']

        if not channel_id:
            await self._destroy()
            return

        self.channel = self.client.get_channel(int(channel_id))

        lavalink_data = {
            't': 'VOICE_STATE_UPDATE',
            'd': data
        }

        await self.lavalink.voice_update_handler(lavalink_data)

    async def connect(self, *, timeout: float, reconnect: bool, self_deaf: bool = False, self_mute: bool = False) -> None:
        self.lavalink.player_manager.create(guild_id=self.channel.guild.id)
        await self.channel.guild.change_voice_state(channel=self.channel, self_mute=self_mute, self_deaf=self_deaf)

    async def disconnect(self, *, force: bool = False) -> None:
        player = self.lavalink.player_manager.get(self.channel.guild.id)

        if not force and not player.is_connected:
            return

        await self.channel.guild.change_voice_state(channel=None)
        player.channel_id = None
        await self._destroy()

    async def _destroy(self):
        self.cleanup()

        if self._destroyed:
            return

        self._destroyed = True

        try:
            await self.lavalink.player_manager.destroy(self.guild_id)
        except ClientError:
            pass


class Music(commands.Cog, name="🎵 Music"):
    def __init__(self, bot):
        self.bot = bot

        if not hasattr(bot, 'lavalink'):
            bot.lavalink = lavalink.Client(bot.user.id)
            bot.lavalink.add_node(host=host, port=port, password=password,
                                  region=region, name=name)

        self.lavalink: lavalink.Client = bot.lavalink
        self.lavalink.add_event_hooks(self)

    def cog_unload(self):
        self.lavalink._event_hooks.clear()

    async def cog_command_error(self, context, error):
        if isinstance(error, commands.CommandInvokeError):
            await context.send(error.original)

    async def create_player(context: commands.Context):
        if context.guild is None:
            raise commands.NoPrivateMessage()

        player = context.bot.lavalink.player_manager.create(context.guild.id)

        should_connect = context.command.name in ('play',)

        voice_client = context.voice_client

        if not context.author.voice or not context.author.voice.channel:
            if voice_client is not None:
                raise commands.CommandInvokeError('You need to join my voice channel first.')

            raise commands.CommandInvokeError('Join a voicechannel first.')

        voice_channel = context.author.voice.channel

        if voice_client is None:
            if not should_connect:
                raise commands.CommandInvokeError("I'm not playing music.")

            permissions = voice_channel.permissions_for(context.me)

            if not permissions.connect or not permissions.speak:
                raise commands.CommandInvokeError('I need the `CONNECT` and `SPEAK` permissions.')

            if voice_channel.user_limit > 0:
                if len(voice_channel.members) >= voice_channel.user_limit and not context.me.guild_permissions.move_members:
                    raise commands.CommandInvokeError('Your voice channel is full!')

            player.store('channel', context.channel.id)
            await context.author.voice.channel.connect(cls=LavalinkVoiceClient)
        elif voice_client.channel.id != voice_channel.id:
            raise commands.CommandInvokeError('You need to be in my voicechannel.')

        return True

    @lavalink.listener(TrackStartEvent)
    async def on_track_start(self, event: TrackStartEvent):
        guild_id = event.player.guild_id
        channel_id = event.player.fetch('channel')
        guild = self.bot.get_guild(guild_id)

        if not guild:
            return await self.lavalink.player_manager.destroy(guild_id)

        channel = guild.get_channel(channel_id)

        if channel:
            await channel.send(f'Now playing: {event.track.title} by {event.track.author}')
            logger.info(f"Now playing {event.track.title} in {guild} ({guild.id})")



    @lavalink.listener(QueueEndEvent)
    async def on_queue_end(self, event: QueueEndEvent):
        guild_id = event.player.guild_id
        guild = self.bot.get_guild(guild_id)

        if guild is not None:
            await guild.voice_client.disconnect(force=True)

    @commands.hybrid_command(
        name="play",
        description="Searches and plays a song from a given query.",
        aliases=['p'],
        usage="play <query or link>"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @commands.check(create_player)
    async def play(self, context, *, query: str):
        player = self.bot.lavalink.player_manager.get(context.guild.id)
        query = query.strip('<>')

        if not url_rx.match(query):
            query = f'ytsearch:{query}'

        results = await player.node.get_tracks(query)

        embed = discord.Embed(color=discord.Color.blurple())

        if results.load_type == LoadType.EMPTY:
            return await context.send("I couldn't find any tracks for that query.")
        elif results.load_type == LoadType.PLAYLIST:
            tracks = results.tracks

            for track in tracks:
                player.add(track=track, requester=context.author.id)

            embed.title = 'Playlist Enqueued!'
            embed.description = f'{results.playlist_info.name} - {len(tracks)} tracks'
        else:
            track = results.tracks[0]
            embed.title = 'Track Enqueued'
            embed.description = f'[{track.title}]({track.uri})'

            player.add(track=track, requester=context.author.id)

        await context.send(embed=embed)

        if not player.is_playing:
            await player.play()

    @commands.hybrid_command(
        name="skip",
        description="Skip to the next song in the queue",
        usage="skip"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @commands.check(create_player)
    async def skip(self, context):
        await self.bot.lavalink.player_manager.get(context.guild.id).skip()

    @commands.hybrid_command(
        name="pause",
        description="Pauses the currently playing track",
        usage="pause"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @commands.check(create_player)
    async def pause(self, context):
        player = self.bot.lavalink.player_manager.get(context.guild.id)

        if player.is_playing:
            await player.set_pause(True)
            await context.send('⏸ | Paused the player.')

    @commands.hybrid_command(
        name="resume",
        description="Resumes the currently paused track",
        usage="resume"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @commands.check(create_player)
    async def resume(self, context):
        player = self.bot.lavalink.player_manager.get(context.guild.id)

        if player.paused:
            await player.set_pause(False)
            await context.send('▶ | Resumed the player.')

    @commands.hybrid_command(
        name="loop",
        description="Enables/disables the loop on the current track",
        aliases=['repeat'],
        usage="loop"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @commands.check(create_player)
    async def loop(self, context):
        player = self.bot.lavalink.player_manager.get(context.guild.id)
        player.loop = not player.loop

        await context.send(f"🔁 | {'Enabled' if player.loop else 'Disabled'} loop.")

    @commands.hybrid_group(
        name="filter",
        description="Commands for managing filters.",
        usage="filter <filter> <args>"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    async def filter(self, context: Context) -> None:
        prefix = await self.bot.get_prefix(context)

        cmds = "\n".join([f"{prefix}filter {cmd.name} - {cmd.description}" for cmd in self.filter.walk_commands()])

        embed = discord.Embed(
            title=f"Help: Filter", description="List of available commands:", color=0xBEBEFE
        )
        embed.add_field(
            name="Commands", value=f"```{cmds}```", inline=False
        )

        await context.send(embed=embed)

    @filter.command(
        name="lowpass",
        description="Sets the strength of the low pass filter",
        usage="filer lowpass <strength>"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @commands.check(create_player)
    async def lowpass(self, context, strength: float = 0.0):
        player = self.bot.lavalink.player_manager.get(context.guild.id)

        strength = max(0, strength)
        strength = min(1000, strength)

        if strength < 1 and strength != 0.0:
            return await context.send('The strength must be greater than 1.')

        embed = discord.Embed(color=discord.Color.blurple(), title='Low Pass Filter')

        if strength == 0.0:
            await player.remove_filter('lowpass')
            embed.description = 'Disabled **Low Pass Filter**'
            return await context.send(embed=embed)

        low_pass = LowPass()
        low_pass.update(smoothing=strength)

        await player.set_filter(low_pass)

        embed.description = f'Set **Low Pass Filter** strength to {strength}.'
        await context.send(embed=embed)


    @filter.command(
        name="pitch",
        description="Sets the player pitch",
        aliases=['ptch'],
        usage="filter pitch <pitch>"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @commands.check(create_player)
    async def pitch(self, context: Context, pitch: float):
        player = self.bot.lavalink.player_manager.get(context.guild.id)

        pitch = max(0.1, pitch)

        timescale = Timescale()
        timescale.pitch = pitch
        await player.set_filter(timescale)

        await context.send(f"🎵 | Set the player pitch to {pitch}.")


    @filter.command(
        name="speed",
        description="Sets the player speed",
        aliases=['spd'],
        usage="filter speed <speed>"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @commands.check(create_player)
    async def speed(self, context: Context, speed: float):
        player = self.bot.lavalink.player_manager.get(context.guild.id)

        speed = max(0.1, speed)

        timescale = Timescale()
        timescale.speed = speed
        await player.set_filter(timescale)

        await context.send(f"🏃 | Set the player speed to {speed}.")

    @commands.hybrid_command(
        name="disconnect",
        description="Disconnects the player from the voice channel and clears the queue",
        aliases=['dc', 'leave', 'stop'],
        usage="disconnect"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @commands.check(create_player)
    async def disconnect(self, context):
        player = self.bot.lavalink.player_manager.get(context.guild.id)

        player.queue.clear()
        await player.stop()
        await context.voice_client.disconnect(force=True)
        await context.send('✳ | Disconnected.')

    @commands.hybrid_command(
        name="volume",
        description="Sets the player volume",
        aliases=['vol'],
        usage="volume <volume>"
    )
    @commands.check(Checks.is_not_blacklisted)
    @commands.check(Checks.command_not_disabled)
    @commands.check(create_player)
    async def volume(self, context: Context, volume: int):
        player = self.bot.lavalink.player_manager.get(context.guild.id)

        volume = max(1, volume)
        volume = min(100, volume)

        await player.set_volume(volume)
        await context.send(f"🔊 | Set the player volume to {volume}.")


async def setup(bot) -> None:
    await bot.add_cog(Music(bot))


================================================
FILE: cogs/owner.py
================================================
# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon

import discord
import ast
import os
import sys
import pymongo
from datetime import datetime

from discord import app_commands
from discord.ext import commands
from discord.ext.commands import Context

from utils import CONSTANTS, DBClient, Checks, CachedDB

client = DBClient.client
db = client.potatobot

def insert_returns(body):
    # insert return stmt if the last expression is a expression statement
    if isinstance(body[-1], ast.Expr):
        body[-1] = ast.Return(body[-1].value)
        ast.fix_missing_locations(body[-1])

    # for if statements, we insert returns into the body and the orelse
    if isinstance(body[-1], ast.If):
        insert_returns(body[-1].body)
        insert_returns(body[-1].orelse)

    # for with blocks, again we insert returns into the body
    if isinstance(body[-1], ast.With):
        insert_returns(body[-1].body)

class Owner(commands.Cog, name="owner"):
    def __init__(self, bot) -> None:
        self.bot = bot

    @commands.hybrid_group(
        name="dev",
        description="Commands for devs",
        usage="dev <subcommand> [args]",
    )
    @commands.check(Checks.is_not_blacklisted)
    @app_commands.allowed_installs(guilds=True, users=True)
    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
    async def dev(self, context: Context) -> None:
        prefix = await self.bot.get_prefix(context)

        cmds = "\n".join([f"{prefix}dev {cmd.name} - {cmd.description}" for cmd in self.dev.walk_commands()])

        embed = discord.Embed(
            title=f"Help: Dev", description="List of available commands:", color=0xBEBEFE
        )
        embed.add_field(
            name="Commands", value=f"```{cmds}```", inline=False
        )

        await context.send(embed=embed)

    @dev.command(
        name="sync",
        description="Sync the slash commands.",
        usage="dev sync guild/global"
    )
    @app_commands.describe(scope="The scope of the sync. Can be `global` or `guild`")
    @commands.is_owner()
    async def sync(self, context: Context, scope: str) -> None:
        await context.defer()

        if scope == "global":
            await context.bot.tree.sync()
            embed = discord.Embed(
                description="Slash commands have been globally synchronized.",
                color=0xBEBEFE,
            )
            await context.send(embed=embed)
            return
        elif scope == "guild":
            context.bot.tree.copy_global_to(guild=context.guild)
            await context.bot.tree.sync(guild=context.guild)
            embed = discord.Embed(
                description="Slash commands have been synchronized in this guild.",
                color=0xBEBEFE,
            )
            await context.send(embed=embed)
            return
        embed = discord.Embed(
            description="The scope must be `global` or `guild`.", color=0xE02B2B
        )
        await context.send(embed=embed)

    @dev.command(
        name="unsync",
        description="Unsync the slash commands",
        usage="dev unsync guild/global"
    )
    @commands.is_owner()
    async def unsync(self, context: Context, scope: str) -> None:
        await context.defer()

        if scope == "global":
            context.bot.tree.clear_commands(guild=None)
            await context.bot.tree.sync()
            embed = discord.Embed(
                description="Slash commands have been globally unsynchronized.",
                color=0xBEBEFE,
            )
            await context.send(embed=embed)
            return
        elif scope == "guild":
            context.bot.tree.clear_commands(guild=context.guild)
            await context.bot.tree.sync(guild=context.guild)
            embed = discord.Embed(
                description="Slash commands have been unsynchronized in this guild.",
                color=0xBEBEFE,
            )
            await context.send(embed=embed)
            return
        embed = discord.Embed(
            description="The scope must be `global` or `guild`.", color=0xE02B2B
        )
        await context.send(embed=embed)

    @dev.command(
        name="sudo",
        description="sus",
        usage="dev sudo <user> <command> [args...]",
    )
    @commands.is_owner()
    async def sudo(self, context: Context, user: discord.Member, *, command: str) -> None:
        message = context.message
        message.author = user
        message.content = context.prefix + command
        await self.bot.process_commands(message)

    @dev.command(
        name="load",
        description="Load a cog",
        usage="dev load <cog>",
    )
    @commands.is_owner()
    @app_commands.allowed_installs(guilds=True, users=True)
    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
    async def load(self, context: Context, cog: str) -> None:
        try:
            await self.bot.load_extension(f"cogs.{cog}")
        except Exception:
            embed = discord.Embed(
                description=f"Could not load the `{cog}` cog.", color=0xE02B2B
            )
            await context.send(embed=embed)
            return
        embed = discord.Embed(
            description=f"Successfully loaded the `{cog}` cog.", color=0xBEBEFE
        )
        await context.send(embed=embed)

    @dev.command(
        name="unload",
        description="Unloads a cog.",
        usage="dev unload <cog>",
    )
    @commands.is_owner()
    @app_
Download .txt
gitextract_qm_y2xv1/

├── .gitignore
├── Dockerfile
├── LICENSE
├── README.md
├── bot.py
├── cogs/
│   ├── ai.py
│   ├── api.py
│   ├── code.py
│   ├── economy.py
│   ├── fun.py
│   ├── general.py
│   ├── github.py
│   ├── giveaway.py
│   ├── level.py
│   ├── music.py
│   ├── owner.py
│   ├── reactionroles.py
│   ├── security.py
│   ├── server.py
│   ├── staff.py
│   ├── starboard.py
│   ├── stats.py
│   ├── ticket.py
│   └── utility.py
├── config.example.json
├── main.py
├── requirements.txt
├── ui/
│   ├── code.py
│   ├── farm.py
│   ├── gambling.py
│   ├── papertrading.py
│   ├── recreate.py
│   ├── setup.py
│   ├── starboard.py
│   ├── ticket.py
│   └── translate.py
└── utils/
    ├── CONSTANTS.py
    ├── CachedDB.py
    ├── Checks.py
    ├── DBClient.py
    ├── ErrorLogger.py
    ├── Errors.py
    └── ServerLogger.py
Download .txt
SYMBOL INDEX (497 symbols across 36 files)

FILE: bot.py
  class LoggingFormatter (line 45) | class LoggingFormatter(logging.Formatter):
    method format (line 63) | def format(self, record):
  class DiscordBot (line 86) | class DiscordBot(commands.AutoShardedBot):
    method __init__ (line 87) | def __init__(self) -> None:
    method get_prefix (line 101) | async def get_prefix(self, message):
    method load_cogs (line 111) | async def load_cogs(self) -> None:
    method status_task (line 125) | async def status_task(self) -> None:
    method before_status_task (line 130) | async def before_status_task(self) -> None:
    method setup_hook (line 134) | async def setup_hook(self) -> None:
    method on_guild_remove (line 170) | async def on_guild_remove(self, guild: discord.Guild):
    method on_guild_join (line 184) | async def on_guild_join(self, guild: discord.Guild):
    method on_error (line 198) | async def on_error(self, event_method, *args, **kwargs):
    method on_message (line 201) | async def on_message(self, message: discord.Message) -> None:
    method on_command_completion (line 234) | async def on_command_completion(self, context: commands.Context) -> None:
    method on_command_error (line 252) | async def on_command_error(self, context: commands.Context, error) -> ...

FILE: cogs/ai.py
  function get_api_key (line 99) | def get_api_key():
  function prompt_ai (line 110) | def prompt_ai(
  class Text2ImageAPI (line 270) | class Text2ImageAPI:
    method __init__ (line 271) | def __init__(self, url):
    method get_model (line 280) | def get_model(self):
    method generate (line 285) | def generate(self, prompt, model, images=1, width=1024, height=1024, s...
    method check_generation (line 305) | def check_generation(self, request_id, attempts=10, delay=10):
  class Ai (line 319) | class Ai(commands.Cog, name="🤖 AI"):
    method __init__ (line 320) | def __init__(self, bot) -> None:
    method on_message (line 330) | async def on_message(self, message: discord.Message) -> None:
    method purge_conversations (line 530) | async def purge_conversations(self):
    method ai (line 544) | async def ai(self, context: Context, *, prompt: str) -> None:
    method set_ai_channel (line 646) | async def set_ai_channel(self, context: Context):
    method unset_ai_channel (line 699) | async def unset_ai_channel(self, context: Context):
    method create_ai_thread (line 723) | async def create_ai_thread(self, context: Context, *, prompt = "Hello"...
    method ai_image (line 787) | async def ai_image(self, context: commands.Context, prompt: str) -> None:
    method imagine (line 864) | async def imagine(self, context: commands.Context, model: str = "none"...
    method generate_image (line 960) | def generate_image(self, context: commands.Context, prompt: str, width...
    method system_prompt (line 983) | async def system_prompt(self, context: Context, *, prompt: str = "") -...
    method reset_ai (line 1017) | async def reset_ai(self, context: Context) -> None:
    method toggle_ai (line 1027) | async def toggle_ai(self, context: Context) -> None:
  function setup (line 1035) | async def setup(bot) -> None:

FILE: cogs/api.py
  class Api (line 12) | class Api(commands.Cog, name="🌐 API"):
    method __init__ (line 13) | def __init__(self, bot) -> None:
    method api (line 25) | async def api(self, context: Context) -> None:
    method api_minecraft (line 47) | async def api_minecraft(self, context: Context, *, username: str) -> N...
    method api_mc_server (line 61) | async def api_mc_server(self, context: Context, *, host: str) -> None:
  function setup (line 116) | async def setup(bot) -> None:

FILE: cogs/code.py
  class Code (line 24) | class Code(commands.Cog, name="💻 Code"):
    method __init__ (line 25) | def __init__(self, bot) -> None:
    method code (line 37) | async def code(self, context: Context) -> None:
  function setup (line 43) | async def setup(bot) -> None:

FILE: cogs/economy.py
  class Economy (line 19) | class Economy(commands.Cog, name="🪙 Economy"):
    method __init__ (line 20) | def __init__(self, bot) -> None:
    method wallet (line 32) | async def wallet(self, context: Context, user: discord.Member = None) ...
    method daily (line 51) | async def daily(self, context: Context) -> None:
    method beg (line 89) | async def beg(self, context: Context) -> None:
    method rob (line 116) | async def rob(self, context: Context, user: discord.Member) -> None:
    method baltop (line 198) | async def baltop(self, context: Context) -> None:
    method pay (line 230) | async def pay(self, context: Context, user: discord.Member, amount: in...
    method set (line 276) | async def set(self, context: Context, user: discord.Member, amount: in...
    method gamble (line 301) | async def gamble(self, context: Context, amount: int) -> None:
    method stockmarket (line 332) | async def stockmarket(self, context: Context) -> None:
    method farm (line 344) | async def farm(self, context: Context) -> None:
  function setup (line 414) | async def setup(bot) -> None:

FILE: cogs/fun.py
  class TicTacToeButton (line 23) | class TicTacToeButton(Button):
    method __init__ (line 24) | def __init__(self, x: int, y: int, player_x: discord.Member, player_o:...
    method callback (line 31) | async def callback(self, interaction: discord.Interaction):
  class TicTacToeView (line 57) | class TicTacToeView(View):
    method __init__ (line 58) | def __init__(self, player_x: discord.Member, player_o: discord.Member):
    method check_winner (line 69) | def check_winner(self):
  class Fun (line 94) | class Fun(commands.Cog, name="🎉 Fun"):
    method __init__ (line 95) | def __init__(self, bot) -> None:
    method joos (line 105) | async def joos(self, context: Context) -> None:
    method http (line 117) | async def http(self, context: Context) -> None:
    method http_cat (line 138) | async def http_cat(self, context: Context, code) -> None:
    method http_dog (line 148) | async def http_dog(self, context: Context, code) -> None:
    method http_fish (line 158) | async def http_fish(self, context: Context, code) -> None:
    method http_goat (line 168) | async def http_goat(self, context: Context, code) -> None:
    method bored (line 179) | async def bored(self, context: Context) -> None:
    method advice (line 215) | async def advice(self, context: Context) -> None:
    method insult (line 230) | async def insult(self, context: Context) -> None:
    method gif (line 247) | async def gif(self, context: Context, *, query="NONE") -> None:
    method avatar (line 296) | async def avatar(self, context: Context) -> None:
    method get (line 317) | async def get(self, context: Context, user: discord.User = None) -> None:
    method blur (line 337) | async def blur(self, context: Context, user: discord.User = None) -> N...
    method pixelate (line 356) | async def pixelate(self, context: Context, user: discord.User = None) ...
    method trigger (line 375) | async def trigger(self, context: Context, user: discord.User = None) -...
    method jail (line 394) | async def jail(self, context: Context, user: discord.User = None) -> N...
    method wasted (line 413) | async def wasted(self, context: Context, user: discord.User = None) ->...
    method passed (line 432) | async def passed(self, context: Context, user: discord.User = None) ->...
    method trans (line 451) | async def trans(self, context: Context, user: discord.User = None) -> ...
    method random (line 472) | async def random(self, context: Context) -> None:
    method boykisser (line 495) | async def boykisser(self, context: Context) -> None:
    method gayrate (line 514) | async def gayrate(self, context: Context, user: discord.User = None) -...
    method random_cat (line 540) | async def random_cat(self, context: Context) -> None:
    method random_cat (line 559) | async def random_cat(self, context: Context) -> None:
    method random_dog (line 579) | async def random_dog(self, context: Context) -> None:
    method random_bird (line 598) | async def random_bird(self, context: Context) -> None:
    method random_fox (line 618) | async def random_fox(self, context: Context) -> None:
    method random_kangaroo (line 638) | async def random_kangaroo(self, context: Context) -> None:
    method random_koala (line 657) | async def random_koala(self, context: Context) -> None:
    method random_panda (line 676) | async def random_panda(self, context: Context) -> None:
    method random_raccoon (line 696) | async def random_raccoon(self, context: Context) -> None:
    method random_red_panda (line 716) | async def random_red_panda(self, context: Context) -> None:
    method image (line 736) | async def image(self, context: Context) -> None:
    method youtube (line 757) | async def youtube(self, context: Context, user: discord.User, *, text:...
    method tweet (line 776) | async def tweet(self, context: Context, user: discord.User, *, tweet: ...
    method tictactoe (line 799) | async def tictactoe(self, context: Context, opponent: discord.User) ->...
    method togif (line 821) | async def togif(self, context: Context, attachment: discord.Attachment...
  function setup (line 850) | async def setup(bot) -> None:

FILE: cogs/general.py
  class General (line 37) | class General(commands.Cog, name="⬜ General"):
    method __init__ (line 38) | def __init__(self, bot) -> None:
    method ctx_remove_spoilers (line 53) | async def ctx_remove_spoilers(
    method ctx_translate (line 70) | async def ctx_translate(
    method help (line 87) | async def help(self, context: Context, *, command: str = "none") -> None:
    method uptime (line 192) | async def uptime(self, context: Context):
    method botinfo (line 206) | async def botinfo(self, context: Context) -> None:
    method ping (line 244) | async def ping(self, context: Context) -> None:
    method bug (line 261) | async def bug(self, context: Context, *, bug: str) -> None:
    method eight_ball (line 285) | async def eight_ball(self, context: Context, *, question: str) -> None:
    method support (line 321) | async def support(self, context: commands.Context) -> None:
    method define (line 334) | async def define(self, context: Context, *, word: str) -> None:
    method urban_dict (line 371) | async def urban_dict(self, context: Context, *, term: str):
    method reddit (line 398) | async def reddit(self, context: Context, subreddit: str = "") -> None:
    method vote (line 468) | async def vote(self, context: Context):
  class VoteButton (line 478) | class VoteButton(discord.ui.Button):
    method __init__ (line 479) | def __init__(self):
    method callback (line 482) | async def callback(self, interaction: discord.Interaction):
  class VoteView (line 485) | class VoteView(discord.ui.View):
    method __init__ (line 486) | def __init__(self):
  class CogSelect (line 490) | class CogSelect(discord.ui.Select):
    method __init__ (line 491) | def __init__(self, cogs, author):
    method callback (line 499) | async def callback(self, interaction: discord.Interaction):
  class CogSelectView (line 524) | class CogSelectView(discord.ui.View):
    method __init__ (line 525) | def __init__(self, cogs, author):
  function setup (line 529) | async def setup(bot) -> None:

FILE: cogs/github.py
  class Github (line 27) | class Github(commands.Cog, name="🖧 Github"):
    method __init__ (line 28) | def __init__(self, bot) -> None:
    method github (line 41) | async def github(self, context: Context) -> None:
    method ghuser (line 63) | async def ghuser(self, context, user: str):
    method ghsearchrepo (line 109) | async def ghsearchrepo(self, context, query: str):
  class ProfileButton (line 163) | class ProfileButton(discord.ui.View):
    method __init__ (line 164) | def __init__(self, url: str):
  class RepoButton (line 169) | class RepoButton(discord.ui.View):
    method __init__ (line 170) | def __init__(self, url: str):
  function setup (line 175) | async def setup(bot) -> None:

FILE: cogs/giveaway.py
  class Giveaway (line 11) | class Giveaway(commands.Cog, name="🎁 Giveaway"):
    method __init__ (line 12) | def __init__(self, bot) -> None:
    method giveaway (line 23) | async def giveaway(self, context: Context) -> None:
    method giveaway_start (line 45) | async def giveaway_start(self, context: Context, *, reward: str) -> None:
    method giveaway_end (line 60) | async def giveaway_end(self, context: Context, message_id) -> None:
  function setup (line 77) | async def setup(bot) -> None:

FILE: cogs/level.py
  class Level (line 16) | class Level(commands.Cog, name="🚀 Level"):
    method __init__ (line 17) | def __init__(self, bot) -> None:
    method level (line 28) | async def level(self, context: Context, user: discord.Member = None) -...
    method leaderboard (line 74) | async def leaderboard(self, context: Context) -> None:
    method on_message (line 114) | async def on_message(self, message: discord.Message) -> None:
    method create_level_roles (line 177) | async def create_level_roles(self, context: Context):
    method delete_level_roles (line 205) | async def delete_level_roles(self, context: Context):
  function setup (line 226) | async def setup(bot) -> None:

FILE: cogs/music.py
  class LavalinkVoiceClient (line 29) | class LavalinkVoiceClient(discord.VoiceProtocol):
    method __init__ (line 30) | def __init__(self, client: discord.Client, channel: discord.abc.Connec...
    method on_voice_server_update (line 43) | async def on_voice_server_update(self, data):
    method on_voice_state_update (line 50) | async def on_voice_state_update(self, data):
    method connect (line 66) | async def connect(self, *, timeout: float, reconnect: bool, self_deaf:...
    method disconnect (line 70) | async def disconnect(self, *, force: bool = False) -> None:
    method _destroy (line 80) | async def _destroy(self):
  class Music (line 94) | class Music(commands.Cog, name="🎵 Music"):
    method __init__ (line 95) | def __init__(self, bot):
    method cog_unload (line 106) | def cog_unload(self):
    method cog_command_error (line 109) | async def cog_command_error(self, context, error):
    method create_player (line 113) | async def create_player(context: commands.Context):
    method on_track_start (line 152) | async def on_track_start(self, event: TrackStartEvent):
    method on_queue_end (line 169) | async def on_queue_end(self, event: QueueEndEvent):
    method play (line 185) | async def play(self, context, *, query: str):
    method skip (line 226) | async def skip(self, context):
    method pause (line 237) | async def pause(self, context):
    method resume (line 252) | async def resume(self, context):
    method loop (line 268) | async def loop(self, context):
    method filter (line 281) | async def filter(self, context: Context) -> None:
    method lowpass (line 303) | async def lowpass(self, context, strength: float = 0.0):
    method pitch (line 337) | async def pitch(self, context: Context, pitch: float):
    method speed (line 358) | async def speed(self, context: Context, speed: float):
    method disconnect (line 378) | async def disconnect(self, context):
    method volume (line 395) | async def volume(self, context: Context, volume: int):
  function setup (line 405) | async def setup(bot) -> None:

FILE: cogs/owner.py
  function insert_returns (line 19) | def insert_returns(body):
  class Owner (line 34) | class Owner(commands.Cog, name="owner"):
    method __init__ (line 35) | def __init__(self, bot) -> None:
    method dev (line 46) | async def dev(self, context: Context) -> None:
    method sync (line 67) | async def sync(self, context: Context, scope: str) -> None:
    method unsync (line 98) | async def unsync(self, context: Context, scope: str) -> None:
    method sudo (line 130) | async def sudo(self, context: Context, user: discord.Member, *, comman...
    method load (line 144) | async def load(self, context: Context, cog: str) -> None:
    method unload (line 166) | async def unload(self, context: Context, cog: str) -> None:
    method reload (line 189) | async def reload(self, context: Context, cog: str) -> None:
    method shutdown (line 209) | async def shutdown(self, context: Context) -> None:
    method say (line 220) | async def say(self, context: Context, *, message: str) -> None:
    method embed (line 229) | async def embed(self, context: Context, description: str = "", title: ...
    method reply (line 244) | async def reply(self, context: Context, message: discord.Message, *, r...
    method eval (line 255) | async def eval(self, context, *, cmd: str):
    method enable_ai (line 291) | async def enable_ai(self, context, server: int = 0):
    method disable_ai (line 316) | async def disable_ai(self, context, server_id: int = 0):
    method blacklist (line 343) | async def blacklist(self, context, user: discord.User, *, reason: str ...
    method unblacklist (line 381) | async def unblacklist(self, context, user: discord.User):
    method ai_ignore (line 416) | async def ai_ignore(self, context, user: discord.User, *, reason: str ...
    method ai_unignore (line 441) | async def ai_unignore(self, context, user: discord.User):
    method inspect (line 466) | async def inspect(self, context, user: discord.User):
    method inspect_clear (line 501) | async def inspect_clear(self, context: Context, user: discord.Member):
    method top_flagged (line 520) | async def top_flagged(self, context):
    method top_nsfw (line 543) | async def top_nsfw(self, context):
    method ai_announce (line 566) | async def ai_announce(self, context, *, message: str):
    method copy_db_to_backup (line 586) | async def copy_db_to_backup(self, context):
    method force_system_prompt (line 733) | async def force_system_prompt(self, context: Context, *, prompt: str) ...
    method strikes (line 751) | async def strikes(self, context: Context):
    method add (line 770) | async def add(self, context: Context, user: discord.User, *, reason: s...
    method remove (line 806) | async def remove(self, context: Context, user: discord.User, id: int):
    method list (line 847) | async def list(self, context: Context, user: discord.User):
    method dm (line 874) | async def dm(self, context: Context, user: discord.User, *, message: s...
    method simulate_level_up (line 887) | async def simulate_level_up(self, context: Context):
  function setup (line 909) | async def setup(bot) -> None:

FILE: cogs/reactionroles.py
  class ReactionRoles (line 14) | class ReactionRoles(commands.Cog, name="🇺🇸 Reaction Roles"):
    method __init__ (line 15) | def __init__(self, bot) -> None:
    method on_raw_reaction_add (line 19) | async def on_raw_reaction_add(self, payload) -> None:
    method on_raw_reaction_remove (line 54) | async def on_raw_reaction_remove(self, payload) -> None:
    method reactionroles (line 103) | async def reactionroles(self, context: Context) -> None:
    method add (line 130) | async def add(self, context: commands.Context, message_id: str, role: ...
  function setup (line 174) | async def setup(bot) -> None:

FILE: cogs/security.py
  class Security (line 32) | class Security(commands.Cog, name="🛡️ Security"):
    method __init__ (line 33) | def __init__(self, bot) -> None:
    method clear_cache (line 38) | async def clear_cache(self) -> None:
    method on_message (line 48) | async def on_message(self, message: discord.Message) -> None:
    method on_guild_role_create (line 240) | async def on_guild_role_create(self, role: discord.Role) -> None:
    method on_guild_role_update (line 307) | async def on_guild_role_update(self, before: discord.Role, after: disc...
    method on_member_ban (line 419) | async def on_member_ban(self, discord_guild: discord.Guild, banned_use...
    method on_member_remove (line 517) | async def on_member_remove(self, member: discord.Member) -> None:
    method on_guild_channel_delete (line 610) | async def on_guild_channel_delete(self, channel: discord.TextChannel) ...
    method on_member_join (line 763) | async def on_member_join(self, member: discord.Member):
    method whitelist (line 781) | async def whitelist(self, context: Context) -> None:
    method add (line 801) | async def add(self, context: Context, user: discord.Member) -> None:
    method remove (line 831) | async def remove(self, context: Context, user: discord.Member) -> None:
    method list (line 861) | async def list(self, context: Context) -> None:
    method trusted (line 885) | async def trusted(self, context: Context) -> None:
    method trusted_add (line 905) | async def trusted_add(self, context: Context, user: discord.Member) ->...
    method trusted_remove (line 935) | async def trusted_remove(self, context: Context, user: discord.Member)...
    method trusted_list (line 965) | async def trusted_list(self, context: Context) -> None:
    method antinuke (line 991) | async def antinuke(self, context: Context) -> None:
    method anti_danger_perms (line 1023) | async def anti_danger_perms(self, context: Context, enabled: bool) -> ...
    method anti_massban (line 1084) | async def anti_massban(self, context: Context, enabled: bool) -> None:
    method anti_masskick (line 1144) | async def anti_masskick(self, context: Context, enabled: bool) -> None:
    method anti_massdelete (line 1205) | async def anti_massdelete(self, context: Context, enabled: bool) -> None:
    method massping (line 1265) | async def massping(self, context: Context, enabled: bool) -> None:
    method anti_webhook_spam (line 1325) | async def anti_webhook_spam(self, context: Context, enabled: bool) -> ...
    method lockdown (line 1385) | async def lockdown(self, context: Context) -> None:
    method unlockdown (line 1424) | async def unlockdown(self, context: Context) -> None:
  class ConfirmView (line 1476) | class ConfirmView(discord.ui.View):
    method __init__ (line 1477) | def __init__(self, value: str, author: discord.Member):
    method confirm (line 1484) | async def confirm(self, interaction: discord.Interaction, button: disc...
    method cancel (line 1521) | async def cancel(self, interaction: discord.Interaction, button: disco...
  function setup (line 1527) | async def setup(bot) -> None:

FILE: cogs/server.py
  class Server (line 18) | class Server(commands.Cog, name="⚙️ Server"):
    method __init__ (line 19) | def __init__(self, bot) -> None:
    method setup (line 29) | async def setup(self, context: Context) -> None:
    method prefix (line 49) | async def prefix(self, context: commands.Context, prefix: str = "none"):
    method groq_api_key (line 68) | async def groq_api_key(self, context: commands.Context, key: str):
    method stealemoji (line 101) | async def stealemoji(self, context: Context, emoji: discord.PartialEmo...
    method emojifromurl (line 126) | async def emojifromurl(self, context: Context, url: str, name: str) ->...
    method settings (line 153) | async def settings(self, context: Context) -> None:
    method show (line 179) | async def show(self, context: Context) -> None:
    method should_announce_levelup (line 215) | async def should_announce_levelup(self, context: Context, enabled: boo...
    method daily_cash (line 236) | async def daily_cash(self, context: Context, amount: int) -> None:
    method tickets_category (line 258) | async def tickets_category(self, context: Context, category: discord.C...
    method level_up_channel (line 280) | async def level_up_channel(self, context: Context, channel: discord.Te...
    method tickets_support_role (line 302) | async def tickets_support_role(self, context: Context, role: discord.R...
    method log_channel (line 324) | async def log_channel(self, context: Context, channel: discord.TextCha...
    method default_role (line 346) | async def default_role(self, context: Context, role: discord.Role) -> ...
    method level_roles (line 385) | async def level_roles(self, context: Context) -> None:
    method show_level_roles (line 414) | async def show_level_roles(self, context: Context) -> None:
    method set (line 442) | async def set(self, context: Context, level: int, role: discord.Role) ...
    method cmd (line 466) | async def cmd(self, context: Context) -> None:
    method disable (line 487) | async def disable(self, context: Context, *, command: str) -> None:
    method cmd_enable (line 518) | async def cmd_enable(self, context: Context, *, command: str) -> None:
  function setup (line 540) | async def setup(bot) -> None:

FILE: cogs/staff.py
  class Staff (line 20) | class Staff(commands.Cog, name="👮‍♂️ Staff"):
    method __init__ (line 21) | def __init__(self, bot) -> None:
    method on_message_delete (line 26) | async def on_message_delete(self, message: discord.Message) -> None:
    method on_message_edit (line 62) | async def on_message_edit(self, before: discord.Message, after: discor...
    method on_member_remove (line 106) | async def on_member_remove(self, user: discord.User) -> None:
    method on_member_ban (line 133) | async def on_member_ban(self, guild: discord.Guild, user: discord.User...
    method on_member_unban (line 159) | async def on_member_unban(self, guild: discord.Guild, user: discord.Us...
    method on_member_kick (line 185) | async def on_member_kick(self, guild: discord.Guild, user: discord.Use...
    method on_member_join (line 211) | async def on_member_join(self, user: discord.User) -> None:
    method on_bulk_message_delete (line 263) | async def on_bulk_message_delete(self, messages) -> None:
    method on_guild_channel_create (line 288) | async def on_guild_channel_create(self, channel: discord.TextChannel):
    method on_guild_channel_delete (line 313) | async def on_guild_channel_delete(self, channel: discord.TextChannel):
    method kick (line 353) | async def kick(
    method nick (line 431) | async def nick(
    method ban (line 459) | async def ban(
    method hackban (line 545) | async def hackban(self, context: Context, user: discord.User, *, reaso...
    method softban (line 598) | async def softban(self, context: Context, user: discord.Member):
    method unban (line 643) | async def unban(self, context: Context, user: discord.User):
    method purge (line 709) | async def purge(self, context: Context, amount: int) -> None:
    method archive (line 727) | async def archive(self, context: Context, limit: int = 10) -> None:
    method mute (line 763) | async def mute(self, context: Context, user: discord.Member, time: str...
    method unmute (line 819) | async def unmute(self, context: Context, user: discord.Member, *, reas...
    method lockdown (line 838) | async def lockdown(self, context: Context, channel: discord.TextChanne...
    method unlock (line 862) | async def unlock(self, context: Context, channel: discord.TextChannel ...
    method jail (line 887) | async def jail(self, context: Context, user: discord.Member, *, reason...
    method unjail (line 995) | async def unjail(self, context: Context, user: discord.Member):
    method warnings (line 1024) | async def warnings(self, context: Context) -> None:
    method warn (line 1051) | async def warn(self, context: Context, user: discord.Member, *, reason...
    method listwarnings (line 1078) | async def listwarnings(self, context: Context, user: discord.Member) -...
    method clearwarnings (line 1109) | async def clearwarnings(self, context: Context, user: discord.Member) ...
    method recreate (line 1132) | async def recreate(self, context: Context, channel: discord.TextChanne...
  function setup (line 1138) | async def setup(bot) -> None:

FILE: cogs/starboard.py
  class Starboard (line 13) | class Starboard(commands.Cog, name="⭐ Starboard"):
    method __init__ (line 14) | def __init__(self, bot) -> None:
    method on_raw_reaction_add (line 18) | async def on_raw_reaction_add(self, payload) -> None:
    method on_raw_reaction_remove (line 93) | async def on_raw_reaction_remove(self, payload) -> None:
    method starboard (line 153) | async def starboard(self, context: Context) -> None:
    method set_starboard (line 181) | async def set_starboard(self, context: Context, channel: discord.TextC...
    method set_threshold (line 206) | async def set_threshold(self, context: Context, threshold: int) -> None:
    method disable_starboard (line 231) | async def disable_starboard(self, context: Context) -> None:
    method enable_starboard (line 257) | async def enable_starboard(self, context: Context) -> None:
  function setup (line 274) | async def setup(bot) -> None:

FILE: cogs/stats.py
  function textangle (line 18) | def textangle(draw, text, xy, angle, fill, font):
  class Stats (line 25) | class Stats(commands.Cog, name="📈 Stats"):
    method __init__ (line 26) | def __init__(self, bot) -> None:
    method on_message (line 32) | async def on_message(self, message: discord.Message):
    method chart (line 69) | async def chart(self, context: Context) -> None:
    method messages (line 95) | async def messages(self, context: Context) -> None:
    method members (line 153) | async def members(self, context: Context) -> None:
  function setup (line 202) | async def setup(bot) -> None:

FILE: cogs/ticket.py
  class Ticket (line 15) | class Ticket(commands.Cog, name="🎫 Ticket"):
    method __init__ (line 16) | def __init__(self, bot) -> None:
    method ticketembed (line 27) | async def ticketembed(self, context):
    method open (line 43) | async def open(self, context: Context):
    method ticket (line 111) | async def ticket(self, context: Context):
    method upgrade (line 138) | async def upgrade(self, context: Context):
    method downgrade (line 172) | async def downgrade(self, context: Context):
    method add (line 209) | async def add(self, context: Context, user: discord.Member):
    method remove (line 241) | async def remove(self, context: Context, user: discord.Member):
    method claim (line 276) | async def claim(self, context: Context):
    method unclaim (line 319) | async def unclaim(self, context: Context):
    method close (line 355) | async def close(self, context: Context):
  function setup (line 430) | async def setup(bot) -> None:

FILE: cogs/utility.py
  class Utility (line 18) | class Utility(commands.Cog, name="⚡ Utility"):
    method __init__ (line 19) | def __init__(self, bot) -> None:
    method convert (line 31) | async def convert(self, context: Context) -> None:
    method convert_mb_gb (line 52) | async def convert_mb_gb(self, context: Context, mb: float, binary: boo...
    method convert_gb_mb (line 67) | async def convert_gb_mb(self, context: Context, gb: float, binary: boo...
    method convert_gb_tb (line 82) | async def convert_gb_tb(self, context: Context, gb: float, binary: boo...
    method convert_tb_gb (line 97) | async def convert_tb_gb(self, context: Context, tb: float, binary: boo...
    method calc (line 115) | async def calc(self, context: Context, *, expression: str) -> None:
    method translate (line 140) | async def translate(self, context: Context, language, *, text: str) ->...
    method color (line 161) | async def color(self, context: Context, color: str) -> None:
  function setup (line 197) | async def setup(bot) -> None:

FILE: main.py
  class JSONEncoder (line 46) | class JSONEncoder(json.JSONEncoder):
    method default (line 47) | def default(self, obj):
  function read_root (line 55) | async def read_root():
  function read_api_root (line 59) | async def read_api_root():
  function get_commands (line 63) | async def get_commands(cog: Optional[str] = "all"):
  function get_cogs (line 96) | async def get_cogs():
  function get_guild (line 103) | async def get_guild(id: int):
  function get_user (line 129) | async def get_user(id: int):
  function get_stats (line 164) | async def get_stats():
  function run_fastapi (line 171) | def run_fastapi():

FILE: ui/code.py
  class CodeModal (line 5) | class CodeModal(ui.Modal, title = "Run Code"):
    method on_submit (line 9) | async def on_submit(self, interaction: discord.Interaction) -> None:

FILE: ui/farm.py
  class FarmModal (line 11) | class FarmModal(Modal, title = "Buy Saplings (5$ per sapling)"):
    method __init__ (line 12) | def __init__(self, message):
    method on_submit (line 19) | async def on_submit(self, interaction: discord.Interaction) -> None:
  class FarmButton (line 88) | class FarmButton(View):
    method __init__ (line 89) | def __init__(self, authorid):
    method farm (line 95) | async def farm(self, interaction: discord.Interaction, button: discord...
    method plant (line 103) | async def plant(self, interaction: discord.Interaction, button: discor...
    method harvest (line 175) | async def harvest(self, interaction: discord.Interaction, button: disc...

FILE: ui/gambling.py
  class GamblingButton (line 12) | class GamblingButton(View):
    method __init__ (line 13) | def __init__(self, amount, authorid):
    method coinflip (line 19) | async def coinflip(self, interaction: discord.Interaction, button: dis...
    method diceroll (line 26) | async def diceroll(self, interaction: discord.Interaction, button: dis...
    method blackjack (line 33) | async def blackjack(self, interaction: discord.Interaction, button: di...
    method slots (line 41) | async def slots(self, interaction: discord.Interaction, button: discor...
  class BlackjackView (line 47) | class BlackjackView(View):
    method __init__ (line 48) | def __init__(self, amount, authorid):
    method create_deck (line 59) | def create_deck(self):
    method calculate_score (line 67) | def calculate_score(self, hand):
    method update_embed (line 84) | def update_embed(self):
    method hit (line 91) | async def hit(self, interaction: discord.Interaction, button: discord....
    method stand (line 128) | async def stand(self, interaction: discord.Interaction, button: discor...
    method interaction_check (line 171) | async def interaction_check(self, interaction: discord.Interaction) ->...
    method on_timeout (line 174) | async def on_timeout(self):
    method start_game (line 178) | async def start_game(self, interaction: discord.Interaction):
  class HeadsOrTailsButton (line 182) | class HeadsOrTailsButton(View):
    method __init__ (line 183) | def __init__(self, amount, authorid):
    method heads (line 189) | async def heads(self, interaction: discord.Interaction, button: Button):
    method tails (line 218) | async def tails(self, interaction: discord.Interaction, button: Button):
  class RollButton (line 247) | class RollButton(View):
    method __init__ (line 248) | def __init__(self, amount, authorid):
    method one (line 254) | async def one(self, interaction: discord.Interaction, button: button):
    method two (line 282) | async def two(self, interaction: discord.Interaction, button: button):
    method three (line 310) | async def three(self, interaction: discord.Interaction, button: button):
    method four (line 339) | async def four(self, interaction: discord.Interaction, button: button):
    method five (line 368) | async def five(self, interaction: discord.Interaction, button: button):
    method six (line 396) | async def six(self, interaction: discord.Interaction, button: button):
  class SlotsButton (line 426) | class SlotsButton(View):
    method __init__ (line 427) | def __init__(self, amount, multii, authorid):
    method getEmbed (line 435) | def getEmbed(self):
    method spin (line 442) | async def spin(self, interaction: discord.Interaction, button: discord...
    method increment_multiplier (line 460) | async def increment_multiplier(self, interaction: discord.Interaction,...
    method decrement_multiplier (line 468) | async def decrement_multiplier(self, interaction: discord.Interaction,...
  function play_slots (line 476) | def play_slots(amount, multii):

FILE: ui/papertrading.py
  class StockPortfolioView (line 32) | class StockPortfolioView(View):
    method __init__ (line 33) | def __init__(self, authorid):
    method buy_stocks (line 39) | async def buy_stocks(self, interaction: discord.Interaction, button: d...
    method sell_stocks (line 56) | async def sell_stocks(self, interaction: discord.Interaction, button: ...
    method view_portfolio (line 73) | async def view_portfolio(self, interaction: discord.Interaction, butto...
  class BuyStocksModal (line 111) | class BuyStocksModal(ui.Modal, title="Buy Stocks"):
    method __init__ (line 112) | def __init__(self, authorid):
    method on_submit (line 119) | async def on_submit(self, interaction: discord.Interaction):
  class SellStocksModal (line 192) | class SellStocksModal(ui.Modal, title="Sell Stocks"):
    method __init__ (line 193) | def __init__(self, authorid):
    method on_submit (line 200) | async def on_submit(self, interaction: discord.Interaction):
  function get_stock_price (line 260) | async def get_stock_price(symbol):
  function start_paper_trading (line 277) | async def start_paper_trading(ctx):

FILE: ui/recreate.py
  class deleteconfirm (line 3) | class deleteconfirm(discord.ui.View):
    method __init__ (line 4) | def __init__(self, user, channel):
    method yes (line 10) | async def yes(self, interaction: discord.Interaction, button: discord....
    method no (line 25) | async def no(self, interaction: discord.Interaction, button: discord.u...

FILE: ui/setup.py
  class StartSetupView (line 8) | class StartSetupView(discord.ui.View):
    method __init__ (line 9) | def __init__(self, server_id) -> None:
    method start_setup (line 14) | async def start_setup(self, interaction: discord.Interaction, button: ...
  class TicketSetupView (line 27) | class TicketSetupView(discord.ui.View):
    method __init__ (line 28) | def __init__(self, server_id) -> None:
    method yes (line 33) | async def yes(self, interaction: discord.Interaction, button: discord....
    method skip (line 49) | async def skip(self, interaction: discord.Interaction, button: discord...
  class TicketCategorySelect (line 58) | class TicketCategorySelect(discord.ui.Select):
    method __init__ (line 59) | def __init__(self, server_id, categories) -> None:
    method callback (line 63) | async def callback(self, interaction: discord.Interaction) -> None:
  class TicketCategoryView (line 108) | class TicketCategoryView(discord.ui.View):
    method __init__ (line 109) | def __init__(self, server_id, categories) -> None:
  class TicketSupportRoleSelect (line 116) | class TicketSupportRoleSelect(discord.ui.Select):
    method __init__ (line 117) | def __init__(self, server_id, roles) -> None:
    method callback (line 121) | async def callback(self, interaction: discord.Interaction) -> None:
  class TicketSupportRoleView (line 137) | class TicketSupportRoleView(discord.ui.View):
    method __init__ (line 138) | def __init__(self, server_id, roles) -> None:
  class LevelingSetupView (line 144) | class LevelingSetupView(discord.ui.View):
    method __init__ (line 145) | def __init__(self, server_id) -> None:
    method yes (line 150) | async def yes(self, interaction: discord.Interaction, button: discord....
    method no (line 164) | async def no(self, interaction: discord.Interaction, button: discord.u...
  class LevelingShouldAnnounceLevelUp (line 175) | class LevelingShouldAnnounceLevelUp(discord.ui.View):
    method __init__ (line 176) | def __init__(self, server_id) -> None:
    method yes (line 181) | async def yes(self, interaction: discord.Interaction, button: discord....
    method no (line 199) | async def no(self, interaction: discord.Interaction, button: discord.u...
  class LevelingChannelSelectView (line 210) | class LevelingChannelSelectView(discord.ui.View):
    method __init__ (line 211) | def __init__(self, server_id, channels) -> None:
    method yes (line 216) | async def yes(self, interaction: discord.Interaction, button: discord....
    method no (line 259) | async def no(self, interaction: discord.Interaction, button: discord.u...
  class StarboardSetupView (line 268) | class StarboardSetupView(discord.ui.View):
    method __init__ (line 269) | def __init__(self, server_id) -> None:
    method yes (line 274) | async def yes(self, interaction: discord.Interaction, button: discord....
    method no (line 345) | async def no(self, interaction: discord.Interaction, button: discord.u...
  class LoggingSetupView (line 356) | class LoggingSetupView(discord.ui.View):
    method __init__ (line 357) | def __init__(self, server_id) -> None:
    method yes (line 362) | async def yes(self, interaction: discord.Interaction, button: discord....
    method no (line 405) | async def no(self, interaction: discord.Interaction, button: discord.u...

FILE: ui/starboard.py
  class JumpToMessageButton (line 3) | class JumpToMessageButton(discord.ui.Button):
    method __init__ (line 4) | def __init__(self, message: discord.message) -> None:
    method callback (line 11) | async def callback(self, interaction: discord.Interaction) -> None:
  class JumpToMessageView (line 14) | class JumpToMessageView(discord.ui.View):
    method __init__ (line 15) | def __init__(self, message: discord.message) -> None:

FILE: ui/ticket.py
  class CreateButton (line 12) | class CreateButton(View):
    method __init__ (line 13) | def __init__(self):
    method ticket (line 17) | async def ticket(self, interaction: discord.Interaction, button: Button):
  class CloseButton (line 78) | class CloseButton(View):
    method __init__ (line 79) | def __init__(self):
    method close (line 83) | async def close(self, interaction: discord.Interaction, button: Button):
  class TrashButton (line 172) | class TrashButton(View):
    method __init__ (line 173) | def __init__(self):
    method trash (line 177) | async def trash(self, interaction: discord.Interaction, button: Button):

FILE: ui/translate.py
  class TranslateModal (line 7) | class TranslateModal(ui.Modal, title = "Translate"):
    method __init__ (line 8) | def __init__(self, message: discord.Message):
    method on_submit (line 14) | async def on_submit(self, interaction: discord.Interaction) -> None:

FILE: utils/CONSTANTS.py
  function guild_data_template (line 9) | def guild_data_template(guild_id):
  function user_data_template (line 47) | def user_data_template(user_id, guild_id):
  function user_global_data_template (line 68) | def user_global_data_template(user_id):

FILE: utils/CachedDB.py
  class JSONEncoder (line 22) | class JSONEncoder(json.JSONEncoder):
    method default (line 23) | def default(self, obj):
  function find_one (line 30) | async def find_one(collection, query, ex=30):
  function update_one (line 49) | async def update_one(collection, filter, update, upsert=False):
  function sync_find_one (line 57) | def sync_find_one(collection, query, ex=30):
  function sync_update_one (line 76) | def sync_update_one(collection, filter, update, upsert=False):

FILE: utils/Checks.py
  function is_not_blacklisted (line 12) | async def is_not_blacklisted(context: Context):
  function has_perm (line 26) | def has_perm(**perms):
  function command_not_disabled (line 37) | async def command_not_disabled(context: Context):

FILE: utils/ErrorLogger.py
  function apply_context_errors (line 18) | def apply_context_errors(embed, context, ignore_message=False):
  function command_error (line 56) | async def command_error(error, context):
  function error (line 70) | async def error(self, event_method, *args, **kwargs):

FILE: utils/Errors.py
  class CommandDisabled (line 3) | class CommandDisabled(CommandError):
  class UserBlacklisted (line 6) | class UserBlacklisted(CommandError):

FILE: utils/ServerLogger.py
  function send_log (line 9) | async def send_log(title: str, guild: discord.Guild, description: str, c...
Condensed preview — 43 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (500K chars).
[
  {
    "path": ".gitignore",
    "chars": 2165,
    "preview": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packagi"
  },
  {
    "path": "Dockerfile",
    "chars": 476,
    "preview": "# Use an official Python runtime as a parent image\nFROM python:3.9-slim-buster\n\n# Set the working directory in the conta"
  },
  {
    "path": "LICENSE",
    "chars": 35149,
    "preview": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
  },
  {
    "path": "README.md",
    "chars": 636,
    "preview": "# PotatoBot\n> The best AIO bot on Discord.\n\ntop.gg: https://top.gg/bot/1226487228914602005 \\\nInvite: https://discord.com"
  },
  {
    "path": "bot.py",
    "chars": 13966,
    "preview": "# pylint: disable-all\n\n# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon\n\nimport"
  },
  {
    "path": "cogs/ai.py",
    "chars": 36910,
    "preview": "# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon\n\nFILTERS = [\n    {\n        \"ol"
  },
  {
    "path": "cogs/api.py",
    "chars": 4396,
    "preview": "# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon\n\nimport discord\nimport aiohttp"
  },
  {
    "path": "cogs/code.py",
    "chars": 1619,
    "preview": "\"\"\"\nThe MIT License (MIT)\n\nCopyright (c) 2022 Ogiroid Development Team\n\nPermission is hereby granted, free of charge, to"
  },
  {
    "path": "cogs/economy.py",
    "chars": 13884,
    "preview": "# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon\n\nimport random\nimport discord\n"
  },
  {
    "path": "cogs/fun.py",
    "chars": 31623,
    "preview": "# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon\n\nimport random\nimport discord\n"
  },
  {
    "path": "cogs/general.py",
    "chars": 20047,
    "preview": "# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon\n\nimport random\nimport os\nimpor"
  },
  {
    "path": "cogs/github.py",
    "chars": 6780,
    "preview": "\"\"\"\nThe MIT License (MIT)\n\nCopyright (c) 2022 Ogiroid Development Team\n\nPermission is hereby granted, free of charge, to"
  },
  {
    "path": "cogs/giveaway.py",
    "chars": 2576,
    "preview": "# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon\n\nimport discord\nimport random\n"
  },
  {
    "path": "cogs/level.py",
    "chars": 8550,
    "preview": "# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon\n\nimport random\nimport pymongo\n"
  },
  {
    "path": "cogs/music.py",
    "chars": 13772,
    "preview": "# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon\n\nimport re\nimport os\nimport lo"
  },
  {
    "path": "cogs/owner.py",
    "chars": 30479,
    "preview": "# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon\n\nimport discord\nimport ast\nimp"
  },
  {
    "path": "cogs/reactionroles.py",
    "chars": 6014,
    "preview": "# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon\n\nimport discord\n\nfrom discord."
  },
  {
    "path": "cogs/security.py",
    "chars": 56776,
    "preview": "# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon\n\nimport discord\nimport asyncio"
  },
  {
    "path": "cogs/server.py",
    "chars": 19166,
    "preview": "# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon\n\nimport discord\nimport os\nimpo"
  },
  {
    "path": "cogs/staff.py",
    "chars": 40184,
    "preview": "# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon\n\nimport os\n\nimport re\nfrom dat"
  },
  {
    "path": "cogs/starboard.py",
    "chars": 9332,
    "preview": "# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon\n\nimport discord\nfrom discord.e"
  },
  {
    "path": "cogs/stats.py",
    "chars": 7540,
    "preview": "# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon\n\nimport discord\nimport os\nfrom"
  },
  {
    "path": "cogs/ticket.py",
    "chars": 17014,
    "preview": "# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon\n\nimport discord\nimport os\nfrom"
  },
  {
    "path": "cogs/utility.py",
    "chars": 6966,
    "preview": "# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon\n\nimport io\n\nfrom asteval impor"
  },
  {
    "path": "config.example.json",
    "chars": 455,
    "preview": "{\n  \"prefix\": \",\",\n  \"invite_link\": \"https://discord.com/oauth2/authorize?client_id=1226487228914602005&scope=bot&permis"
  },
  {
    "path": "main.py",
    "chars": 5058,
    "preview": "# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon\n\nimport os\nimport threading\nim"
  },
  {
    "path": "requirements.txt",
    "chars": 166,
    "preview": "aiohttp\nasteval\nasyncpraw\nbetter_profanity\ncryptography\ndeep_translator\ndiscord.py\neasy_pil\nfastapi\ngroq\nlavalink\npickle"
  },
  {
    "path": "ui/code.py",
    "chars": 2159,
    "preview": "import discord\nimport aiohttp\nfrom discord import ui\n\nclass CodeModal(ui.Modal, title = \"Run Code\"):\n    language = ui.T"
  },
  {
    "path": "ui/farm.py",
    "chars": 7652,
    "preview": "import discord\nimport time\n\nfrom discord import ui\nfrom discord.ui import button, View, Modal\n\nfrom utils import DBClien"
  },
  {
    "path": "ui/gambling.py",
    "chars": 19595,
    "preview": "import discord\nimport asyncio\nimport random\n\nfrom discord import ui\nfrom discord.ui import Button, button, View\n\nfrom ut"
  },
  {
    "path": "ui/papertrading.py",
    "chars": 12731,
    "preview": "import discord\r\nimport asyncio\r\nimport aiohttp\r\nimport json\r\nimport os\r\nfrom datetime import datetime\r\nfrom discord impo"
  },
  {
    "path": "ui/recreate.py",
    "chars": 855,
    "preview": "import discord\n\nclass deleteconfirm(discord.ui.View):\n    def __init__(self, user, channel):\n        super().__init__(ti"
  },
  {
    "path": "ui/setup.py",
    "chars": 17594,
    "preview": "import discord\nimport asyncio\n\nfrom utils import DBClient\n\ndb = DBClient.db\n\nclass StartSetupView(discord.ui.View):\n    "
  },
  {
    "path": "ui/starboard.py",
    "chars": 604,
    "preview": "import discord\n\nclass JumpToMessageButton(discord.ui.Button):\n    def __init__(self, message: discord.message) -> None:\n"
  },
  {
    "path": "ui/ticket.py",
    "chars": 7875,
    "preview": "import discord\nimport asyncio\nimport os\nfrom datetime import datetime\n\nfrom discord.ui import Button, button, View\n\nfrom"
  },
  {
    "path": "ui/translate.py",
    "chars": 1070,
    "preview": "import discord\nimport aiohttp\nfrom discord import ui\n\nfrom deep_translator import GoogleTranslator\n\nclass TranslateModal"
  },
  {
    "path": "utils/CONSTANTS.py",
    "chars": 4994,
    "preview": "# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon\n\nfrom __future__ import annota"
  },
  {
    "path": "utils/CachedDB.py",
    "chars": 2842,
    "preview": "# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon\n\nimport pymongo\nimport redis\ni"
  },
  {
    "path": "utils/Checks.py",
    "chars": 1785,
    "preview": "# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon\n\nimport discord\n\nfrom utils im"
  },
  {
    "path": "utils/DBClient.py",
    "chars": 194,
    "preview": "# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon\n\nimport pymongo\nimport os\n\ncli"
  },
  {
    "path": "utils/ErrorLogger.py",
    "chars": 2939,
    "preview": "# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon\n\nimport os\nimport sys\nimport j"
  },
  {
    "path": "utils/Errors.py",
    "chars": 140,
    "preview": "from discord.ext.commands import CommandError\n\nclass CommandDisabled(CommandError):\n    pass\n\nclass UserBlacklisted(Comm"
  },
  {
    "path": "utils/ServerLogger.py",
    "chars": 907,
    "preview": "# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon\n\nimport discord\n\nfrom utils im"
  }
]

About this extraction

This page contains the full source code of the Cyteon/potatobot GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 43 files (464.5 KB), approximately 103.8k tokens, and a symbol index with 497 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!