Initial commit
This commit is contained in:
674
LICENSE
Normal file
674
LICENSE
Normal file
@@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
22
README.md
22
README.md
@@ -1,3 +1,23 @@
|
||||
# Yuuki-Cogs
|
||||
Custom Cog Repo for the Red Discord bot
|
||||
|
||||
Custom Cogs for the Red Discord bot
|
||||
## Installation
|
||||
```
|
||||
[p]repo add Yuuki-Cogs https://github.com/YuukiEatsYou/Yuuki-Cogs
|
||||
```
|
||||
```
|
||||
[p]cog install [Cog-Name]
|
||||
```
|
||||
|
||||
## Overview
|
||||
|
||||
| Name | Description | Finished? |
|
||||
| :------------------- | :----------: | :----------: |
|
||||
| Referral | Get rewarded for inviting new members! | ✅ |
|
||||
| Kys | Tell the Bot to kys | ✅ |
|
||||
| Shop | Custom shop system including user marketplace | ✅ |
|
||||
| Tutorial | Displays a tutorial specific to my server. Fork to customize | ✅ |
|
||||
| RPG | Turn based combat game | ❌ |
|
||||
| Word Filter | Automatically delete messages containing certain words | ✅ |
|
||||
| Battlepass | Daily Rewards for Battlepass owners | ✅ |
|
||||
| Lottery | A lottery system | ✅ |
|
||||
|
5
battlepass/__init__.py
Normal file
5
battlepass/__init__.py
Normal file
@@ -0,0 +1,5 @@
|
||||
from .battlepass import BattlePass
|
||||
|
||||
|
||||
async def setup(bot):
|
||||
await bot.add_cog(BattlePass(bot))
|
BIN
battlepass/__pycache__/__init__.cpython-311.pyc
Normal file
BIN
battlepass/__pycache__/__init__.cpython-311.pyc
Normal file
Binary file not shown.
BIN
battlepass/__pycache__/battlepass.cpython-311.pyc
Normal file
BIN
battlepass/__pycache__/battlepass.cpython-311.pyc
Normal file
Binary file not shown.
296
battlepass/battlepass.py
Normal file
296
battlepass/battlepass.py
Normal file
@@ -0,0 +1,296 @@
|
||||
import discord
|
||||
import asyncio
|
||||
from datetime import datetime, timedelta
|
||||
from dateutil.parser import parse
|
||||
from redbot.core import commands, Config, bank
|
||||
from typing import Literal
|
||||
|
||||
class BattlePass(commands.Cog):
|
||||
"""Battle Pass system for daily rewards"""
|
||||
|
||||
def __init__(self, bot):
|
||||
self.bot = bot
|
||||
self.config = Config.get_conf(self, identifier=987654321)
|
||||
|
||||
default_global = {
|
||||
"price": 5000,
|
||||
"rewards": {}
|
||||
}
|
||||
|
||||
default_user = {
|
||||
"battle_pass": {
|
||||
"active": False,
|
||||
"purchase_date": None,
|
||||
"last_claim": None,
|
||||
"days_claimed": 0
|
||||
}
|
||||
}
|
||||
|
||||
self.config.register_global(**default_global)
|
||||
self.config.register_user(**default_user)
|
||||
|
||||
async def get_currency_name(self, ctx):
|
||||
"""Get currency name for the guild"""
|
||||
return await bank.get_currency_name(ctx.guild)
|
||||
|
||||
async def get_shop_cog(self):
|
||||
"""Get the shop cog instance"""
|
||||
return self.bot.get_cog("ShopSystem")
|
||||
|
||||
@commands.group()
|
||||
async def battlepass(self, ctx):
|
||||
"""Battle Pass commands"""
|
||||
pass
|
||||
|
||||
@battlepass.command(name="buy")
|
||||
async def battlepass_buy(self, ctx):
|
||||
"""Purchase the Battle Pass"""
|
||||
async with self.config.user(ctx.author).battle_pass() as bp:
|
||||
if bp["active"]:
|
||||
return await ctx.send("❌ You already have an active Battle Pass!")
|
||||
|
||||
price = await self.config.price()
|
||||
currency_name = await self.get_currency_name(ctx)
|
||||
|
||||
if await bank.get_balance(ctx.author) < price:
|
||||
return await ctx.send(
|
||||
f"❌ You need {price} {currency_name} to buy the Battle Pass!"
|
||||
)
|
||||
|
||||
await bank.withdraw_credits(ctx.author, price)
|
||||
bp["active"] = True
|
||||
bp["purchase_date"] = datetime.utcnow().isoformat()
|
||||
bp["last_claim"] = None
|
||||
bp["days_claimed"] = 0
|
||||
|
||||
await ctx.send(
|
||||
f"✅ Successfully purchased the Battle Pass for {price} {currency_name}!\n"
|
||||
"Use `!battlepass claim` to claim your first reward."
|
||||
)
|
||||
|
||||
@battlepass.command(name="claim")
|
||||
async def battlepass_claim(self, ctx):
|
||||
"""Claim your daily Battle Pass reward"""
|
||||
async with self.config.user(ctx.author).battle_pass() as bp:
|
||||
# Check if active
|
||||
if not bp["active"]:
|
||||
return await ctx.send("❌ You don't have an active Battle Pass!")
|
||||
|
||||
# Check if expired
|
||||
purchase_date = parse(bp["purchase_date"])
|
||||
if (datetime.utcnow() - purchase_date).days >= 30:
|
||||
bp["active"] = False
|
||||
return await ctx.send("❌ Your Battle Pass has expired!")
|
||||
|
||||
# Check cooldown
|
||||
last_claim = parse(bp["last_claim"]) if bp["last_claim"] else None
|
||||
if last_claim and (datetime.utcnow() - last_claim).total_seconds() < 86400:
|
||||
next_claim = last_claim + timedelta(days=1)
|
||||
remaining = next_claim - datetime.utcnow()
|
||||
hours = int(remaining.total_seconds() // 3600)
|
||||
minutes = int((remaining.total_seconds() % 3600) // 60)
|
||||
return await ctx.send(
|
||||
f"⏳ You can claim again in {hours}h {minutes}m!"
|
||||
)
|
||||
|
||||
# Get reward for current day
|
||||
rewards = await self.config.rewards()
|
||||
current_day = bp["days_claimed"] + 1
|
||||
reward = rewards.get(str(current_day))
|
||||
|
||||
if not reward:
|
||||
return await ctx.send("❌ Reward not configured for this day!")
|
||||
|
||||
# Process reward
|
||||
currency_name = await self.get_currency_name(ctx)
|
||||
shop_cog = await self.get_shop_cog()
|
||||
|
||||
if reward["type"] == "credits":
|
||||
amount = reward["amount"]
|
||||
await bank.deposit_credits(ctx.author, amount)
|
||||
message = f"💵 Received {amount} {currency_name}!"
|
||||
elif reward["type"] == "item":
|
||||
item_id = reward["id"]
|
||||
quantity = reward.get("quantity", 1)
|
||||
|
||||
if not shop_cog:
|
||||
return await ctx.send("❌ Shop system is not loaded!")
|
||||
|
||||
await shop_cog.ensure_ready()
|
||||
|
||||
# Check inventory space
|
||||
user_inv = await shop_cog.config.user(ctx.author).inventory()
|
||||
if len(user_inv) + quantity > 50:
|
||||
return await ctx.send("❌ Your inventory is full! Free up space and try again.")
|
||||
|
||||
# Add items
|
||||
for _ in range(quantity):
|
||||
user_inv.append(item_id)
|
||||
|
||||
await shop_cog.config.user(ctx.author).inventory.set(user_inv)
|
||||
item_name = shop_cog.shop_items[item_id]["name"]
|
||||
message = f"🎁 Received {quantity}x {item_name}!"
|
||||
else:
|
||||
return await ctx.send("❌ Invalid reward type configured!")
|
||||
|
||||
# Update user data
|
||||
bp["last_claim"] = datetime.utcnow().isoformat()
|
||||
bp["days_claimed"] = current_day
|
||||
|
||||
await ctx.send(
|
||||
f"🎉 Day {current_day} reward claimed! {message}\n"
|
||||
f"Total claimed: {current_day}/30 days"
|
||||
)
|
||||
|
||||
@battlepass.command(name="status")
|
||||
async def battlepass_status(self, ctx):
|
||||
"""Check your Battle Pass status"""
|
||||
bp = await self.config.user(ctx.author).battle_pass()
|
||||
|
||||
if not bp["active"]:
|
||||
return await ctx.send("ℹ️ You don't have an active Battle Pass!")
|
||||
|
||||
purchase_date = parse(bp["purchase_date"])
|
||||
days_active = (datetime.utcnow() - purchase_date).days
|
||||
days_left = 30 - days_active
|
||||
last_claim = parse(bp["last_claim"]) if bp["last_claim"] else None
|
||||
|
||||
embed = discord.Embed(
|
||||
title="Battle Pass Status",
|
||||
color=discord.Color.gold()
|
||||
)
|
||||
embed.add_field(name="Purchased On", value=purchase_date.strftime("%Y-%m-%d"), inline=True)
|
||||
embed.add_field(name="Days Active", value=f"{days_active}/30", inline=True)
|
||||
embed.add_field(name="Days Left", value=days_left, inline=True)
|
||||
embed.add_field(name="Rewards Claimed", value=f"{bp['days_claimed']}/30", inline=True)
|
||||
|
||||
if last_claim:
|
||||
next_claim = last_claim + timedelta(days=1)
|
||||
if datetime.utcnow() < next_claim:
|
||||
remaining = next_claim - datetime.utcnow()
|
||||
hours = int(remaining.total_seconds() // 3600)
|
||||
minutes = int((remaining.total_seconds() % 3600) // 60)
|
||||
embed.add_field(name="Next Claim", value=f"{hours}h {minutes}m", inline=True)
|
||||
else:
|
||||
embed.add_field(name="Next Claim", value="Available Now!", inline=True)
|
||||
else:
|
||||
embed.add_field(name="Next Claim", value="Available Now!", inline=True)
|
||||
|
||||
await ctx.send(embed=embed)
|
||||
|
||||
@commands.group()
|
||||
@commands.admin()
|
||||
async def battlepassadmin(self, ctx):
|
||||
"""Battle Pass admin commands"""
|
||||
pass
|
||||
|
||||
@battlepassadmin.command(name="price")
|
||||
async def battlepass_price(self, ctx, price: int):
|
||||
"""Set the Battle Pass price"""
|
||||
if price < 0:
|
||||
return await ctx.send("❌ Price must be positive!")
|
||||
|
||||
await self.config.price.set(price)
|
||||
currency_name = await self.get_currency_name(ctx)
|
||||
await ctx.send(f"✅ Battle Pass price set to {price} {currency_name}!")
|
||||
|
||||
@battlepassadmin.command(name="setreward")
|
||||
async def battlepass_setreward(self, ctx, day: int,
|
||||
reward_type: Literal["credits", "item"],
|
||||
*args):
|
||||
"""Set a Battle Pass reward
|
||||
|
||||
For credits: !battlepassadmin setreward [day] credits [amount]
|
||||
For items: !battlepassadmin setreward [day] item [item_id] [quantity=1]
|
||||
"""
|
||||
if day < 1 or day > 30:
|
||||
return await ctx.send("❌ Day must be between 1-30!")
|
||||
|
||||
rewards = await self.config.rewards()
|
||||
|
||||
if reward_type == "credits":
|
||||
if len(args) != 1:
|
||||
return await ctx.send("❌ Usage: `!battlepassadmin setreward [day] credits [amount]`")
|
||||
|
||||
try:
|
||||
amount = int(args[0])
|
||||
except ValueError:
|
||||
return await ctx.send("❌ Amount must be a number!")
|
||||
|
||||
if amount <= 0:
|
||||
return await ctx.send("❌ Amount must be positive!")
|
||||
|
||||
rewards[str(day)] = {"type": "credits", "amount": amount}
|
||||
|
||||
elif reward_type == "item":
|
||||
if not args:
|
||||
return await ctx.send("❌ Usage: `!battlepassadmin setreward [day] item [item_id] [quantity=1]`")
|
||||
|
||||
item_id = args[0].lower()
|
||||
quantity = int(args[1]) if len(args) > 1 else 1
|
||||
|
||||
if quantity < 1:
|
||||
return await ctx.send("❌ Quantity must be at least 1!")
|
||||
|
||||
# Verify item exists
|
||||
shop_cog = await self.get_shop_cog()
|
||||
if not shop_cog:
|
||||
return await ctx.send("❌ Shop system is not loaded!")
|
||||
|
||||
await shop_cog.ensure_ready()
|
||||
if item_id not in shop_cog.shop_items:
|
||||
return await ctx.send("❌ Item does not exist in the shop!")
|
||||
|
||||
rewards[str(day)] = {"type": "item", "id": item_id, "quantity": quantity}
|
||||
|
||||
await self.config.rewards.set(rewards)
|
||||
await ctx.send(f"✅ Reward for day {day} set!")
|
||||
|
||||
@battlepassadmin.command(name="viewrewards")
|
||||
async def battlepass_viewrewards(self, ctx):
|
||||
"""View all Battle Pass rewards (paginated)"""
|
||||
rewards = await self.config.rewards()
|
||||
shop_cog = await self.get_shop_cog()
|
||||
|
||||
if shop_cog:
|
||||
await shop_cog.ensure_ready()
|
||||
|
||||
if not rewards:
|
||||
return await ctx.send("ℹ️ No rewards configured yet!")
|
||||
|
||||
# Split rewards into pages (10 per page)
|
||||
sorted_rewards = sorted(rewards.items(), key=lambda x: int(x[0]))
|
||||
pages = []
|
||||
page = []
|
||||
|
||||
for day, reward in sorted_rewards:
|
||||
if reward["type"] == "credits":
|
||||
page.append(f"**Day {day}:** 💵 {reward['amount']} credits")
|
||||
elif reward["type"] == "item" and shop_cog:
|
||||
item_data = shop_cog.shop_items.get(reward["id"], {})
|
||||
name = item_data.get("name", f"Unknown Item ({reward['id']})")
|
||||
quantity = reward.get("quantity", 1)
|
||||
page.append(f"**Day {day}:** 🎁 {quantity}x {name}")
|
||||
else:
|
||||
page.append(f"**Day {day}:** ❌ Invalid reward configuration")
|
||||
|
||||
# Start new page after 10 entries
|
||||
if len(page) >= 10:
|
||||
pages.append("\n".join(page))
|
||||
page = []
|
||||
|
||||
# Add any remaining rewards
|
||||
if page:
|
||||
pages.append("\n".join(page))
|
||||
|
||||
# Create paginated embeds
|
||||
for i, page_content in enumerate(pages):
|
||||
embed = discord.Embed(
|
||||
title=f"Battle Pass Rewards (Page {i+1}/{len(pages)})",
|
||||
description=page_content,
|
||||
color=discord.Color.blue()
|
||||
)
|
||||
await ctx.send(embed=embed)
|
||||
|
||||
async def setup(bot):
|
||||
await bot.add_cog(BattlePass(bot))
|
14
battlepass/info.json
Normal file
14
battlepass/info.json
Normal file
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"author": ["YuukiEatsYou"],
|
||||
"description": "Battlepass System",
|
||||
"install_msg": "Thank you for installing battlepass!",
|
||||
"short": "Battlepass",
|
||||
"end_user_data_statement": "This cog stores user data.",
|
||||
"min_bot_version": "3.5.0",
|
||||
"max_bot_version": "3.5.20",
|
||||
"min_python_version": [3, 11, 0],
|
||||
"hidden": false,
|
||||
"disabled": false,
|
||||
"tags": ["fun", "economy"],
|
||||
"type": "COG"
|
||||
}
|
6
info.json
Normal file
6
info.json
Normal file
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"author": ["YuukiEatsYou"],
|
||||
"description": "Collection of useful cogs for Red Discord Bot",
|
||||
"install_msg": "Thanks for adding my repo! Use `[p]cog list your-repo-name` to see available cogs.",
|
||||
"short": "Yuuki's custom cogs"
|
||||
}
|
5
kys/__init__.py
Normal file
5
kys/__init__.py
Normal file
@@ -0,0 +1,5 @@
|
||||
from .kys import KysCog
|
||||
|
||||
|
||||
async def setup(bot):
|
||||
await bot.add_cog(KysCog(bot))
|
14
kys/info.json
Normal file
14
kys/info.json
Normal file
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"author": ["YuukiEatsYou"],
|
||||
"description": "Tell your bot to kys!",
|
||||
"install_msg": "Thank you for installing kys!",
|
||||
"short": "Kys",
|
||||
"end_user_data_statement": "This cog doesn't store any user data.",
|
||||
"min_bot_version": "3.5.0",
|
||||
"max_bot_version": "3.5.20",
|
||||
"min_python_version": [3, 11, 0],
|
||||
"hidden": false,
|
||||
"disabled": false,
|
||||
"tags": ["fun"],
|
||||
"type": "COG"
|
||||
}
|
39
kys/kys.py
Normal file
39
kys/kys.py
Normal file
@@ -0,0 +1,39 @@
|
||||
from redbot.core import commands
|
||||
import discord
|
||||
import random
|
||||
|
||||
class KysCog(commands.Cog):
|
||||
"""Responds with a random GIF when !kys is used"""
|
||||
|
||||
def __init__(self, bot):
|
||||
self.bot = bot
|
||||
# Add your DIRECT GIF URLs here
|
||||
self.gif_urls = [
|
||||
"https://media.tenor.com/fYukkGwzLbsAAAAd/tenor.gif",
|
||||
"https://media.tenor.com/znYZvCPVkPQAAAAd/tenor.gif",
|
||||
"https://media.tenor.com/EKk-IX4CAjYAAAAd/tenor.gif",
|
||||
"https://media.tenor.com/eohEkLqD9AgAAAAd/tenor.gif",
|
||||
"https://media.tenor.com/iRRfRNU7IGMAAAAd/tenor.gif",
|
||||
"https://media.tenor.com/0uGObo7wlWMAAAAd/tenor.gif",
|
||||
"https://media.tenor.com/eOvNbqR1ANUAAAAd/tenor.gif",
|
||||
"https://media.tenor.com/WZ2FaJkLXgcAAAAd/tenor.gif",
|
||||
"https://media.tenor.com/51ADdhpqqo4AAAAd/tenor.gif",
|
||||
"https://media.tenor.com/9IMZudPio58AAAAd/tenor.gif",
|
||||
# Add more GIFs as needed
|
||||
]
|
||||
@commands.command()
|
||||
async def kys(self, ctx):
|
||||
|
||||
# Select a random GIF
|
||||
gif_url = random.choice(self.gif_urls)
|
||||
|
||||
# Send the GIF
|
||||
try:
|
||||
embed = discord.Embed(color=await ctx.embed_color())
|
||||
embed.set_image(url=gif_url)
|
||||
await ctx.send(embed=embed)
|
||||
except:
|
||||
await ctx.send("GIF failed to load 😢 Please check the URLs!")
|
||||
|
||||
async def setup(bot):
|
||||
await bot.add_cog(KysCog(bot))
|
5
lottery/__init__.py
Normal file
5
lottery/__init__.py
Normal file
@@ -0,0 +1,5 @@
|
||||
from .lottery import Lottery
|
||||
|
||||
|
||||
async def setup(bot):
|
||||
await bot.add_cog(Lottery(bot))
|
BIN
lottery/__pycache__/__init__.cpython-311.pyc
Normal file
BIN
lottery/__pycache__/__init__.cpython-311.pyc
Normal file
Binary file not shown.
BIN
lottery/__pycache__/lottery.cpython-311.pyc
Normal file
BIN
lottery/__pycache__/lottery.cpython-311.pyc
Normal file
Binary file not shown.
14
lottery/info.json
Normal file
14
lottery/info.json
Normal file
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"author": ["YuukiEatsYou"],
|
||||
"description": "Lottery",
|
||||
"install_msg": "Thank you for installing lottery!",
|
||||
"short": "Lotto",
|
||||
"end_user_data_statement": "This cog stores user data.",
|
||||
"min_bot_version": "3.5.0",
|
||||
"max_bot_version": "3.5.20",
|
||||
"min_python_version": [3, 11, 0],
|
||||
"hidden": false,
|
||||
"disabled": false,
|
||||
"tags": ["fun"],
|
||||
"type": "COG"
|
||||
}
|
266
lottery/lottery.py
Normal file
266
lottery/lottery.py
Normal file
@@ -0,0 +1,266 @@
|
||||
import asyncio
|
||||
import random
|
||||
import discord
|
||||
import time
|
||||
from redbot.core import commands, Config, bank
|
||||
from redbot.core.bot import Red
|
||||
from typing import Dict, List, Tuple, Optional
|
||||
|
||||
class Lottery(commands.Cog):
|
||||
def __init__(self, bot: Red):
|
||||
self.bot = bot
|
||||
self.config = Config.get_conf(self, identifier=1234567890)
|
||||
default_guild = {
|
||||
"pool": 0, # Current prize pool (credits)
|
||||
"tickets": {}, # {user_id: [n1, n2, n3, n4, n5]}
|
||||
"channel_id": None, # Announcement channel ID
|
||||
"cycle_minutes": 300, # Default 5 hours (300 minutes)
|
||||
"multiplier": 1, # Default prize pool multiplier
|
||||
"next_draw": 0, # Timestamp of next draw
|
||||
}
|
||||
self.config.register_guild(**default_guild)
|
||||
self.lottery_task = None
|
||||
self.bot.loop.create_task(self.initialize_scheduler())
|
||||
|
||||
async def initialize_scheduler(self):
|
||||
await self.bot.wait_until_ready()
|
||||
self.lottery_task = self.bot.loop.create_task(self.lottery_scheduler())
|
||||
|
||||
def cog_unload(self):
|
||||
if self.lottery_task:
|
||||
self.lottery_task.cancel()
|
||||
|
||||
async def lottery_scheduler(self):
|
||||
while True:
|
||||
data = await self.config.guild(self.bot.guilds[0]).all()
|
||||
next_draw = data["next_draw"]
|
||||
current_time = time.time()
|
||||
|
||||
# Calculate wait time
|
||||
if next_draw <= current_time:
|
||||
# Draw immediately if we missed the schedule
|
||||
wait_time = 0
|
||||
await self.config.guild(self.bot.guilds[0]).next_draw.set(
|
||||
current_time + data["cycle_minutes"] * 60
|
||||
)
|
||||
else:
|
||||
wait_time = next_draw - current_time
|
||||
|
||||
await asyncio.sleep(wait_time)
|
||||
await self.draw_lottery(self.bot.guilds[0])
|
||||
|
||||
# Set next draw time
|
||||
cycle_minutes = await self.config.guild(self.bot.guilds[0]).cycle_minutes()
|
||||
next_draw = time.time() + cycle_minutes * 60
|
||||
await self.config.guild(self.bot.guilds[0]).next_draw.set(next_draw)
|
||||
|
||||
@commands.command()
|
||||
@commands.cooldown(1, 1, commands.BucketType.user)
|
||||
async def lottobuy(self, ctx: commands.Context):
|
||||
"""Buy a lottery ticket for 5000 credits (1 per draw cycle)"""
|
||||
async with self.config.guild(ctx.guild).all() as data:
|
||||
user_id = str(ctx.author.id)
|
||||
|
||||
# Check existing ticket
|
||||
if user_id in data["tickets"]:
|
||||
await ctx.send("You already have a ticket for this draw cycle!")
|
||||
return
|
||||
|
||||
# Check balance
|
||||
if await bank.get_balance(ctx.author) < 5000:
|
||||
await ctx.send("You need 5000 credits to buy a ticket!")
|
||||
return
|
||||
|
||||
# Deduct credits and add to pool
|
||||
await bank.withdraw_credits(ctx.author, 5000)
|
||||
data["pool"] += 5000
|
||||
|
||||
# Generate ticket
|
||||
ticket = [random.randint(0, 9) for _ in range(5)]
|
||||
data["tickets"][user_id] = ticket
|
||||
|
||||
# Calculate time until next draw
|
||||
next_draw = await self.config.guild(ctx.guild).next_draw()
|
||||
time_left = next_draw - time.time()
|
||||
if time_left <= 0:
|
||||
time_str = "soon"
|
||||
else:
|
||||
hours = int(time_left // 3600)
|
||||
minutes = int((time_left % 3600) // 60)
|
||||
time_str = f"{hours} hours and {minutes} minutes"
|
||||
|
||||
await ctx.send(
|
||||
f"Ticket purchased! Your numbers: `{ticket}`\n"
|
||||
f"Next draw in approximately {time_str}"
|
||||
)
|
||||
|
||||
@commands.command()
|
||||
async def lottopool(self, ctx: commands.Context):
|
||||
"""Show current lottery prize pool"""
|
||||
data = await self.config.guild(ctx.guild).all()
|
||||
base_pool = data["pool"]
|
||||
multiplier = data["multiplier"]
|
||||
total_pool = base_pool * multiplier
|
||||
|
||||
tickets = data["tickets"]
|
||||
next_draw = data["next_draw"]
|
||||
time_left = next_draw - time.time()
|
||||
|
||||
if time_left <= 0:
|
||||
time_str = "soon"
|
||||
else:
|
||||
hours = int(time_left // 3600)
|
||||
minutes = int((time_left % 3600) // 60)
|
||||
time_str = f"{hours}h {minutes}m"
|
||||
|
||||
await ctx.send(
|
||||
f"**Base Pool:** {base_pool} credits\n"
|
||||
f"**Multiplier:** {multiplier}x\n"
|
||||
f"**Total Prize Pool:** {total_pool} credits\n"
|
||||
f"**Tickets Sold:** {len(tickets)}\n"
|
||||
f"**Next Draw:** {time_str}"
|
||||
)
|
||||
|
||||
@commands.group()
|
||||
@commands.admin_or_permissions(manage_guild=True)
|
||||
async def lottoset(self, ctx: commands.Context):
|
||||
"""Lottery admin settings"""
|
||||
pass
|
||||
|
||||
@lottoset.command()
|
||||
async def channel(self, ctx: commands.Context, channel: discord.TextChannel):
|
||||
"""Set the lottery announcement channel"""
|
||||
await self.config.guild(ctx.guild).channel_id.set(channel.id)
|
||||
await ctx.send(f"Lottery announcements will now be sent to {channel.mention}")
|
||||
|
||||
@lottoset.command()
|
||||
async def cycle(self, ctx: commands.Context, minutes: int):
|
||||
"""Set draw cycle length in minutes (applies next cycle)"""
|
||||
if minutes < 1:
|
||||
return await ctx.send("Cycle must be at least 1 minute")
|
||||
await self.config.guild(ctx.guild).cycle_minutes.set(minutes)
|
||||
await ctx.send(f"Draw cycle set to {minutes} minutes. Will apply after current cycle.")
|
||||
|
||||
@lottoset.command()
|
||||
async def multiplier(self, ctx: commands.Context, multiplier: int):
|
||||
"""Set prize pool multiplier (e.g., 10 for 10x)"""
|
||||
if multiplier < 1:
|
||||
return await ctx.send("Multiplier must be at least 1")
|
||||
await self.config.guild(ctx.guild).multiplier.set(multiplier)
|
||||
await ctx.send(f"Prize pool multiplier set to {multiplier}x")
|
||||
|
||||
async def draw_lottery(self, guild: discord.Guild):
|
||||
data = await self.config.guild(guild).all()
|
||||
if not data["tickets"]:
|
||||
# Reset timer if no tickets
|
||||
next_draw = time.time() + data["cycle_minutes"] * 60
|
||||
await self.config.guild(guild).next_draw.set(next_draw)
|
||||
return
|
||||
|
||||
# Apply multiplier to prize pool
|
||||
base_pool = data["pool"]
|
||||
multiplier = data["multiplier"]
|
||||
prize_pool = base_pool * multiplier
|
||||
|
||||
# Generate winning numbers
|
||||
winning_numbers = [random.randint(0, 9) for _ in range(5)]
|
||||
winners = [] # (user_id, match_count, ticket)
|
||||
|
||||
# Check tickets
|
||||
for user_id, ticket in data["tickets"].items():
|
||||
matches = sum(1 for i in range(5) if ticket[i] == winning_numbers[i])
|
||||
if matches > 0:
|
||||
winners.append((int(user_id), matches, ticket))
|
||||
|
||||
total_wins = sum(match_count for _, match_count, _ in winners)
|
||||
|
||||
# Calculate winnings
|
||||
payouts = {}
|
||||
if winners:
|
||||
if total_wins <= 5:
|
||||
per_win = int(prize_pool * 0.2)
|
||||
for user_id, match_count, _ in winners:
|
||||
payout = match_count * per_win
|
||||
payouts[user_id] = payouts.get(user_id, 0) + payout
|
||||
else:
|
||||
per_win = prize_pool // total_wins
|
||||
for user_id, match_count, _ in winners:
|
||||
payout = match_count * per_win
|
||||
payouts[user_id] = payouts.get(user_id, 0) + payout
|
||||
|
||||
# Distribute winnings
|
||||
for user_id, amount in payouts.items():
|
||||
user = guild.get_member(user_id)
|
||||
if user:
|
||||
await bank.deposit_credits(user, amount)
|
||||
|
||||
# Calculate leftover
|
||||
total_payout = sum(payouts.values())
|
||||
leftover = base_pool - (total_payout // multiplier) # Revert multiplier for storage
|
||||
|
||||
# Save results
|
||||
await self.config.guild(guild).pool.set(leftover)
|
||||
await self.config.guild(guild).tickets.set({})
|
||||
|
||||
# Send announcement
|
||||
channel_id = data["channel_id"]
|
||||
if not channel_id:
|
||||
return
|
||||
|
||||
channel = guild.get_channel(channel_id)
|
||||
if not channel:
|
||||
return
|
||||
|
||||
embed = discord.Embed(
|
||||
title="🎰 Lottery Draw Results 🎰",
|
||||
color=discord.Color.gold()
|
||||
)
|
||||
|
||||
# Format winning numbers
|
||||
win_str = " ".join(str(n) for n in winning_numbers)
|
||||
embed.add_field(name="Winning Numbers", value=f"`{win_str}`", inline=False)
|
||||
|
||||
# Format results
|
||||
if not winners:
|
||||
result = "No winning tickets! Prize pool carries over to next draw."
|
||||
else:
|
||||
result = []
|
||||
for user_id, match_count, ticket in winners:
|
||||
user = guild.get_member(user_id)
|
||||
ticket_str = " ".join(str(n) for n in ticket)
|
||||
payout = payouts.get(user_id, 0)
|
||||
result.append(
|
||||
f"**{user.mention if user else 'Unknown'}** - "
|
||||
f"`{ticket_str}` ({match_count}/5) - "
|
||||
f"**{payout} credits**"
|
||||
)
|
||||
result = "\n".join(result)
|
||||
|
||||
embed.add_field(
|
||||
name="Results",
|
||||
value=result or "No winners",
|
||||
inline=False
|
||||
)
|
||||
|
||||
# Get next cycle time for footer
|
||||
cycle_minutes = await self.config.guild(guild).cycle_minutes()
|
||||
hours = cycle_minutes // 60
|
||||
minutes = cycle_minutes % 60
|
||||
footer = f"Next draw in {hours} hours {minutes} minutes"
|
||||
|
||||
embed.add_field(
|
||||
name="Prize Pool Breakdown",
|
||||
value=(
|
||||
f"**Base Pool:** {base_pool} credits\n"
|
||||
f"**Multiplier:** {multiplier}x\n"
|
||||
f"**Total Pool:** {prize_pool} credits\n"
|
||||
f"**Paid Out:** {total_payout} credits\n"
|
||||
f"**Carry Over:** {leftover} credits"
|
||||
)
|
||||
)
|
||||
|
||||
embed.set_footer(text=footer)
|
||||
await channel.send(embed=embed)
|
||||
|
||||
def setup(bot: Red):
|
||||
bot.add_cog(Lottery(bot))
|
5
referral/__init__.py
Normal file
5
referral/__init__.py
Normal file
@@ -0,0 +1,5 @@
|
||||
from .referral import ReferralSystem
|
||||
|
||||
|
||||
async def setup(bot):
|
||||
await bot.add_cog(ReferralSystem(bot))
|
BIN
referral/__pycache__/__init__.cpython-311.pyc
Normal file
BIN
referral/__pycache__/__init__.cpython-311.pyc
Normal file
Binary file not shown.
BIN
referral/__pycache__/referral.cpython-311.pyc
Normal file
BIN
referral/__pycache__/referral.cpython-311.pyc
Normal file
Binary file not shown.
14
referral/info.json
Normal file
14
referral/info.json
Normal file
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"author": ["YuukiEatsYou"],
|
||||
"description": "Invite members to get Credits!",
|
||||
"install_msg": "Thank you for installing referral!",
|
||||
"short": "Referral System",
|
||||
"end_user_data_statement": "This cog stores user data.",
|
||||
"min_bot_version": "3.5.0",
|
||||
"max_bot_version": "3.5.20",
|
||||
"min_python_version": [3, 11, 0],
|
||||
"hidden": false,
|
||||
"disabled": false,
|
||||
"tags": ["fun", "economy"],
|
||||
"type": "COG"
|
||||
}
|
130
referral/referral.py
Normal file
130
referral/referral.py
Normal file
@@ -0,0 +1,130 @@
|
||||
import json
|
||||
import secrets
|
||||
import time
|
||||
import asyncio
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
|
||||
import discord
|
||||
from redbot.core import commands, bank, data_manager
|
||||
from redbot.core.errors import BankError
|
||||
|
||||
class ReferralSystem(commands.Cog):
|
||||
"""Referral system with one-time use codes and credit rewards"""
|
||||
|
||||
def __init__(self, bot):
|
||||
self.bot = bot
|
||||
self.data_path = Path(data_manager.cog_data_path(self)) / "referral_data.json"
|
||||
self.data = self._load_data()
|
||||
self.lock = asyncio.Lock() # For safe data writing
|
||||
|
||||
def _load_data(self):
|
||||
"""Load referral data from JSON file"""
|
||||
if not self.data_path.exists():
|
||||
return {"referral_codes": {}, "claimed_users": {}}
|
||||
|
||||
try:
|
||||
with open(self.data_path, "r") as f:
|
||||
return json.load(f)
|
||||
except (json.JSONDecodeError, FileNotFoundError):
|
||||
return {"referral_codes": {}, "claimed_users": {}}
|
||||
|
||||
async def _save_data(self):
|
||||
"""Save data to JSON file with thread lock"""
|
||||
async with self.lock:
|
||||
with open(self.data_path, "w") as f:
|
||||
json.dump(self.data, f, indent=4)
|
||||
|
||||
def _generate_code(self) -> str:
|
||||
"""Create a unique 8-character referral code"""
|
||||
while True:
|
||||
code = secrets.token_urlsafe(6)[:8].upper()
|
||||
if code not in self.data["referral_codes"]:
|
||||
return code
|
||||
|
||||
@commands.command()
|
||||
async def refer(self, ctx):
|
||||
"""Generate your personal referral code"""
|
||||
user_id = str(ctx.author.id)
|
||||
new_code = self._generate_code()
|
||||
|
||||
self.data["referral_codes"][new_code] = {
|
||||
"referrer": user_id,
|
||||
"created_at": time.time(),
|
||||
"used": False
|
||||
}
|
||||
|
||||
await self._save_data()
|
||||
await ctx.send(
|
||||
f"**Your referral code: `{new_code}`**\n"
|
||||
"Share this with friends! When they join and use "
|
||||
f"`!claimreferral {new_code}`, you'll both get rewards!"
|
||||
)
|
||||
|
||||
@commands.command()
|
||||
@commands.guild_only()
|
||||
async def claimreferral(self, ctx, code: str):
|
||||
"""Claim a referral reward using a referral code"""
|
||||
user_id = str(ctx.author.id)
|
||||
code = code.strip().upper()
|
||||
|
||||
# Check if user already claimed a referral
|
||||
if user_id in self.data["claimed_users"]:
|
||||
return await ctx.send("❌ You've already claimed a referral reward!")
|
||||
|
||||
# Validate code
|
||||
code_data = self.data["referral_codes"].get(code)
|
||||
if not code_data:
|
||||
return await ctx.send("❌ Invalid referral code!")
|
||||
if code_data["used"]:
|
||||
return await ctx.send("❌ This code has already been used!")
|
||||
|
||||
# Prevent self-claiming
|
||||
if user_id == code_data["referrer"]:
|
||||
return await ctx.send("❌ You can't claim your own referral code!")
|
||||
|
||||
# Verify join time (must be within last 24 hours)
|
||||
join_time = ctx.author.joined_at.replace(tzinfo=timezone.utc)
|
||||
time_since_join = datetime.now(timezone.utc) - join_time
|
||||
|
||||
if time_since_join > timedelta(hours=24):
|
||||
return await ctx.send(
|
||||
"❌ You joined more than 24 hours ago!\n"
|
||||
"Referral rewards can only be claimed by new members."
|
||||
)
|
||||
|
||||
# Process rewards
|
||||
reward = 10000 # Credits to award
|
||||
referrer = ctx.guild.get_member(int(code_data["referrer"]))
|
||||
|
||||
try:
|
||||
# Award new user
|
||||
await bank.deposit_credits(ctx.author, reward)
|
||||
|
||||
# Award referrer if still in server
|
||||
if referrer:
|
||||
await bank.deposit_credits(referrer, reward)
|
||||
except BankError as e:
|
||||
return await ctx.send(f"❌ Banking error: {e}")
|
||||
|
||||
# Update tracking
|
||||
code_data["used"] = True
|
||||
self.data["claimed_users"][user_id] = code
|
||||
await self._save_data()
|
||||
|
||||
# Send confirmation
|
||||
await ctx.send(
|
||||
f"🎉 Success! {ctx.author.mention} received **{reward} credits**.\n"
|
||||
f"Referrer {referrer.mention if referrer else 'someone'} also received **{reward} credits**!"
|
||||
)
|
||||
|
||||
@claimreferral.error
|
||||
async def claimreferral_error(self, ctx, error):
|
||||
"""Handle missing code argument"""
|
||||
if isinstance(error, commands.MissingRequiredArgument):
|
||||
await ctx.send("❌ Please specify a referral code! Example: `!claimreferral CODE123`")
|
||||
elif isinstance(error, commands.CommandInvokeError) and "NoneType" in str(error):
|
||||
await ctx.send("❌ Could not verify your join time. Please contact an admin.")
|
||||
|
||||
async def setup(bot):
|
||||
await bot.add_cog(ReferralSystem(bot))
|
5
rpg/__init__.py
Normal file
5
rpg/__init__.py
Normal file
@@ -0,0 +1,5 @@
|
||||
from .combat import CombatGame
|
||||
|
||||
|
||||
async def setup(bot):
|
||||
await bot.add_cog(CombatGame(bot))
|
BIN
rpg/__pycache__/__init__.cpython-311.pyc
Normal file
BIN
rpg/__pycache__/__init__.cpython-311.pyc
Normal file
Binary file not shown.
BIN
rpg/__pycache__/combat.cpython-311.pyc
Normal file
BIN
rpg/__pycache__/combat.cpython-311.pyc
Normal file
Binary file not shown.
BIN
rpg/__pycache__/mycog.cpython-311.pyc
Normal file
BIN
rpg/__pycache__/mycog.cpython-311.pyc
Normal file
Binary file not shown.
332
rpg/combat.py
Normal file
332
rpg/combat.py
Normal file
@@ -0,0 +1,332 @@
|
||||
from redbot.core import commands, Config, bank
|
||||
from redbot.core.errors import BalanceTooHigh, BankError
|
||||
import discord
|
||||
from discord.ui import Button, View
|
||||
import random
|
||||
|
||||
class CombatGame(commands.Cog):
|
||||
"""JRPG-style Combat System with Healing"""
|
||||
|
||||
def __init__(self, bot):
|
||||
self.bot = bot
|
||||
self.config = Config.get_conf(self, identifier=246813579)
|
||||
self.config.register_user(
|
||||
health=100,
|
||||
max_health=100,
|
||||
attack=15,
|
||||
defense=5
|
||||
)
|
||||
self.active_combats = {}
|
||||
self.reward_amount = 100 # Credits per victory
|
||||
self.heal_cost = 50 # Cost to fully heal
|
||||
|
||||
@commands.command()
|
||||
@commands.is_owner()
|
||||
async def resetplayer(self, ctx, user: discord.User):
|
||||
await self.config.user(user).clear()
|
||||
await ctx.send(f"Reset {user.name}'s data!")
|
||||
|
||||
@commands.command()
|
||||
async def heal(self, ctx):
|
||||
"""Restore your health to full for 100 credits"""
|
||||
user = ctx.author
|
||||
|
||||
# Ensure user is initialized
|
||||
await self.initialize_user(user)
|
||||
|
||||
# Check if user is in combat
|
||||
if user.id in self.active_combats:
|
||||
return await ctx.send("You can't heal while in combat!")
|
||||
|
||||
# Get player stats
|
||||
health = await self.config.user(user).health()
|
||||
max_health = await self.config.user(user).max_health()
|
||||
|
||||
# Check if already at full health
|
||||
if health >= max_health:
|
||||
return await ctx.send("You're already at full health!")
|
||||
|
||||
# Check player's balance
|
||||
try:
|
||||
balance = await bank.get_balance(user)
|
||||
if balance < self.heal_cost:
|
||||
currency_name = await bank.get_currency_name(ctx.guild)
|
||||
return await ctx.send(
|
||||
f"You need {self.heal_cost} {currency_name} to heal! "
|
||||
f"You only have {balance} {currency_name}."
|
||||
)
|
||||
|
||||
# Deduct credits
|
||||
await bank.withdraw_credits(user, self.heal_cost)
|
||||
|
||||
# Restore health
|
||||
await self.config.user(user).health.set(max_health)
|
||||
|
||||
# Get currency name for display
|
||||
currency_name = await bank.get_currency_name(ctx.guild)
|
||||
|
||||
# Create success embed
|
||||
embed = discord.Embed(
|
||||
title="💖 Healing Complete!",
|
||||
description=(
|
||||
f"Your health has been restored to {max_health}!\n"
|
||||
f"Paid {self.heal_cost} {currency_name}\n"
|
||||
f"New balance: {balance - self.heal_cost} {currency_name}"
|
||||
),
|
||||
color=0x00ff00
|
||||
)
|
||||
await ctx.send(embed=embed)
|
||||
|
||||
except BankError as e:
|
||||
await ctx.send(f"Healing failed: {str(e)}")
|
||||
except Exception as e:
|
||||
await ctx.send(f"An error occurred: {str(e)}")
|
||||
|
||||
async def initialize_user(self, user):
|
||||
"""Ensure user has initial stats"""
|
||||
async with self.config.user(user).all() as user_data:
|
||||
if user_data["health"] == 0: # If new user
|
||||
user_data["health"] = 100
|
||||
user_data["max_health"] = 100
|
||||
user_data["attack"] = 15
|
||||
user_data["defense"] = 5
|
||||
|
||||
@commands.command()
|
||||
async def combat(self, ctx):
|
||||
"""Start a combat encounter"""
|
||||
user = ctx.author
|
||||
user_id = user.id
|
||||
|
||||
# Ensure user is initialized
|
||||
await self.initialize_user(user)
|
||||
|
||||
# Check if user already in combat
|
||||
if user_id in self.active_combats:
|
||||
return await ctx.send("You're already in combat!")
|
||||
|
||||
# Get player health from config
|
||||
player_health = await self.config.user(user).health()
|
||||
|
||||
# Initialize combat
|
||||
combat_data = {
|
||||
"player_health": player_health,
|
||||
"enemy_health": random.randint(40, 150),
|
||||
"player_defending": False,
|
||||
"enemy_defending": False,
|
||||
"message": None
|
||||
}
|
||||
self.active_combats[user_id] = combat_data
|
||||
|
||||
# Create combat interface
|
||||
embed = await self.create_combat_embed(user, combat_data)
|
||||
view = self.create_combat_view()
|
||||
combat_data["message"] = await ctx.send(embed=embed, view=view)
|
||||
|
||||
async def create_combat_embed(self, user, combat_data):
|
||||
"""Create embed for combat"""
|
||||
max_health = await self.config.user(user).max_health()
|
||||
|
||||
embed = discord.Embed(
|
||||
title=f"⚔️ {user.display_name}'s Battle",
|
||||
color=0xff0000
|
||||
)
|
||||
embed.add_field(
|
||||
name="Your Health",
|
||||
value=f"❤️ {combat_data['player_health']}/{max_health}",
|
||||
inline=True
|
||||
)
|
||||
|
||||
# Show enemy status with defense icon if defending
|
||||
enemy_status = "💀"
|
||||
if combat_data["enemy_defending"]:
|
||||
enemy_status = "🛡️"
|
||||
embed.add_field(
|
||||
name="Enemy Health",
|
||||
value=f"{enemy_status} {combat_data['enemy_health']}",
|
||||
inline=True
|
||||
)
|
||||
|
||||
# Show reward info if available
|
||||
if await bank.is_global():
|
||||
currency_name = await bank.get_currency_name(ctx.guild)
|
||||
embed.set_footer(text=f"Reward: {self.reward_amount} {currency_name} per victory")
|
||||
return embed
|
||||
|
||||
def create_combat_view(self):
|
||||
"""Create button view"""
|
||||
view = View(timeout=60.0)
|
||||
|
||||
# Attack Button
|
||||
attack_btn = Button(style=discord.ButtonStyle.danger, label="⚔️ Attack")
|
||||
attack_btn.callback = self.attack_handler
|
||||
view.add_item(attack_btn)
|
||||
|
||||
# Defend Button
|
||||
defend_btn = Button(style=discord.ButtonStyle.primary, label="🛡️ Defend")
|
||||
defend_btn.callback = self.defend_handler
|
||||
view.add_item(defend_btn)
|
||||
|
||||
return view
|
||||
|
||||
async def enemy_turn(self, user, combat_data):
|
||||
"""Enemy AI: Randomly choose to attack or defend"""
|
||||
# 70% chance to attack, 30% chance to defend
|
||||
if random.random() < 0.7:
|
||||
# Enemy attacks
|
||||
enemy_damage = random.randint(8, 12)
|
||||
|
||||
# Reduce damage if player is defending
|
||||
if combat_data["player_defending"]:
|
||||
enemy_damage = max(1, enemy_damage // 2) # At least 1 damage
|
||||
combat_data["player_defending"] = False # Reset defense
|
||||
return f"The enemy attacks! You block for **{enemy_damage}** reduced damage!"
|
||||
else:
|
||||
combat_data["player_health"] = max(0, combat_data["player_health"] - enemy_damage)
|
||||
return f"The enemy attacks for **{enemy_damage}** damage!"
|
||||
else:
|
||||
# Enemy defends
|
||||
combat_data["enemy_defending"] = True
|
||||
return "The enemy assumes a defensive stance! 🛡️"
|
||||
|
||||
async def award_victory_rewards(self, user, embed):
|
||||
"""Award credits to user after victory"""
|
||||
try:
|
||||
# Get currency name based on bank configuration
|
||||
if await bank.is_global():
|
||||
currency_name = await bank.get_currency_name(None)
|
||||
else:
|
||||
currency_name = await bank.get_currency_name(user.guild)
|
||||
|
||||
# Deposit credits
|
||||
await bank.deposit_credits(user, self.reward_amount)
|
||||
|
||||
# Add reward message to embed
|
||||
embed.description += f"\n\n🏆 **Victory Reward**: {self.reward_amount} {currency_name}!"
|
||||
|
||||
# Check new balance
|
||||
new_balance = await bank.get_balance(user)
|
||||
embed.set_footer(text=f"New balance: {new_balance} {currency_name}")
|
||||
|
||||
except BalanceTooHigh:
|
||||
max_balance = await bank.get_max_balance(user)
|
||||
await bank.set_balance(user, max_balance)
|
||||
currency_name = await bank.get_currency_name(user.guild)
|
||||
embed.description += f"\n\n🏆 **Victory Reward**: Reached max {currency_name} capacity!"
|
||||
except Exception as e:
|
||||
embed.description += f"\n\n⚠️ Reward failed: {str(e)}"
|
||||
|
||||
async def attack_handler(self, interaction):
|
||||
user = interaction.user
|
||||
user_id = user.id
|
||||
|
||||
if user_id not in self.active_combats:
|
||||
await interaction.response.send_message("No active combat!", ephemeral=True)
|
||||
return
|
||||
|
||||
combat_data = self.active_combats[user_id]
|
||||
|
||||
# Player attack
|
||||
player_attack = await self.config.user(user).attack()
|
||||
base_damage = random.randint(player_attack - 5, player_attack + 5)
|
||||
|
||||
# Reduce damage if enemy is defending
|
||||
if combat_data["enemy_defending"]:
|
||||
damage = max(1, base_damage // 2) # At least 1 damage
|
||||
combat_data["enemy_defending"] = False # Reset defense
|
||||
damage_msg = f"You attack for **{damage}** reduced damage! (Enemy defended)"
|
||||
else:
|
||||
damage = base_damage
|
||||
damage_msg = f"You attack for **{damage}** damage!"
|
||||
|
||||
combat_data["enemy_health"] = max(0, combat_data["enemy_health"] - damage)
|
||||
combat_data["player_defending"] = False # Player wasn't defending this turn
|
||||
|
||||
# Enemy turn if still alive
|
||||
enemy_msg = ""
|
||||
if combat_data["enemy_health"] > 0:
|
||||
enemy_msg = await self.enemy_turn(user, combat_data)
|
||||
|
||||
# Update embed
|
||||
embed = await self.create_combat_embed(user, combat_data)
|
||||
embed.description = f"{damage_msg}\n{enemy_msg}"
|
||||
|
||||
# Check combat outcome
|
||||
if combat_data["player_health"] <= 0:
|
||||
embed.description += "\n\n**You were defeated!**"
|
||||
await interaction.response.edit_message(embed=embed, view=None)
|
||||
del self.active_combats[user_id]
|
||||
return
|
||||
|
||||
if combat_data["enemy_health"] <= 0:
|
||||
embed.description += "\n\n**You defeated the enemy!**"
|
||||
await self.config.user(user).health.set(combat_data["player_health"])
|
||||
|
||||
# Award victory rewards
|
||||
await self.award_victory_rewards(user, embed)
|
||||
|
||||
await interaction.response.edit_message(embed=embed, view=None)
|
||||
del self.active_combats[user_id]
|
||||
return
|
||||
|
||||
await interaction.response.edit_message(embed=embed)
|
||||
|
||||
async def defend_handler(self, interaction):
|
||||
user = interaction.user
|
||||
user_id = user.id
|
||||
|
||||
if user_id not in self.active_combats:
|
||||
await interaction.response.send_message("No active combat!", ephemeral=True)
|
||||
return
|
||||
|
||||
combat_data = self.active_combats[user_id]
|
||||
combat_data["player_defending"] = True
|
||||
combat_data["enemy_defending"] = False # Reset enemy defense
|
||||
|
||||
# Enemy turn
|
||||
enemy_msg = await self.enemy_turn(user, combat_data)
|
||||
|
||||
# Update embed
|
||||
embed = await self.create_combat_embed(user, combat_data)
|
||||
embed.description = f"You assume a defensive stance! 🛡️\n{enemy_msg}"
|
||||
|
||||
# Check combat outcome
|
||||
if combat_data["player_health"] <= 0:
|
||||
embed.description += "\n\n**You were defeated!**"
|
||||
await interaction.response.edit_message(embed=embed, view=None)
|
||||
del self.active_combats[user_id]
|
||||
return
|
||||
|
||||
await interaction.response.edit_message(embed=embed)
|
||||
|
||||
@commands.command()
|
||||
@commands.is_owner()
|
||||
async def setreward(self, ctx, amount: int):
|
||||
"""Set the victory reward amount (owner only)"""
|
||||
if amount < 0:
|
||||
return await ctx.send("Reward amount must be positive!")
|
||||
|
||||
self.reward_amount = amount
|
||||
currency_name = await bank.get_currency_name(ctx.guild)
|
||||
await ctx.send(f"Victory reward set to {amount} {currency_name}!")
|
||||
|
||||
|
||||
@commands.command()
|
||||
@commands.is_owner()
|
||||
async def sethealcost(self, ctx, cost: int):
|
||||
"""Set the healing cost amount (owner only)"""
|
||||
if cost < 1:
|
||||
return await ctx.send("Healing cost must be at least 1 credit!")
|
||||
|
||||
self.heal_cost = cost
|
||||
currency_name = await bank.get_currency_name(ctx.guild)
|
||||
await ctx.send(f"Healing cost set to {cost} {currency_name}!")
|
||||
|
||||
@commands.Cog.listener()
|
||||
async def on_view_timeout(self, view):
|
||||
"""Clean up timed out combats"""
|
||||
for user_id, data in list(self.active_combats.items()):
|
||||
if data["message"] and data["message"].id == view.message.id:
|
||||
del self.active_combats[user_id]
|
||||
|
||||
async def setup(bot):
|
||||
await bot.add_cog(CombatGame(bot))
|
14
rpg/info.json
Normal file
14
rpg/info.json
Normal file
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"author": ["YuukiEatsYou"],
|
||||
"description": "Beat enemies to get Credits!",
|
||||
"install_msg": "Thank you for installing rpg!",
|
||||
"short": "RPG Combat Game",
|
||||
"end_user_data_statement": "This cog doesn't store any user data.",
|
||||
"min_bot_version": "3.5.0",
|
||||
"max_bot_version": "3.5.20",
|
||||
"min_python_version": [3, 11, 0],
|
||||
"hidden": false,
|
||||
"disabled": false,
|
||||
"tags": ["fun", "economy"],
|
||||
"type": "COG"
|
||||
}
|
5
russianroulette/__init__.py
Normal file
5
russianroulette/__init__.py
Normal file
@@ -0,0 +1,5 @@
|
||||
from .rr import RussianRoulette
|
||||
|
||||
|
||||
async def setup(bot):
|
||||
await bot.add_cog(RussianRoulette(bot))
|
14
russianroulette/info.json
Normal file
14
russianroulette/info.json
Normal file
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"author": ["YuukiEatsYou"],
|
||||
"description": "Russian Roulette!",
|
||||
"install_msg": "Thank you for installing russian roulette!",
|
||||
"short": "Russian Roulette",
|
||||
"end_user_data_statement": "This cog doesn't store any user data.",
|
||||
"min_bot_version": "3.5.0",
|
||||
"max_bot_version": "3.5.20",
|
||||
"min_python_version": [3, 11, 0],
|
||||
"hidden": false,
|
||||
"disabled": false,
|
||||
"tags": ["fun", "economy"],
|
||||
"type": "COG"
|
||||
}
|
240
russianroulette/rr.py
Normal file
240
russianroulette/rr.py
Normal file
@@ -0,0 +1,240 @@
|
||||
import random
|
||||
import asyncio
|
||||
import discord
|
||||
from redbot.core import commands, bank
|
||||
from redbot.core.errors import BalanceTooHigh
|
||||
|
||||
class RussianRoulette(commands.Cog):
|
||||
"""Multiplayer Russian Roulette with consistent bullet mechanics"""
|
||||
|
||||
ENTRY_FEE = 100000
|
||||
|
||||
def __init__(self, bot):
|
||||
self.bot = bot
|
||||
self.games = {}
|
||||
self.join_lock = asyncio.Lock()
|
||||
|
||||
async def get_member(self, guild: discord.Guild, user_id: int) -> discord.Member:
|
||||
"""Get member from guild or fetch globally if needed"""
|
||||
member = guild.get_member(user_id)
|
||||
if member:
|
||||
return member
|
||||
|
||||
try:
|
||||
return await guild.fetch_member(user_id)
|
||||
except discord.NotFound:
|
||||
try:
|
||||
return await self.bot.fetch_user(user_id)
|
||||
except discord.NotFound:
|
||||
return None
|
||||
|
||||
async def refund_player(self, ctx, guild: discord.Guild, user_id: int):
|
||||
"""Safely refund a player"""
|
||||
try:
|
||||
member = await self.get_member(guild, user_id)
|
||||
if member:
|
||||
await bank.deposit_credits(member, self.ENTRY_FEE)
|
||||
return True
|
||||
except (BalanceTooHigh, ValueError, TypeError, AttributeError):
|
||||
pass
|
||||
return False
|
||||
|
||||
async def refund_lobby(self, ctx, guild_id: int):
|
||||
"""Refund all players in a lobby"""
|
||||
if guild_id not in self.games:
|
||||
return [], []
|
||||
|
||||
guild = self.bot.get_guild(guild_id)
|
||||
if not guild:
|
||||
return [], []
|
||||
|
||||
game = self.games[guild_id]
|
||||
refunded = []
|
||||
failed = []
|
||||
|
||||
for user_id, user_name in list(game["players"].items()):
|
||||
if await self.refund_player(ctx, guild, user_id):
|
||||
refunded.append(f"<@{user_id}> ({user_name})")
|
||||
else:
|
||||
failed.append(f"<@{user_id}> ({user_name})")
|
||||
|
||||
del self.games[guild_id]
|
||||
return refunded, failed
|
||||
|
||||
@commands.command()
|
||||
@commands.guild_only()
|
||||
async def rrjoin(self, ctx):
|
||||
"""Join Russian Roulette (10,000 credit entry)"""
|
||||
guild = ctx.guild
|
||||
user = ctx.author
|
||||
entry_fee = self.ENTRY_FEE
|
||||
|
||||
async with self.join_lock:
|
||||
# Initialize game state
|
||||
if guild.id not in self.games:
|
||||
self.games[guild.id] = {
|
||||
"players": {},
|
||||
"pot": 0,
|
||||
"in_progress": False
|
||||
}
|
||||
|
||||
game = self.games[guild.id]
|
||||
|
||||
# Validation checks
|
||||
if game["in_progress"]:
|
||||
return await ctx.send("🚨 A game is in progress! Join the next round.")
|
||||
if user.id in game["players"]:
|
||||
return await ctx.send("⚠️ You're already in the lobby!")
|
||||
if len(game["players"]) >= 6:
|
||||
return await ctx.send("🔒 Lobby full! Use `!rrstart` to begin")
|
||||
|
||||
# Bank check
|
||||
try:
|
||||
balance = await bank.get_balance(user)
|
||||
if balance < entry_fee:
|
||||
return await ctx.send(f"❌ You need {entry_fee} credits! (You have: {balance})")
|
||||
|
||||
await bank.withdraw_credits(user, entry_fee)
|
||||
except Exception as e:
|
||||
return await ctx.send(f"❌ Bank error: {str(e)}")
|
||||
|
||||
# Add player
|
||||
game["players"][user.id] = user.display_name
|
||||
game["pot"] += entry_fee
|
||||
await ctx.send(
|
||||
f"🔫 {user.mention} joined! "
|
||||
f"Players: **{len(game['players'])}/6** | "
|
||||
f"Pot: **{game['pot']:,} credits**\n"
|
||||
f"Use `{ctx.prefix}rrstart` to begin or wait for more players"
|
||||
)
|
||||
|
||||
# Auto-start if full
|
||||
if len(game["players"]) == 6:
|
||||
await ctx.invoke(self.rrstart)
|
||||
|
||||
@commands.command()
|
||||
@commands.guild_only()
|
||||
async def rrstart(self, ctx):
|
||||
"""Start Russian Roulette with current players"""
|
||||
guild = ctx.guild
|
||||
|
||||
# Lobby check
|
||||
if guild.id not in self.games or not self.games[guild.id]["players"]:
|
||||
return await ctx.send("❌ No active lobby! Use `!rrjoin` first")
|
||||
|
||||
game = self.games[guild.id]
|
||||
|
||||
if game["in_progress"]:
|
||||
return await ctx.send("🚨 Game already running!")
|
||||
|
||||
if len(game["players"]) < 2:
|
||||
refunded, failed = await self.refund_lobby(ctx, guild.id)
|
||||
msg = "⚠️ Need at least 2 players! "
|
||||
if refunded:
|
||||
msg += f"Refunded: {', '.join(refunded)}. "
|
||||
if failed:
|
||||
msg += f"Failed to refund: {', '.join(failed)}"
|
||||
return await ctx.send(msg)
|
||||
|
||||
try:
|
||||
# Game setup
|
||||
game["in_progress"] = True
|
||||
player_data = list(game["players"].items())
|
||||
random.shuffle(player_data)
|
||||
|
||||
# Create chamber with random bullets (1-5)
|
||||
chamber = [False] * 6 # False = empty, True = bullet
|
||||
bullet_count = random.randint(1, 5)
|
||||
bullet_positions = random.sample(range(6), bullet_count)
|
||||
for pos in bullet_positions:
|
||||
chamber[pos] = True
|
||||
|
||||
# Start at random position
|
||||
current_chamber = random.randint(0, 5)
|
||||
|
||||
# Show game start
|
||||
embed = discord.Embed(
|
||||
title="💀 RUSSIAN ROULETTE STARTING",
|
||||
color=0xff0000,
|
||||
description=(
|
||||
f"**Pot:** {game['pot']:,} credits\n"
|
||||
f"**Bullets:** {bullet_count}/6\n"
|
||||
f"**Players:** {len(player_data)}"
|
||||
)
|
||||
)
|
||||
|
||||
await ctx.send(embed=embed)
|
||||
|
||||
# Game sequence
|
||||
survivors = []
|
||||
for user_id, display_name in player_data:
|
||||
await asyncio.sleep(2)
|
||||
|
||||
# Check current chamber
|
||||
if chamber[current_chamber]:
|
||||
await ctx.send(f"💥 **BANG!** <@{user_id}> ({display_name}) is eliminated!")
|
||||
else:
|
||||
await ctx.send(f"✅ *click* <@{user_id}> ({display_name}) survives!")
|
||||
survivors.append((user_id, display_name))
|
||||
|
||||
# Advance to next chamber
|
||||
current_chamber = (current_chamber + 1) % 6
|
||||
|
||||
# Payouts
|
||||
await asyncio.sleep(1)
|
||||
if survivors:
|
||||
winnings = game["pot"] // len(survivors)
|
||||
winners_msg = []
|
||||
failed_msg = []
|
||||
|
||||
for user_id, display_name in survivors:
|
||||
try:
|
||||
member = await self.get_member(guild, user_id)
|
||||
if member:
|
||||
await bank.deposit_credits(member, winnings)
|
||||
winners_msg.append(f"<@{user_id}> ({display_name})")
|
||||
else:
|
||||
raise ValueError("Player not found")
|
||||
except Exception as e:
|
||||
failed_msg.append(f"<@{user_id}> - {str(e)}")
|
||||
|
||||
result = f"🎉 **{len(survivors)} SURVIVOR(S) WIN!**\nEach receives **{winnings:,} credits**"
|
||||
if winners_msg:
|
||||
result += f"\nWinners: {', '.join(winners_msg)}"
|
||||
if failed_msg:
|
||||
result += f"\n❌ Failed payments: {', '.join(failed_msg)}"
|
||||
|
||||
await ctx.send(result)
|
||||
else:
|
||||
await ctx.send("☠️ **NO SURVIVORS!** The house keeps the pot!")
|
||||
|
||||
except Exception as e:
|
||||
await ctx.send(f"⚠️ Game error: {str(e)}. Refunding all players...")
|
||||
refunded, failed = await self.refund_lobby(ctx, guild.id)
|
||||
if refunded:
|
||||
await ctx.send(f"✅ Refunded: {', '.join(refunded)}")
|
||||
if failed:
|
||||
await ctx.send(f"❌ Failed to refund: {', '.join(failed)}")
|
||||
finally:
|
||||
# Cleanup
|
||||
if guild.id in self.games:
|
||||
del self.games[guild.id]
|
||||
|
||||
@commands.command()
|
||||
@commands.guild_only()
|
||||
async def rrcancel(self, ctx):
|
||||
"""Cancel the current lobby and refund players"""
|
||||
guild = ctx.guild
|
||||
if guild.id not in self.games:
|
||||
return await ctx.send("❌ No active lobby!")
|
||||
|
||||
refunded, failed = await self.refund_lobby(ctx, guild.id)
|
||||
msg = "✅ Lobby canceled. "
|
||||
if refunded:
|
||||
msg += f"Refunded: {', '.join(refunded)}. "
|
||||
if failed:
|
||||
msg += f"Failed to refund: {', '.join(failed)}"
|
||||
await ctx.send(msg)
|
||||
|
||||
async def setup(bot):
|
||||
await bot.add_cog(RussianRoulette(bot))
|
5
shop/__init__.py
Normal file
5
shop/__init__.py
Normal file
@@ -0,0 +1,5 @@
|
||||
from .shop import ShopSystem
|
||||
|
||||
|
||||
async def setup(bot):
|
||||
await bot.add_cog(ShopSystem(bot))
|
BIN
shop/__pycache__/__init__.cpython-311.pyc
Normal file
BIN
shop/__pycache__/__init__.cpython-311.pyc
Normal file
Binary file not shown.
BIN
shop/__pycache__/shop.cpython-311.pyc
Normal file
BIN
shop/__pycache__/shop.cpython-311.pyc
Normal file
Binary file not shown.
14
shop/info.json
Normal file
14
shop/info.json
Normal file
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"author": ["YuukiEatsYou"],
|
||||
"description": "Shop system that integrates with the Bank System",
|
||||
"install_msg": "Thank you for installing Shop! Run !shop, then !shopfile and modify the json file to add your own items.",
|
||||
"short": "Shop System",
|
||||
"end_user_data_statement": "This cog stores user data.",
|
||||
"min_bot_version": "3.5.0",
|
||||
"max_bot_version": "3.5.20",
|
||||
"min_python_version": [3, 11, 0],
|
||||
"hidden": false,
|
||||
"disabled": false,
|
||||
"tags": ["bank", "economy"],
|
||||
"type": "COG"
|
||||
}
|
649
shop/shop.py
Normal file
649
shop/shop.py
Normal file
@@ -0,0 +1,649 @@
|
||||
import json
|
||||
import asyncio
|
||||
import discord
|
||||
import math
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
from typing import Literal, Optional
|
||||
from redbot.core import commands, Config, bank, checks, data_manager
|
||||
from discord.ui import Button, View
|
||||
|
||||
class PaginatorView(View):
|
||||
"""View for paginating embeds with navigation buttons"""
|
||||
def __init__(self, embeds, timeout=60):
|
||||
super().__init__(timeout=timeout)
|
||||
self.embeds = embeds
|
||||
self.current_page = 0
|
||||
self.message = None
|
||||
|
||||
# Update button states
|
||||
self.update_buttons()
|
||||
|
||||
def update_buttons(self):
|
||||
"""Update button states based on current page"""
|
||||
# Clear existing buttons
|
||||
self.clear_items()
|
||||
|
||||
# Previous button
|
||||
prev_button = Button(emoji="⬅️", style=discord.ButtonStyle.secondary,
|
||||
disabled=self.current_page == 0)
|
||||
prev_button.callback = self.previous_page
|
||||
self.add_item(prev_button)
|
||||
|
||||
# Page counter
|
||||
page_button = Button(label=f"{self.current_page+1}/{len(self.embeds)}",
|
||||
style=discord.ButtonStyle.primary, disabled=True)
|
||||
self.add_item(page_button)
|
||||
|
||||
# Next button
|
||||
next_button = Button(emoji="➡️", style=discord.ButtonStyle.secondary,
|
||||
disabled=self.current_page == len(self.embeds)-1)
|
||||
next_button.callback = self.next_page
|
||||
self.add_item(next_button)
|
||||
|
||||
async def previous_page(self, interaction):
|
||||
"""Go to previous page"""
|
||||
if self.current_page > 0:
|
||||
self.current_page -= 1
|
||||
self.update_buttons()
|
||||
await interaction.response.edit_message(embed=self.embeds[self.current_page], view=self)
|
||||
|
||||
async def next_page(self, interaction):
|
||||
"""Go to next page"""
|
||||
if self.current_page < len(self.embeds) - 1:
|
||||
self.current_page += 1
|
||||
self.update_buttons()
|
||||
await interaction.response.edit_message(embed=self.embeds[self.current_page], view=self)
|
||||
|
||||
async def on_timeout(self):
|
||||
"""Disable buttons when view times out"""
|
||||
for item in self.children:
|
||||
item.disabled = True
|
||||
await self.message.edit(view=self)
|
||||
|
||||
class ShopSystem(commands.Cog):
|
||||
"""Shop system with inventory, global shop, and player marketplace"""
|
||||
|
||||
def __init__(self, bot):
|
||||
self.bot = bot
|
||||
self.data_path = data_manager.cog_data_path(self)
|
||||
self.shop_file = self.data_path / "shop_items.json"
|
||||
self.config = Config.get_conf(self, identifier=584930284)
|
||||
|
||||
default_user = {
|
||||
"inventory": []
|
||||
}
|
||||
|
||||
default_guild = {
|
||||
"market": []
|
||||
}
|
||||
|
||||
self.config.register_user(**default_user)
|
||||
self.config.register_guild(**default_guild)
|
||||
|
||||
# Initialize shop items
|
||||
self.shop_items = {}
|
||||
self.ready = asyncio.Event()
|
||||
bot.loop.create_task(self._load_shop_items())
|
||||
|
||||
async def _load_shop_items(self):
|
||||
"""Load shop items from JSON file"""
|
||||
try:
|
||||
# Create directory if it doesn't exist
|
||||
self.data_path.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
if not self.shop_file.exists():
|
||||
# Create default items if file doesn't exist
|
||||
default_items = {
|
||||
"sword": {
|
||||
"name": "Steel Sword",
|
||||
"description": "A sharp blade for combat",
|
||||
"price": 500,
|
||||
"limited": True,
|
||||
"quantity": 10,
|
||||
"image_url": "https://raw.githubusercontent.com/yourusername/yourrepo/main/sword.png"
|
||||
},
|
||||
"potion": {
|
||||
"name": "Health Potion",
|
||||
"description": "Restores 50 HP",
|
||||
"price": 100,
|
||||
"limited": False,
|
||||
"image_url": "https://raw.githubusercontent.com/yourusername/yourrepo/main/potion.png"
|
||||
},
|
||||
"shield": {
|
||||
"name": "Wooden Shield",
|
||||
"description": "Basic protection from attacks",
|
||||
"price": 300,
|
||||
"limited": True,
|
||||
"quantity": 5,
|
||||
"image_url": "https://raw.githubusercontent.com/yourusername/yourrepo/main/shield.png"
|
||||
}
|
||||
}
|
||||
with self.shop_file.open("w") as f:
|
||||
json.dump({"items": default_items}, f, indent=4)
|
||||
self.shop_items = default_items
|
||||
else:
|
||||
# Load existing items
|
||||
with self.shop_file.open("r") as f:
|
||||
data = json.load(f)
|
||||
self.shop_items = data.get("items", {})
|
||||
|
||||
# Ensure all items have required fields
|
||||
for item_id, item_data in self.shop_items.items():
|
||||
if "limited" not in item_data:
|
||||
item_data["limited"] = False
|
||||
if "quantity" not in item_data and item_data["limited"]:
|
||||
item_data["quantity"] = 1
|
||||
except Exception as e:
|
||||
print(f"Error loading shop items: {e}")
|
||||
self.shop_items = {}
|
||||
finally:
|
||||
self.ready.set()
|
||||
|
||||
async def _save_shop_items(self):
|
||||
"""Save shop items to JSON file"""
|
||||
try:
|
||||
with self.shop_file.open("w") as f:
|
||||
json.dump({"items": self.shop_items}, f, indent=4)
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"Error saving shop items: {e}")
|
||||
return False
|
||||
|
||||
async def ensure_ready(self):
|
||||
"""Ensure shop data is loaded before proceeding"""
|
||||
await self.ready.wait()
|
||||
|
||||
async def get_currency_name(self, ctx):
|
||||
"""Get the currency name for the guild"""
|
||||
return await bank.get_currency_name(ctx.guild)
|
||||
|
||||
@commands.command()
|
||||
async def shop(self, ctx):
|
||||
"""View the global shop with pagination"""
|
||||
await self.ensure_ready()
|
||||
if not self.shop_items:
|
||||
return await ctx.send("🛒 The shop is currently empty!")
|
||||
|
||||
currency_name = await self.get_currency_name(ctx)
|
||||
items_to_show = []
|
||||
|
||||
# Collect available items
|
||||
for item_id, item_data in self.shop_items.items():
|
||||
if item_data.get("limited", False) and item_data.get("quantity", 0) <= 0:
|
||||
continue
|
||||
items_to_show.append((item_id, item_data))
|
||||
|
||||
if not items_to_show:
|
||||
return await ctx.send("🛒 The shop is currently sold out! Check back later.")
|
||||
|
||||
# Create paginated embeds
|
||||
embeds = []
|
||||
items_per_page = 5
|
||||
pages = (len(items_to_show) // items_per_page)
|
||||
if len(items_to_show) % items_per_page != 0:
|
||||
pages += 1
|
||||
|
||||
for page in range(pages):
|
||||
start_idx = page * items_per_page
|
||||
end_idx = start_idx + items_per_page
|
||||
page_items = items_to_show[start_idx:end_idx]
|
||||
|
||||
embed = discord.Embed(
|
||||
title=f"🛒 Global Shop - Page {page+1}/{pages}",
|
||||
color=discord.Color.blue()
|
||||
)
|
||||
|
||||
for item_id, item_data in page_items:
|
||||
stock = "∞" if not item_data.get("limited", False) else f"{item_data['quantity']} left"
|
||||
embed.add_field(
|
||||
name=f"{item_data['name']} ({item_id})",
|
||||
value=f"💵 Price: {item_data['price']} {currency_name}\n"
|
||||
f"📦 Stock: {stock}\n"
|
||||
f"📝 {item_data['description']}",
|
||||
inline=False
|
||||
)
|
||||
|
||||
embed.set_footer(text=f"Use !buy [item_id] to purchase")
|
||||
embeds.append(embed)
|
||||
|
||||
# Create and send paginator view
|
||||
view = PaginatorView(embeds)
|
||||
view.message = await ctx.send(embed=embeds[0], view=view)
|
||||
|
||||
@commands.command()
|
||||
async def buy(self, ctx, item_id: str, quantity: int = 1):
|
||||
"""Buy an item from the shop"""
|
||||
await self.ensure_ready()
|
||||
item_id = item_id.lower()
|
||||
item_data = self.shop_items.get(item_id)
|
||||
currency_name = await self.get_currency_name(ctx)
|
||||
|
||||
if not item_data:
|
||||
return await ctx.send("❌ That item doesn't exist!")
|
||||
|
||||
if quantity <= 0:
|
||||
return await ctx.send("❌ Quantity must be at least 1!")
|
||||
|
||||
if item_data.get("limited", False):
|
||||
if item_data["quantity"] <= 0:
|
||||
return await ctx.send("❌ This item is out of stock!")
|
||||
if quantity > item_data["quantity"]:
|
||||
return await ctx.send(f"❌ Only {item_data['quantity']} available!")
|
||||
|
||||
total_price = item_data["price"] * quantity
|
||||
user_balance = await bank.get_balance(ctx.author)
|
||||
|
||||
if user_balance < total_price:
|
||||
return await ctx.send(f"❌ You need {total_price} {currency_name} to buy this!")
|
||||
|
||||
# Check inventory space
|
||||
user_inv = await self.config.user(ctx.author).inventory()
|
||||
if len(user_inv) + quantity > 50:
|
||||
return await ctx.send("❌ Your inventory is full! (Max 50 items)")
|
||||
|
||||
# Process transaction
|
||||
await bank.withdraw_credits(ctx.author, total_price)
|
||||
|
||||
# Add items to inventory
|
||||
for _ in range(quantity):
|
||||
user_inv.append(item_id)
|
||||
|
||||
await self.config.user(ctx.author).inventory.set(user_inv)
|
||||
|
||||
# Update limited stock
|
||||
if item_data.get("limited", False):
|
||||
self.shop_items[item_id]["quantity"] -= quantity
|
||||
await self._save_shop_items()
|
||||
|
||||
await ctx.send(f"✅ Purchased {quantity}x {item_data['name']} for {total_price} {currency_name}!")
|
||||
|
||||
@commands.command()
|
||||
async def sell(self, ctx, item_id: str, quantity: int = 1):
|
||||
"""Sell an item back to the shop for 80% of the original price"""
|
||||
await self.ensure_ready()
|
||||
item_id = item_id.lower()
|
||||
item_data = self.shop_items.get(item_id)
|
||||
currency_name = await self.get_currency_name(ctx)
|
||||
|
||||
if not item_data:
|
||||
return await ctx.send("❌ That item doesn't exist in the shop!")
|
||||
|
||||
if quantity <= 0:
|
||||
return await ctx.send("❌ Quantity must be at least 1!")
|
||||
|
||||
# Get user inventory
|
||||
user_inv = await self.config.user(ctx.author).inventory()
|
||||
|
||||
# Count how many of this item the user has
|
||||
item_count = user_inv.count(item_id)
|
||||
if item_count < quantity:
|
||||
return await ctx.send(f"❌ You only have {item_count} of this item!")
|
||||
|
||||
# Calculate sell price (80% of original price, rounded down)
|
||||
sell_price_per_item = math.floor(item_data["price"] * 0.8)
|
||||
total_sell_price = sell_price_per_item * quantity
|
||||
|
||||
# Remove items from inventory
|
||||
# We'll remove the specified quantity of this item
|
||||
removed = 0
|
||||
new_inv = [item for item in user_inv if not (item == item_id and (removed := removed + 1) <= quantity)]
|
||||
|
||||
await self.config.user(ctx.author).inventory.set(new_inv)
|
||||
|
||||
# Deposit money to user
|
||||
await bank.deposit_credits(ctx.author, total_sell_price)
|
||||
|
||||
# Restock if it's a limited item
|
||||
if item_data.get("limited", False):
|
||||
self.shop_items[item_id]["quantity"] += quantity
|
||||
await self._save_shop_items()
|
||||
|
||||
await ctx.send(f"✅ Sold {quantity}x {item_data['name']} for {total_sell_price} {currency_name}!")
|
||||
|
||||
@commands.command()
|
||||
async def inventory(self, ctx, user: Optional[discord.User] = None):
|
||||
"""View your inventory with pagination"""
|
||||
await self.ensure_ready()
|
||||
target = user or ctx.author
|
||||
user_inv = await self.config.user(target).inventory()
|
||||
|
||||
if not user_inv:
|
||||
return await ctx.send(f"📭 {target.display_name}'s inventory is empty!")
|
||||
|
||||
# Count items
|
||||
item_counts = {}
|
||||
for item_id in user_inv:
|
||||
item_counts[item_id] = item_counts.get(item_id, 0) + 1
|
||||
|
||||
# Create paginated embeds
|
||||
embeds = []
|
||||
items_per_page = 9 # 3x3 grid
|
||||
items = list(item_counts.items())
|
||||
pages = (len(items) + items_per_page - 1) // items_per_page
|
||||
|
||||
for page in range(pages):
|
||||
start_idx = page * items_per_page
|
||||
end_idx = start_idx + items_per_page
|
||||
page_items = items[start_idx:end_idx]
|
||||
|
||||
embed = discord.Embed(
|
||||
title=f"🎒 {target.display_name}'s Inventory - Page {page+1}/{pages or 1}",
|
||||
description=f"{len(user_inv)}/50 slots used",
|
||||
color=discord.Color.green()
|
||||
)
|
||||
|
||||
for item_id, count in page_items:
|
||||
item_data = self.shop_items.get(item_id, {"name": f"Unknown Item ({item_id})"})
|
||||
embed.add_field(
|
||||
name=item_data["name"],
|
||||
value=f"ID: `{item_id}`\nQuantity: {count}",
|
||||
inline=True
|
||||
)
|
||||
|
||||
# Add empty fields to keep grid alignment
|
||||
if len(page_items) % 3 != 0:
|
||||
for _ in range(3 - (len(page_items) % 3)):
|
||||
embed.add_field(name="\u200b", value="\u200b", inline=True)
|
||||
|
||||
embeds.append(embed)
|
||||
|
||||
# Create and send paginator view
|
||||
view = PaginatorView(embeds)
|
||||
view.message = await ctx.send(embed=embeds[0], view=view)
|
||||
|
||||
@commands.command()
|
||||
async def item(self, ctx, item_id: str):
|
||||
"""View item information with image"""
|
||||
await self.ensure_ready()
|
||||
item_id = item_id.lower()
|
||||
item_data = self.shop_items.get(item_id)
|
||||
currency_name = await self.get_currency_name(ctx)
|
||||
|
||||
if not item_data:
|
||||
return await ctx.send("❌ Item not found!")
|
||||
|
||||
embed = discord.Embed(
|
||||
title=item_data["name"],
|
||||
description=item_data["description"],
|
||||
color=discord.Color.blue()
|
||||
)
|
||||
embed.add_field(name="Item ID", value=item_id, inline=True)
|
||||
embed.add_field(name="Price", value=f"{item_data['price']} {currency_name}", inline=True)
|
||||
|
||||
# Calculate sell price (80% of original)
|
||||
sell_price = math.floor(item_data["price"] * 0.8)
|
||||
embed.add_field(name="Sell Price", value=f"{sell_price} {currency_name}", inline=True)
|
||||
|
||||
if item_data.get("limited", False):
|
||||
stock = f"{item_data['quantity']} available"
|
||||
else:
|
||||
stock = "Unlimited supply"
|
||||
embed.add_field(name="Availability", value=stock, inline=False)
|
||||
|
||||
# Add image if available
|
||||
if image_url := item_data.get("image_url"):
|
||||
embed.set_image(url=image_url)
|
||||
else:
|
||||
embed.add_field(name="Image", value="No image available", inline=False)
|
||||
|
||||
await ctx.send(embed=embed)
|
||||
|
||||
@commands.command()
|
||||
async def market(self, ctx):
|
||||
"""View marketplace listings with pagination"""
|
||||
await self.ensure_ready()
|
||||
market_data = await self.config.guild(ctx.guild).market()
|
||||
currency_name = await self.get_currency_name(ctx)
|
||||
|
||||
if not market_data:
|
||||
return await ctx.send("ℹ️ The marketplace is empty!")
|
||||
|
||||
# Create paginated embeds
|
||||
embeds = []
|
||||
items_per_page = 5
|
||||
pages = (len(market_data) + items_per_page - 1) // items_per_page
|
||||
|
||||
for page in range(pages):
|
||||
start_idx = page * items_per_page
|
||||
end_idx = start_idx + items_per_page
|
||||
page_listings = market_data[start_idx:end_idx]
|
||||
|
||||
embed = discord.Embed(
|
||||
title=f"🏪 Player Marketplace - Page {page+1}/{pages or 1}",
|
||||
color=discord.Color.orange()
|
||||
)
|
||||
|
||||
for listing in page_listings:
|
||||
seller = self.bot.get_user(listing["seller_id"])
|
||||
item_data = self.shop_items.get(listing["item_id"], {"name": f"Unknown Item ({listing['item_id']})"})
|
||||
|
||||
embed.add_field(
|
||||
name=f"{item_data['name']} - 💵 {listing['price']} {currency_name}",
|
||||
value=f"Seller: {seller.mention if seller else 'Unknown'}\n"
|
||||
f"Listing ID: `{listing['id']}`\n"
|
||||
f"Item ID: `{listing['item_id']}`",
|
||||
inline=False
|
||||
)
|
||||
|
||||
embed.set_footer(text=f"Use !buymarket [listing_id] to purchase")
|
||||
embeds.append(embed)
|
||||
|
||||
# Create and send paginator view
|
||||
view = PaginatorView(embeds)
|
||||
view.message = await ctx.send(embed=embeds[0], view=view)
|
||||
|
||||
@commands.command()
|
||||
async def buymarket(self, ctx, listing_id: str):
|
||||
"""Buy an item from the marketplace
|
||||
|
||||
Example: !buymarket d93a8b7c-...
|
||||
"""
|
||||
await self.ensure_ready()
|
||||
market_data = await self.config.guild(ctx.guild).market()
|
||||
currency_name = await self.get_currency_name(ctx)
|
||||
|
||||
listing = next((l for l in market_data if l["id"] == listing_id), None)
|
||||
|
||||
if not listing:
|
||||
return await ctx.send("❌ Listing not found!")
|
||||
|
||||
# Check buyer's balance
|
||||
buyer_balance = await bank.get_balance(ctx.author)
|
||||
if buyer_balance < listing["price"]:
|
||||
return await ctx.send(f"❌ You need {listing['price']} {currency_name} to buy this!")
|
||||
|
||||
# Check inventory space
|
||||
buyer_inv = await self.config.user(ctx.author).inventory()
|
||||
if len(buyer_inv) >= 50:
|
||||
return await ctx.send("❌ Your inventory is full! (Max 50 items)")
|
||||
|
||||
# Process transaction
|
||||
seller = ctx.guild.get_member(listing["seller_id"])
|
||||
if seller:
|
||||
await bank.deposit_credits(seller, listing["price"])
|
||||
await bank.withdraw_credits(ctx.author, listing["price"])
|
||||
|
||||
# Transfer item
|
||||
buyer_inv.append(listing["item_id"])
|
||||
await self.config.user(ctx.author).inventory.set(buyer_inv)
|
||||
|
||||
# Remove listing
|
||||
market_data = [l for l in market_data if l["id"] != listing_id]
|
||||
await self.config.guild(ctx.guild).market.set(market_data)
|
||||
|
||||
await ctx.send(f"✅ Purchased item from marketplace for {listing['price']} {currency_name}!")
|
||||
|
||||
@commands.command()
|
||||
async def sellmarket(self, ctx, item_id: str, price: int):
|
||||
"""Sell an item on the marketplace
|
||||
|
||||
Example: !sellmarket sword 500
|
||||
"""
|
||||
await self.ensure_ready()
|
||||
currency_name = await self.get_currency_name(ctx)
|
||||
|
||||
if price <= 0:
|
||||
return await ctx.send("❌ Price must be positive!")
|
||||
|
||||
item_id = item_id.lower()
|
||||
user_inv = await self.config.user(ctx.author).inventory()
|
||||
|
||||
# Check if item exists in inventory
|
||||
if item_id not in user_inv:
|
||||
return await ctx.send("❌ You don't have that item in your inventory!")
|
||||
|
||||
# Check if item exists in shop
|
||||
if item_id not in self.shop_items:
|
||||
return await ctx.send("❌ That item doesn't exist in the shop!")
|
||||
|
||||
# Remove item from inventory
|
||||
user_inv.remove(item_id)
|
||||
await self.config.user(ctx.author).inventory.set(user_inv)
|
||||
|
||||
# Create listing
|
||||
new_listing = {
|
||||
"id": str(uuid4()),
|
||||
"seller_id": ctx.author.id,
|
||||
"item_id": item_id,
|
||||
"price": price
|
||||
}
|
||||
|
||||
market_data = await self.config.guild(ctx.guild).market()
|
||||
market_data.append(new_listing)
|
||||
await self.config.guild(ctx.guild).market.set(market_data)
|
||||
|
||||
await ctx.send(f"✅ Listed {self.shop_items[item_id]['name']} for {price} {currency_name}!")
|
||||
|
||||
# Admin commands
|
||||
@checks.admin()
|
||||
@commands.command()
|
||||
async def shopfile(self, ctx):
|
||||
"""Display the path to the shop items JSON file (Admin only)"""
|
||||
# Get absolute path to the JSON file
|
||||
abs_path = self.shop_file.resolve()
|
||||
|
||||
# Check if file exists
|
||||
file_exists = self.shop_file.exists()
|
||||
|
||||
# Create embed with information
|
||||
embed = discord.Embed(
|
||||
title="Shop System File Path",
|
||||
color=discord.Color.blue()
|
||||
)
|
||||
embed.add_field(
|
||||
name="JSON File Path",
|
||||
value=f"`{abs_path}`",
|
||||
inline=False
|
||||
)
|
||||
embed.add_field(
|
||||
name="File Exists",
|
||||
value="✅ Yes" if file_exists else "❌ No",
|
||||
inline=False
|
||||
)
|
||||
embed.add_field(
|
||||
name="File Size",
|
||||
value=f"{abs_path.stat().st_size} bytes" if file_exists else "N/A",
|
||||
inline=False
|
||||
)
|
||||
|
||||
# Add troubleshooting tips
|
||||
if not file_exists:
|
||||
embed.add_field(
|
||||
name="Troubleshooting",
|
||||
value="The file doesn't exist. The cog should create it automatically when loaded for the first time.",
|
||||
inline=False
|
||||
)
|
||||
|
||||
await ctx.send(embed=embed)
|
||||
|
||||
# If file exists, offer to show contents
|
||||
if file_exists:
|
||||
await ctx.send("Would you like to see the file contents? Type `yes` to confirm.")
|
||||
try:
|
||||
response = await self.bot.wait_for(
|
||||
"message",
|
||||
timeout=30,
|
||||
check=lambda m: m.author == ctx.author and m.channel == ctx.channel
|
||||
)
|
||||
if response.content.lower() == "yes":
|
||||
with open(self.shop_file, 'r') as f:
|
||||
content = f.read()
|
||||
# Discord has 2000 char limit, so truncate if needed
|
||||
if len(content) > 1900:
|
||||
content = content[:1900] + "\n... (truncated)"
|
||||
await ctx.send(f"```json\n{content}\n```")
|
||||
except asyncio.TimeoutError:
|
||||
pass
|
||||
|
||||
@checks.admin()
|
||||
@commands.command()
|
||||
async def shopadd(self, ctx, item_id: str, name: str, price: int,
|
||||
description: str, image_url: str,
|
||||
limited: Literal["yes", "no"] = "no", quantity: int = 1):
|
||||
"""Add a new item to the shop (Admin only)
|
||||
|
||||
Example: !shopadd gem "Rare Gem" 1000 "Shiny gem" https://.../gem.png yes 5
|
||||
"""
|
||||
await self.ensure_ready()
|
||||
item_id = item_id.lower()
|
||||
if item_id in self.shop_items:
|
||||
return await ctx.send("❌ Item ID already exists!")
|
||||
|
||||
self.shop_items[item_id] = {
|
||||
"name": name,
|
||||
"price": price,
|
||||
"description": description,
|
||||
"image_url": image_url,
|
||||
"limited": (limited.lower() == "yes")
|
||||
}
|
||||
|
||||
if self.shop_items[item_id]["limited"]:
|
||||
self.shop_items[item_id]["quantity"] = quantity
|
||||
|
||||
if await self._save_shop_items():
|
||||
await ctx.send(f"✅ Added {name} to the shop!")
|
||||
else:
|
||||
await ctx.send("❌ Failed to save shop items!")
|
||||
|
||||
@checks.admin()
|
||||
@commands.command()
|
||||
async def shopimage(self, ctx, item_id: str, image_url: str):
|
||||
"""Edit an item's image URL (Admin only)
|
||||
|
||||
Example: !shopimage sword https://.../new_sword.png
|
||||
"""
|
||||
await self.ensure_ready()
|
||||
item_id = item_id.lower()
|
||||
if item_id not in self.shop_items:
|
||||
return await ctx.send("❌ Item not found!")
|
||||
|
||||
self.shop_items[item_id]["image_url"] = image_url
|
||||
if await self._save_shop_items():
|
||||
await ctx.send(f"✅ Updated image for {self.shop_items[item_id]['name']}!")
|
||||
else:
|
||||
await ctx.send("❌ Failed to save shop items!")
|
||||
|
||||
@checks.admin()
|
||||
@commands.command()
|
||||
async def shoprestock(self, ctx, item_id: str, quantity: int):
|
||||
"""Restock a limited item (Admin only)
|
||||
|
||||
Example: !shoprestock sword 10
|
||||
"""
|
||||
await self.ensure_ready()
|
||||
item_id = item_id.lower()
|
||||
if item_id not in self.shop_items:
|
||||
return await ctx.send("❌ Item not found!")
|
||||
|
||||
if not self.shop_items[item_id].get("limited", False):
|
||||
return await ctx.send("❌ This item is not limited!")
|
||||
|
||||
self.shop_items[item_id]["quantity"] += quantity
|
||||
if await self._save_shop_items():
|
||||
await ctx.send(f"✅ Restocked {self.shop_items[item_id]['name']} by {quantity} units!")
|
||||
else:
|
||||
await ctx.send("❌ Failed to save shop items!")
|
||||
|
||||
async def setup(bot):
|
||||
await bot.add_cog(ShopSystem(bot))
|
35
shop/shop_items.json
Normal file
35
shop/shop_items.json
Normal file
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"items": {
|
||||
"taosocks": {
|
||||
"name": "Hu Tao's used socks",
|
||||
"description": "A pair of socks worn by Hu Tao",
|
||||
"price": 500,
|
||||
"limited": true,
|
||||
"quantity": 10,
|
||||
"image_url": "https://raw.githubusercontent.com/yourusername/yourrepo/main/sword.png"
|
||||
},
|
||||
"potion": {
|
||||
"name": "Health Potion",
|
||||
"description": "Restores 50 HP",
|
||||
"price": 100,
|
||||
"limited": false,
|
||||
"image_url": "https://raw.githubusercontent.com/yourusername/yourrepo/main/potion.png"
|
||||
},
|
||||
"shield": {
|
||||
"name": "Wooden Shield",
|
||||
"description": "Basic protection from attacks",
|
||||
"price": 300,
|
||||
"limited": true,
|
||||
"quantity": 5,
|
||||
"image_url": "https://raw.githubusercontent.com/yourusername/yourrepo/main/shield.png"
|
||||
},
|
||||
"gem": {
|
||||
"name": "Rare Gem",
|
||||
"description": "Shiny gem with mysterious powers",
|
||||
"price": 1000,
|
||||
"limited": true,
|
||||
"quantity": 3,
|
||||
"image_url": "https://raw.githubusercontent.com/yourusername/yourrepo/main/gem.png"
|
||||
}
|
||||
}
|
||||
}
|
5
tutorial/__init__.py
Normal file
5
tutorial/__init__.py
Normal file
@@ -0,0 +1,5 @@
|
||||
from .tutorial import TutorialCog
|
||||
|
||||
|
||||
async def setup(bot):
|
||||
await bot.add_cog(TutorialCog(bot))
|
BIN
tutorial/__pycache__/__init__.cpython-311.pyc
Normal file
BIN
tutorial/__pycache__/__init__.cpython-311.pyc
Normal file
Binary file not shown.
BIN
tutorial/__pycache__/tutorial.cpython-311.pyc
Normal file
BIN
tutorial/__pycache__/tutorial.cpython-311.pyc
Normal file
Binary file not shown.
14
tutorial/info.json
Normal file
14
tutorial/info.json
Normal file
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"author": ["YuukiEatsYou"],
|
||||
"description": "Tutorial for my Server specifically",
|
||||
"install_msg": "Thank you for installing Tutorial!",
|
||||
"short": "Church of Yuuki Tutorial",
|
||||
"end_user_data_statement": "This cog doesn't store any user data.",
|
||||
"min_bot_version": "3.5.0",
|
||||
"max_bot_version": "3.5.20",
|
||||
"min_python_version": [3, 11, 0],
|
||||
"hidden": false,
|
||||
"disabled": false,
|
||||
"tags": ["help", "tutorial"],
|
||||
"type": "COG"
|
||||
}
|
77
tutorial/tutorial.py
Normal file
77
tutorial/tutorial.py
Normal file
@@ -0,0 +1,77 @@
|
||||
from redbot.core import commands
|
||||
import discord
|
||||
|
||||
class TutorialCog(commands.Cog):
|
||||
"""Detailed tutorial commands for new users"""
|
||||
|
||||
def __init__(self, bot):
|
||||
self.bot = bot
|
||||
|
||||
@commands.command()
|
||||
@commands.cooldown(1, 30, commands.BucketType.user)
|
||||
async def tutorial(self, ctx):
|
||||
"""Display a detailed server tutorial"""
|
||||
|
||||
# Create main tutorial embed
|
||||
embed = discord.Embed(
|
||||
title="YuukiCoin Tutorial",
|
||||
description="Everything you need to know about YuukiCoins:",
|
||||
color=discord.Color.blue()
|
||||
)
|
||||
|
||||
# Add command sections
|
||||
embed.add_field(
|
||||
name="Economy",
|
||||
value=(
|
||||
"`!bank balance` - Shows your YuukiCoin balance\n"
|
||||
"`!bank transfer <user> <amount>` - Send YuukiCoins to other users\n"
|
||||
"`!freecredits all` - Claim all available YuukiCoins\n"
|
||||
"`!freecredits hourly` - Claim hourly YuukiCoins\n"
|
||||
"`!freecredits daily` - Claim daily YuukiCoins\n"
|
||||
"`!freecredits weekly` - Claim weekly YuukiCoins\n"
|
||||
"`!leaderboard` - View the top users by YuukiCoins\n"
|
||||
"`!refer` - Invite members to get Credits!\n"
|
||||
"`!claimreferral <referral_code>` - New members can claim the referral bonus!"
|
||||
),
|
||||
inline=False
|
||||
)
|
||||
|
||||
embed.add_field(
|
||||
name="Shop",
|
||||
value=(
|
||||
"`!shop` - view the item shop\n"
|
||||
"`!buy <item_id>` - buy items from the shop\n"
|
||||
"`!sell <item_id>` - sell items back to the shop\n"
|
||||
"`!inventory` - view your inventory\n"
|
||||
"`!item <item_id>` - view item details\n"
|
||||
"`!market` - view the marketplace\n"
|
||||
"`!sellmarket <item_id> <price>` - sell items to the marketplace\n"
|
||||
"`!buymarket <market_id>` - buy items from the marketplace"),
|
||||
inline=False
|
||||
)
|
||||
|
||||
embed.add_field(
|
||||
name="Games",
|
||||
value=(
|
||||
"`!slot <amount>` - Play slots game\n"
|
||||
"`!hol` - Play higher or lower\n"
|
||||
"`!combat` - Start a combat challenge\n"
|
||||
"`!heal` - Heal yourself for 50 YuukiCoins\n"
|
||||
"`!lottobuy` - Buy a lottery ticket for 5k YuukiCoins\n"
|
||||
"`!lottopool` - View the current lottery price pool\n"
|
||||
"`!battlepass buy` - Buy the current Battlepass for 5k YuukiCoins\n"
|
||||
"`!battlepass claim` - Claim your Battlepass rewards every 24 hours\n"
|
||||
"`!battlepass status` - View the current status of your Battlepass\n"
|
||||
"`!rrjoin` - Create or join a Russian Roulette lobby\n"
|
||||
"`!rrstart` - Start the current Russian Roulette lobby\n"
|
||||
"`!rrcancel` - Cancel the current Russian Roulette lobby"
|
||||
),
|
||||
inline=False
|
||||
)
|
||||
|
||||
# Send tutorial embed
|
||||
await ctx.send(embed=embed)
|
||||
|
||||
# Cog setup function required by Red
|
||||
async def setup(bot):
|
||||
await bot.add_cog(TutorialCog(bot))
|
5
userreact/__init__.py
Normal file
5
userreact/__init__.py
Normal file
@@ -0,0 +1,5 @@
|
||||
from .reactionmonitor import ReactionMonitor
|
||||
|
||||
|
||||
async def setup(bot):
|
||||
await bot.add_cog(ReactionMonitor(bot))
|
14
userreact/info.json
Normal file
14
userreact/info.json
Normal file
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"author": ["YuukiEatsYou"],
|
||||
"description": "Automatic user reactions!",
|
||||
"install_msg": "Thank you for installing user react!",
|
||||
"short": "User React",
|
||||
"end_user_data_statement": "This cog doesn't store any user data.",
|
||||
"min_bot_version": "3.5.0",
|
||||
"max_bot_version": "3.5.20",
|
||||
"min_python_version": [3, 11, 0],
|
||||
"hidden": false,
|
||||
"disabled": false,
|
||||
"tags": ["fun", "economy"],
|
||||
"type": "COG"
|
||||
}
|
86
userreact/reactionmonitor.py
Normal file
86
userreact/reactionmonitor.py
Normal file
@@ -0,0 +1,86 @@
|
||||
from redbot.core import commands, Config
|
||||
from redbot.core.bot import Red
|
||||
import discord
|
||||
|
||||
class ReactionMonitor(commands.Cog):
|
||||
"""Auto-reacts to messages from a specific user"""
|
||||
|
||||
def __init__(self, bot: Red):
|
||||
self.bot = bot
|
||||
self.config = Config.get_conf(self, identifier=1234567890, force_registration=True)
|
||||
self.config.register_guild(
|
||||
target_user_id=None,
|
||||
emoji_data=None
|
||||
)
|
||||
|
||||
@commands.guild_only()
|
||||
@commands.admin()
|
||||
@commands.command()
|
||||
async def setreacttarget(self, ctx, user: discord.User, emoji: str):
|
||||
"""Set the target user and reaction emoji for this server."""
|
||||
try:
|
||||
# Try to convert to PartialEmoji if custom emoji
|
||||
partial_emoji = await commands.PartialEmojiConverter().convert(ctx, emoji)
|
||||
emoji_data = {
|
||||
"id": partial_emoji.id,
|
||||
"name": partial_emoji.name,
|
||||
"animated": partial_emoji.animated
|
||||
}
|
||||
display_emoji = str(partial_emoji)
|
||||
except commands.BadArgument:
|
||||
# Treat as unicode emoji
|
||||
emoji_data = {"unicode": emoji}
|
||||
display_emoji = emoji
|
||||
|
||||
await self.config.guild(ctx.guild).target_user_id.set(user.id)
|
||||
await self.config.guild(ctx.guild).emoji_data.set(emoji_data)
|
||||
await ctx.send(f"✅ Now reacting to {user.mention}'s messages with {display_emoji}")
|
||||
|
||||
@commands.guild_only()
|
||||
@commands.admin()
|
||||
@commands.command()
|
||||
async def clearreacttarget(self, ctx):
|
||||
"""Clear the reaction settings for this server"""
|
||||
await self.config.guild(ctx.guild).target_user_id.set(None)
|
||||
await self.config.guild(ctx.guild).emoji_data.set(None)
|
||||
await ctx.send("✅ Reaction settings cleared")
|
||||
|
||||
@commands.Cog.listener()
|
||||
async def on_message(self, message: discord.Message):
|
||||
if message.guild is None or message.author.bot:
|
||||
return
|
||||
|
||||
# Get config values separately to avoid NoneType errors
|
||||
target_user_id = await self.config.guild(message.guild).target_user_id()
|
||||
emoji_data = await self.config.guild(message.guild).emoji_data()
|
||||
|
||||
# Check if configuration exists
|
||||
if target_user_id is None or emoji_data is None:
|
||||
return
|
||||
|
||||
if message.author.id != target_user_id:
|
||||
return
|
||||
|
||||
try:
|
||||
# Handle custom emoji
|
||||
if "id" in emoji_data:
|
||||
emoji = self.bot.get_emoji(emoji_data["id"])
|
||||
if emoji is None:
|
||||
# Use PartialEmoji if not found in cache
|
||||
emoji = discord.PartialEmoji(
|
||||
name=emoji_data["name"],
|
||||
animated=emoji_data["animated"],
|
||||
id=emoji_data["id"]
|
||||
)
|
||||
# Handle unicode emoji
|
||||
else:
|
||||
emoji = emoji_data["unicode"]
|
||||
|
||||
await message.add_reaction(emoji)
|
||||
except discord.HTTPException:
|
||||
pass # Silently fail if we can't react
|
||||
except KeyError as e:
|
||||
print(f"Invalid emoji data format: {e}")
|
||||
|
||||
async def setup(bot: Red):
|
||||
await bot.add_cog(ReactionMonitor(bot))
|
5
wordfilter/__init__.py
Normal file
5
wordfilter/__init__.py
Normal file
@@ -0,0 +1,5 @@
|
||||
from .wordfilter import WordFilter
|
||||
|
||||
|
||||
async def setup(bot):
|
||||
await bot.add_cog(WordFilter(bot))
|
14
wordfilter/info.json
Normal file
14
wordfilter/info.json
Normal file
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"author": ["YuukiEatsYou"],
|
||||
"description": "Blacklist and auto delete certain words",
|
||||
"install_msg": "Thank you for installing WordFilter!",
|
||||
"short": "WordFilter",
|
||||
"end_user_data_statement": "This cog doesn't store any user data.",
|
||||
"min_bot_version": "3.5.0",
|
||||
"max_bot_version": "3.5.20",
|
||||
"min_python_version": [3, 11, 0],
|
||||
"hidden": false,
|
||||
"disabled": false,
|
||||
"tags": ["help"],
|
||||
"type": "COG"
|
||||
}
|
172
wordfilter/wordfilter.py
Normal file
172
wordfilter/wordfilter.py
Normal file
@@ -0,0 +1,172 @@
|
||||
import discord
|
||||
from redbot.core import commands, Config
|
||||
import unicodedata
|
||||
|
||||
class WordFilter(commands.Cog):
|
||||
"""Automatically delete messages containing filtered words"""
|
||||
|
||||
def __init__(self, bot):
|
||||
self.bot = bot
|
||||
self.config = Config.get_conf(self, identifier=7345167902)
|
||||
default_guild = {
|
||||
"blacklist": []
|
||||
}
|
||||
self.config.register_guild(**default_guild)
|
||||
|
||||
def normalize_text(self, text):
|
||||
"""Normalize text by converting to lowercase and removing diacritics"""
|
||||
# Normalize to NFKD form which separates characters and diacritics
|
||||
normalized = unicodedata.normalize('NFKD', text.lower())
|
||||
# Remove diacritical marks and convert to ASCII
|
||||
cleaned = ''.join(c for c in normalized if not unicodedata.combining(c))
|
||||
# Remove non-ASCII characters and return
|
||||
return cleaned.encode('ascii', 'ignore').decode('ascii')
|
||||
|
||||
async def check_and_delete(self, message):
|
||||
"""Check if a message contains filtered words and delete it if found"""
|
||||
# Ignore messages from bots, server owners, and DMs
|
||||
if (
|
||||
not message.guild or
|
||||
message.author.bot or
|
||||
message.author == message.guild.owner
|
||||
):
|
||||
return False
|
||||
|
||||
# Get filtered words for this guild
|
||||
blacklist = await self.config.guild(message.guild).blacklist()
|
||||
|
||||
if not blacklist:
|
||||
return False
|
||||
|
||||
# Normalize message content for better matching
|
||||
normalized_content = self.normalize_text(message.content)
|
||||
|
||||
# Check if message contains any filtered word
|
||||
for bad_word in blacklist:
|
||||
# Normalize the bad word too for consistency
|
||||
normalized_bad = self.normalize_text(bad_word)
|
||||
if normalized_bad and normalized_bad in normalized_content:
|
||||
try:
|
||||
await message.delete()
|
||||
return True
|
||||
except discord.NotFound:
|
||||
pass # Message already deleted
|
||||
except discord.Forbidden:
|
||||
pass # Missing permissions
|
||||
return False
|
||||
|
||||
@commands.Cog.listener()
|
||||
async def on_message(self, message):
|
||||
"""Handle new messages"""
|
||||
await self.check_and_delete(message)
|
||||
|
||||
@commands.Cog.listener()
|
||||
async def on_message_edit(self, before, after):
|
||||
"""Handle edited messages"""
|
||||
# Only process if content actually changed
|
||||
if before.content != after.content:
|
||||
await self.check_and_delete(after)
|
||||
|
||||
@commands.group()
|
||||
@commands.guild_only()
|
||||
@commands.admin_or_permissions(administrator=True)
|
||||
async def wordfilter(self, ctx):
|
||||
"""Manage filtered words for auto-deletion"""
|
||||
pass
|
||||
|
||||
@wordfilter.command(name="add")
|
||||
async def wordfilter_add(self, ctx, *, word: str):
|
||||
"""Add a word to the filter"""
|
||||
if len(word) < 2:
|
||||
await ctx.send("Word must be at least 2 characters long.")
|
||||
return
|
||||
|
||||
async with self.config.guild(ctx.guild).blacklist() as blacklist:
|
||||
# Check both original and normalized versions for duplicates
|
||||
normalized_new = self.normalize_text(word)
|
||||
for existing in blacklist:
|
||||
if self.normalize_text(existing) == normalized_new:
|
||||
await ctx.send(f"`{word}` or a similar variation is already in the word filter.")
|
||||
return
|
||||
blacklist.append(word)
|
||||
|
||||
await ctx.send(f"Added `{word}` to the word filter.")
|
||||
|
||||
@wordfilter.command(name="remove", aliases=["rm", "delete"])
|
||||
async def wordfilter_remove(self, ctx, *, word: str):
|
||||
"""Remove a word from the filter"""
|
||||
async with self.config.guild(ctx.guild).blacklist() as blacklist:
|
||||
original_length = len(blacklist)
|
||||
# Normalize the word to remove
|
||||
normalized_target = self.normalize_text(word)
|
||||
# Case-insensitive and accent-insensitive removal
|
||||
blacklist[:] = [w for w in blacklist
|
||||
if self.normalize_text(w) != normalized_target]
|
||||
|
||||
if len(blacklist) == original_length:
|
||||
await ctx.send(f"`{word}` or its variations were not found in the word filter.")
|
||||
return
|
||||
|
||||
await ctx.send(f"Removed all variations of `{word}` from the word filter.")
|
||||
|
||||
@wordfilter.command(name="list")
|
||||
async def wordfilter_list(self, ctx):
|
||||
"""List all filtered words"""
|
||||
blacklist = await self.config.guild(ctx.guild).blacklist()
|
||||
|
||||
if not blacklist:
|
||||
await ctx.send("The word filter is empty.")
|
||||
return
|
||||
|
||||
formatted_list = "\n".join(f"• {word}" for word in blacklist)
|
||||
embed = discord.Embed(
|
||||
title="Filtered Words",
|
||||
description=formatted_list,
|
||||
color=await ctx.embed_color()
|
||||
)
|
||||
await ctx.send(embed=embed)
|
||||
|
||||
@wordfilter.command(name="clear")
|
||||
@commands.admin_or_permissions(administrator=True)
|
||||
async def wordfilter_clear(self, ctx):
|
||||
"""Clear all words from the filter (with confirmation)"""
|
||||
# Create confirmation message
|
||||
embed = discord.Embed(
|
||||
title="⚠️ Confirm Clear",
|
||||
description="This will remove **ALL** words from the filter!\nAre you sure?",
|
||||
color=0xFFCC4D
|
||||
)
|
||||
confirm_msg = await ctx.send(embed=embed)
|
||||
|
||||
# Add reactions
|
||||
await confirm_msg.add_reaction("✅") # Check mark
|
||||
await confirm_msg.add_reaction("❌") # X mark
|
||||
|
||||
# Wait for reaction
|
||||
def check(reaction, user):
|
||||
return (
|
||||
user == ctx.author and
|
||||
reaction.message.id == confirm_msg.id and
|
||||
str(reaction.emoji) in ["✅", "❌"]
|
||||
)
|
||||
|
||||
try:
|
||||
reaction, user = await self.bot.wait_for("reaction_add", timeout=30.0, check=check)
|
||||
except TimeoutError:
|
||||
await confirm_msg.delete()
|
||||
return
|
||||
|
||||
# Process reaction
|
||||
if str(reaction.emoji) == "✅":
|
||||
await self.config.guild(ctx.guild).blacklist.set([])
|
||||
await ctx.send("✅ All words have been removed from the filter.")
|
||||
else:
|
||||
await ctx.send("❌ Clear operation cancelled.")
|
||||
|
||||
try:
|
||||
await confirm_msg.delete()
|
||||
except discord.NotFound:
|
||||
pass
|
||||
|
||||
async def setup(bot):
|
||||
await bot.add_cog(WordFilter(bot))
|
Reference in New Issue
Block a user