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.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
================================================
FILE: README.md
================================================
# 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("", " ") # 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 ",
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 **")
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 "
)
@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 **")
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 **")
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 ",
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: ")
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 "
)
@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: "
)
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 "
)
@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 [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 "
)
@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 "
)
@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 "
)
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 "
)
@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 "
)
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 "
)
@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 "
)
@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 "
)
@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"",
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 "
)
@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 "
)
@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 "
)
@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 "
)
@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 "
)
@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 "
)
@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 "
)
@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 "
)
@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 "
)
@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 "
)
@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 "
)
@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 "
)
@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}: ")
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 "
)
@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 "
)
@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 ",
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 ",
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 ")
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 [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 "
)
@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 "
)
@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 "
)
@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 "
)
@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 "
)
@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 "
)
@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 "
)
@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 "
)
@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 "
)
@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 "
)
@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 [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 [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 ",
)
@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 ",
)
@commands.is_owner()
@app_commands.allowed_installs(guilds=True, users=True)
@app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
async def unload(self, context: Context, cog: str) -> None:
try:
await self.bot.unload_extension(f"cogs.{cog}")
except Exception:
embed = discord.Embed(
description=f"Could not unload the `{cog}` cog.", color=0xE02B2B
)
await context.send(embed=embed)
return
embed = discord.Embed(
description=f"Successfully unloaded the `{cog}` cog.", color=0xBEBEFE
)
await context.send(embed=embed)
@dev.command(
name="reload",
description="Reloads a cog",
usage="dev reload ",
)
@app_commands.describe(cog="The name of the cog to reload")
@app_commands.allowed_installs(guilds=True, users=True)
@app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
@commands.is_owner()
async def reload(self, context: Context, cog: str) -> None:
try:
await self.bot.reload_extension(f"cogs.{cog}")
except Exception:
embed = discord.Embed(
description=f"Could not reload the `{cog}` cog.", color=0xE02B2B
)
await context.send(embed=embed)
return
embed = discord.Embed(
description=f"Successfully reloaded the `{cog}` cog.", color=0xBEBEFE
)
await context.send(embed=embed)
@dev.command(
name="shutdown",
description="bye",
usage="dev shutdown"
)
@commands.is_owner()
async def shutdown(self, context: Context) -> None:
embed = discord.Embed(description="Shutting down. Bye! :wave:", color=0xBEBEFE)
await context.send(embed=embed)
sys.exit(0)
@dev.command(
name="say",
description="talk",
usage="dev say ",
)
@commands.is_owner()
async def say(self, context: Context, *, message: str) -> None:
await context.channel.send(message)
@commands.command(
name="embed",
description="say smth in embed",
usage="embed [footer]",
)
@commands.is_owner()
async def embed(self, context: Context, description: str = "", title: str = "", footer: str = "") -> None:
embed = discord.Embed(
title=title, description=description, color=0xBEBEFE
)
embed.set_footer(text=footer)
await context.channel.send(embed=embed)
@dev.command(
name="reply",
description="Reply to a message",
usage="dev reply ",
)
@commands.is_owner()
async def reply(self, context: Context, message: discord.Message, *, reply: str) -> None:
await message.reply(reply)
@dev.command(
name="eval",
description=":D",
usage="eval ",
)
@commands.is_owner()
@app_commands.allowed_installs(guilds=True, users=True)
@app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
async def eval(self, context, *, cmd: str):
fn_name = "_eval_expr"
cmd = cmd.strip("` ")
# add a layer of indentation
cmd = "\n".join(f" {i}" for i in cmd.splitlines())
# wrap in async def body
body = f"async def {fn_name}():\n{cmd}"
parsed = ast.parse(body)
body = parsed.body[0].body
insert_returns(body)
env = {
'bot': context.bot,
'discord': discord,
'commands': commands,
'context': context,
'db': db,
'__import__': __import__
}
exec(compile(parsed, filename="", mode="exec"), env)
result = (await eval(f"{fn_name}()", env))
await context.send(result)
@dev.command(
name="enable-ai",
description="Give server AI access",
usage="dev enable-ai [optional: server id]",
)
@commands.is_owner()
async def enable_ai(self, context, server: int = 0):
c = db["guilds"]
data = c.find_one(
{
"id": server if server != 0 else context.guild.id
}
)
if not data:
data = CONSTANTS.guild_data_template(context.guild.id)
c.insert_one(data)
newdata = { "$set": { "ai_access": True } }
c.update_one({"id": context.guild.id}, newdata)
await context.send("AI access have been enabled in this server")
@dev.command(
name="disable-ai",
description="Disable server AI access",
usage="dev disable-ai [optional: server id]",
)
@commands.is_owner()
async def disable_ai(self, context, server_id: int = 0):
c = db["guilds"]
data = c.find_one(
{
"id": server_id if server_id != 0 else context.guild.id
}
)
if not data:
data = CONSTANTS.guild_data_template(context.guild.id)
c.insert_one(data)
newdata = { "$set": { "ai_access": False } }
c.update_one({"id": context.guild.id}, newdata)
await context.send("AI access have been disabled in this server")
@dev.command(
name="blacklist",
description="Blacklist a user",
usage="dev blacklist [reason: optional]",
)
@commands.is_owner()
@app_commands.allowed_installs(guilds=True, users=True)
@app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
async def blacklist(self, context, user: discord.User, *, reason: str = "No reason provided"):
users_global = db["users_global"]
user_data = users_global.find_one({"id": user.id})
if user is None:
user_data = CONSTANTS.user_global_data_template(user.id)
users_global.insert_one(user_data)
newdata = {
"$set": {
"blacklisted": True,
"blacklist_reason": reason
}
}
await CachedDB.update_one(users_global, {"id": user.id}, newdata)
await context.send(f"{user} has been blacklisted.")
embed = discord.Embed(
title=f"You have been blacklisted from using the bot",
color=0xE02B2B,
description=f"Reason: {reason}"
)
try:
await user.send(embed=embed)
except Exception as e:
await context.send(f"Could not send message to {user.mention} due to: {e}")
@dev.command(
name="unblacklist",
description="Unblacklist a user",
usage="dev unblacklist ",
)
@commands.is_owner()
@app_commands.allowed_installs(guilds=True, users=True)
@app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
async def unblacklist(self, context, user: discord.User):
users_global = db["users_global"]
user_data = users_global.find_one({"id": user.id})
if user_data is None:
user_data = CONSTANTS.user_global_data_template(user.id)
users_global.insert_one(user_data)
newdata = {
"$set": {
"blacklisted": False,
"blacklist_reason": ""
}
}
await CachedDB.update_one(users_global, {"id": user.id}, newdata)
await context.send(f"{user} has been unblacklisted.")
embed = discord.Embed(
title=f"You have been unblacklisted from using the bot",
color=0xBEBEFE,
)
try:
await user.send(embed=embed)
except Exception as e:
await context.send(f"Could not send message to {user.mention} due to: {e}")
@commands.hybrid_command(
name="ai-ignore",
description="Make the AI ignore someone",
usage="ai_ignore [reason: optional]",
)
@commands.is_owner()
async def ai_ignore(self, context, user: discord.User, *, reason: str = "No reason provided"):
users_global = db["users_global"]
user_data = users_global.find_one({"id": user.id})
if user_data is None:
user_data = CONSTANTS.user_global_data_template(user.id)
user_data.insert_one(user_data)
newdata = {
"$set": {
"ai_ignore": True,
"ai_ignore_reason": reason
}
}
await CachedDB.update_one(users_global, {"id": user.id}, newdata)
await context.send(f"{user} will now be ignored by the AI.")
@commands.hybrid_command(
name="ai-unignore",
description="Make the AI not ignore someone",
usage="ai-unignore ",
)
@commands.is_owner()
async def ai_unignore(self, context, user: discord.User):
users_global = db["users_global"]
user_data = users_global.find_one({"id": user.id})
if user_data is None:
user_data = CONSTANTS.user_global_data_template(user.id)
users_global.insert_one(user_data)
newdata = {
"$set": {
"ai_ignore": False,
"ai_ignore_reason": ""
}
}
await CachedDB.update_one(users_global, {"id": user.id}, newdata)
await context.send(f"{user} will no longer be ignored by the AI")
@commands.command(
name="inspect",
description="Inspect a user",
usage="inspect ",
)
@commands.is_owner()
async def inspect(self, context, user: discord.User):
users_global = db["users_global"]
user_data = users_global.find_one({"id": user.id})
if user_data is None:
user_data = CONSTANTS.user_global_data_template(user.id)
users_global.insert_one(user_data)
embed = discord.Embed(
title=f"Inspecting {user}",
color=0xBEBEFE
)
embed.add_field(name="Total Commands", value=user_data["inspect"]["total_commands"])
embed.add_field(name="Times Flagged", value=user_data["inspect"]["times_flagged"])
embed.add_field(name="NSFW Requests", value=user_data["inspect"]["nsfw_requests"])
# STUFF THAT MIGHT NOT BE FOUND
if "ai_requests" in user_data["inspect"]:
embed.add_field(name="AI Requests", value=user_data["inspect"]["ai_requests"])
if user_data["blacklisted"]:
embed.add_field(name="Blacklist Reason", value=user_data["blacklist_reason"])
if user_data["ai_ignore"]:
embed.add_field(name="AI Ignore Reason", value=user_data["ai_ignore_reason"])
await context.send(embed=embed)
@commands.command(
name="inspect-clear",
description="Clear someones inspect data",
usage="inspect-clear ",
)
@commands.is_owner()
async def inspect_clear(self, context: Context, user: discord.Member):
users_global = db["users_global"]
newdata = {
"$set": {"inspect.total_commands": 0, "inspect.times_flagged": 0, "inspect.nsfw_requests": 0, "inspect.ai_requests": 0}
}
users_global.update_one({"id": user.id}, newdata)
user_new = users_global.find_one({"id": user.id})
await context.send(f"Cleared inspect info for {user.mention}")
@commands.command(
name="top-flagged",
description="Get the top flagged users",
usage="top-flagged"
)
@commands.is_owner()
async def top_flagged(self, context):
users_global = db["users_global"]
users = users_global.find().sort("inspect.times_flagged", -1).limit(10)
embed = discord.Embed(
title="Top Flagged Users",
color=0xBEBEFE
)
for user in users:
discord_user = self.bot.get_user(user["id"])
if not discord_user:
continue
embed.add_field(name=f"{str(discord_user).capitalize()} ({discord_user.id})", value= f"Flagged **{user['inspect']['times_flagged']}** times", inline=False)
await context.send(embed=embed)
@commands.command(
name="top-nsfw",
description="Get the top NSFW requesters",
usage="top-nsfw"
)
@commands.is_owner()
async def top_nsfw(self, context):
users_global = db["users_global"]
users = users_global.find().sort("inspect.nsfw_requests", -1).limit(10)
embed = discord.Embed(
title="Top NSFW Requesters",
color=0xBEBEFE
)
for user in users:
discord_user = self.bot.get_user(user["id"])
if not discord_user:
continue
embed.add_field(name=f"{str(discord_user).capitalize()} ({discord_user.id})", value= f"**{user['inspect']['nsfw_requests']}** NSFW requests", inline=False)
await context.send(embed=embed)
@commands.command(
name="ai-announce",
description="Announce smth",
usage="ai-announce "
)
@commands.is_owner()
async def ai_announce(self, context, *, message: str):
channels = db["ai_channels"]
listOfChannels = channels.find_one({"listOfChannels": True})
embed = discord.Embed(description=message)
for channel_id in listOfChannels["ai_channels"]:
channel = self.bot.get_channel(channel_id)
if channel:
if channel.permissions_for(channel.guild.me).send_messages:
await channel.send(embed=embed)
await context.send("Announced")
@dev.command(
name="copy-db-to-backup",
description="Copy the database to a backup",
usage="dev copy-db-to-backup"
)
@commands.is_owner()
async def copy_db_to_backup(self, context):
backup_db = pymongo.MongoClient(os.getenv("MONGODB_BACKUP_URL")).potatobot
message = await context.send("""
Status:
Removing old data: :tools:
Copying guilds: :x:
Copying ai_channels: :x:
Copying users: :x:
Copying AI convos: :x:
Copying global user data: :x:
Copying starboard: :x:
Copying reaction roles: :x:
""")
backup_db["ai_convos"].drop()
backup_db["guilds"].drop()
backup_db["ai_channels"].drop()
backup_db["users"].drop()
backup_db["starboard"].drop()
backup_db["users_global"].drop()
backup_db["reactionroles"].drop()
for guild in db["guilds"].find():
backup_db["guilds"].insert_one(guild)
await message.edit(content="""
Status:
Removing old data: :white_check_mark:
Copying guilds: :tools:
Copying ai_channels: :x:
Copying users: :x:
Copying AI convos: :x:
Copying global user data: :x:
Copying starboard: :x:
Copying reaction roles: :x:
""")
await message.edit(content="""
Status:
Removing old data: :white_check_mark:
Copying guilds: :white_check_mark:
Copying ai_channels: :tools:
Copying users: :x:
Copying AI convos: :x:
Copying global user data: :x:
Copying starboard: :x:
Copying reaction roles: :x:
""")
for channel in db["ai_channels"].find():
backup_db["ai_channels"].insert_one(channel)
await message.edit(content="""
Status:
Removing old data: :white_check_mark:
Copying guilds: :white_check_mark:
Copying ai_channels: :white_check_mark:
Copying users: :tools:
Copying AI convos: :x:
Copying global user data: :x:
Copying starboard: :x:
Copying reaction roles: :x:
""")
for user in db["users"].find():
backup_db["users"].insert_one(user)
await message.edit(content="""
Status:
Removing old data: :white_check_mark:
Copying guilds: :white_check_mark:
Copying ai_channels: :white_check_mark:
Copying users: :white_check_mark:
Copying AI convos: :tools:
Copying global user data: :x:
Copying starboard: :x:
Copying reaction roles: :x:
""")
for convo in db["ai_convos"].find():
backup_db["ai_convos"].insert_one(convo)
await message.edit(content="""
Status:
Removing old data: :white_check_mark:
Copying guilds: :white_check_mark:
Copying ai_channels: :white_check_mark:
Copying users: :white_check_mark:
Copying AI convos: :white_check_mark:
Copying global user data: :tools:
Copying starboard: :x:
Copying reaction roles: :x:
""")
for user in db["users_global"].find():
backup_db["users_global"].insert_one(user)
await message.edit(content="""
Status:
Removing old data: :white_check_mark:
Copying guilds: :white_check_mark:
Copying ai_channels: :white_check_mark:
Copying users: :white_check_mark:
Copying AI convos: :white_check_mark:
Copying global user data: :white_check_mark:
Copying starboard: :tools:
Copying reaction roles: :x:
""")
for starboard in db["starboard"].find():
backup_db["starboard"].insert_one(starboard)
await message.edit(content="""
Status:
Removing old data: :white_check_mark:
Copying guilds: :white_check_mark:
Copying ai_channels: :white_check_mark:
Copying users: :white_check_mark:
Copying AI convos: :white_check_mark:
Copying global user data: :white_check_mark:
Copying starboard: :white_check_mark:
Copying reaction roles: :tools:
""")
for starboard in db["reactionroles"].find():
backup_db["reactionroles"].insert_one(starboard)
await message.edit(content="""
Status:
Removing old data: :white_check_mark:
Copying guilds: :white_check_mark:
Copying ai_channels: :white_check_mark:
Copying users: :white_check_mark:
Copying AI convos: :white_check_mark:
Copying global user data: :white_check_mark:
Copying starboard: :white_check_mark:
Copying reaction roles: :white_check_mark:
**Backup Done!!!**
""")
@commands.command(
name="force_system_prompt",
description="Set the system prompt for the AI",
)
@commands.is_owner()
async def force_system_prompt(self, context: Context, *, prompt: str) -> None:
c = db["guilds"]
data = c.find_one({"id": context.guild.id})
newdata = {
"$set": { "system_prompt": prompt }
}
c.update_one(
{ "id": context.guild.id }, newdata
)
await context.send("System prompt set to: " + prompt)
@commands.hybrid_group(
name="strikes",
description="Stuff for striking users"
)
async def strikes(self, context: Context):
prefix = await self.bot.get_prefix(context)
cmds = "\n".join([f"{prefix}strikes {cmd.name} - {cmd.description}" for cmd in self.strikes.walk_commands()])
embed = discord.Embed(
title=f"Help: Strikes", description="List of available commands:", color=0xBEBEFE
)
embed.add_field(
name="Commands", value=f"```{cmds}```", inline=False
)
await context.send(embed=embed)
@strikes.command(
name="add",
description="Strike a user"
)
@commands.is_owner()
async def add(self, context: Context, user: discord.User, *, reason: str):
users = db["users_global"]
user_data = users.find_one({"id": user.id})
if user_data is None:
user_data = CONSTANTS.user_global_data_template(user.id)
users.insert_one(user_data)
if not "strikes" in user_data:
user_data["strikes"] = []
user_data["strikes"].append({"reason": reason, "time": datetime.now().strftime("%d.%m.%Y %H:%M:%S")})
newdata = {"$set": {"strikes": user_data["strikes"]}}
users.update_one({"id": user.id}, newdata)
await context.send(f"{user.mention} has been striked for **{reason}** | This is strike {len(user_data['strikes'])}")
embed = discord.Embed(
title=f"You have received a global strike",
color=0xE02B2B,
description=f"Reason: {reason}"
)
embed.set_footer(text="Time: " + datetime.now().strftime("%d.%m.%Y %H:%M:%S"))
try:
await user.send(embed=embed)
except Exception as e:
await context.send(f"Could not send message to {user.mention} due to: {e}")
@strikes.command(
name="remove",
description="Remove a strike from a user"
)
@commands.is_owner()
async def remove(self, context: Context, user: discord.User, id: int):
users = db["users_global"]
user_data = users.find_one({"id": user.id})
if user_data is None:
user_data = CONSTANTS.user_global_data_template(user.id)
users.insert_one(user_data)
if not "strikes" in user_data:
user_data["strikes"] = []
if id > len(user_data["strikes"]):
await context.send("That strike does not exist")
return
reason = user_data["strikes"][id]["reason"]
user_data["strikes"].pop(id)
newdata = {"$set": {"strikes": user_data["strikes"]}}
users.update_one({"id": user.id}, newdata)
await context.send(f"Strike **{id}** has been removed from {user.mention}")
embed = discord.Embed(
title=f"Globally removed strike | ID: {id}",
color=0xBEBEFE,
description=f"Reason: {reason}"
)
embed.set_footer(text="Time: " + datetime.now().strftime("%d.%m.%Y %H:%M:%S"))
try:
await user.send(embed=embed)
except Exception as e:
await context.send(f"Could not send message to {user.mention} due to: {e}")
@strikes.command(
name="list",
description="Lists a users strikes"
)
@commands.is_owner()
async def list(self, context: Context, user: discord.User):
users = db["users_global"]
user_data = users.find_one({"id": user.id})
if user_data is None:
user_data = CONSTANTS.user_global_data_template(user.id)
users.insert_one(user_data)
if not "strikes" in user_data:
user_data["strikes"] = []
embed = discord.Embed(
title=f"Strikes for {user}",
color=0xBEBEFE
)
for i, strike in enumerate(user_data["strikes"]):
embed.add_field(name=f"Strike at {strike['time']} | ID: {i}", value=strike["reason"], inline=False)
await context.send(embed=embed)
@commands.command(
name="dm",
description="DM a user",
usage="dev dm "
)
@commands.is_owner()
async def dm(self, context: Context, user: discord.User, *, message: str) -> None:
try:
await user.send(message)
await context.send(f"Sent message to {user.mention}")
except Exception as e:
await context.send(f"Could not send message to {user.mention} due to: {e}")
@dev.command(
name="simulate-level-up",
description="",
usage="dev simulate-level-up"
)
@commands.is_owner()
async def simulate_level_up(self, context: Context):
author = context.author
c = db["users"]
data = await CachedDB.find_one(c, {"id": author.id, "guild_id": context.guild.id})
guilds = db["guilds"]
guild_data = await CachedDB.find_one(guilds, {"id": context.guild.id})
if data:
channel = context.channel
if guild_data:
if "level_announce_channel" in guild_data:
if guild_data["level_announce_channel"] != 0:
channel = context.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']}!")
async def setup(bot) -> None:
await bot.add_cog(Owner(bot))
================================================
FILE: cogs/reactionroles.py
================================================
# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon
import discord
from discord.ext import commands
from discord.ext.commands import Context
from utils import CachedDB, DBClient
db = DBClient.db
from utils import Checks
class ReactionRoles(commands.Cog, name="🇺🇸 Reaction Roles"):
def __init__(self, bot) -> None:
self.bot = bot
@commands.Cog.listener()
async def on_raw_reaction_add(self, payload) -> None:
message_data = await CachedDB.find_one(db["reaction_roles"], {"message_id": payload.message_id})
if not message_data:
return
# Determine the emoji identifier
if payload.emoji.id is None:
# This is a Unicode emoji
emoji_id = str(payload.emoji)
else:
# This is a custom emoji
emoji_id = str(payload.emoji.id)
if emoji_id not in message_data["roles"]:
return
guild = self.bot.get_guild(payload.guild_id)
if not guild:
return
role = guild.get_role(int(message_data["roles"][emoji_id]))
if not role:
return
member = guild.get_member(payload.user_id)
if not member:
return
try:
await member.add_roles(role)
print(f"Added role {role.name} to {member.name}")
except discord.HTTPException as e:
print(f"Failed to add role: {e}")
@commands.Cog.listener()
async def on_raw_reaction_remove(self, payload) -> None:
message_data = await CachedDB.find_one(db["reaction_roles"], {"message_id": payload.message_id})
if not message_data:
return
# Determine the emoji identifier
if payload.emoji.id is None:
# This is a Unicode emoji
emoji_id = str(payload.emoji)
else:
# This is a custom emoji
emoji_id = str(payload.emoji.id)
if emoji_id not in message_data["roles"]:
try:
message = await self.bot.get_channel(payload.channel_id).fetch_message(payload.message_id)
await message.remove_reaction(payload.emoji, self.bot.get_user(payload.user_id))
except Exception as e:
print(e)
pass
return
guild = self.bot.get_guild(payload.guild_id)
if not guild:
return
role = guild.get_role(int(message_data["roles"][emoji_id]))
if not role:
return
member = guild.get_member(payload.user_id)
if not member:
return
try:
await member.remove_roles(role)
print(f"Removed role {role.name} from {member.name}")
except discord.HTTPException as e:
print(f"Failed to remove role: {e}")
@commands.hybrid_group(
name="reactionroles",
description="Command to manage reaction roles",
usage="reactionroles",
aliases=["rr"]
)
@commands.check(Checks.is_not_blacklisted)
@commands.check(Checks.command_not_disabled)
@commands.has_permissions(manage_roles=True)
async def reactionroles(self, context: Context) -> None:
subcommands = [cmd for cmd in self.reactionroles.walk_commands()]
data = []
for subcommand in subcommands:
description = subcommand.description.partition("\n")[0]
data.append(f"{await self.bot.get_prefix(context)}reactionroles {subcommand.name} - {description}")
help_text = "\n".join(data)
embed = discord.Embed(
title=f"Help: Reaction Roles", description="List of available commands:", color=0xBEBEFE
)
embed.add_field(
name="Commands", value=f"```{help_text}```", inline=False
)
await context.send(embed=embed)
@reactionroles.command(
name="add",
description="Add a reaction role to a message",
usage="reactionroles add ",
)
@commands.check(Checks.is_not_blacklisted)
@commands.check(Checks.command_not_disabled)
@commands.has_permissions(manage_roles=True)
async def add(self, context: commands.Context, message_id: str, role: discord.Role, emoji: str):
try:
message_id = int(message_id)
except:
await context.send("Invalid message ID.")
return
try:
message = await context.channel.fetch_message(message_id)
except discord.NotFound:
await context.send("Message not found.")
return
# Convert emoji to a format we can use
try:
# Try to convert to Discord emoji
emoji_obj = await commands.EmojiConverter().convert(context, emoji)
emoji_id = str(emoji_obj.id)
except commands.BadArgument:
# If conversion fails, assume it's a Unicode emoji
emoji_id = emoji
try:
await message.add_reaction(emoji)
except discord.HTTPException:
await context.send("Failed to add reaction. Make sure the bot has permission to add reactions.")
return
message_data = await CachedDB.find_one(db["reaction_roles"], {"message_id": message_id})
if not message_data:
db["reaction_roles"].insert_one({
"message_id": message_id,
"roles": {emoji_id: str(role.id)}
})
await context.send("Reaction role added.")
else:
if emoji_id in message_data["roles"]:
await context.send("Reaction role already exists.")
else:
message_data["roles"][emoji_id] = str(role.id)
await CachedDB.update_one(db["reaction_roles"], {"message_id": message_id}, {"$set": {"roles": message_data["roles"]}})
await context.send("Reaction role added.")
async def setup(bot) -> None:
await bot.add_cog(ReactionRoles(bot))
================================================
FILE: cogs/security.py
================================================
# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon
import discord
import asyncio
import datetime
import logging
import os
logger = logging.getLogger("discord_bot")
from discord.ext import commands, tasks
from discord.ext.commands import Context
from utils import CONSTANTS, DBClient, Checks, CachedDB
KICK_TRESHOLD = 5
BAN_TRESHOLD = 3
DELETE_TRESHOLD = 2
PING_TRESHOLD = 12
WEBHOOK_TRESHOLD = 40
client = DBClient.client
db = client.potatobot
ban_cache = {}
kick_cache = {}
ping_cache = {}
webhook_cache = {}
delete_cache = {}
deleted_channels = {}
class Security(commands.Cog, name="🛡️ Security"):
def __init__(self, bot) -> None:
self.bot = bot
self.clear_cache.start()
@tasks.loop(minutes=10)
async def clear_cache(self) -> None:
ban_cache.clear()
kick_cache.clear()
ping_cache.clear()
webhook_cache.clear()
delete_cache.clear()
deleted_channels.clear()
@commands.Cog.listener()
async def on_message(self, message: discord.Message) -> None:
if message.guild == None:
return
if message.author.id == self.bot.user.id:
return
if message.guild.owner:
if message.author.id == message.guild.owner.id:
return
if message.webhook_id:
try:
webhook = await self.bot.fetch_webhook(message.webhook_id)
except discord.NotFound:
webhook = None
if not webhook:
return
if message.webhook_id in webhook_cache:
webhook_cache[message.webhook_id] += 1
if "@everyone" in message.content or "@here" in message.content:
webhook_cache[message.webhook_id] += 11
if webhook_cache[message.webhook_id] > WEBHOOK_TRESHOLD:
guilds = db["guilds"]
data = guilds.find_one({"id": message.guild.id})
if not data:
data = CONSTANTS.guild_data_template(message.guild.id)
guilds.insert_one(data)
if not "security" in data:
return
if "anti_webhook_spam" not in data["security"]["antinuke"]:
return
if not data["security"]["antinuke"]["anti_webhook_spam"]:
return
await message.delete()
log_channel = message.guild.get_channel(data["log_channel"])
try:
await webhook.delete()
embed = discord.Embed(
title="AntiSpam Warning",
description=f"Webhook **{message.webhook_id}** has been deleted for spamming",
color=discord.Color.green()
)
if log_channel != None:
await log_channel.send(embed=embed)
except:
embed = discord.Embed(
title="AntiSpam Warning",
description=f"Unable to delete webhook **{message.webhook_id}** for spamming, please delete it manually",
color=discord.Color.red()
)
if log_channel != None:
await log_channel.send(embed=embed)
embed = discord.Embed(
title="AntiSpam Warning",
description=f"Webhook **{message.webhook_id}** has triggered the antispam system, last message: `{message.content}`",
color=discord.Color.orange()
)
if log_channel != None:
await log_channel.send(embed=embed)
else:
webhook_cache[message.webhook_id] = 1
if message.author in ping_cache:
if len(message.role_mentions) > 0:
if message.author.guild_permissions.mention_everyone:
ping_cache[message.author] += len(message.role_mentions) * 2
if len(message.mentions) > 0:
ping_cache[message.author] += len(message.mentions)/2
if message.author in message.mentions:
ping_cache[message.author] -= 0.5
if "@everyone" in message.content or "@here" in message.content:
if message.author.guild_permissions.mention_everyone:
ping_cache[message.author] += 11
if ping_cache[message.author] > PING_TRESHOLD:
logger.info("boom")
ping_cache[message.author] = 0
users = db["users"]
user_data = users.find_one({"id": message.author.id, "guild_id": message.guild.id})
if not user_data:
user_data = CONSTANTS.user_data_template(message.author.id, message.guild.id)
users.insert_one(user_data)
if "whitelisted" in user_data:
if user_data["whitelisted"]:
return
guilds = db["guilds"]
data = guilds.find_one({"id": message.guild.id})
if not data:
data = CONSTANTS.guild_data_template(message.guild.id)
guilds.insert_one(data)
if not "security" in data:
return
if "anti_massping" not in data["security"]["antinuke"]:
return
if not data["security"]["antinuke"]["anti_massping"]:
return
await message.delete()
embed = discord.Embed(
title="AntiSpam Warning",
description=f"**{message.author.mention}** has triggered the antispam system, last message: `{message.content}`",
color=discord.Color.orange()
)
try:
message.channel.send(embed=embed)
except:
pass
log_channel = message.guild.get_channel(data["log_channel"])
if log_channel != None:
await log_channel.send(embed=embed)
try:
try:
embed = discord.Embed(
title="You have been kicked",
description=f"You have been kicked from **{message.guild.name}** for mass pinging",
color=discord.Color.red()
)
await message.author.send(embed=embed)
except:
pass
await message.author.kick(reason="AntiNuke Alert - Mass pinging")
ban_cache[self.bot.user] = 0
embed = discord.Embed(
title="User Kicked",
description=f"**{message.author.mention}** has been kicked for mass pinging",
color=discord.Color.red()
)
if log_channel != None:
await log_channel.send(embed=embed)
except discord.Forbidden:
embed = discord.Embed(
title="AntiNuke Error",
description=f"I was unable to kick the user {message.author.mention}",
color=discord.Color.red()
)
if log_channel != None:
await log_channel.send(embed=embed)
try:
guild_owner = message.guild.owner
await guild_owner.send(embed=embed)
except discord.Forbidden:
embed = discord.Embed(
title="AntiNuke Error",
description=f"Unable to alert the guild owner using DMs",
color=discord.Color.red()
)
if log_channel != None:
await log_channel.send(embed=embed)
else:
ping_cache[message.author] = 0
@commands.Cog.listener()
async def on_guild_role_create(self, role: discord.Role) -> None:
if role.permissions.administrator:
guilds = db["guilds"]
guild = guilds.find_one({"id": role.guild.id})
if not guild:
guild = CONSTANTS.guild_data_template(role.guild.id)
guilds.insert_one(guild)
if guild and "security" in guild and "antinuke" in guild["security"]:
antinuke = guild["security"]["antinuke"]
if antinuke.get("anti_danger_perms", False):
discord_guild = role.guild
user = None
async for entry in discord_guild.audit_logs(action=discord.AuditLogAction.role_create, limit=2):
if entry.target == role:
user = entry.user
if user is None:
return
if user.id == discord_guild.owner.id:
return
if user.id == self.bot.user.id:
return
users = db["users"]
user_data = users.find_one({"id": user.id, "guild_id": role.guild.id})
if not user_data:
user_data = CONSTANTS.user_data_template(user.id, role.guild.id)
users.insert_one(user_data)
if "whitelisted" in user_data:
if user_data["whitelisted"]:
embed = discord.Embed(
title="AntiNuke Warning",
description=f"**{user.mention}** created a dangerous role",
color=discord.Color.orange()
)
log_channel = role.guild.get_channel(guild["log_channel"])
if log_channel is None:
return
await log_channel.send(embed=embed)
return
await role.delete()
log_channel = role.guild.get_channel(guild["log_channel"])
if log_channel is None:
return
embed = discord.Embed(
title="AntiNuke Alert",
description=f"**{user.mention}** tried to create a dangerous role!",
color=discord.Color.red()
)
await log_channel.send(embed=embed)
@commands.Cog.listener()
async def on_guild_role_update(self, before: discord.Role, after: discord.Role) -> None:
if after.permissions.administrator and not before.permissions.administrator:
guilds = db["guilds"]
guild = guilds.find_one({"id": after.guild.id})
if not guild:
guild = CONSTANTS.guild_data_template(after.guild.id)
guilds.insert_one(guild)
if guild and "security" in guild and "antinuke" in guild["security"]:
antinuke = guild["security"]["antinuke"]
if antinuke.get("anti_danger_perms", False):
discord_guild = before.guild
user = None
async for entry in discord_guild.audit_logs(action=discord.AuditLogAction.role_update, limit=2):
if entry.target == before or after:
if user == discord_guild.owner:
continue
user = entry.user
if user is None:
pass
if user.id == self.bot.user.id:
return
if user.id == after.guild.owner.id:
return
users = db["users"]
user_data = users.find_one({"id": user.id, "guild_id": after.guild.id})
if not user_data:
user_data = CONSTANTS.user_data_template(user.id, after.guild.id)
users.insert_one(user_data)
if "whitelisted" in user_data:
if user_data["whitelisted"]:
embed = discord.Embed(
title="AntiNuke Warning",
description=f"**{user.mention}** gave **{after.mention}** dangerous permissions",
color=discord.Color.orange()
)
log_channel = after.guild.get_channel(guild["log_channel"])
if log_channel is None:
return
await log_channel.send(embed=embed)
return
await after.edit(permissions=before.permissions)
log_channel = after.guild.get_channel(guild["log_channel"])
if log_channel is None:
return
embed = discord.Embed(
title="AntiNuke Alert",
description=f"**{user.mention}** tried to give **{after.mention}** dangerous permissions!",
color=discord.Color.red()
)
await log_channel.send(embed=embed)
embed = discord.Embed(
title="Role Changes Reverted",
description=f"**{before.mention}** has been reverted to its previous permissions!",
color=discord.Color.green()
)
await log_channel.send(embed=embed)
try:
await discord_guild.ban(user, reason="AntiNuke Alert - Dangerous permissions granted")
ban_cache[self.bot.user] = 0
embed = discord.Embed(
title="User Banned",
description=f"**{user.mention}** has been banned for trying to give dangerous permissions!",
color=discord.Color.red()
)
if log_channel is not None:
await log_channel.send(embed=embed)
except discord.Forbidden:
embed = discord.Embed(
title="AntiNuke Error",
description=f"I was unable to ban the user {user.mention}",
color=discord.Color.red()
)
if log_channel is not None:
await log_channel.send(embed=embed)
try:
guild_owner = discord_guild.owner
await guild_owner.send(embed=embed)
except discord.Forbidden:
embed = discord.Embed(
title="AntiNuke Error",
description=f"Unable to alert the guild owner using DMs",
color=discord.Color.red()
)
if log_channel is not None:
await log_channel.send(embed=embed)
@commands.Cog.listener()
async def on_member_ban(self, discord_guild: discord.Guild, banned_user: discord.User) -> None:
guilds = db["guilds"]
guild = guilds.find_one({"id": discord_guild.id})
if not guild:
guild = CONSTANTS.guild_data_template(discord_guild.id)
guilds.insert_one(guild)
if guild and "security" in guild and "antinuke" in guild["security"]:
antinuke = guild["security"]["antinuke"]
if antinuke.get("anti_massban", False):
user = None
await asyncio.sleep(0.5) # So audit log can update
async for entry in discord_guild.audit_logs(action=discord.AuditLogAction.ban, limit=2):
if entry.target == banned_user:
user = entry.user
if user is None:
return
if user.id == self.bot.user.id:
return
if user.id == discord_guild.owner.id:
return
users = db["users"]
user_data = users.find_one({"id": user.id, "guild_id": discord_guild.id})
if not user_data:
user_data = CONSTANTS.user_data_template(user.id, discord_guild.id)
users.insert_one(user_data)
if "whitelisted" in user_data:
if user_data["whitelisted"]:
return
over_limit = False
if user in ban_cache:
ban_cache[user] += 1
if ban_cache[user] > BAN_TRESHOLD:
over_limit = True
else:
ban_cache[user] = 1
if over_limit:
await discord_guild.unban(banned_user, reason="Mass ban detected")
ban_cache[self.bot.user] = 0
embed = discord.Embed(
title="AntiNuke Warning",
description=f"**{user.mention}** has triggered the antinuke system, last banned user: **{banned_user.mention}**",
color=discord.Color.orange()
)
log_channel = discord_guild.get_channel(guild["log_channel"])
if log_channel != None:
await log_channel.send(embed=embed)
try:
await discord_guild.ban(user, reason="AntiNuke Alert - Mass ban detected")
ban_cache[self.bot.user] = 0
embed = discord.Embed(
title="User Banned",
description=f"**{user.mention}** has been banned for trying to mass ban members!",
color=discord.Color.red()
)
if log_channel != None:
await log_channel.send(embed=embed)
except discord.Forbidden:
embed = discord.Embed(
title="AntiNuke Error",
description=f"I was unable to ban the user {user.mention}",
color=discord.Color.red()
)
if log_channel != None:
await log_channel.send(embed=embed)
try:
guild_owner = discord_guild.owner
await guild_owner.send(embed=embed)
except discord.Forbidden:
embed = discord.Embed(
title="AntiNuke Error",
description=f"Unable to alert the guild owner using DMs",
color=discord.Color.red()
)
if log_channel != None:
await log_channel.send(embed=embed)
@commands.Cog.listener()
async def on_member_remove(self, member: discord.Member) -> None:
guilds = db["guilds"]
guild = guilds.find_one({"id": member.guild.id})
if not guild:
guild = CONSTANTS.guild_data_template(member.guild.id)
guilds.insert_one(guild)
if guild and "security" in guild and "antinuke" in guild["security"]:
antinuke = guild["security"]["antinuke"]
if antinuke.get("anti_masskick", False):
user = None
async for entry in member.guild.audit_logs(action=discord.AuditLogAction.kick, limit=2):
if entry.target == member:
user = entry.user
if user is None:
return
if user.id == self.bot.user.id:
return
if user.id == member.guild.owner.id:
return
users = db["users"]
user_data = users.find_one({"id": user.id, "guild_id": member.guild.id})
if not user_data:
user_data = CONSTANTS.user_data_template(user.id, member.guild.id)
users.insert_one(user_data)
if "whitelisted" in user_data:
if user_data["whitelisted"]:
return
over_limit = False
if user in kick_cache:
kick_cache[user] += 1
if kick_cache[user] > KICK_TRESHOLD:
over_limit = True
else:
kick_cache[user] = 1
if over_limit:
embed = discord.Embed(
title="AntiNuke Warning",
description=f"**{user.mention}** has triggered the antinuke system, last kicked user: **{member.mention}**",
color=discord.Color.orange()
)
log_channel = member.guild.get_channel(guild["log_channel"])
if log_channel != None:
await log_channel.send(embed=embed)
try:
await member.guild.ban(user, reason="AntiNuke Alert - Mass kick detected")
ban_cache[self.bot.user] = 0
embed = discord.Embed(
title="User Banned",
description=f"**{user.mention}** has been banned for trying to mass kick members!",
color=discord.Color.red()
)
if log_channel != None:
await log_channel.send(embed=embed)
except discord.Forbidden:
embed = discord.Embed(
title="AntiNuke Error",
description=f"I was unable to ban the user {user.mention}",
color=discord.Color.red()
)
if log_channel != None:
await log_channel.send(embed=embed)
try:
guild_owner = member.guild.owner
await guild_owner.send(embed=embed)
except discord.Forbidden:
embed = discord.Embed(
title="AntiNuke Error",
description=f"Unable to alert the guild owner using DMs",
color=discord.Color.red()
)
if log_channel != None:
await log_channel.send(embed=embed)
@commands.Cog.listener()
async def on_guild_channel_delete(self, channel: discord.TextChannel) -> None:
guilds = db["guilds"]
guild = guilds.find_one({"id": channel.guild.id})
if not guild:
guild = CONSTANTS.guild_data_template(channel.guild.id)
guilds.insert_one(guild)
if guild and "security" in guild and "antinuke" in guild["security"]:
antinuke = guild["security"]["antinuke"]
if antinuke.get("anti_massdelete", False):
user = None
async for entry in channel.guild.audit_logs(action=discord.AuditLogAction.channel_delete, limit=2):
if entry.target.id == channel.id and entry.user:
user = entry.user
if channel.guild in deleted_channels:
deleted_channels[channel.guild].append(channel)
else:
deleted_channels[channel.guild] = [channel]
if user is None:
return
if user == self.bot.user:
return
if user == channel.guild.owner:
pass
users = db["users"]
user_data = users.find_one({"id": user.id, "guild_id": channel.guild.id})
if not user_data:
user_data = CONSTANTS.user_data_template(user.id, channel.guild.id)
users.insert_one(user_data)
if "whitelisted" in user_data:
if user_data["whitelisted"]:
return
over_limit = False
if user in delete_cache:
delete_cache[user] += 1
if delete_cache[user] > DELETE_TRESHOLD:
over_limit = True
else:
delete_cache[user] = 1
if over_limit:
log_channel = channel.guild.get_channel(guild["log_channel"])
try:
await channel.guild.ban(user, reason="AntiNuke Alert - Mass delete detected")
ban_cache[self.bot.user] = 0
embed = discord.Embed(
title="User Banned",
description=f"**{user.mention}** has been banned for trying to mass delete channels!",
color=discord.Color.red()
)
if log_channel != None:
await log_channel.send(embed=embed)
except discord.Forbidden:
embed = discord.Embed(
title="AntiNuke Error",
description=f"I was unable to ban the user {user.mention}",
color=discord.Color.red()
)
if log_channel != None:
await log_channel.send(embed=embed)
try:
guild_owner = channel.guild.owner
await guild_owner.send(embed=embed)
except discord.Forbidden:
embed = discord.Embed(
title="AntiNuke Error",
description=f"Unable to alert the guild owner using DMs",
color=discord.Color.red()
)
if log_channel != None:
await log_channel.send(embed=embed)
embed = discord.Embed(
title="AntiNuke Warning",
description=f"**{user.mention}** has triggered the antinuke system, last deleted channel: **{channel.mention}** ({channel.name})",
color=discord.Color.orange()
)
if log_channel != None:
try:
await log_channel.send(embed=embed)
except:
await channel.guild.owner.send(embed=embed)
else:
await channel.guild.owner.send(embed=embed)
for del_channel in deleted_channels[channel.guild]:
if not del_channel in deleted_channels[channel.guild]:
return
deleted_channels[channel.guild].remove(del_channel)
try:
new_channel = await del_channel.clone(reason="AntiNuke Alert - Mass delete detected")
ban_cache[self.bot.user] = 0
embed = discord.Embed(
title="Channel Restored",
description=f"**{new_channel.mention}** has been restored!",
color=discord.Color.green()
)
if log_channel != None:
await log_channel.send(embed=embed)
embed = discord.Embed(
title="This channel was nuked",
description=f"**{new_channel.mention}** was nuked by **{user.mention}**, channel is restored but message log is gone",
color=discord.Color.red()
)
await new_channel.send(embed=embed)
await new_channel.edit(position=del_channel.position)
except Exception as e:
embed = discord.Embed(
title="Error",
description=f"An error occured while trying to restore channel **{del_channel.name}**",
color=discord.Color.red()
)
embed.add_field(
name="Error",
value=f"```{e}```"
)
if log_channel != None:
await log_channel.send(embed=embed)
await asyncio.sleep(60)
deleted_channels[channel.guild].clear()
@commands.Cog.listener()
async def on_member_join(self, member: discord.Member):
guild = await CachedDB.find_one(db["guilds"], {"id": member.guild.id})
if not guild:
return
if "lockdown" not in guild:
return
if guild["lockdown"]:
await member.kick(reason="Guild is in lockdown")
###
@commands.hybrid_group(
name="whitelist",
description="Whitelist users from security measures (guild owner only)"
)
async def whitelist(self, context: Context) -> None:
prefix = await self.bot.get_prefix(context)
cmds = "\n".join([f"{prefix}whitelist {cmd.name} - {cmd.description}" for cmd in self.whitelist.walk_commands()])
embed = discord.Embed(
title=f"Help: Whitelist", description="List of available commands:", color=0xBEBEFE
)
embed.add_field(
name="Commands", value=f"```{cmds}```", inline=False
)
await context.send(embed=embed)
@whitelist.command(
name="add",
description="Whitelist a user from security measures (guild owner only)",
usage="whitelist add "
)
@commands.check(Checks.is_not_blacklisted)
async def add(self, context: Context, user: discord.Member) -> None:
guild_owner = context.guild.owner
if context.author != guild_owner and context.author.id != int(os.getenv("OWNER_ID")):
await context.send("You must be the guild owner to use this command!")
return
users = db["users"]
user_data = users.find_one({"id": user.id, "guild_id": context.guild.id})
if user is None:
user_data = CONSTANTS.user_data_template(user.id, context.guild.id)
users.insert_one(user_data)
newdata = {
"$set": {
"whitelisted": True
}
}
users.update_one({"id": user.id, "guild_id": context.guild.id}, newdata)
await context.send(f"Whitelisted {user.mention}")
@whitelist.command(
name="remove",
description="Remove a user from the whitelist (guild owner only)",
usage="whitelist remove "
)
@commands.check(Checks.is_not_blacklisted)
async def remove(self, context: Context, user: discord.Member) -> None:
guild_owner = context.guild.owner
if context.author != guild_owner:
await context.send("You must be the guild owner to use this command!")
return
users = db["users"]
user_data = users.find_one({"id": user.id, "guild_id": context.guild.id})
if user is None:
user_data = CONSTANTS.user_data_template(user.id, context.guild.id)
users.insert_one(user_data)
newdata = {
"$set": {
"whitelisted": False
}
}
users.update_one({"id": user.id, "guild_id": context.guild.id}, newdata)
await context.send(f"Unwhitelisted {user.mention}")
@whitelist.command(
name="list",
description="List all whitelisted users (guild owner only)",
usage="whitelist list"
)
@commands.check(Checks.is_not_blacklisted)
async def list(self, context: Context) -> None:
users = db["users"]
whitelisted = users.find({"guild_id": context.guild.id, "whitelisted": True})
list = "```"
for user in whitelisted:
user = context.guild.get_member(user["id"])
list += f"{user.name}\n"
list += "```"
embed = discord.Embed(
title="Whitelisted Users",
description=list
)
await context.send(embed=embed)
@commands.hybrid_group(
name="trusted",
description="Trusted users can bypass security measures and change security settings"
)
async def trusted(self, context: Context) -> None:
prefix = await self.bot.get_prefix(context)
cmds = "\n".join([f"{prefix}trusted {cmd.name} - {cmd.description}" for cmd in self.trusted.walk_commands()])
embed = discord.Embed(
title=f"Help: Trusted", description="List of available commands:", color=0xBEBEFE
)
embed.add_field(
name="Commands", value=f"```{cmds}```", inline=False
)
await context.send(embed=embed)
@trusted.command(
name="add",
description="Trust a user (guild owner only)",
usage="trusted add "
)
@commands.check(Checks.is_not_blacklisted)
async def trusted_add(self, context: Context, user: discord.Member) -> None:
guild_owner = context.guild.owner
if context.author != guild_owner and context.author.id != int(os.getenv("OWNER_ID")):
await context.send("You must be the guild owner to use this command!")
return
users = db["users"]
user_data = users.find_one({"id": user.id, "guild_id": context.guild.id})
if user is None:
user_data = CONSTANTS.user_data_template(user.id, context.guild.id)
users.insert_one(user_data)
newdata = {
"$set": {
"trusted": True
}
}
users.update_one({"id": user.id, "guild_id": context.guild.id}, newdata)
await context.send(f"Trusted {user.mention}")
@trusted.command(
name="remove",
description="Remove a trusted user (guild owner only)",
usage="trusted remove "
)
@commands.check(Checks.is_not_blacklisted)
async def trusted_remove(self, context: Context, user: discord.Member) -> None:
guild_owner = context.guild.owner
if context.author != guild_owner:
await context.send("You must be the guild owner to use this command!")
return
users = db["users"]
user_data = users.find_one({"id": user.id, "guild_id": context.guild.id})
if user is None:
user_data = CONSTANTS.user_data_template(user.id, context.guild.id)
users.insert_one(user_data)
newdata = {
"$set": {
"trusted": False
}
}
users.update_one({"id": user.id, "guild_id": context.guild.id}, newdata)
await context.send(f"Untrusted {user.mention}")
@trusted.command(
name="list",
description="List all trusted users",
usage="trusted list"
)
@commands.check(Checks.is_not_blacklisted)
async def trusted_list(self, context: Context) -> None:
users = db["users"]
whitelisted = users.find({"guild_id": context.guild.id, "trusted": True})
list = "```"
for user in whitelisted:
user = context.guild.get_member(user["id"])
list += f"{user.name}\n"
list += "```"
embed = discord.Embed(
title="Trusted Users",
description=list
)
await context.send(embed=embed)
@commands.hybrid_group(
name="antinuke",
description="Commands to manage antinuke (guild owner/trusted only)",
usage="antinuke "
)
@commands.check(Checks.is_not_blacklisted)
async def antinuke(self, context: Context) -> None:
embed = discord.Embed(
title="Antinuke",
description="Commands"
)
# get all subcommands in group
subcommands = [cmd for cmd in self.antinuke.walk_commands()]
data = []
for subcommand in subcommands:
description = subcommand.description.partition("\n")[0]
data.append(f"{await self.bot.get_prefix(context)}antinuke {subcommand.name} - {description}")
help_text = "\n".join(data)
embed = discord.Embed(
title=f"Help: Antinuke", description="List of available commands:", color=0xBEBEFE
)
embed.add_field(
name="Commands", value=f"```{help_text}```", inline=False
)
await context.send(embed=embed)
@antinuke.command(
name="anti_danger_perms",
description="Prevent someone from giving dangerous perms to @everyone (guild owner/trusted only)",
usage="antinuke anti_danger_perms "
)
@commands.check(Checks.is_not_blacklisted)
async def anti_danger_perms(self, context: Context, enabled: bool) -> None:
guild_owner = context.guild.owner
if context.author != guild_owner:
users = db["users"]
user_data = users.find_one({"id": context.author.id, "guild_id": context.guild.id})
if not user_data:
user_data = CONSTANTS.user_data_template(context.author.id, context.guild.id)
users.insert_one(user_data)
if "trusted" in user_data:
if not user_data["trusted"]:
await context.send("You must be the guild owner or trusted to use this command!")
return
else:
return
guilds = db["guilds"]
guild = guilds.find_one({"id": context.guild.id})
if not guild:
guild = CONSTANTS.guild_data_template(context.guild.id)
guilds.insert_one(guild)
if "security" not in guild:
newdata = {
"$set": {
"security": {
"antinuke": {
"anti_danger_perms": enabled,
"anti_massban": False,
"anti_masskick": False,
"anti_masscreate": False,
"anti_massdelete": False,
"anti_massping": False,
"anti_webhook_spam": False
}
}
}
}
guilds.update_one({"id": context.guild.id}, newdata)
else:
newdata = {
"$set": {
"security.antinuke.anti_danger_perms": enabled
}
}
guilds.update_one({"id": context.guild.id}, newdata)
await context.send(f"Set `anti_danger_perms` to `{enabled}`")
@antinuke.command(
name="anti_massban",
description="Prevent someone from mass banning members (guild owner/trusted only)",
usage="antinuke anti_massban "
)
@commands.check(Checks.is_not_blacklisted)
async def anti_massban(self, context: Context, enabled: bool) -> None:
guild_owner = context.guild.owner
if context.author != guild_owner:
users = db["users"]
user_data = users.find_one({"id": context.author.id, "guild_id": context.guild.id})
if not user_data:
user_data = CONSTANTS.user_data_template(context.author.id, context.guild.id)
users.insert_one(user_data)
if "trusted" in user_data:
if not user_data["trusted"]:
await context.send("You must be the guild owner or trusted to use this command!")
return
else:
return
guilds = db["guilds"]
guild = guilds.find_one({"id": context.guild.id})
if not guild:
guild = CONSTANTS.guild_data_template(context.guild.id)
guilds.insert_one(guild)
if "security" not in guild:
newdata = {
"$set": {
"security": {
"antinuke": {
"anti_danger_perms": False,
"anti_massban": enabled,
"anti_masskick": False,
"anti_masscreate": False,
"anti_massdelete": False,
"anti_massping": False,
"anti_webhook_spam": False
}
}
}
}
guilds.update_one({"id": context.guild.id}, newdata)
else:
newdata = {
"$set": {
"security.antinuke.anti_massban": enabled
}
}
guilds.update_one({"id": context.guild.id}, newdata)
await context.send(f"Set `anti_massban` to `{enabled}`")
@antinuke.command(
name="anti_masskick",
description="Prevent someone from mass kicking members (guild owner/trusted only)",
usage="antinuke anti_masskick "
)
@commands.check(Checks.is_not_blacklisted)
async def anti_masskick(self, context: Context, enabled: bool) -> None:
guild_owner = context.guild.owner
if context.author != guild_owner:
users = db["users"]
user_data = users.find_one({"id": context.author.id, "guild_id": context.guild.id})
if not user_data:
user_data = CONSTANTS.user_data_template(context.author.id, context.guild.id)
users.insert_one(user_data)
if "trusted" in user_data:
if not user_data["trusted"]:
await context.send("You must be the guild owner or trusted to use this command!")
return
else:
return
guilds = db["guilds"]
guild = guilds.find_one({"id": context.guild.id})
if not guild:
guild = CONSTANTS.guild_data_template(context.guild.id)
guilds.insert_one(guild)
if "security" not in guild:
newdata = {
"$set": {
"security": {
"antinuke": {
"anti_danger_perms": False,
"anti_massban": False,
"anti_masskick": enabled,
"anti_masscreate": False,
"anti_massdelete": False,
"anti_massping": False,
"anti_webhook_spam": False
}
}
}
}
guilds.update_one({"id": context.guild.id}, newdata)
else:
newdata = {
"$set": {
"security.antinuke.anti_masskick": enabled
}
}
guilds.update_one({"id": context.guild.id}, newdata)
await context.send(f"Set `anti_masskick` to `{enabled}`")
@antinuke.command(
name="anti_massdelete",
description="Prevent someone from mass deleting channels (guild owner/trusted only)",
usage="antinuke anti_massdelete "
)
@commands.check(Checks.is_not_blacklisted)
async def anti_massdelete(self, context: Context, enabled: bool) -> None:
guild_owner = context.guild.owner
if context.author != guild_owner:
users = db["users"]
user_data = users.find_one({"id": context.author.id, "guild_id": context.guild.id})
if not user_data:
user_data = CONSTANTS.user_data_template(context.author.id, context.guild.id)
users.insert_one(user_data)
if "trusted" in user_data:
if not user_data["trusted"]:
await context.send("You must be the guild owner or trusted to use this command!")
return
else:
return
guilds = db["guilds"]
guild = guilds.find_one({"id": context.guild.id})
if not guild:
guild = CONSTANTS.guild_data_template(context.guild.id)
guilds.insert_one(guild)
if "security" not in guild:
newdata = {
"$set": {
"security": {
"antinuke": {
"anti_danger_perms": False,
"anti_massban": False,
"anti_masskick": False,
"anti_masscreate": False,
"anti_massdelete": enabled,
"anti_massping": False,
"anti_webhook_spam": False
}
}
}
}
guilds.update_one({"id": context.guild.id}, newdata)
else:
newdata = {
"$set": {
"security.antinuke.anti_massdelete": enabled
}
}
guilds.update_one({"id": context.guild.id}, newdata)
await context.send(f"Set `anti_massdelete` to `{enabled}`")
@antinuke.command(
name="anti_massping",
description="Prevent mass pinging (guild owner/trusted only)",
usage="antinuke anti_massping "
)
@commands.check(Checks.is_not_blacklisted)
async def massping(self, context: Context, enabled: bool) -> None:
guild_owner = context.guild.owner
if context.author != guild_owner:
users = db["users"]
user_data = users.find_one({"id": context.author.id, "guild_id": context.guild.id})
if not user_data:
user_data = CONSTANTS.user_data_template(context.author.id, context.guild.id)
users.insert_one(user_data)
if "trusted" in user_data:
if not user_data["trusted"]:
await context.send("You must be the guild owner or trusted to use this command!")
return
else:
return
guilds = db["guilds"]
guild = guilds.find_one({"id": context.guild.id})
if not guild:
guild = CONSTANTS.guild_data_template(context.guild.id)
guilds.insert_one(guild)
if "security" not in guild:
newdata = {
"$set": {
"security": {
"antinuke": {
"anti_danger_perms": False,
"anti_massban": False,
"anti_masskick": False,
"anti_masscreate": False,
"anti_massdelete": False,
"anti_massping": enabled,
"anti_webhook_spam": False
}
}
}
}
guilds.update_one({"id": context.guild.id}, newdata)
else:
newdata = {
"$set": {
"security.antinuke.anti_massping": enabled
}
}
guilds.update_one({"id": context.guild.id}, newdata)
await context.send(f"Set `anti_massping` to `{enabled}`")
@antinuke.command(
name="anti_webhook_spam",
description="Prevent webhook spam (guild owner/trusted only)",
usage="antinuke anti_webhook_spam "
)
@commands.check(Checks.is_not_blacklisted)
async def anti_webhook_spam(self, context: Context, enabled: bool) -> None:
guild_owner = context.guild.owner
if context.author != guild_owner:
users = db["users"]
user_data = users.find_one({"id": context.author.id, "guild_id": context.guild.id})
if not user_data:
user_data = CONSTANTS.user_data_template(context.author.id, context.guild.id)
users.insert_one(user_data)
if "trusted" in user_data:
if not user_data["trusted"]:
await context.send("You must be the guild owner or trusted to use this command!")
return
else:
return
guilds = db["guilds"]
guild = guilds.find_one({"id": context.guild.id})
if not guild:
guild = CONSTANTS.guild_data_template(context.guild.id)
guilds.insert_one(guild)
if "security" not in guild:
newdata = {
"$set": {
"security": {
"antinuke": {
"anti_danger_perms": False,
"anti_massban": False,
"anti_masskick": False,
"anti_masscreate": False,
"anti_massdelete": False,
"anti_massping": False,
"anti_webhook_spam": enabled
}
}
}
}
guilds.update_one({"id": context.guild.id}, newdata)
else:
newdata = {
"$set": {
"security.antinuke.anti_webhook_spam": enabled
}
}
guilds.update_one({"id": context.guild.id}, newdata)
await context.send(f"Set `anti_webhook_spam` to `{enabled}`")
@commands.hybrid_command(
name="lockdown",
description="Lockdown the server (guild owner/trusted only)",
usage="lockdown"
)
@commands.check(Checks.is_not_blacklisted)
async def lockdown(self, context: Context) -> None:
guild_owner = context.guild.owner
if context.author != guild_owner:
users = db["users"]
user_data = users.find_one({"id": context.author.id, "guild_id": context.guild.id})
if not user_data:
user_data = CONSTANTS.user_data_template(context.author.id, context.guild.id)
users.insert_one(user_data)
if "trusted" in user_data:
if not user_data["trusted"]:
await context.send("You must be the guild owner or trusted to use this command!")
return
else:
return
guilds = db["guilds"]
guild = guilds.find_one({"id": context.guild.id})
if not guild:
guild = CONSTANTS.guild_data_template(context.guild.id)
guilds.insert_one(guild)
embed = discord.Embed(
title = "Confirm Action",
description = "Are you sure you want to lockdown the server?",
color = discord.Color.red()
)
await context.send(embed=embed, view=ConfirmView("lockdown", context.author))
@commands.hybrid_command(
name="unlockdown",
description="Unlockdown the server (guild owner/trusted only)",
usage="unlockdown"
)
@commands.check(Checks.is_not_blacklisted)
async def unlockdown(self, context: Context) -> None:
guild_owner = context.guild.owner
try:
await context.send("Starting Unlockdown")
except:
pass
if context.author != guild_owner:
users = db["users"]
user_data = users.find_one({"id": context.author.id, "guild_id": context.guild.id})
if not user_data:
user_data = CONSTANTS.user_data_template(context.author.id, context.guild.id)
users.insert_one(user_data)
if "trusted" in user_data:
if not user_data["trusted"]:
await context.send("You must be the guild owner or trusted to use this command!")
return
else:
return
guilds = db["guilds"]
guild_data = guilds.find_one({"id": context.guild.id})
if not guild_data:
guild_data = CONSTANTS.guild_data_template(context.guild.id)
guilds.insert_one(guild_data)
if "oldperms" in guild_data:
for channel in context.guild.text_channels:
try:
channel_id_str = str(channel.id)
if channel_id_str in guild_data["oldperms"]:
# Deserialize the permissions
perms_dict = guild_data["oldperms"][channel_id_str]
overwrite = discord.PermissionOverwrite(**perms_dict)
await channel.set_permissions(context.guild.default_role, overwrite=overwrite)
except:
try:
await context.send("Failed to change perms for channel " + channel.name)
except:
pass
guilds.update_one({"id": context.guild.id}, {"$unset": {"oldperms": ""}})
guilds.update_one({"id": context.guild.id}, {"$set": {"lockdown": False}})
await context.send("Server unlockdown complete.")
class ConfirmView(discord.ui.View):
def __init__(self, value: str, author: discord.Member):
super().__init__()
self.value = value
self.author = author
@discord.ui.button(label="Confirm", style=discord.ButtonStyle.danger)
async def confirm(self, interaction: discord.Interaction, button: discord.ui.Button):
if self.author != interaction.user:
return interaction.response.send_message("no", ephemeral=True)
await interaction.response.defer()
if self.value == "lockdown":
await interaction.message.edit(content="Locking down the server...", view=None, embed=None)
oldperms = {}
for channel in interaction.guild.text_channels:
try:
overwrite = channel.overwrites_for(interaction.guild.default_role)
# Serialize the PermissionOverwrite object
perms_dict = {perm: value for perm, value in overwrite}
oldperms[str(channel.id)] = perms_dict
overwrite.send_messages = False
await channel.set_permissions(interaction.guild.default_role, overwrite=overwrite)
except:
pass
newdata = {
"$set": {
"lockdown": True,
"oldperms": oldperms
}
}
guilds = db["guilds"]
guilds.update_one({"id": interaction.guild.id}, newdata)
await interaction.message.edit(content="Server lockdown complete.", view=None, embed=None)
@discord.ui.button(label="Cancel", style=discord.ButtonStyle.primary)
async def cancel(self, interaction: discord.Interaction, button: discord.ui.Button):
if self.author != interaction.user:
return interaction.response.send_message("no", ephemeral=True)
await interaction.response.edit_message("Action cancelled", view=None)
async def setup(bot) -> None:
await bot.add_cog(Security(bot))
================================================
FILE: cogs/server.py
================================================
# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon
import discord
import os
import aiohttp
from cryptography.fernet import Fernet
from discord.ext import commands
from discord.ext.commands import Context
from utils import CachedDB, Checks, DBClient, CONSTANTS
from ui.setup import StartSetupView
db = DBClient.db
class Server(commands.Cog, name="⚙️ Server"):
def __init__(self, bot) -> None:
self.bot = bot
self.prefixDB = bot.prefixDB
@commands.hybrid_command(
name="setup",
description="It's setup time!!!!!!",
usage="testcommand"
)
@commands.check(Checks.is_not_blacklisted)
async def setup(self, context: Context) -> None:
if context.author.id != context.guild.owner.id:
await context.send("You must be the owner of the server to run this command.")
return
embed = discord.Embed(
title="Setup",
description="Let's set up your server!",
color=0x2F3136
)
await context.send(embed=embed, view=StartSetupView(context.guild.id))
@commands.command(
name="prefix",
description="Change the bot prefix",
usage="prefix "
)
@commands.check(Checks.is_not_blacklisted)
@commands.has_permissions(manage_channels=True)
async def prefix(self, context: commands.Context, prefix: str = "none"):
if prefix == "none":
return await context.send("Current prefix is: `" + self.prefixDB.get(str(context.guild.id)) + "`")
if prefix == "/":
return await context.send("Prefix cannot be `/`")
guild_id = str(context.guild.id)
self.prefixDB.set(guild_id, prefix)
self.prefixDB.save()
await context.send(f"Prefix set to {prefix}")
@commands.hybrid_command(
name="groq-api-key",
description="Set API key for AI (run in private channel please)",
usage="groq-api-key "
)
@commands.check(Checks.is_not_blacklisted)
@commands.has_permissions(manage_channels=True)
async def groq_api_key(self, context: commands.Context, key: str):
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)
cipher_suite = Fernet(os.getenv("HASHING_SECRET"))
cipher_text = cipher_suite.encrypt(key.encode())
try:
await context.message.delete()
except:
pass
if key == "NONE":
cipher_text = "NONE"
newdata = { "$set": { "groq_api_key": cipher_text } }
c.update_one({"id": context.guild.id}, newdata)
await context.send(f"Set groq api key")
@commands.hybrid_command(
name="stealemoji",
description="Steal an emoji from another server.",
usage="stealemoji "
)
@commands.check(Checks.is_not_blacklisted)
@commands.has_permissions(manage_emojis=True)
@commands.bot_has_permissions(manage_emojis=True)
async def stealemoji(self, context: Context, emoji: discord.PartialEmoji, name: str) -> None:
try:
emoji_bytes = await emoji.read()
await context.guild.create_custom_emoji(
name=name if name else emoji.name,
image=emoji_bytes,
reason=f"Emoji yoinked by {context.author} VIA {context.guild.me.name}",
)
await context.send(
embed=discord.Embed(
description=f"Emoji Stolen",
color=discord.Color.random(),
).set_image(url=emoji.url)
)
except Exception as e:
await context.send(str(e))
@commands.hybrid_command(
name="emojifromurl",
description="Add an emoji from a URL.",
usage="emojifromurl "
)
@commands.check(Checks.is_not_blacklisted)
@commands.has_permissions(manage_emojis=True)
@commands.bot_has_permissions(manage_emojis=True)
async def emojifromurl(self, context: Context, url: str, name: str) -> None:
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
if response.status == 200:
emoji_bytes = await response.read()
await context.guild.create_custom_emoji(
name=name,
image=emoji_bytes,
reason=f"Emoji added by {context.author} VIA {context.guild.me.name}",
)
await context.send(
embed=discord.Embed(
description=f"Emoji added",
color=discord.Color.random(),
).set_image(url=url)
)
else:
await context.send("Failed to download the emoji")
@commands.hybrid_group(
name="settings",
description="Command to change server settings",
aliases=["setting"],
usage="settings [args]"
)
@commands.check(Checks.is_not_blacklisted)
@commands.has_permissions(manage_channels=True)
async def settings(self, context: Context) -> None:
subcommands = [cmd for cmd in self.settings.walk_commands()]
data = []
for subcommand in subcommands:
description = subcommand.description.partition("\n")[0]
data.append(f"{await self.bot.get_prefix(context)}settings {subcommand.name} - {description}")
help_text = "\n".join(data)
embed = discord.Embed(
title=f"Help: Settings", description="List of available commands:", color=0xBEBEFE
)
embed.add_field(
name="Commands", value=f"```{help_text}```", inline=False
)
await context.send(embed=embed)
@settings.command(
name="show",
description="Show server settings",
usage="settings show"
)
@commands.check(Checks.is_not_blacklisted)
@commands.has_permissions(manage_channels=True)
async def show(self, context: Context) -> 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)
embed = discord.Embed(
title="Server Settings",
color=discord.Color.blue()
)
embed.add_field( name="Daily Cash", value=data["daily_cash"] )
embed.add_field( name="Tickets Category",
value=context.guild.get_channel(data["tickets_category"]).name.capitalize() if data["tickets_category"] else "None" )
embed.add_field( name="Tickets Support Role",
value=context.guild.get_role(data["tickets_support_role"]).mention if data["tickets_support_role"] else "None" )
embed.add_field( name="Log Channel", value=context.guild.get_channel(data["log_channel"]).mention if data["log_channel"] else "None" )
embed.add_field( name="Level Roles", value="`/setting level_roles show`")
embed.add_field( name="Level Announce Channel",
value=context.guild.get_channel( data["level_announce_channel"]).mention if (
"level_announce_channel" in data and context.guild.get_channel(data["level_announce_channel"]) != None
) else "None"
)
embed.add_field( name="Should announce levelup", value=data["should_announce_levelup"] if "should_announce_levelup" in data else "idk")
await context.send(embed=embed)
@settings.command(
name="announce-levelup",
description="Should levelups be announced?",
usage="settings announce-levelup "
)
@commands.check(Checks.is_not_blacklisted)
@commands.has_permissions(manage_roles=True)
async def should_announce_levelup(self, context: Context, enabled: bool) -> 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)
newdata = { "$set": { "should_announce_levelup": enabled } }
c.update_one({"id": context.guild.id}, newdata)
await context.send(f"Set should announce levelup to {enabled}")
@settings.command(
name="daily-cash",
description="Set daily cash amount",
usage="settings daily-cash "
)
@commands.check(Checks.is_not_blacklisted)
@commands.has_permissions(administrator=True)
async def daily_cash(self, context: Context, amount: int) -> 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)
newdata = { "$set": { "daily_cash": amount } }
c.update_one({"id": context.guild.id}, newdata)
await context.send(f"Set daily cash to {amount}")
@settings.command(
name="tickets-category",
description="Set category where tickets are created",
usage="settings tickets-category "
)
@commands.check(Checks.is_not_blacklisted)
@commands.has_permissions(administrator=True)
async def tickets_category(self, context: Context, category: discord.CategoryChannel) -> 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)
newdata = { "$set": { "tickets_category": category.id } }
c.update_one({"id": context.guild.id}, newdata)
await context.send(f"Set tickets category to {category.mention}")
@settings.command(
name="level-up-channel",
description="Set level up announce channel",
usage="settings level-up-channel "
)
@commands.check(Checks.is_not_blacklisted)
@commands.has_permissions(manage_channels=True)
async def level_up_channel(self, context: Context, channel: discord.TextChannel) -> 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)
newdata = { "$set": { "level_announce_channel": channel.id } }
c.update_one({"id": context.guild.id}, newdata)
await context.send(f"Set level announce channel to {channel.mention}")
@settings.command(
name="tickets-support-role",
description="Set ticket support role",
usage="settings tickets-support-role "
)
@commands.check(Checks.is_not_blacklisted)
@commands.has_permissions(manage_roles=True)
async def tickets_support_role(self, context: Context, role: discord.Role) -> 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)
newdata = { "$set": { "tickets_support_role": role.id } }
c.update_one({"id": context.guild.id}, newdata)
await context.send(f"Set tickets support role to {role.mention}")
@settings.command(
name="log-channel",
description="Set log channel",
usage="settings log-channel "
)
@commands.check(Checks.is_not_blacklisted)
@commands.has_permissions(manage_channels=True)
async def log_channel(self, context: Context, channel: discord.TextChannel) -> 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)
newdata = { "$set": { "log_channel": channel.id } }
c.update_one({"id": context.guild.id}, newdata)
await context.send(f"Set log channel to {channel.mention}")
@settings.command(
name="default-role",
description="Set default role to be given to new members",
usage="settings default-role "
)
@commands.check(Checks.is_not_blacklisted)
@commands.has_permissions(manage_roles=True)
async def default_role(self, context: Context, role: discord.Role) -> 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)
dangerous_permissions = [
"administrator",
"manage_guild",
"manage_roles",
"manage_channels",
"manage_messages",
"kick_members",
"ban_members",
"manage_webhooks",
"manage_emojis",
"manage_nicknames",
]
for permission in dangerous_permissions:
if getattr(role.permissions, permission):
return await context.send("The role has dangerous permissions. Please choose a role without dangerous permissions.")
newdata = { "$set": { "default_role": role.id } }
c.update_one({"id": context.guild.id}, newdata)
await context.send(f"Set default role to {role.name}")
@settings.group(
name="level-roles",
description="Commands to set up level roles",
usage="settings level-roles"
)
@commands.check(Checks.is_not_blacklisted)
@commands.has_permissions(manage_roles=True)
async def level_roles(self, context: Context) -> 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)
embed = discord.Embed(
title="Level Roles",
color=discord.Color.blue()
)
for r in data["level_roles"]:
embed.add_field(
name=r,
value=context.guild.get_role(data["level_roles"][r]).mention
)
await context.send(embed=embed)
@level_roles.command(
name="show",
description="Show level roles",
usage="settings level-roles show"
)
@commands.check(Checks.is_not_blacklisted)
@commands.has_permissions(manage_roles=True)
async def show_level_roles(self, context: Context) -> 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)
embed = discord.Embed(
title="Level Roles",
color=discord.Color.blue()
)
for r in data["level_roles"]:
embed.add_field(
name=r,
value=context.guild.get_role(data["level_roles"][r]).mention
)
await context.send(embed=embed)
@level_roles.command(
name="set",
description="Set level roles",
usage="settings level-roles set "
)
@commands.check(Checks.is_not_blacklisted)
@commands.has_permissions(manage_roles=True)
async def set(self, context: Context, level: int, role: discord.Role) -> 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)
level_roles = data["level_roles"]
level_roles[str(level)] = role.id
newdata = { "$set": { "level_roles": level_roles } }
c.update_one({"id": context.guild.id}, newdata)
await context.send(f"Set level {level} role to {role.name}")
@commands.hybrid_group(
name="command",
description="Commands to re-enable/disable commands",
aliases=["cmd"],
usage="Command [args]"
)
@commands.check(Checks.is_not_blacklisted)
@commands.has_permissions(manage_channels=True)
async def cmd(self, context: Context) -> None:
prefix = await self.bot.get_prefix(context)
cmds = "\n".join([f"{prefix}cmd {cmd.name} - {cmd.description}" for cmd in self.cmd.walk_commands()])
embed = discord.Embed(
title=f"Help: Command", description="List of available commands:", color=0xBEBEFE
)
embed.add_field(
name="Commands", value=f"```{cmds}```", inline=False
)
await context.send(embed=embed)
@cmd.command(
name="disable",
description="Disable a command",
usage="cmd disable "
)
@commands.check(Checks.is_not_blacklisted)
@commands.has_permissions(administrator=True)
async def disable(self, context: Context, *, command: str) -> None:
cmd = self.bot.get_command(command)
if not cmd:
return await context.send("Command not found")
if cmd.qualified_name.startswith("command") or cmd.qualified_name.startswith("cmd"):
return await context.send("You cannot disable this command")
guild = await CachedDB.find_one(db["guilds"], {"id": context.guild.id})
if not guild:
guild = CONSTANTS.guild_data_template(context.guild.id)
db["guilds"].insert_one(guild)
if cmd.qualified_name in guild["disabled_commands"]:
return await context.send(f"The command `{cmd.qualified_name}` is already disabled")
guild["disabled_commands"].append(cmd.qualified_name)
await CachedDB.update_one(db["guilds"], {"id": context.guild.id}, {"$set": {"disabled_commands": guild["disabled_commands"]}})
await context.send(f"Disabled the command `{cmd.qualified_name}`")
@cmd.command(
name="enable",
description="Re-enable a command",
usage="cmd enable "
)
@commands.check(Checks.is_not_blacklisted)
@commands.has_permissions(administrator=True)
async def cmd_enable(self, context: Context, *, command: str) -> None:
cmd = self.bot.get_command(command)
if not cmd:
return await context.send("Command not found")
guild = await CachedDB.find_one(db["guilds"], {"id": context.guild.id})
if not guild:
guild = CONSTANTS.guild_data_template(context.guild.id)
db["guilds"].insert_one(guild)
if command not in guild["disabled_commands"]:
return await context.send(f"The command `{cmd.qualified_name}` is not disabled")
guild["disabled_commands"].remove(cmd.qualified_name)
await CachedDB.update_one(db["guilds"], {"id": context.guild.id}, {"$set": {"disabled_commands": guild["disabled_commands"]}})
await context.send(f"Re-enabled the command `{cmd.qualified_name}`")
async def setup(bot) -> None:
await bot.add_cog(Server(bot))
================================================
FILE: cogs/staff.py
================================================
# This project is licensed under the terms of the GPL v3.0 license. Copyright 2024 Cyteon
import os
import re
from datetime import datetime, timedelta
import discord
from discord import app_commands
from discord.ext import commands
from discord.ext.commands import Context
from utils import DBClient, CONSTANTS, Checks, CachedDB
from ui.recreate import deleteconfirm
client = DBClient.client
db = client.potatobot
class Staff(commands.Cog, name="👮♂️ Staff"):
def __init__(self, bot) -> None:
self.bot = bot
self.prefixDB = bot.prefixDB
@commands.Cog.listener()
async def on_message_delete(self, message: discord.Message) -> None:
if message.author == self.bot.user or message.author.bot:
return
if message.author.guild_permissions.administrator:
return
c = db["guilds"]
data = await CachedDB.find_one(c, {"id": message.guild.id})
if not data:
data = CONSTANTS.guild_data_template(message.guild.id)
c.insert_one(data)
if not data["log_channel"]:
return
log_channel = message.guild.get_channel(data["log_channel"])
if not log_channel:
return
embed = discord.Embed(
title="Message Deleted",
description=f"Message sent by {message.author.mention} deleted in {message.channel.mention}",
color=0xff6961
)
embed.add_field(
name="Content",
value=message.content
)
await log_channel.send(embed=embed)
@commands.Cog.listener()
async def on_message_edit(self, before: discord.Message, after: discord.Message) -> None:
if before.author == self.bot.user or before.author.bot:
return
if before.author.guild_permissions.administrator:
return
if before.content == after.content:
return
c = db["guilds"]
data = await CachedDB.find_one(c, {"id": before.guild.id})
if not data:
data = CONSTANTS.guild_data_template(before.guild.id)
c.insert_one(data)
if not data["log_channel"]:
return
log_channel = before.guild.get_channel(data["log_channel"])
if not log_channel:
return
embed = discord.Embed(
title="Message Edited",
description=f"Message sent by {before.author.mention} edited in {before.channel.mention}",
color=0xfdfd96
)
embed.add_field(
name="Before",
value=before.content
)
embed.add_field(
name="After",
value=after.content
)
await log_channel.send(embed=embed)
@commands.Cog.listener()
async def on_member_remove(self, user: discord.User) -> None:
c = db["guilds"]
guild = user.guild
data = await CachedDB.find_one(c, {"id": guild.id})
if not data:
data = CONSTANTS.guild_data_template(guild.id)
c.insert_one(data)
if not data["log_channel"]:
return
log_channel = guild.get_channel(data["log_channel"])
if not log_channel:
return
embed = discord.Embed(
title="Member Left",
description=f"{user.mention} ({user}) left the server",
color=0xff6961
)
await log_channel.send(embed=embed)
@commands.Cog.listener()
async def on_member_ban(self, guild: discord.Guild, user: discord.User) -> None:
c = db["guilds"]
data = await CachedDB.find_one(c, {"id": guild.id})
if not data:
data = CONSTANTS.guild_data_template(guild.id)
c.insert_one(data)
if not data["log_channel"]:
return
log_channel = guild.get_channel(data["log_channel"])
if not log_channel:
return
embed = discord.Embed(
title="Member Banned",
description=f"{user.mention} was banned",
color=0xff6961
)
await log_channel.send(embed=embed)
@commands.Cog.listener()
async def on_member_unban(self, guild: discord.Guild, user: discord.User) -> None:
c = db["guilds"]
data = await CachedDB.find_one(c, {"id": guild.id})
if not data:
data = CONSTANTS.guild_data_template(guild.id)
c.insert_one(data)
if not data["log_channel"]:
return
log_channel = guild.get_channel(data["log_channel"])
if not log_channel:
return
embed = discord.Embed(
title="Member Unbanned",
description=f"{user.mention} was unbanned",
color=discord.Color.green()
)
await log_channel.send(embed=embed)
@commands.Cog.listener()
async def on_member_kick(self, guild: discord.Guild, user: discord.User) -> None:
c = db["guilds"]
data = await CachedDB.find_one(c, {"id": guild.id})
if not data:
data = CONSTANTS.guild_data_template(guild.id)
c.insert_one(data)
if not data["log_channel"]:
return
log_channel = guild.get_channel(data["log_channel"])
if not log_channel:
return
embed = discord.Embed(
title="Member Kicked",
description=f"{user.mention} was kicked",
color=0xff6961
)
await log_channel.send(embed=embed)
@commands.Cog.listener()
async def on_member_join(self, user: discord.User) -> None:
if user.bot:
return
users = db["users"]
user_data = await CachedDB.find_one(users, {"id": user.id})
guilds = db["guilds"]
data = await CachedDB.find_one(guilds, {"id": user.guild.id})
if not data:
data = CONSTANTS.guild_data_template(user.guild.id)
guilds.insert_one(data)
if user_data:
if "jailed" in user_data:
if user_data["jailed"]:
if "jail_role" in data:
role = None
jail_channel = None
if data["jail_role"] == 0:
role = await user.guild.create_role(name="Jailed", reason="Jail role created by PotatoBot")
data["jail_role"] = role.id
newdata = {"$set": {"jail_role": role.id}}
guilds.update_one({"id": user.guild.id}, newdata)
else:
role = user.guild.get_role(data["jail_role"])
for old_role in user.roles:
if old_role == user.guild.default_role:
continue
await user.remove_roles(old_role)
await user.add_roles(role, reason="User is jailed and tried to rejoin")
return
if not "default_role" in data:
return
default_role = user.guild.get_role(data["default_role"])
if default_role:
await user.add_roles(default_role)
@commands.Cog.listener()
async def on_bulk_message_delete(self, messages) -> None:
embed = discord.Embed(
title="Bulk Message Delete",
description=f"{len(messages)} messages were deleted",
color=0xff6961
)
c = db["guilds"]
data = await CachedDB.find_one(c, {"id": messages[0].guild.id})
if not data:
data = CONSTANTS.guild_data_template(messages[0].guild.id)
c.insert_one(data)
if not data["log_channel"]:
return
log_channel = messages[0].guild.get_channel(data["log_channel"])
if not log_channel:
return
await log_channel.send(embed=embed)
@commands.Cog.listener()
async def on_guild_channel_create(self, channel: discord.TextChannel):
embed = discord.Embed(
title = "Channel Created",
description = f"Channel {channel.mention} was created",
color = discord.Color.green()
)
c = db["guilds"]
data = c.find_one({"id": channel.guild.id})
if not data:
data = CONSTANTS.guild_data_template(channel.guild.id)
c.insert_one(data)
if not data["log_channel"]:
return
log_channel = channel.guild.get_channel(data["log_channel"])
if not log_channel:
return
await log_channel.send(embed=embed)
@commands.Cog.listener()
async def on_guild_channel_delete(self, channel: discord.TextChannel):
embed = discord.Embed(
title = "Channel Deleted",
description = f"Channel {channel.mention} ({channel.name}) was deleted",
color = 0xff6961
)
c = db["guilds"]
data = c.find_one({"id": channel.guild.id})
if not data:
data = CONSTANTS.guild_data_template(channel.guild.id)
c.insert_one(data)
if not data["log_channel"]:
return
log_channel = channel.guild.get_channel(data["log_channel"])
if not log_channel:
return
try:
await log_channel.send(embed=embed)
except:
pass
###
@commands.hybrid_command(
name="kick",
aliases=["k", "yeet"],
description="Kick a user out of the server.",
usage="kick [reason]",
extras={"example":"kick @user advertising"}
)
@commands.check(Checks.is_not_blacklisted)
@commands.check(Checks.command_not_disabled)
@Checks.has_perm(kick_members=True)
@commands.bot_has_permissions(kick_members=True)
async def kick(
self, context: Context, member: discord.Member, *, reason: str = "Not specified"
) -> None:
if context.author.top_role.position <= member.top_role.position:
embed = discord.Embed(
description="You cannot kick a user with a higher or equal role than you.",
color=0xE02B2B,
)
return await context.send(embed=embed)
if member == self.bot.user:
return await context.send("what did i do :C")
if member.guild_permissions.administrator:
embed = discord.Embed(
description="User has administrator permissions.", color=0xE02B2B
)
await context.send(embed=embed)
else:
try:
messaged = False
try:
await member.send(f"You were kicked by **{context.author}** from **{context.guild.name}**!\nReason: {reason}")
messaged = True
except:
pass
await member.kick(reason=reason)
embed = discord.Embed(
description=f"**{member}** was kicked by **{context.author}**!",
color=0xBEBEFE,
)
embed.add_field(name="Reason:", value=reason)
embed.add_field(name="Messaged User:", value="Yes" if messaged else "No")
await context.send(embed=embed)
guilds = db["guilds"]
data = guilds.find_one({"id": context.guild.id})
if not data:
data = CONSTANTS.guild_data_template(context.guild.id)
guilds.insert_one(data)
if "log_channel" in data:
log_channel = context.guild.get_channel(data["log_channel"])
if log_channel:
embed = discord.Embed(
title="Member Kicked",
description=f"{member.mention} was kicked by {context.author.mention}",
color=0xff6961
)
embed.add_field(
name="Reason",
value=reason
)
await log_channel.send(embed=embed)
except:
embed = discord.Embed(
description="An error occurred while trying to kick the user. Make sure my role is above the role of the user you want to kick.",
color=0xE02B2B,
)
await context.send(embed=embed)
@commands.hybrid_command(
name="nick",
aliases=["n"],
description="Change the nickname of a user on a server.",
usage="nick ",
extras={"example":"nick @user new nickname"}
)
@commands.check(Checks.is_not_blacklisted)
@commands.check(Checks.command_not_disabled)
@Checks.has_perm(manage_nicknames=True)
@commands.bot_has_permissions(manage_nicknames=True)
async def nick(
self, context: Context, member: discord.Member, *, nickname: str = None
) -> None:
try:
await member.edit(nick=nickname)
embed = discord.Embed(
description=f"**{member}'s** new nickname is **{nickname}**!",
color=0xBEBEFE,
)
await context.send(embed=embed)
except:
embed = discord.Embed(
description="An error occurred while trying to change the nickname of the user. Make sure my role is above the role of the user you want to change the nickname.",
color=0xE02B2B,
)
await context.send(embed=embed)
@commands.hybrid_command(
name="ban",
aliases=["b"],
description="Bans a user from the server.",
usage="ban [reason]",
extras={"example": "ban @user spamming"},
)
@commands.check(Checks.is_not_blacklisted)
@commands.check(Checks.command_not_disabled)
@Checks.has_perm(ban_members=True)
@commands.bot_has_permissions(ban_members=True)
async def ban(
self, context: Context, member: discord.Member, *, reason: str = "Not specified"
) -> None:
if context.author.top_role.position <= member.top_role.position:
embed = discord.Embed(
description="You cannot kick a user with a higher or equal role than you.",
color=0xE02B2B,
)
return await context.send(embed=embed)
if member == self.bot.user:
return await context.send("what did i do :C")
try:
if member.guild_permissions.administrator:
embed = discord.Embed(
description="User has administrator permissions.", color=0xE02B2B
)
await context.send(embed=embed)
else:
messaged = False
try:
embed = discord.Embed(
title="You were banned!",
description=f"You were banned from **{context.guild.name}**",
color=0xff6961
)
embed.add_field(name="Reason", value=reason)
await member.send(embed=embed)
messaged = True
except:
pass
await member.ban(reason=reason, delete_message_days=0)
embed = discord.Embed(
description=f"**{member}** was banned by **{context.author}**!",
color=0xBEBEFE,
)
embed.add_field(name="Reason:", value=reason)
embed.add_field(name="Messaged User:", value="Yes" if messaged else "No")
await context.send(embed=embed)
guilds = db["guilds"]
data = guilds.find_one({"id": context.guild.id})
if not data:
data = CONSTANTS.guild_data_template(context.guild.id)
guilds.insert_one(data)
if "log_channel" in data:
log_channel = context.guild.get_channel(data["log_channel"])
if log_channel:
embed = discord.Embed(
title="Member Banned",
description=f"{member.mention} was banned by {context.author.mention}",
color=0xff6961
)
embed.add_field(
name="Reason",
value=reason
)
await log_channel.send(embed=embed)
except:
embed = discord.Embed(
title="Error!",
description="An error occurred while trying to ban the user. Make sure my role is above the role of the user you want to ban.",
color=0xE02B2B,
)
await context.send(embed=embed)
@commands.hybrid_command(
name="hackban",
description="Ban a user that is not in the server",
usage="hackban [reason]",
extras={"example": "hackban 1226487228914602005 spamming"}
)
@commands.check(Checks.is_not_blacklisted)
@commands.check(Checks.command_not_disabled)
@Checks.has_perm(ban_members=True)
@commands.bot_has_permissions(ban_members=True)
async def hackban(self, context: Context, user: discord.User, *, reason: str = "Not specified"):
if user == self.bot.user:
return await context.send("what did i do :C")
member = await context.guild.fetch_member(user.id)
if member:
return await context.send("User is already in the server! Use the `ban` command instead.")
try:
await context.guild.ban(user, reason=reason, delete_message_days=0)
embed = discord.Embed(
title="User Hackbanned",
description=f"**{user}** was hackbanned by **{context.author}**!",
color=0xBEBEFE,
)
embed.add_field(name="Reason:", value=reason)
guilds = db["guilds"]
data = guilds.find_one({"id": context.guild.id})
if not data:
data = CONSTANTS.guild_data_template(context.guild.id)
guilds.insert_one(data)
if "log_channel" in data:
log_channel = context.guild.get_channel(data["log_channel"])
if log_channel:
await log_channel.send(embed=embed)
await context.send(f"Banned **{user}**!")
except:
embed = discord.Embed(
title="Error!",
description="An error occurred while trying to ban the user.",
color=0xE02B2B,
)
await context.send(embed=embed)
@commands.hybrid_command(
name="softban",
description="Bans and unbans a user from the server to delete messages",
usage="softban ",
extras={"example": "softban @user"}
)
@commands.check(Checks.is_not_blacklisted)
@commands.check(Checks.command_not_disabled)
@Checks.has_perm(ban_members=True)
@commands.bot_has_permissions(ban_members=True)
async def softban(self, context: Context, user: discord.Member):
if context.author.top_role.position <= user.top_role.position:
embed = discord.Embed(
description="You cannot kick a user with a higher or equal role than you.",
color=0xE02B2B,
)
return await context.send(embed=embed)
if user == self.bot.user:
return await context.send("what did i do :C")
try:
if user.guild_permissions.administrator:
embed = discord.Embed(
description="User has administrator permissions.", color=0xE02B2B
)
return await context.send(embed=embed)
await context.guild.ban(user, reason="Softban", delete_message_days=7)
await context.guild.unban(user, reason="Softban")
embed = discord.Embed(
description=f"**{user}** was softbanned by **{context.author}**!",
color=0xBEBEFE,
)
await context.send(embed=embed)
except Exception as e:
embed = discord.Embed(
description="An error occurred while trying to softban the user, " + str(e),
color=0xE02B2B,
)
await context.send(embed=embed)
@commands.hybrid_command(
name="unban",
description="Unban a user from the server.",
usage="unban ",
extras={"example": "unban 1226487228914602005"}
)
@commands.check(Checks.is_not_blacklisted)
@commands.check(Checks.command_not_disabled)
@Checks.has_perm(ban_members=True)
@commands.bot_has_permissions(ban_members=True)
async def unban(self, context: Context, user: discord.User):
try:
banned_users = context.guild.bans()
async for ban_entry in banned_users:
if ban_entry.user.id == user.id:
await context.guild.unban(user)
embed = discord.Embed(
description=f"**{user}** was unbanned by **{context.author}**!",
color=0xBEBEFE,
)
await context.send(embed=embed)
try:
embed = discord.Embed(
title="You were unbanned!",
description=f"You were unbanned from **{context.guild.name}**",
color=discord.Color.green()
)
await user.send(embed=embed)
except:
pass
guilds = db["guilds"]
guild = guilds.find_one({"id": context.guild.id})
if not guild:
guild = CONSTANTS.guild_data_template(context.guild.id)
guilds.insert_one(guild)
if "log_channel" in guild:
log_channel = context.guild.get_channel(guild["log_channel"])
if log_channel:
embed = discord.Embed(
title="Member Unbanned",
description=f"{user.mention} was unbanned by {context.author.mention}",
color=discord.Color.green()
)
await log_channel.send(embed=embed)
return
embed = discord.Embed(
description="User is not banned.", color=0xE02B2B
)
await context.send(embed=embed)
except Exception as e:
embed = discord.Embed(
description="An error occurred while trying to unban the user: " + str(e),
color=0xE02B2B,
)
await context.send(embed=embed)
@commands.hybrid_command(
name="purge",
aliases=["clear"],
description="Delete a number of messages.",
usage="purge ",
extras={"example": "purge 10"}
)
@commands.check(Checks.is_not_blacklisted)
@commands.check(Checks.command_not_disabled)
@Checks.has_perm(manage_messages=True)
@commands.bot_has_permissions(manage_messages=True)
@app_commands.describe(amount="The amount of messages that should be deleted.")
async def purge(self, context: Context, amount: int) -> None:
await context.defer()
purged_messages = await context.channel.purge(limit=amount + 1)
embed = discord.Embed(
description=f"**{context.author}** cleared **{len(purged_messages)-1}** messages!",
color=0xBEBEFE,
)
await context.channel.send(embed=embed)
@commands.hybrid_command(
name="archive",
description="Archives in a text file the last messages with a chosen limit of messages.",
usage="archive ",
extras={"example": "archive 10"}
)
@commands.check(Checks.is_not_blacklisted)
@commands.check(Checks.command_not_disabled)
@Checks.has_perm(manage_messages=True)
async def archive(self, context: Context, limit: int = 10) -> None:
os.makedirs("logs", exist_ok=True)
log_file = f"logs/{context.channel.id}.log"
with open(log_file, "w", encoding="UTF-8") as f:
f.write(
f'Archived messages from: #{context.channel} ({context.channel.id}) in the guild "{context.guild}" ({context.guild.id}) at {datetime.now().strftime("%d.%m.%Y %H:%M:%S")}\n'
)
async for message in context.channel.history(
limit=limit, before=context.message
):
attachments = []
for attachment in message.attachments:
attachments.append(attachment.url)
attachments_text = (
f"[Attached File{'s' if len(attachments) >= 2 else ''}: {', '.join(attachments)}]"
if len(attachments) >= 1
else ""
)
f.write(
f"{message.created_at.strftime('%d.%m.%Y %H:%M:%S')} {message.author} {message.id}: {message.clean_content} {attachments_text}\n"
)
f = discord.File(log_file)
await context.send(file=f)
os.remove(log_file)
@commands.hybrid_command(
name="mute",
aliases=["timeout"],
description="Mute a user in the server.",
usage="mute