Compare commits

...

No commits in common. "Commando" and "Slash-V14" have entirely different histories.

206 changed files with 12005 additions and 2792 deletions

20
.env.example Normal file
View file

@ -0,0 +1,20 @@
token=YourToken
clientId=BotClientId
guildId=DevGuildId
ownerId=OwnerUserId
statusChannel=CHannelIdForStatus
uptimeURL=UptimeKumaOrWhateverStatusThingYouUseOrJustLeaveEmpty
uptimeInterval=60
twiConsumer=TwitterConsumerToken
twiConsumerSecret=TwitterConsumerSecretToken
twiToken=TwitterToken
twiTokenSecret=TwitterSecretToken
twiChannel=ChannelWhereJustTheTwitterLinkAreSent
twiLogChannel=ChannelWhereTheDetailedInfoOfTheCommandIsSent
botsggToken=APITokenForBots.gg
botsggEndpoint=https://discord.bots.gg/api/v1
stableHordeApi=0000000000
stableHordeID=0000
NODE_ENV=development
ytdlpMaxResolution=720
proxy=socks5://localhost:3128

37
.github/ISSUE_TEMPLATE/bug.md vendored Normal file
View file

@ -0,0 +1,37 @@
---
name: "Bug"
about: "Use this if you found a bug in the bot."
title: "[BUG] "
ref: "main"
labels:
- bug
---
<!-- Please provide the commit of the bot at the time of the report. You can find it by doing /about or haha about. -->
**Commit number**
**Bot varient**
<!-- Put a x between the brackets to signify the version you used. -->
- [ ] Slash <!-- The current and latest version that use the slash commands. -->
- [ ] Legacy <!-- The old version of the bot with the "haha" prefix. -->
**Describe the issue**
**Intended result**
**Screenshots**
**Steps to reproduce the issue**
-
-
-
-
**Did someone already report that bug?**
- [ ] Yes <!-- If you have to put yes you don't need to submit that bug report. -->
- [ ] No

19
.github/ISSUE_TEMPLATE/feature.md vendored Normal file
View file

@ -0,0 +1,19 @@
---
name: "Feature request"
about: "Use this if you want a new feature in the bot."
title: "[Feature request] "
ref: "main"
labels:
- Feature request
---
**Describe the feature you want**
**Did someone already request that feature?**
- [ ] Yes <!-- If you have to put yes you don't need to submit that feature request. -->
- [ ] No

29
.gitignore vendored
View file

@ -1,13 +1,16 @@
config.json .env
package-lock.json node_modules/
.DS_Store config/config.json
node_modules json/board/
node_modules\ unloaded/
.vscode database.sqlite3
video.mp4 tmp/*.js
json/autoresponse.json
json/blacklist.json bin/yt-dlp*
json/customresponse.json bin/HandBrakeCLI*
tag/* bin/upload.sh
tts.mp3 bin/dectalk
ttsvc.mp3
asset/ytp/sources
asset/ytp/music
asset/ytp/sounds

17
.vscode/launch.json vendored Normal file
View file

@ -0,0 +1,17 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "pwa-node",
"request": "launch",
"name": "Launch Program",
"skipFiles": [
"<node_internals>/**"
],
"program": "${workspaceFolder}/index.js"
}
]
}

848
LICENSE
View file

@ -1,281 +1,620 @@
GNU GENERAL PUBLIC LICENSE GNU AFFERO GENERAL PUBLIC LICENSE
Version 2, June 1991 Version 3, 19 November 2007
Copyright (C) 1989, 1991 Free Software Foundation, Inc., <http://fsf.org/> Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed. of this license document, but changing it is not allowed.
Preamble Preamble
The licenses for most software are designed to take away your The GNU Affero General Public License is a free, copyleft license for
freedom to share and change it. By contrast, the GNU General Public software and other kinds of works, specifically designed to ensure
License is intended to guarantee your freedom to share and change free cooperation with the community in the case of network server software.
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software The licenses for most software and other practical works are designed
Foundation's software and to any other program whose authors commit to to take away your freedom to share and change the works. By contrast,
using it. (Some other Free Software Foundation software is covered by our General Public Licenses are intended to guarantee your freedom to
the GNU Lesser General Public License instead.) You can apply it to share and change all versions of a program--to make sure it remains free
your programs, too. software for all its users.
When we speak of free software, we are referring to freedom, not When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it them if you wish), that you receive source code or can get it if you
if you want it, that you can change the software or use pieces of it want it, that you can change the software or use pieces of it in new
in new free programs; and that you know you can do these things. free programs, and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid Developers that use our General Public Licenses protect your rights
anyone to deny you these rights or to ask you to surrender the rights. with two steps: (1) assert copyright on the software, and (2) offer
These restrictions translate to certain responsibilities for you if you you this License which gives you legal permission to copy, distribute
distribute copies of the software, or if you modify it. and/or modify the software.
For example, if you distribute copies of such a program, whether A secondary benefit of defending all users' freedom is that
gratis or for a fee, you must give the recipients all the rights that improvements made in alternate versions of the program, if they
you have. You must make sure that they, too, receive or can get the receive widespread use, become available for other developers to
source code. And you must show them these terms so they know their incorporate. Many developers of free software are heartened and
rights. encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
We protect your rights with two steps: (1) copyright the software, and The GNU Affero General Public License is designed specifically to
(2) offer you this license which gives you legal permission to copy, ensure that, in such cases, the modified source code becomes available
distribute and/or modify the software. to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
Also, for each author's protection and ours, we want to make certain An older license, called the Affero General Public License and
that everyone understands that there is no warranty for this free published by Affero, was designed to accomplish similar goals. This is
software. If the software is modified by someone else and passed on, we a different license, not a version of the Affero GPL, but Affero has
want its recipients to know that what they have is not the original, so released a new version of the Affero GPL which permits relicensing under
that any problems introduced by others will not reflect on the original this license.
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and The precise terms and conditions for copying, distribution and
modification follow. modification follow.
GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains 0. Definitions.
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not "This License" refers to version 3 of the GNU Affero General Public License.
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's "Copyright" also means copyright-like laws that apply to other kinds of
source code as you receive it, in any medium, provided that you works, such as semiconductor masks.
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and "The Program" refers to any copyrightable work licensed under this
you may at your option offer warranty protection in exchange for a fee. License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
2. You may modify your copy or copies of the Program or any portion To "modify" a work means to copy from or adapt all or part of the work
of it, thus forming a work based on the Program, and copy and in a fashion requiring copyright permission, other than the making of an
distribute such modifications or work under the terms of Section 1 exact copy. The resulting work is called a "modified version" of the
above, provided that you also meet all of these conditions: earlier work or a work "based on" the earlier work.
a) You must cause the modified files to carry prominent notices A "covered work" means either the unmodified Program or a work based
stating that you changed the files and the date of any change. on the Program.
b) You must cause any work that you distribute or publish, that in To "propagate" a work means to do anything with it that, without
whole or in part contains or is derived from the Program or any permission, would make you directly or secondarily liable for
part thereof, to be licensed as a whole at no charge to all third infringement under applicable copyright law, except executing it on a
parties under the terms of this License. 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.
c) If the modified program normally reads commands interactively To "convey" a work means any kind of propagation that enables other
when run, you must cause it, when started running for such parties to make or receive copies. Mere interaction with a user through
interactive use in the most ordinary way, to print or display an a computer network, with no transfer of a copy, is not conveying.
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If An interactive user interface displays "Appropriate Legal Notices"
identifiable sections of that work are not derived from the Program, to the extent that it includes a convenient and prominently visible
and can be reasonably considered independent and separate works in feature that (1) displays an appropriate copyright notice, and (2)
themselves, then this License, and its terms, do not apply to those tells the user that there is no warranty for the work (except to the
sections when you distribute them as separate works. But when you extent that warranties are provided), that licensees may convey the
distribute the same sections as part of a whole which is a work based work under this License, and how to view a copy of this License. If
on the Program, the distribution of the whole must be on the terms of the interface presents a list of user commands or options, such as a
this License, whose permissions for other licensees extend to the menu, a prominent item in the list meets this criterion.
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest 1. Source Code.
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program The "source code" for a work means the preferred form of the work
with the Program (or with a work based on the Program) on a volume of for making modifications to it. "Object code" means any non-source
a storage or distribution medium does not bring the other work under form of a work.
the scope of this License.
3. You may copy and distribute the Program (or a work based on it, A "Standard Interface" means an interface that either is an official
under Section 2) in object code or executable form under the terms of standard defined by a recognized standards body, or, in the case of
Sections 1 and 2 above provided that you also do one of the following: interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
a) Accompany it with the complete corresponding machine-readable The "System Libraries" of an executable work include anything, other
source code, which must be distributed under the terms of Sections than the work as a whole, that (a) is included in the normal form of
1 and 2 above on a medium customarily used for software interchange; or, 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.
b) Accompany it with a written offer, valid for at least three The "Corresponding Source" for a work in object code form means all
years, to give any third party, for a charge no more than your the source code needed to generate, install, and (for an executable
cost of physically performing source distribution, a complete work) run the object code and to modify the work, including scripts to
machine-readable copy of the corresponding source code, to be control those activities. However, it does not include the work's
distributed under the terms of Sections 1 and 2 above on a medium System Libraries, or general-purpose tools or generally available free
customarily used for software interchange; or, 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.
c) Accompany it with the information you received as to the offer The Corresponding Source need not include anything that users
to distribute corresponding source code. (This alternative is can regenerate automatically from other parts of the Corresponding
allowed only for noncommercial distribution and only if you Source.
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for The Corresponding Source for a work in source code form is that
making modifications to it. For an executable work, complete source same work.
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering 2. Basic Permissions.
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program All rights granted under this License are granted for the term of
except as expressly provided under this License. Any attempt copyright on the Program, and are irrevocable provided the stated
otherwise to copy, modify, sublicense or distribute the Program is conditions are met. This License explicitly affirms your unlimited
void, and will automatically terminate your rights under this License. permission to run the unmodified Program. The output from running a
However, parties who have received copies, or rights, from you under covered work is covered by this License only if the output, given its
this License will not have their licenses terminated so long as such content, constitutes a covered work. This License acknowledges your
parties remain in full compliance. rights of fair use or other equivalent, as provided by copyright law.
5. You are not required to accept this License, since you have not You may make, run and propagate covered works that you do not
signed it. However, nothing else grants you permission to modify or convey, without conditions so long as your license otherwise remains
distribute the Program or its derivative works. These actions are in force. You may convey covered works to others for the sole purpose
prohibited by law if you do not accept this License. Therefore, by of having them make modifications exclusively for you, or provide you
modifying or distributing the Program (or any work based on the with facilities for running those works, provided that you comply with
Program), you indicate your acceptance of this License to do so, and the terms of this License in conveying all material for which you do
all its terms and conditions for copying, distributing or modifying not control copyright. Those thus making or running the covered works
the Program or works based on it. 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.
6. Each time you redistribute the Program (or any work based on the Conveying under any other circumstances is permitted solely under
Program), the recipient automatically receives a license from the the conditions stated below. Sublicensing is not allowed; section 10
original licensor to copy, distribute or modify the Program subject to makes it unnecessary.
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein. 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
You are not responsible for enforcing compliance by third parties to
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. this License.
7. If, as a consequence of a court judgment or allegation of patent Each contributor grants you a non-exclusive, worldwide, royalty-free
infringement or for any other reason (not limited to patent issues), patent license under the contributor's essential patent claims, to
conditions are imposed on you (whether by court order, agreement or 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 otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot excuse you from the conditions of this License. If you cannot convey a
distribute so as to satisfy simultaneously your obligations under this covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you License and any other pertinent obligations, then as a consequence you may
may not distribute the Program at all. For example, if a patent not convey it at all. For example, if you agree to terms that obligate you
license would not permit royalty-free redistribution of the Program by to collect a royalty for further conveying from those to whom you convey
all those who receive copies directly or indirectly through you, then the Program, the only way you could satisfy both those terms and this
the only way you could satisfy both it and this License would be to License would be to refrain entirely from conveying the Program.
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under 13. Remote Network Interaction; Use with the GNU General Public License.
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any Notwithstanding any other provision of this License, if you modify the
patents or other property right claims or to contest validity of any Program, your modified version must prominently offer all users
such claims; this section has the sole purpose of protecting the interacting with it remotely through a computer network (if your version
integrity of the free software distribution system, which is supports such interaction) an opportunity to receive the Corresponding
implemented by public license practices. Many people have made Source of your version by providing access to the Corresponding Source
generous contributions to the wide range of software distributed from a network server at no charge, through some standard or customary
through that system in reliance on consistent application of that means of facilitating copying of software. This Corresponding Source
system; it is up to the author/donor to decide if he or she is willing shall include the Corresponding Source for any work covered by version 3
to distribute software through any other system and a licensee cannot of the GNU General Public License that is incorporated pursuant to the
impose that choice. following paragraph.
This section is intended to make thoroughly clear what is believed to Notwithstanding any other provision of this License, you have
be a consequence of the rest of this License. permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
8. If the distribution and/or use of the Program is restricted in 14. Revised Versions of this License.
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions The Free Software Foundation may publish revised and/or new versions of
of the General Public License from time to time. Such new versions will the GNU Affero General Public License from time to time. Such new versions
be similar in spirit to the present version, but may differ in detail to will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns. address new problems or concerns.
Each version is given a distinguishing version number. If the Program Each version is given a distinguishing version number. If the
specifies a version number of this License which applies to it and "any Program specifies that a certain numbered version of the GNU Affero General
later version", you have the option of following the terms and conditions Public License "or any later version" applies to it, you have the
either of that version or of any later version published by the Free option of following the terms and conditions either of that numbered
Software Foundation. If the Program does not specify a version number of version or of any later version published by the Free Software
this License, you may choose any version ever published by the Free Software Foundation. If the Program does not specify a version number of the
Foundation. GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
10. If you wish to incorporate parts of the Program into other free If the Program specifies that a proxy can decide which future
programs whose distribution conditions are different, write to the author versions of the GNU Affero General Public License can be used, that proxy's
to ask for permission. For software which is copyrighted by the Free public statement of acceptance of a version permanently authorizes you
Software Foundation, write to the Free Software Foundation; we sometimes to choose that version for the Program.
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY 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.
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 15. Disclaimer of 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.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
POSSIBILITY OF SUCH DAMAGES.
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 END OF TERMS AND CONDITIONS
@ -287,53 +626,36 @@ 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 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 to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least 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. the "copyright" line and a pointer to where the full notice is found.
{description} <one line to give the program's name and a brief idea of what it does.>
Copyright (C) {year} {fullname} Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify 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 it under the terms of the GNU Affero General Public License as published
the Free Software Foundation; either version 2 of the License, or by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
This program is distributed in the hope that it will be useful, This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU Affero General Public License for more details.
You should have received a copy of the GNU General Public License along You should have received a copy of the GNU Affero General Public License
with this program; if not, write to the Free Software Foundation, Inc., along with this program. If not, see <https://www.gnu.org/licenses/>.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail. Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this If your software can interact with users remotely through a computer
when it starts in an interactive mode: network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
Gnomovision version 69, Copyright (C) year name of author You should also get your employer (if you work as a programmer) or school,
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. if any, to sign a "copyright disclaimer" for the program, if necessary.
This is free software, and you are welcome to redistribute it For more information on this, and how to apply and follow the GNU AGPL, see
under certain conditions; type `show c' for details. <https://www.gnu.org/licenses/>.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
{signature of Ty Coon}, 1 April 1989
Ty Coon, President of Vice
This 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.

BIN
asset/ytp/error1.mp4 Normal file

Binary file not shown.

BIN
asset/ytp/error2.mp4 Normal file

Binary file not shown.

BIN
asset/ytp/intro.mp4 Normal file

Binary file not shown.

BIN
asset/ytp/outro.mp4 Normal file

Binary file not shown.

0
bin/.keep Normal file
View file

View file

@ -1,4 +0,0 @@
module.exports = function blacklist(reasons, message){
return message.channel.send(`You have been blacklisted for the following reasons: **${reasons}**`)
}

171
commands/AI/img2img.js Normal file
View file

@ -0,0 +1,171 @@
/* TODO
*
* To be merged with commands/AI/txt2img.js
*
*/
import { SlashCommandBuilder, EmbedBuilder, AttachmentBuilder, ButtonBuilder, ActionRowBuilder, ButtonStyle } from 'discord.js';
import fetch from 'node-fetch';
import os from 'node:os';
import fs from 'node:fs';
import stream from 'node:stream';
import util from 'node:util';
import db from '../../models/index.js';
const { stableHordeApi, stableHordeID } = process.env;
export default {
data: new SlashCommandBuilder()
.setName('img2img')
.setDescription('AI generated image with stable diffusion (If credit are low it may be slow)')
.addAttachmentOption(option =>
option.setName('image')
.setDescription('Image you want to modify')
.setRequired(true))
.addStringOption(option =>
option.setName('prompt')
.setDescription('What do you want the AI to generate?')
.setRequired(true)),
category: 'AI',
alias: ['i2i'],
async execute(interaction, args, client) {
await interaction.deferReply();
const streamPipeline = util.promisify(stream.pipeline);
const res = await fetch(args.image.url);
if (!res.ok) return interaction.editReply('An error has occured while trying to download your image.');
await streamPipeline(res.body, fs.createWriteStream(`${os.tmpdir()}/${args.image.name}.webp`));
const b64Image = fs.readFileSync(`${os.tmpdir()}/${args.image.name}.webp`, { encoding: 'base64' });
generate(interaction, args.prompt, client, b64Image);
},
};
async function generate(i, prompt, client, b64Img) {
console.log('Generating image');
const body = {
prompt: prompt,
params: {
n: 1,
width: 512,
height: 512,
},
cfg_scale: 9,
use_gfpgan: true,
use_real_esrgan: true,
use_ldsr: true,
use_upscaling: true,
steps: 50,
nsfw: i.channel.nsfw ? true : false,
censor_nsfw: i.channel.nsfw ? true : false,
source_image: b64Img,
source_processing: 'img2img',
shared: true,
};
const isOptOut = await db.optout.findOne({ where: { userID: i.user.id } });
if (isOptOut) {
body.shared = false;
}
const fetchParameters = {
method: 'post',
body: JSON.stringify(body),
headers: { 'Content-Type': 'application/json', 'apikey': stableHordeApi },
};
let response = await fetch('https://stablehorde.net/api/v2/generate/async', fetchParameters);
response = await response.json();
if (!response.id) {
console.log(response);
return i.editReply({ content: `An error has occured, please try again later. \`${response.message}\`` });
}
let wait_time = 5000;
let checkURL = `https://stablehorde.net/api/v2/generate/check/${response.id}`;
const checking = setInterval(async () => {
const checkResult = await checkGeneration(checkURL);
if (checkResult === undefined) return;
if (!checkResult.done) {
if (checkResult.wait_time === -1) {
console.log(checkResult.raw);
return i.editReply({ content: `An error has occured, please try again later. \`${checkResult.raw.message}\`` });
}
if (checkResult.wait_time < 0) {
console.log(checkResult.raw);
clearInterval(checking);
return i.editReply({ content: 'No servers are currently available to fulfill your request, please try again later.' });
}
if (checkResult.wait_time === 0) {
checkURL = `https://stablehorde.net/api/v2/generate/status/${response.id}`;
}
wait_time = checkResult.wait_time;
}
else if (checkResult.done && checkResult.image) {
clearInterval(checking);
let creditResponse = await fetch(`https://stablehorde.net/api/v2/users/${stableHordeID}`);
creditResponse = await creditResponse.json();
const streamPipeline = util.promisify(stream.pipeline);
const res = await fetch(checkResult.image);
if (!res.ok) return i.editReply('An error has occured while trying to download your image.');
await streamPipeline(res.body, fs.createWriteStream(`${os.tmpdir()}/${i.id}.webp`));
const generatedImg = new AttachmentBuilder(`${os.tmpdir()}/${i.id}.webp`);
const stableEmbed = new EmbedBuilder()
.setColor(i.member ? i.member.displayHexColor : 'Navy')
.setTitle(prompt)
.setURL('https://aqualxx.github.io/stable-ui/')
.setImage(`attachment://${i.id}.webp`)
.setFooter({ text: `**Credit left: ${creditResponse.kudos}** Seed: ${checkResult.seed} worker ID: ${checkResult.worker_id} worker name: ${checkResult.worker_name}` });
const row = new ActionRowBuilder()
.addComponents(
new ButtonBuilder()
.setCustomId(`regenerate${i.user.id}${i.id}`)
.setLabel('🔄 Regenerate')
.setStyle(ButtonStyle.Primary),
);
await i.editReply({ embeds: [stableEmbed], components: [row], files: [generatedImg] });
listenButton(client, i, prompt);
}
}, wait_time);
}
async function checkGeneration(url) {
let check = await fetch(url);
check = await check.json();
if (!check.is_possible) {
return { done: false, wait_time: -1, raw: check };
}
if (check.done) {
if (!check.generations) {
return { done: false, wait_time: check.wait_time * 1000, raw: check };
}
return { done: true, image: check.generations[0].img, seed: check.generations[0].seed, worker_id: check.generations[0].worker_id, worker_name: check.generations[0].worker_name, raw: check };
}
}
async function listenButton(client, interaction, prompt) {
client.once('interactionCreate', async (interactionMenu) => {
if (!interactionMenu.isButton()) return;
await interactionMenu.update({ components: [] });
if (interactionMenu.customId === `regenerate${interactionMenu.user.id}${interaction.id}`) {
await interactionMenu.deferReply();
await generate(interactionMenu, prompt, client);
}
});
}

145
commands/AI/txt2img.js Normal file
View file

@ -0,0 +1,145 @@
/* TODO
*
* To be merged with commands/AI/img2img.js
*
*/
import { SlashCommandBuilder, EmbedBuilder, AttachmentBuilder, ButtonBuilder, ActionRowBuilder, ButtonStyle } from 'discord.js';
import fetch from 'node-fetch';
import os from 'node:os';
import fs from 'node:fs';
import stream from 'node:stream';
import util from 'node:util';
import db from '../../models/index.js';
const { stableHordeApi, stableHordeID } = process.env;
export default {
data: new SlashCommandBuilder()
.setName('txt2img')
.setDescription('AI generated image with stable diffusion (If credit are low it may be slow)')
.addStringOption(option =>
option.setName('prompt')
.setDescription('What do you want the AI to generate?')
.setRequired(true)),
category: 'AI',
alias: ['t2i'],
async execute(interaction, args, client) {
await interaction.deferReply();
generate(interaction, args.prompt, client);
},
};
async function generate(i, prompt, client) {
const body = {
prompt: prompt,
params: {
n: 1,
width: 512,
height: 512,
},
cfg_scale: 9,
use_gfpgan: true,
use_real_esrgan: true,
use_ldsr: true,
use_upscaling: true,
steps: 50,
nsfw: i.channel.nsfw ? true : false,
censor_nsfw: i.channel.nsfw ? true : false,
shared: true,
};
const isOptOut = await db.optout.findOne({ where: { userID: i.user.id } });
if (isOptOut) {
body.shared = false;
}
const fetchParameters = {
method: 'post',
body: JSON.stringify(body),
headers: { 'Content-Type': 'application/json', 'apikey': stableHordeApi },
};
let response = await fetch('https://stablehorde.net/api/v2/generate/async', fetchParameters);
response = await response.json();
let wait_time = 5000;
let checkURL = `https://stablehorde.net/api/v2/generate/check/${response.id}`;
const checking = setInterval(async () => {
const checkResult = await checkGeneration(checkURL);
if (checkResult === undefined) return;
if (!checkResult.done) {
if (checkResult.wait_time < 0) {
clearInterval(checking);
return i.editReply({ content: 'No servers are currently available to fulfill your request, please try again later.' });
}
if (checkResult.wait_time === 0) {
checkURL = `https://stablehorde.net/api/v2/generate/status/${response.id}`;
}
wait_time = checkResult.wait_time;
}
else if (checkResult.done && checkResult.image) {
clearInterval(checking);
let creditResponse = await fetch(`https://stablehorde.net/api/v2/users/${stableHordeID}`);
creditResponse = await creditResponse.json();
const streamPipeline = util.promisify(stream.pipeline);
const res = await fetch(checkResult.image);
if (!res.ok) return i.editReply('An error has occured while trying to download your image.');
await streamPipeline(res.body, fs.createWriteStream(`${os.tmpdir()}/${i.id}.webp`));
const generatedImg = new AttachmentBuilder(`${os.tmpdir()}/${i.id}.webp`);
const stableEmbed = new EmbedBuilder()
.setColor(i.member ? i.member.displayHexColor : 'Navy')
.setTitle(prompt)
.setURL('https://aqualxx.github.io/stable-ui/')
.setImage(`attachment://${i.id}.webp`)
.setFooter({ text: `**Credit left: ${creditResponse.kudos}** Seed: ${checkResult.seed} worker ID: ${checkResult.worker_id} worker name: ${checkResult.worker_name}` });
const row = new ActionRowBuilder()
.addComponents(
new ButtonBuilder()
.setCustomId(`regenerate${i.user.id}${i.id}`)
.setLabel('🔄 Regenerate')
.setStyle(ButtonStyle.Primary),
);
await i.editReply({ embeds: [stableEmbed], components: [row], files: [generatedImg] });
listenButton(client, i, prompt);
}
}, wait_time);
}
async function checkGeneration(url) {
let check = await fetch(url);
check = await check.json();
if (!check.is_possible) {
return { done: false, wait_time: -1 };
}
if (check.done) {
if (!check.generations) {
return { done: false, wait_time: check.wait_time * 1000 };
}
return { done: true, image: check.generations[0].img, seed: check.generations[0].seed, worker_id: check.generations[0].worker_id, worker_name: check.generations[0].worker_name };
}
}
async function listenButton(client, interaction, prompt) {
client.once('interactionCreate', async (interactionMenu) => {
if (!interactionMenu.isButton()) return;
await interactionMenu.update({ components: [] });
if (interactionMenu.customId === `regenerate${interactionMenu.user.id}${interaction.id}`) {
await interactionMenu.deferReply();
await generate(interactionMenu, prompt, client);
}
});
}

View file

@ -1,72 +1,62 @@
const { Command } = require('discord.js-commando'); import { SlashCommandBuilder, ButtonBuilder, ButtonStyle, ActionRowBuilder, PermissionFlagsBits } from 'discord.js';
const blacklist = require('../../json/blacklist.json'); import db from '../../models/index.js';
const fs = require('fs');
const { prefix } = require('../../config.json')
module.exports = class AutoresponseCommand extends Command {
constructor(client) {
super(client, {
name: 'autoresponse',
group: 'admin',
memberName: 'autoresponse',
userPermissions: ['ADMINISTRATOR'],
description: `Can disable autoresponse in the channel (you can add "ALL" like this "${prefix} enable/disable all" to enable/disable in every channel (EXPERIMENTAL))`,
args: [
{
key: 'text',
prompt: 'Disable or enable?',
type: 'string',
oneOf: ['disable', 'enable','disable all', 'enable all'],
},
{
key: 'all',
prompt: 'Disable or enable in every channel? (EXPERIMENTAL)',
type: 'string',
oneOf: ['all', ''],
default: ''
}
]
});
}
async run(message, { text, all }) { export default {
if(blacklist[message.author.id]) data: new SlashCommandBuilder()
return message.channel.send("You are blacklisted") .setName('autoresponse')
.setDescription('Enable or disable autoresponse')
.setDefaultMemberPermissions(PermissionFlagsBits.ManageMessages),
category: 'admin',
async execute(interaction, args, client) {
const autoresponseStat = await db.autoresponseStat.findOne({ where: { serverID: interaction.guild.id } });
if (!autoresponseStat) {
const body = { serverID: interaction.guild.id, stat: 'enable' };
await db.autoresponseStat.create(body);
return await interaction.reply({ content: 'Autoresponse has been enabled.', ephemeral: true });
}
let autoresponse = {}
let json = JSON.stringify(autoresponse)
if (all == 'all') { const row = new ActionRowBuilder()
const guild = this.client.guilds.get(message.guild.id); .addComponents(
fs.readFile('./json/autoresponse.json', 'utf8', function readFileCallback(err, data){ new ButtonBuilder()
if (err){ .setCustomId(`yes${interaction.user.id}${interaction.id}`)
console.log(err); .setLabel('Yes')
} else { .setStyle(ButtonStyle.Primary),
autoresponse = JSON.parse(data); //now it an object )
guild.channels.forEach(channel => autoresponse [channel] = text) .addComponents(
json = JSON.stringify(autoresponse); //convert it back to json new ButtonBuilder()
json = json.replace(/[<#>]/g, '') .setCustomId(`no${interaction.user.id}${interaction.id}`)
fs.writeFile('./json/autoresponse.json', json, 'utf8', function(err) { .setLabel('No')
if(err) { .setStyle(ButtonStyle.Danger),
return console.log(err); );
}
})}});
return message.say('Auto response have been disable/enable on every channel') if (autoresponseStat.stat === 'enable') {
} else if(text == 'disable' || 'enable') { await interaction.reply({ content: 'Autoresponse is already enabled, do you wish to disable it?', components: [row], ephemeral: true });
fs.readFile('./json/autoresponse.json', 'utf8', function readFileCallback(err, data){ }
if (err){ else {
console.log(err); const body = { serverID: interaction.guild.id, stat: 'enable' };
} else { await db.autoresponseStat.update(body, { where: { serverID: interaction.guild.id } });
autoresponse = JSON.parse(data); //now it an object return interaction.editReply({ content: 'Auto response has been enabled.', ephemeral: true });
autoresponse [message.channel.id] = text }
json = JSON.stringify(autoresponse); //convert it back to json
fs.writeFile('./json/autoresponse.json', json, 'utf8', function(err) { return listenButton(client, interaction, interaction.user);
if(err) { },
return console.log(err); };
}
})}}); async function listenButton(client, interaction, user = interaction.user, originalId = interaction.id) {
client.once('interactionCreate', async (interactionMenu) => {
return message.say(`Autoresponse have been ${text}d`); if (user !== interactionMenu.user) return listenButton(client, interaction, user, originalId);
} if (!interactionMenu.isButton()) return;
}
}; await interactionMenu.update({ components: [] });
if (interactionMenu.customId === `yes${interaction.user.id}${originalId}`) {
const body = { serverID: interaction.guild.id, stat: 'disable' };
await db.autoresponseStat.update(body, { where: { serverID: interaction.guild.id } });
return interaction.editReply({ content: 'Auto response has been disabled.', ephemeral: true });
}
else {
return interaction.editReply({ content: 'Nothing has been changed.', ephemeral: true });
}
});
}

View file

@ -1,48 +0,0 @@
const { Command } = require('discord.js-commando');
const blacklist = require('../../json/blacklist.json');
module.exports = class BanCommand extends Command {
constructor(client) {
super(client, {
name: 'ban',
group: 'admin',
memberName: 'ban',
description: 'ban the mentionned user',
guildOnly: true,
clientPermissions: ['BAN_MEMBERS'],
userPermissions: ['BAN_MEMBERS'],
args: [
{
key: 'member',
prompt: 'Wich member would you like to ban?',
type: 'member',
},
{
key: 'reasons',
prompt: 'What is the reasons of the kick',
type: 'string',
default: ''
}
]
});
}
async run(message, { member, reasons }) {
if(member == this.client)
return message.say('Cant kick me fool')
if(!reasons)
reasons = 'Nothing have been specified'
if(member.id === message.author.id)
return message.say("Why would you ban yourself ?")
try {
await member.send(`https://youtu.be/55-mHgUjZfY\nYou have been banned for the following reasons: "${reasons}"`)
} catch(err) {
console.error(`Could not dm the user, probably disabled\n${err}`)
}
member.ban(`Banned by : ${message.author.username} for the following reasons : ${reasons}`)
.then(() => message.reply(`${member.user.username} was succesfully banned with the following reasons "${reasons}".`))
};
};

74
commands/admin/bye.js Normal file
View file

@ -0,0 +1,74 @@
import { SlashCommandBuilder, ButtonBuilder, ButtonStyle, ActionRowBuilder, PermissionFlagsBits } from 'discord.js';
import db from '../../models/index.js';
export default {
data: new SlashCommandBuilder()
.setName('bye')
.setDescription('Set a leave message')
.addStringOption(option =>
option.setName('message')
.setDescription('The message you want the bot to say when someone leave in the current channel.')),
category: 'admin',
userPermissions: [PermissionFlagsBits.ManageChannels],
async execute(interaction, args, client) {
const leave = await db.leaveChannel.findOne({ where: { guildID: interaction.guild.id } });
if (!leave && !args.message) {
return interaction.reply({ content: 'You need a message for me to say anything!', ephemeral: true });
}
else if (!leave) {
const body = { guildID: interaction.guild.id, channelID: interaction.channel.id, message: args.message };
await db.leaveChannel.create(body);
return interaction.reply({ content: `The leave message have been set with ${args.message}`, ephemeral: true });
}
const row = new ActionRowBuilder()
.addComponents(
new ButtonBuilder()
.setCustomId(`edit${interaction.user.id}${interaction.id}`)
.setLabel('Edit')
.setStyle(ButtonStyle.Primary),
)
.addComponents(
new ButtonBuilder()
.setCustomId(`remove${interaction.user.id}${interaction.id}`)
.setLabel('Remove')
.setStyle(ButtonStyle.Danger),
)
.addComponents(
new ButtonBuilder()
.setCustomId(`nothing${interaction.user.id}${interaction.id}`)
.setLabel('Do nothing')
.setStyle(ButtonStyle.Secondary),
);
await interaction.reply({ content: 'The server already has a message set, do you want to edit it or remove it?', components: [row], ephemeral: true });
return listenButton(client, interaction, args, interaction.user);
},
};
async function listenButton(client, interaction, args, user = interaction.user, originalId = interaction.id) {
client.once('interactionCreate', async (interactionMenu) => {
if (user !== interactionMenu.user) return listenButton(client, interaction, args, user, originalId);
if (!interactionMenu.isButton()) return;
await interactionMenu.update({ components: [] });
if (interactionMenu.customId === `edit${interaction.user.id}${originalId}`) {
if (!args.message) {
return interaction.reply({ content: 'You need to input a message for me to edit!', ephemeral: true });
}
const body = { guildID: interaction.guild.id, channelID: interaction.channel.id, message: args.message };
await db.leaveChannel.update(body, { where: { guildID: interaction.guild.id } });
return interaction.editReply({ content: `The leave message has been set to ${args.message}`, ephemeral: true });
}
else if (interactionMenu.customId === `remove${interaction.user.id}${originalId}`) {
db.leaveChannel.destroy({ where: { guildID: interaction.guild.id, channelID: interaction.channel.id } });
return interaction.editReply({ content: 'The leave message has been deleted.', ephemeral: true });
}
else {
return interaction.editReply({ content: 'Nothing has been changed.', ephemeral: true });
}
});
}

View file

@ -1,20 +0,0 @@
const { Command } = require('discord.js-commando');
const blacklist = require('../../json/blacklist.json');
module.exports = class cbCommand extends Command {
constructor(client) {
super(client, {
name: 'cb',
group: 'admin',
memberName: 'cb',
description: 'spam a bunch of dot to quickly make something disspear',
userPermissions: ['MANAGE_MESSAGES'],
guildOnly: true,
});
}
run(message) {
message.say('.\n.\n.\n.\n.\n.\n.\n.\n.\n.\n.\n.\n.\n.\n.\n.\n.\n.\n.\n.\n.\n.\n.\n.\n.\n.\n.\n.\n.\n.\n.\n.\n.\n.\n.\n.\n.\n.\n.\n.\n.\n.\n.\n.\n.\n.\n.\n.\n.\n.\n.\n.\n.\n.\n.')
}
};

View file

@ -1,42 +0,0 @@
const { Command } = require('discord.js-commando');
const blacklist = require('../../json/blacklist.json');
module.exports = class KickCommand extends Command {
constructor(client) {
super(client, {
name: 'kick',
group: 'admin',
memberName: 'kick',
description: 'Kick the mentionned user',
guildOnly: true,
clientPermissions: ['KICK_MEMBERS'],
userPermissions: ['KICK_MEMBERS'],
args: [
{
key: 'member',
prompt: 'Wich member would you like to kick?',
type: 'member',
},
{
key: 'reasons',
prompt: 'What is the reasons of the kick',
type: 'string',
default: ''
}
]
});
}
async run(message, { member, reasons }) {
if(member == this.client)
message.say('Cant kick me fool')
if(!reasons)
reasons = 'Nothing have been specified.'
if(member.id === message.author.id)
return message.say("Why would you kick yourself ?")
await member.send(`You have been kicked for the following reasons: "${reasons}"`)
.error(err => console.error(`Could not dm the user, probably disabled\n${err}`))
member.kick(`Kicked by : ${message.author.username} for the following reasons : ${reasons}`)
.then(() => message.reply(`${member.user.username} was succesfully kicked with the following reasons "${reasons}".`))
};
};

View file

@ -1,32 +0,0 @@
const { Command } = require('discord.js-commando');
const blacklist = require('../../json/blacklist.json');
module.exports = class PruneCommand extends Command {
constructor(client) {
super(client, {
name: 'prune',
aliases: ['purge', 'clear', 'clean'],
group: 'admin',
memberName: 'prune',
description: 'Bulk delete messages.',
clientPermissions: ['READ_MESSAGE_HISTORY', 'MANAGE_MESSAGES'],
userPermissions: ['MANAGE_MESSAGES'],
guildOnly: true,
args: [
{
key: 'amount',
prompt: 'How many messages would you like to delete? ( choose a number between 1 & 99 )',
type: 'integer',
min: '1',
max: '99'
}
]
});
}
run(message, { amount }) {
amount = amount+1
message.channel.bulkDelete(amount, true);
}
};

View file

@ -0,0 +1,62 @@
import { SlashCommandBuilder, ButtonBuilder, ButtonStyle, ActionRowBuilder, PermissionFlagsBits } from 'discord.js';
import db from '../../models/index.js';
export default {
data: new SlashCommandBuilder()
.setName('quotation')
.setDescription('Enable or disable quotations')
.setDefaultMemberPermissions(PermissionFlagsBits.ManageMessages),
category: 'admin',
async execute(interaction, args, client) {
const quotationstat = await db.quotationStat.findOne({ where: { serverID: interaction.guild.id } });
if (!quotationstat) {
const body = { serverID: interaction.guild.id, stat: 'enable' };
await db.quotationStat.create(body);
return await interaction.reply({ content: 'Quotation has been enabled.', ephemeral: true });
}
const row = new ActionRowBuilder()
.addComponents(
new ButtonBuilder()
.setCustomId(`yes${interaction.user.id}${interaction.id}`)
.setLabel('Yes')
.setStyle(ButtonStyle.Primary),
)
.addComponents(
new ButtonBuilder()
.setCustomId(`no${interaction.user.id}${interaction.id}`)
.setLabel('No')
.setStyle(ButtonStyle.Danger),
);
if (quotationstat.stat === 'enable') {
await interaction.reply({ content: 'Quotation is already enabled, do you wish to disable it?', components: [row], ephemeral: true });
}
else {
const body = { serverID: interaction.guild.id, stat: 'enable' };
await db.autoresponseStat.update(body, { where: { serverID: interaction.guild.id } });
return interaction.editReply({ content: 'Quotation has been enabled.', ephemeral: true });
}
return listenButton(client, interaction, interaction.user);
},
};
async function listenButton(client, interaction, user = interaction.user, originalId = interaction.id) {
client.once('interactionCreate', async (interactionMenu) => {
if (user !== interactionMenu.user) return listenButton(client, interaction, user, originalId);
if (!interactionMenu.isButton()) return;
interactionMenu.update({ components: [] });
if (interactionMenu.customId === `yes${interaction.user.id}${originalId}`) {
await db.quotationStat.destroy({ where: { serverID: interaction.guild.id } });
return interaction.editReply({ content: 'Quotation has been disabled.', ephemeral: true });
}
else {
return interaction.editReply({ content: 'Nothing has been changed.', ephemeral: true });
}
});
}

View file

@ -0,0 +1,38 @@
import { SlashCommandBuilder, PermissionFlagsBits } from 'discord.js';
import fs from 'node:fs';
export default {
data: new SlashCommandBuilder()
.setName('shameboard')
.setDescription('Set shameboard to the current channel.')
.addStringOption(option =>
option.setName('emote')
.setDescription('The emote that should be used to enter the shameboard.'))
.addStringOption(option =>
option.setName('count')
.setDescription('How many react for it to enter shameboard.'))
.addBooleanOption(option =>
option.setName('remove')
.setDescription('Remove the shameboard')
.setRequired(false)),
category: 'admin',
userPermissions: [PermissionFlagsBits.ManageChannels],
async execute(interaction, args) {
if (args.remove) {
fs.unlink(`./json/board/shame${interaction.guild.id}.json`, (err) => {
if (err) {return interaction.reply('There is no shameboard');}
return interaction.reply('Deleted the shameboard');
});
}
else {
if (!args.emote || !args.count) return interaction.reply('You are missing the emote or the count arg!');
fs.writeFile(`./json/board/shame${interaction.guild.id}.json`, `{"shameboard": "${interaction.channel.id}", "emote": "${args.emote}", "count": "${args.count}"}`, (err) => {
if (err) {
console.log(err);
}
});
return interaction.reply(`This channel have been set as the shameboard with ${args.emote} with the minimum of ${args.count}`);
}
},
};

View file

@ -1,51 +0,0 @@
const { Command } = require('discord.js-commando');
module.exports = class CustomResponseCommand extends Command {
constructor(client) {
super(client, {
name: 'slowmode',
aliases: ['slow'],
group: 'admin',
memberName: 'slowmode',
description: `Custom auto response`,
userPermissions: ['MANAGE_CHANNELS'],
clientPermissions: ['MANAGE_CHANNELS'],
args: [
{
key: 'slowmodeNumber',
prompt: 'How many seconds should the slowmode be? ( 0 to remove it )',
type: 'integer',
},
{
key: 'realtime',
prompt: 'How long shoud it remain',
default: '',
type: 'integer',
}
]
});
}
async run(message, { slowmodeNumber, realtime }) {
if (slowmodeNumber > 120)
return message.say("Slowmode can only be set to 120 seconds or lower!");
message.channel.setRateLimitPerUser(slowmodeNumber);
if (realtime) {
let time = 60000 * realtime;
message.say(`Slowmode have been set to ${slowmodeNumber} seconds and will end in ${realtime} minutes!`);
setTimeout (function (){
message.channel.setRateLimitPerUser(0);
return message.say("Slowmode is now disabled!")
}, time);
} else {
if (slowmodeNumber == 0)
return message.say("Slowmode have been disabled!")
return message.say(`Slowmode have been set to ${slowmodeNumber} seconds!`);
}
}
};

View file

@ -0,0 +1,38 @@
import { SlashCommandBuilder, PermissionFlagsBits } from 'discord.js';
import fs from 'node:fs';
export default {
data: new SlashCommandBuilder()
.setName('starboard')
.setDescription('Set starboard to the current channel.')
.addStringOption(option =>
option.setName('emote')
.setDescription('The emote that should be used to enter the starboard.'))
.addStringOption(option =>
option.setName('count')
.setDescription('How many react for it to enter starboard.'))
.addBooleanOption(option =>
option.setName('remove')
.setDescription('Remove the starboard')
.setRequired(false)),
category: 'admin',
userPermissions: [PermissionFlagsBits.ManageChannels],
async execute(interaction, args) {
if (args.remove) {
fs.unlink(`./json/board/star${interaction.guild.id}.json`, (err) => {
if (err) {return interaction.reply('There is no starboard');}
return interaction.reply('Deleted the starboard');
});
}
else {
if (!args.emote || !args.count) return interaction.reply('You are missing the emote or the count arg!');
fs.writeFile(`./json/board/star${interaction.guild.id}.json`, `{"starboard": "${interaction.channel.id}", "emote": "${args.emote}", "count": "${args.count}"}`, (err) => {
if (err) {
console.log(err);
}
});
return interaction.reply(`This channel have been set as the starboard with ${args.emote} with the minimum of ${args.count}`);
}
},
};

View file

@ -1,63 +1,127 @@
const { Command } = require('discord.js-commando'); import { SlashCommandBuilder, ButtonBuilder, ButtonStyle, ActionRowBuilder, PermissionFlagsBits, PermissionsBitField } from 'discord.js';
const blacklist = require('../../json/blacklist.json'); import os from 'node:os';
const fs = require('fs'); import fs from 'node:fs';
module.exports = class CustomResponseCommand extends Command { import db from '../../models/index.js';
constructor(client) {
super(client, {
name: 'tag',
aliases: ['customresponse'],
group: 'admin',
memberName: 'tag',
description: `Custom auto response`,
userPermissions: ['MANAGE_MESSAGES'],
args: [
{
key: 'trigger',
prompt: 'The word that will trigger the autoresponse (use "--" instead of spaces)',
type: 'string',
},
{
key: 'response',
prompt: 'The response to the word ( you can use spaces here )',
type: 'string',
}
]
});
}
async run(message, { trigger, response }) { const { ownerId } = process.env;
if(blacklist[message.author.id])
return message.channel.send("You are blacklisted")
trigger = trigger.toLowerCase(); export default {
do { data: new SlashCommandBuilder()
trigger = trigger.replace('--', ' ') .setName('tag')
} while (trigger.includes('--')) .setDescription('Create custom autoresponse')
.addStringOption(option =>
let customresponse = {} option.setName('trigger')
let json = JSON.stringify(customresponse) .setDescription('The strings that will trigger the tag')
.setRequired(false))
.addStringOption(option =>
option.setName('response')
.setDescription('What it will answer back')
.setRequired(false))
.addBooleanOption(option =>
option.setName('remove')
.setDescription('(ADMIN ONLY!) Remove the tag')
.setRequired(false))
.addBooleanOption(option =>
option.setName('list')
.setDescription('List all the tags for the server')
.setRequired(false)),
category: 'admin',
userPermissions: [PermissionFlagsBits.ManageChannels],
async execute(interaction, args, client) {
await interaction.deferReply();
if (args.list) {
let tagList = await db.Tag.findAll({ attributes: ['trigger', 'response', 'ownerID'], where: { serverID: interaction.guild.id } });
if (args.trigger) {
tagList = await db.Tag.findOne({ attributes: ['trigger', 'response', 'ownerID'], where: { trigger: args.trigger, serverID: interaction.guild.id } });
}
fs.readFile(`./tag/${message.guild.id}.json`, 'utf8', function readFileCallback(err, data){ if (!tagList) return interaction.editReply('It looks like the server has no tags.');
if (err){
fs.writeFile(`./tag/${message.guild.id}.json`, `{"${trigger}":"${response}"}`, function (err) { const path = `${os.tmpdir()}/${interaction.guild.id}.json`;
if (err){ fs.writeFile(path, JSON.stringify(tagList, null, 2), function(err) {
console.log(err); if (err) return console.error(err);
} });
}) return interaction.editReply({ files: [path] });
} else { }
customresponse = JSON.parse(data); //now it an object
customresponse [trigger] = response const tag = await db.Tag.findOne({ where: { trigger: args.trigger, serverID: interaction.guild.id } });
json = JSON.stringify(customresponse); //convert it back to json
fs.writeFile(`./tag/${message.guild.id}.json`, json, 'utf8', function(err) { if (args.remove) {
if(err) { if (tag) {
return console.log(err); if (tag.get('ownerID') == interaction.user.id || interaction.member.permissionsIn(interaction.channel).has(PermissionsBitField.Flags.Administrator) || interaction.user.id == ownerId) {
} db.Tag.destroy({ where: { trigger: args.trigger, serverID: interaction.guild.id } });
})}}); return interaction.editReply('successfully deleted the following tag: ' + args.trigger);
}
return message.say(`autoresponse have been set to ${trigger} : ${response}`); else {
} return interaction.editReply(`You are not the owner of this tag, if you think it is problematic ask a user with the 'Administrator' permission to remove it by doing ${this.client.commandHandler.prefix[0]}tag ${args.trigger} --remove`);
}; }
}
else {
return interaction.editReply('Did not find the specified tag, are you sure it exist?');
}
}
if (!args.trigger) return interaction.editReply('You need to specify what you want me to respond to.');
if (!args.response) return interaction.editReply('You need to specify what you want me to answer with.');
if (!tag) {
const body = { trigger: args.trigger, response: args.response, ownerID: interaction.user.id, serverID: interaction.guild.id };
await db.Tag.create(body);
return interaction.editReply(`tag have been set to ${args.trigger} : ${args.response}`);
}
else if (tag.get('ownerID') == interaction.user.id || interaction.member.permissionsIn(interaction.channel).has('ADMINISTRATOR') || interaction.user.id == ownerId) {
const row = new ActionRowBuilder()
.addComponents(
new ButtonBuilder()
.setCustomId(`edit${interaction.user.id}${interaction.id}`)
.setLabel('Edit')
.setStyle(ButtonStyle.Primary),
)
.addComponents(
new ButtonBuilder()
.setCustomId(`remove${interaction.user.id}${interaction.id}`)
.setLabel('Remove')
.setStyle(ButtonStyle.Danger),
)
.addComponents(
new ButtonBuilder()
.setCustomId(`nothing${interaction.user.id}${interaction.id}`)
.setLabel('Do nothing')
.setStyle(ButtonStyle.Secondary),
);
await interaction.editReply({ content: 'This tag already exist, do you want to update it, remove it or do nothing?', components: [row], ephemeral: true });
return listenButton(client, interaction, args, interaction.user);
}
else {
return interaction.editReply(`You are not the owner of this tag, if you think it is problematic ask an admin to remove it by doing ${this.client.commandHandler.prefix[0]}tag ${args.trigger} --remove`);
}
},
};
async function listenButton(client, interaction, args, user = interaction.user, originalId = interaction.id) {
client.once('interactionCreate', async (interactionMenu) => {
if (user !== interactionMenu.user) return listenButton(client, interaction, args, user, originalId);
if (!interactionMenu.isButton()) return;
await interactionMenu.update({ components: [] });
if (interactionMenu.customId === `edit${interaction.user.id}${originalId}`) {
const body = { trigger: args.trigger, response: args.response, ownerID: interaction.user.id, serverID: interaction.guild.id };
db.Tag.update(body, { where: { serverID: interaction.guild.id } });
return interaction.editReply({ content: `The tag ${args.trigger} has been set to ${args.response}`, ephemeral: true });
}
else if (interactionMenu.customId === `remove${interaction.user.id}${originalId}`) {
db.Tag.destroy({ where: { trigger: args.trigger, serverID: interaction.guild.id } });
return interaction.editReply({ content: `The tag ${args.trigger} has been deleted`, ephemeral: true });
}
else {
return interaction.editReply({ content: 'Nothing has been changed.', ephemeral: true });
}
});
}

View file

@ -1,28 +0,0 @@
const { Command } = require('discord.js-commando');
const blacklist = require('../../json/blacklist.json');
module.exports = class UnbanCommand extends Command {
constructor(client) {
super(client, {
name: 'unban',
group: 'admin',
memberName: 'unban',
description: 'unban the provided id',
guildOnly: true,
clientPermissions: ['BAN_MEMBERS'],
userPermissions: ['BAN_MEMBERS'],
args: [
{
key: 'member',
prompt: 'Wich member would you like to unban?',
type: 'user',
}
]
});
}
async run(message, { member }) {
message.guild.unban(member)
.then(() => message.reply(`user was succesfully unbanned.`));
};
};

View file

@ -1,48 +0,0 @@
const { Command } = require('discord.js-commando');
const blacklist = require('../../json/blacklist.json');
const fs = require('fs');
module.exports = class CustomResponseCommand extends Command {
constructor(client) {
super(client, {
name: 'untag',
aliases: ['rmcustomresponse'],
group: 'admin',
memberName: 'untag',
description: `remove custom autoresponse`,
userPermissions: ['MANAGE_MESSAGES'],
args: [
{
key: 'trigger',
prompt: 'What is the word to remove',
type: 'string',
}
]
});
}
async run(message, { trigger }) {
if(blacklist[message.author.id])
return message.channel.send("You are blacklisted")
trigger = trigger.toLowerCase();
let customresponse = {}
let json = JSON.stringify(customresponse)
fs.readFile(`./tag/${message.guild.id}.json`, 'utf8', function readFileCallback(err, data){
if (err){
console.log(err);
} else {
customresponse = JSON.parse(data); //now it an object
delete customresponse[trigger]
json = JSON.stringify(customresponse); //convert it back to json
fs.writeFile(`./tag/${message.guild.id}.json`, json, 'utf8', function(err) {
if(err) {
return console.log(err);
}
})}});
return message.say(`The following autoresponse have been deleted: ${trigger}`);
}
};

75
commands/admin/welcome.js Normal file
View file

@ -0,0 +1,75 @@
import { SlashCommandBuilder, ButtonBuilder, ButtonStyle, ActionRowBuilder, PermissionFlagsBits } from 'discord.js';
import db from '../../models/index.js';
export default {
data: new SlashCommandBuilder()
.setName('welcome')
.setDescription('Set a join message')
.addStringOption(option =>
option.setName('message')
.setDescription('The message you want the bot to say when someone join in the current channel.')),
category: 'admin',
userPermissions: [PermissionFlagsBits.ManageChannels],
async execute(interaction, args, client) {
const join = await db.joinChannel.findOne({ where: { guildID: interaction.guild.id } });
if (!join && !args.message) {
return interaction.reply({ content: 'You need a message for me to say anything!', ephemeral: true });
}
else if (!join) {
const body = { guildID: interaction.guild.id, channelID: interaction.channel.id, message: args.message };
await db.joinChannel.create(body);
return interaction.reply({ content: `The join message have been set with ${args.message}`, ephemeral: true });
}
const row = new ActionRowBuilder()
.addComponents(
new ButtonBuilder()
.setCustomId(`edit${interaction.user.id}${interaction.id}`)
.setLabel('Edit')
.setStyle(ButtonStyle.Primary),
)
.addComponents(
new ButtonBuilder()
.setCustomId(`remove${interaction.user.id}${interaction.id}`)
.setLabel('Remove')
.setStyle(ButtonStyle.Danger),
)
.addComponents(
new ButtonBuilder()
.setCustomId(`nothing${interaction.user.id}${interaction.id}`)
.setLabel('Do nothing')
.setStyle(ButtonStyle.Secondary),
);
await interaction.reply({ content: 'The server already has a message set, do you want to edit it or remove it?', components: [row], ephemeral: true });
return listenButton(client, interaction, args, interaction.user);
},
};
async function listenButton(client, interaction, args, user = interaction.user, originalId = interaction.id) {
client.once('interactionCreate', async (interactionMenu) => {
if (user !== interactionMenu.user) return listenButton(client, interaction, args, user, originalId);
if (!interactionMenu.isButton()) return;
await interactionMenu.update({ components: [] });
if (interactionMenu.customId === `edit${interaction.user.id}${originalId}`) {
if (!args.message) {
return interaction.reply({ content: 'You need to input a message for me to edit!', ephemeral: true });
}
const body = { guildID: interaction.guild.id, channelID: interaction.channel.id, message: args.message };
await db.joinChannel.update(body, { where: { guildID: interaction.guild.id } });
return interaction.editReply({ content: `The join message has been set to ${args.message}`, ephemeral: true });
}
else if (interactionMenu.customId === `remove${interaction.user.id}${originalId}`) {
db.joinChannel.destroy({ where: { guildID: interaction.guild.id, channelID: interaction.channel.id } });
return interaction.editReply({ content: 'The join message has been deleted.', ephemeral: true });
}
else {
return interaction.editReply({ content: 'Nothing has been changed.', ephemeral: true });
}
});
}

93
commands/fun/4chan.js Normal file
View file

@ -0,0 +1,93 @@
import { SlashCommandBuilder } from 'discord.js';
import { EmbedBuilder } from 'discord.js';
import TurndownService from 'turndown';
const turndown = new TurndownService();
import fetch from 'node-fetch';
import fourChan from '../../json/4chan.json' with {type: 'json'};
export default {
data: new SlashCommandBuilder()
.setName('4chan')
.setDescription('Send random images from a 4chan board of your choosing!')
.addStringOption(option =>
option.setName('board')
.setDescription('The board you wish to see')
.setRequired(true)),
category: 'fun',
async execute(interaction, args) {
let board = args.board;
if (fourChan[board] == undefined) {
return interaction.reply({ content: 'Uh oh! The board you are looking for does not exist? You think this is a mistake? Please send a feedback telling me so!', ephemeral: true });
}
if (fourChan[board].nsfw && !interaction.channel.nsfw) {
return interaction.reply({ content: 'Uh oh! This is a NSFW board! Try again in a NSFW channel!', ephemeral: true });
}
await interaction.deferReply({ ephemeral: false });
board = board.replace(/\//g, '');
let i = Math.floor((Math.random() * 5) + 1);
fetch(`https://a.4cdn.org/${board}/${i}.json`).then((response) => {
return response.json();
}).then((response) => {
if (!response.threads) {
return interaction.editReply('Not a valid board! Try again!');
}
i = Math.floor((Math.random() * response.threads.length) + 1);
// Loop until it found a threads
while (!response.threads[i]) {
i = Math.floor((Math.random() * response.threads.length) + 1);
}
// If post is sticky search again
while (response.threads[i].posts[0].sticky == 1 || !response.threads[i].posts) {
i = Math.floor((Math.random() * response.threads.length));
}
let title = response.threads[i].posts[0].sub;
let description = response.threads[i].posts[0].com;
let boardName = fourChan[board].title;
if (boardName == undefined) {
boardName = board;
}
// If title or description is undefined, change it to "no title/description"
if (!description) {
description = 'No description';
}
if (!title) {
title = 'No title';
}
const FourchanEmbed = new EmbedBuilder()
.setColor(interaction.member ? interaction.member.displayHexColor : 'Navy')
.setTitle(turndown.turndown(title))
.setDescription(turndown.turndown(description))
.setImage(`https://i.4cdn.org/${board}/${response.threads[i].posts[0].tim}${response.threads[i].posts[0].ext}`)
.setURL(`https://boards.4chan.org/${board}/thread/${response.threads[i].posts[0].no}/${response.threads[i].posts[0].semantic_url}`)
.setFooter({ text: `${boardName} | ${response.threads[i].posts[0].name} | ${response.threads[i].posts[0].no} | ${response.threads[i].posts[0].now}` });
// If file type dosen't work on embed, send it as a link
if (response.threads[i].posts[0].ext == '.webm' || response.threads[i].posts[0].ext == '.pdf' || response.threads[i].posts[0].ext == '.swf') {
interaction.editReply({ embeds: [FourchanEmbed] });
interaction.followUp(`https://i.4cdn.org/${board}/${response.threads[i].posts[0].tim}${response.threads[i].posts[0].ext}`);
}
else {
interaction.editReply({ embeds: [FourchanEmbed] });
}
})
.catch((err) => {
if (err.type == 'invalid-json') return interaction.editReply('Could not find the board! Try again!');
console.error(err);
return interaction.editReply('Uh-oh, an error has occurred! Try again! If this keeps happening, tell the developers!');
});
},
};

View file

@ -1,34 +0,0 @@
const { Command } = require('discord.js-commando');
const Discord = require('discord.js');
const fetch = require('node-fetch')
const SelfReloadJSON = require('self-reload-json');
const blacklist = require('../../json/blacklist.json');
module.exports = class AdviceCommand extends Command {
constructor(client) {
super(client, {
name: 'advice',
group: 'fun',
memberName: 'advice',
description: `Show some random advice`,
});
}
async run(message) {
let blacklistJson = new SelfReloadJSON('./json/blacklist.json');
if(blacklistJson[message.author.id])
return blacklist(blacklistJson[message.author.id] , message)
fetch("http://api.adviceslip.com/advice").then((response) => {
return response.json();
}).then((response) => {
const adviceEmbed = new Discord.RichEmbed()
.setColor("#ff9900")
.setTitle(response.slip.slip_id)
.setDescription(response.slip.advice)
message.say(adviceEmbed);
});
}};

View file

@ -0,0 +1,60 @@
/* TODO
*
* Merge with commands/fun/image2audio.js
*
*/
import { SlashCommandBuilder } from 'discord.js';
import fs from 'node:fs';
import os from 'node:os';
import fetch from 'node-fetch';
import util from 'node:util';
import stream from 'node:stream';
import utils from '../../utils/videos.js';
export default {
data: new SlashCommandBuilder()
.setName('audio2image')
.setDescription('Transform an audio file into an image.')
.addAttachmentOption(option =>
option.setName('audio')
.setDescription('The audio that will become image.')
.setRequired(true)),
category: 'fun',
alias: ['a2i'],
async execute(interaction, args) {
if (!args.audio) return interaction.reply('Please attach an image with your message.');
await interaction.deferReply();
ifExistDelete(`${os.tmpdir()}/${args.audio.name}`);
ifExistDelete(`${os.tmpdir()}/${args.audio.name}.png`);
ifExistDelete(`${os.tmpdir()}/${args.audio.name}.sw`);
ifExistDelete(`${os.tmpdir()}/${args.audio.name}.mp3`);
const streamPipeline = util.promisify(stream.pipeline);
const res = await fetch(args.audio.url);
if (!res.ok) return interaction.editReply('An error has occured while trying to download your image.');
await streamPipeline(res.body, fs.createWriteStream(`${os.tmpdir()}/${args.audio.name}`));
await utils.ffmpeg(['-i', `${os.tmpdir()}/${args.audio.name}`, '-sample_rate', '44100', '-ac', '1', '-f', 's16le', '-acodec', 'pcm_s16le', `${os.tmpdir()}/${args.audio.name}.sw`]);
await utils.ffmpeg(['-pixel_format', 'rgb24', '-video_size', '128x128', '-f', 'rawvideo', '-i', `${os.tmpdir()}/${args.audio.name}.sw`, '-frames:v', '1', `${os.tmpdir()}/${args.audio.name}.png`]);
const file = fs.statSync(`${os.tmpdir()}/${args.audio.name}.png`);
const fileSize = (file.size / 1000000.0).toFixed(2);
if (fileSize > await utils.getMaxFileSize(interaction.guild)) return interaction.editReply('error');
interaction.editReply({ content: `Image file is ${fileSize} MB` });
return interaction.followUp({ files: [`${os.tmpdir()}/${args.audio.name}.png`] });
},
};
async function ifExistDelete(path) {
if (fs.existsSync(path)) {
fs.rm(path, (err) => {
console.log('deleted');
if (err) {
return;
}
});
}
}

View file

@ -1,35 +0,0 @@
const { Command } = require('discord.js-commando');
const fetch = require('node-fetch')
const SelfReloadJSON = require('self-reload-json');
const blacklist = require('../../json/blacklist.json');
module.exports = class BadMemeCommand extends Command {
constructor(client) {
super(client, {
name: 'badmeme',
group: 'fun',
memberName: 'badmeme',
description: `Take random images from imgur`,
});
}
async run(message) {
let blacklistJson = new SelfReloadJSON('./json/blacklist.json');
if(blacklistJson[message.author.id])
return blacklist(blacklistJson[message.author.id] , message)
fetch("https://api.imgur.com/3/gallery/hot/day?showViral=true&mature=false&perPage=100&album_previews=true", {
headers: { "Authorization": "Client-ID e4cb6948f80f295" },
}).then((response) => {
return response.json();
}).then((response) => {
if (response.success == 'false')
return message.say('An error has occured')
const i = Math.floor((Math.random() * response.data.length));
message.say(`**${response.data[i].title}**`)
message.say(response.data[i].link);
});
}};

View file

@ -1,30 +0,0 @@
const { Command } = require('discord.js-commando');
const SelfReloadJSON = require('self-reload-json');
const blacklist = require('../../json/blacklist.json');
module.exports = class clapCommand extends Command {
constructor(client) {
super(client, {
name: 'clap',
group: 'fun',
memberName: 'clap',
description: `Repeat the text you send with clap`,
args: [
{
key: 'text',
prompt: 'What do you want me to say',
type: 'string',
}
]
});
}
async run(message, { text }) {
let blacklistJson = new SelfReloadJSON('./json/blacklist.json');
if(blacklistJson[message.author.id])
return blacklist(blacklistJson[message.author.id] , message)
let clap = text.replace(/ /g, ' 👏 ');
message.delete();
message.say(`${clap} 👏`);
}};

View file

@ -1,25 +0,0 @@
const { Command } = require('discord.js-commando');
const responseObject = require("../../json/randVid.json");
const SelfReloadJSON = require('self-reload-json');
const blacklist = require('../../json/blacklist.json');
module.exports = class dankCommand extends Command {
constructor(client) {
super(client, {
name: 'dank',
group: 'fun',
memberName: 'dank',
description: `send some random dank vid (yea sorry for that name). There is currently **${Object.keys(responseObject).length}** vid`,
});
}
async run(message) {
let blacklistJson = new SelfReloadJSON('./json/blacklist.json');
if(blacklistJson[message.author.id])
return blacklist(blacklistJson[message.author.id] , message)
const number = Object.keys(responseObject).length;
const vidNumber = Math.floor (Math.random() * (number - 1 + 1)) + 1;
message.channel.send(`${vidNumber}: ${responseObject[vidNumber]}`);
}
};

View file

@ -1,59 +0,0 @@
const { Command } = require('discord.js-commando');
const responseObject = require("../../json/despacito.json");
const { createCanvas, loadImage, getContext } = require('canvas')
const superagent = require('superagent')
const Discord = require('discord.js');
const SelfReloadJSON = require('self-reload-json');
const blacklist = require('../../json/blacklist.json');
module.exports = class DespacitoCommand extends Command {
constructor(client) {
super(client, {
name: 'despacito',
group: 'fun',
memberName: 'despacito',
description: `despacito`,
args: [
{
key: 'user',
prompt: 'What do you want me to say',
type: 'user',
default: ''
}
]
});
}
async run(message, { user }) {
let blacklistJson = new SelfReloadJSON('./json/blacklist.json');
if(blacklistJson[message.author.id])
return blacklist(blacklistJson[message.author.id] , message)
if (!user) {
const number = Object.keys(responseObject).length;
const despacitoNumber = Math.floor (Math.random() * (number - 1 + 1)) + 1;
return message.channel.send({files: [responseObject[despacitoNumber]]}).catch(error => {
message.say('an error as occured')
})
} else if (user.id === this.client.user.id) {
return message.say('Nice try but you wont get me :^)');
} else {
const canvas = createCanvas(660, 660);
const ctx = canvas.getContext('2d');
const background = await loadImage(user.avatarURL);
ctx.drawImage(background, 5, 12, canvas.width, canvas.height);
const { body: buffer } = await superagent.get('https://image.noelshack.com/fichiers/2018/41/6/1539381851-untitled.png');
const bg = await loadImage(buffer);
ctx.drawImage(bg, 0, 0, canvas.width, canvas.height);
const attachment = new Discord.Attachment(canvas.toBuffer(), 'despacito.png');
message.delete();
message.say(`${user.username}, you have been despacito'd`, attachment).catch(error => {
message.say('an error as occured')
})
}
}
};

View file

@ -1,36 +0,0 @@
const { Command } = require('discord.js-commando');
const emojiCharacters = require('../../emojiCharacters');
const SelfReloadJSON = require('self-reload-json');
const blacklist = require('../../json/blacklist.json');
module.exports = class emoteSayCommand extends Command {
constructor(client) {
super(client, {
name: 'emotesay',
group: 'fun',
memberName: 'emotesay',
description: `repeat the text in dancing letters`,
args: [
{
key: 'text',
prompt: 'What do you want me to say',
type: 'string',
}
]
});
}
async run(message, { text }) {
let blacklistJson = new SelfReloadJSON('./json/blacklist.json');
if(blacklistJson[message.author.id])
return blacklist(blacklistJson[message.author.id] , message)
message.delete();
let emojiArray = [];
for (let i = 0; i < text.length; i++)
emojiArray[i] = emojiCharacters[text.toLowerCase().split('')[i]];
message.say(emojiArray.join(""))
}
};

49
commands/fun/fakeuser.js Normal file
View file

@ -0,0 +1,49 @@
import { SlashCommandBuilder } from 'discord.js';
import { PermissionFlagsBits } from 'discord.js';
export default {
data: new SlashCommandBuilder()
.setName('fakeuser')
.setDescription('Fake a user with webhooks')
.addMentionableOption(option =>
option.setName('user')
.setDescription('Who do you want to fake?')
.setRequired(true))
.addStringOption(option =>
option.setName('message')
.setDescription('What message do you want me to send?')
.setRequired(true))
.addAttachmentOption(option =>
option.setName('image')
.setDescription('Optional attachment.')
.setRequired(false)),
category: 'fun',
clientPermissions: [ PermissionFlagsBits.ManageWebhooks ],
async execute(interaction, args) {
await interaction.deferReply({ ephemeral: true });
await interaction.guild.members.fetch();
const member = args.user;
const message = args.message;
const attachment = args.image;
const username = member.nickname ? member.nickname : member.user.username;
const webhook = await interaction.channel.createWebhook({
name: username,
avatar: member.user.displayAvatarURL(),
reason: `Fakebot/user command triggered by: ${interaction.user.username}`,
});
if (attachment) {
await webhook.send({ content: message, files: [attachment] });
}
else {
await webhook.send({ content: message });
}
await webhook.delete(`Fakebot/user command triggered by: ${interaction.user.username}`);
if (interaction.isMessage) {
await interaction.delete();
await interaction.deleteReply();
}
else {
await interaction.editReply({ content: `Faked the user ${member}` });
}
},
};

View file

@ -1,25 +0,0 @@
const { Command } = require('discord.js-commando');
const responseObject = require("../../json/funfact.json");
const SelfReloadJSON = require('self-reload-json');
const blacklist = require('../../json/blacklist.json');
module.exports = class FunFactCommand extends Command {
constructor(client) {
super(client, {
name: 'funfact',
group: 'fun',
memberName: 'funfact',
description: `Send some fun fact. If you would like to see some of yours fun fact you can send them to @Supositware | Baguette#8211. There is currently **${Object.keys(responseObject).length}** fun fact.`,
});
}
async run(message) {
let blacklistJson = new SelfReloadJSON('./json/blacklist.json');
if(blacklistJson[message.author.id])
return blacklist(blacklistJson[message.author.id] , message)
const number = Object.keys(responseObject).length;
const funFactNumber = Math.floor (Math.random() * (number - 1 + 1)) + 1;
message.channel.send(`Fun fact: ${responseObject[funFactNumber]}`);
}
};

93
commands/fun/guess Normal file
View file

@ -0,0 +1,93 @@
// Tried something to make it work purely with slash commands but it did not work.
// The interaction created from a modal lack the showModal function so I can't just call another modal on top
// A "solution" for this that I could see is creating a button between each response asking the player to continue or stop which would create a new interaction and (maybe) allow to display a new modal
import { SlashCommandBuilder, ActionRowBuilder, TextInputBuilder, SelectMenuBuilder, ModalBuilder, TextInputStyle, InteractionType } from 'discord.js';
export default {
data: new SlashCommandBuilder()
.setName('guess')
.setDescription('Guess the number'),
category: 'fun',
async execute(interaction, args, client) {
const row = new ActionRowBuilder()
.addComponents(
new SelectMenuBuilder()
.setCustomId('difficulty')
.setPlaceholder('Nothing selected')
.addOptions([
{ label: 'Easy', value: '100' },
{ label: 'Normal', value: '1000' },
{ label: 'Hard', value: '10000' },
]),
);
await interaction.reply({ content: 'Which difficulty do you want to play?', ephemeral: true, components: [row] });
let numberTry = 0;
let secretnumber = 0;
client.on('interactionCreate', async (interactionMenu) => {
if (interaction.user !== interactionMenu.user) return;
const modal = new ModalBuilder()
.setCustomId('guessModal')
.setTitle('Your guess');
const textRow = new ActionRowBuilder()
.addComponents(
new TextInputBuilder()
.setCustomId('input')
.setLabel('What is the number?')
.setStyle(TextInputStyle.Short),
);
modal.addComponents(textRow);
async function tryAgain(input) {
if (input != secretnumber) {
if (input > secretnumber) {
modal.setTitle('Its less!\nWhat is the number?');
}
else if (input < secretnumber) {
modal.setTitle('Its more!\nWhat is the number?');
}
}
await interactionMenu.showModal(modal);
}
async function checkNumber(input) {
numberTry++;
if (input.toLowerCase() === 'stop') {
return interaction.reply('Ok, let\'s stop playing :(');
}
else if (input != secretnumber) {
console.log('trying again');
tryAgain(input);
}
else if (numberTry > 1) {
return interaction.reply(`Congratulations! You won! It took you ${numberTry} turns!`);
}
else {
return interaction.reply('Congratulations! You won! It took you 1 Turn!');
}
}
if (interactionMenu.type === InteractionType.ModalSubmit) {
if (interactionMenu.customId === 'guessModal') {
const input = interactionMenu.fields.getTextInputValue('input');
checkNumber(input);
}
}
else if (interactionMenu.isSelectMenu()) {
if (interactionMenu.customId === 'difficulty') {
secretnumber = Math.floor((Math.random() * parseInt(interactionMenu.values[0])) + 1);
console.log(secretnumber);
// await interaction.followUp({ content: 'What is the number?', ephemeral: true });
await interactionMenu.showModal(modal);
}
}
});
},
};

View file

@ -1,26 +0,0 @@
const { Command } = require('discord.js-commando');
const fetch = require('node-fetch')
const SelfReloadJSON = require('self-reload-json');
const blacklist = require('../../json/blacklist.json');
module.exports = class BadMemeCommand extends Command {
constructor(client) {
super(client, {
name: 'ib',
aliases: ['inspirobot'],
group: 'fun',
memberName: 'ib',
description: `Return a random inspiration from inspirobot`,
});
}
async run(message) {
let blacklistJson = new SelfReloadJSON('./json/blacklist.json');
if(blacklistJson[message.author.id])
return blacklist(blacklistJson[message.author.id] , message)
fetch('http://inspirobot.me/api?generate=true')
.then(res => res.text())
.then(body => message.channel.send({files: [body]}))
}}

View file

@ -0,0 +1,59 @@
/* TODO
*
* Merge with commands/fun/audio2image.js
*
*/
import { SlashCommandBuilder } from 'discord.js';
import fs from 'node:fs';
import os from 'node:os';
import fetch from 'node-fetch';
import util from 'node:util';
import stream from 'node:stream';
import utils from '../../utils/videos.js';
export default {
data: new SlashCommandBuilder()
.setName('image2audio')
.setDescription('Transform an image binary data into audio ( MIGHT BE VERY LOUD )')
.addAttachmentOption(option =>
option.setName('img')
.setDescription('The image that will become audio. Only tested with png and jpg.')
.setRequired(true)),
category: 'fun',
alias: ['i2a'],
async execute(interaction, args) {
if (!args.img) return interaction.reply('Please attach an image with your message.');
await interaction.deferReply();
ifExistDelete(`${os.tmpdir()}/${args.img.name}`);
ifExistDelete(`${os.tmpdir()}/1${args.img.name}`);
ifExistDelete(`${os.tmpdir()}/${args.img.name}.mp3`);
const streamPipeline = util.promisify(stream.pipeline);
const res = await fetch(args.img.url);
if (!res.ok) return interaction.editReply('An error has occured while trying to download your image.');
await streamPipeline(res.body, fs.createWriteStream(`${os.tmpdir()}/${args.img.name}`));
await utils.ffmpeg(['-i', `${os.tmpdir()}/${args.img.name}`, '-f', 'rawvideo', `${os.tmpdir()}/1${args.img.name}`]);
await utils.ffmpeg(['-sample_rate', '44100', '-ac', '1', '-f', 's16le', '-i', `${os.tmpdir()}/1${args.img.name}`, `${os.tmpdir()}/${args.img.name}.mp3`]);
const file = fs.statSync(`${os.tmpdir()}/${args.img.name}.mp3`);
const fileSize = (file.size / 1000000.0).toFixed(2);
if (fileSize > await utils.getMaxFileSize(interaction.guild)) return interaction.editReply('error');
interaction.editReply({ content: `Audio file is ${fileSize} MB` });
return interaction.followUp({ files: [`${os.tmpdir()}/${args.img.name}.mp3`] });
},
};
async function ifExistDelete(path) {
if (fs.existsSync(path)) {
fs.rm(path, (err) => {
console.log('deleted');
if (err) {
return;
}
});
}
}

View file

@ -0,0 +1,15 @@
import { SlashCommandBuilder } from 'discord.js';
import fetch from 'node-fetch';
export default {
data: new SlashCommandBuilder()
.setName('inspirobot')
.setDescription('Get an image from inspirobot'),
category: 'fun',
alias: ['ib'],
async execute(interaction) {
fetch('http://inspirobot.me/api?generate=true')
.then(res => res.text())
.then(body => interaction.reply({ files: [body] }));
},
};

View file

@ -1,45 +0,0 @@
const { Command } = require('discord.js-commando');
const printer = require('printer');
const { printChannel } = require('../../config.json');
const SelfReloadJSON = require('self-reload-json');
const blacklist = require('../../json/blacklist.json');
module.exports = class printCommand extends Command {
constructor(client) {
super(client, {
name: 'print',
aliases: ['dundermifflin', 'wastedevinkandmoney'],
group: 'fun',
memberName: 'print',
description: 'print whatever you want using the dev printer ! ( yea really, send a feedback requesting the image and i\'il send it to you. )',
throttling: {
usages: 1,
duration: 86400,
},
args: [
{
key: 'text',
prompt: 'What do you want to print? ( text only )',
type: 'string',
}
]
});
}
async run(message, { text }) {
let blacklistJson = new SelfReloadJSON('./json/blacklist.json');
if(blacklistJson[message.author.id])
return blacklist(blacklistJson[message.author.id] , message)
const channel = this.client.channels.get(printChannel);
printer.printDirect({data:`Printed by: ${message.author.username}\n\n${text}`
, type: 'TEXT' // type: RAW, TEXT, PDF, JPEG, .. depends on platform
, success:function(jobID){
console.log("sent to printer with ID: "+jobID);
message.say("Printing now! ( You will receive your print shortly ( if the dev isint sleeping that is ))");
channel.send(`${message.author.username} (${message.author.id}) Asked for a print with the following text: ${text}`);
}
, error:function(err){console.log(err); message.say("An error has occured, the printer is most likely disconnected, try again later")}
});
}
};

View file

@ -1,56 +1,46 @@
const { Command } = require('discord.js-commando'); import { SlashCommandBuilder, EmbedBuilder } from 'discord.js';
const Discord = require('discord.js'); import fetch from 'node-fetch';
const fetch = require('node-fetch');
const SelfReloadJSON = require('self-reload-json');
const { prefix } = require('../../config.json')
const blacklist = require('../../json/blacklist.json');
module.exports = class redditCommand extends Command { export default {
constructor(client) { data: new SlashCommandBuilder()
super(client, { .setName('reddit')
name: 'reddit', .setDescription('Send random images from the subreddit you choose')
group: 'fun', .addStringOption(option =>
memberName: 'reddit', option.setName('subreddit')
description: `Show a random images from the subreddit you choose`, .setDescription('The subreddit you wish to see')
args: [ .setRequired(true)),
{ category: 'fun',
key: 'sub', async execute(interaction, args) {
prompt: 'Wich subreddit would you like to see?', await interaction.deferReply({ ephemeral: false });
type: 'string', const subreddit = args.subreddit;
} fetch('https://www.reddit.com/r/' + subreddit + '.json?limit=100').then((response) => {
] return response.json();
}); }).then((response) => {
} if (response.error == 404) {
return interaction.editReply('Not a valid subreddit');
}
if (response.data.dist == 0) {
return interaction.editReply('Not a valid subreddit');
async run(message, { sub }) { }
let blacklistJson = new SelfReloadJSON('./json/blacklist.json'); const i = Math.floor((Math.random() * response.data.children.length));
if(blacklistJson[message.author.id]) if (response.data.children[i].data.over_18 == true && !interaction.channel.nsfw) {
return blacklist(blacklistJson[message.author.id] , message) return interaction.editReply('No nsfw');
}
let /* the bodies hit the */ i = Math.floor((Math.random() * 10) + 1);
let a = 0
fetch('https://www.reddit.com/r/' + sub + '.json?limit=100').then((response) => {
return response.json();
}).then((response) => {
if (!response.data)
return message.say('Not a valid subreddit')
while (response.data.children[i].data.post_hint !== 'image') {
i = Math.floor((Math.random() * response.data.children.length));
a++ let description = response.data.children[i].data.selftext;
if (a == 5) if (description === '') {
return message.say("Could not find any images") description = 'No description.';
} }
if (response.data.children[i].data.over_18 == true) const redditEmbed = new EmbedBuilder()
return message.say(`No nsfw ( if you want a nsfw version of this commands use the feedback commands "${prefix} feedback <your feedback>")`) .setColor(interaction.member ? interaction.member.displayHexColor : 'Navy')
const redditEmbed = new Discord.RichEmbed() .setTitle(response.data.children[i].data.title)
.setColor("#ff9900") .setDescription(description)
.setTitle(response.data.children[i].data.title) .setURL('https://reddit.com' + response.data.children[i].data.permalink)
.setImage(response.data.children[i].data.url) .setFooter({ text: `/r/${response.data.children[i].data.subreddit} | ⬆ ${response.data.children[i].data.ups} 🗨 ${response.data.children[i].data.num_comments}` });
.setURL('https://reddit.com' + response.data.children[i].data.permalink)
.setFooter(`${response.data.children[i].data.ups} 💬 ${response.data.children[i].data.num_comments}`) interaction.followUp({ embeds: [redditEmbed] });
interaction.followUp(response.data.children[i].data.url);
message.say(redditEmbed); });
} },
};
)}}

View file

@ -1,80 +0,0 @@
const { Command } = require('discord.js-commando');
const SelfReloadJSON = require('self-reload-json');
const blacklist = require('../../json/blacklist.json');
module.exports = class sayCommand extends Command {
constructor(client) {
super(client, {
name: 'say',
aliases: ['repeat'],
group: 'fun',
memberName: 'say',
description: `Repeat the text you send ( can also use [verb] [noun] [adverbs] [adjective] [activities] [celebrities] [countries] [diseases] [elements] [hobbies] [music] [prefixes] [pronoun] [state] [title] [unit] [member] [number] to replace it with something else )`,
args: [
{
key: 'text',
prompt: 'What do you want me to say',
type: 'string',
}
]
});
}
async run(message, { text }) {
let blacklistJson = new SelfReloadJSON('./json/blacklist.json');
if(blacklistJson[message.author.id])
return blacklist(blacklistJson[message.author.id] , message)
// Load all the different files
const verb = require('../../dictionary/verbs.json')
const noun = require('../../dictionary/noun.json')
const adverbs = require('../../dictionary/adjectives.json')
const adjective = require('../../dictionary/adverbs.json')
const activities = require('../../dictionary/activities.json')
const celebreties = require('../../dictionary/celebreties.json')
const countries = require('../../dictionary/countries.json')
const diseases = require('../../dictionary/diseases.json')
const elements = require('../../dictionary/elements.json')
const hobbies = require('../../dictionary/hobbies.json')
const music = require('../../dictionary/music.json')
const prefixes = require('../../dictionary/prefixes.json')
const pronouns = require('../../dictionary/pronouns.json')
const states = require('../../dictionary/states.json')
const titles = require('../../dictionary/titles.json')
const units = require('../../dictionary/units.json')
// Generate a random number
function randNumber(file) {
let Rand = Math.floor((Math.random() * file.length) + 1);
return Rand;
}
// Replace with a random word from the json
do {
text = text.replace(/\[verb\]/, verb[randNumber(verb)])
text = text.replace(/\[adverbs\]/, adverbs[randNumber(adverbs)])
text = text.replace(/\[noun\]/, noun[randNumber(noun)])
text = text.replace(/\[adjective\]/, adjective[randNumber(adjective)])
text = text.replace(/\[activities\]/, activities[randNumber(activities)])
text = text.replace(/\[celebrities\]/, celebreties[randNumber(celebreties)])
text = text.replace(/\[countries\]/, countries[randNumber(countries)])
text = text.replace(/\[diseases\]/, diseases[randNumber(diseases)])
text = text.replace(/\[elements\]/, elements[randNumber(elements)])
text = text.replace(/\[hobbies\]/, hobbies[randNumber(hobbies)])
text = text.replace(/\[music\]/, music[randNumber(music)])
text = text.replace(/\[prefixes\]/, prefixes[randNumber(prefixes)])
text = text.replace(/\[pronoun\]/, pronouns[randNumber(pronouns)])
text = text.replace(/\[state\]/, states[randNumber(states)])
text = text.replace(/\[title\]/, titles[randNumber(titles)])
text = text.replace(/\[unit\]/, units[randNumber(units)])
text = text.replace(/\[member\]/, message.guild.members.random().user.username)
text = text.replace(/\[number\]/, Math.floor((Math.random() * 9) + 1))
// Verify if it replaced everything
} while( text.includes('[verb]') || text.includes('[adverbs]') || text.includes('[noun]') || text.includes('[adjective]') || text.includes('[member]') || text.includes('[number]') || text.includes('[activities]') || text.includes('[celebrities]') || text.includes('[countries]') || text.includes('[diseases]') || text.includes('[elements]') || text.includes('[hobbies]') || text.includes('[music]') || text.includes('[prefixes]') || text.includes('[pronoun]') || text.includes('[state]') || text.includes('[title]') || text.includes('[unit]'))
// Send the final text
message.say(text);
}
};

View file

@ -1,82 +0,0 @@
const { Command } = require('discord.js-commando');
const SelfReloadJSON = require('self-reload-json');
const blacklist = require('../../json/blacklist.json');
module.exports = class saydCommand extends Command {
constructor(client) {
super(client, {
name: 'sayd',
aliases: ['repeatd'],
group: 'fun',
memberName: 'sayd',
description: `Repeat the text you send and delete it after ward( can also use [verb] [noun] [adverbs] [adjective] [activities] [celebrities] [countries] [diseases] [elements] [hobbies] [music] [prefixes] [pronoun] [state] [title] [unit] [member] [number] to replace it with something else )`,
args: [
{
key: 'text',
prompt: 'What do you want me to say',
type: 'string',
}
]
});
}
async run(message, { text }) {
let blacklistJson = new SelfReloadJSON('./json/blacklist.json');
if(blacklistJson[message.author.id])
return blacklist(blacklistJson[message.author.id] , message)
// Load all the different files
const verb = require('../../dictionary/verbs.json')
const noun = require('../../dictionary/noun.json')
const adverbs = require('../../dictionary/adjectives.json')
const adjective = require('../../dictionary/adverbs.json')
const activities = require('../../dictionary/activities.json')
const celebreties = require('../../dictionary/celebreties.json')
const countries = require('../../dictionary/countries.json')
const diseases = require('../../dictionary/diseases.json')
const elements = require('../../dictionary/elements.json')
const hobbies = require('../../dictionary/hobbies.json')
const music = require('../../dictionary/music.json')
const prefixes = require('../../dictionary/prefixes.json')
const pronouns = require('../../dictionary/pronouns.json')
const states = require('../../dictionary/states.json')
const titles = require('../../dictionary/titles.json')
const units = require('../../dictionary/units.json')
// Generate a random number
function randNumber(file) {
let Rand = Math.floor((Math.random() * file.length) + 1);
return Rand;
}
// Replace with a random word from the json
do {
text = text.replace(/\[verb\]/, verb[randNumber(verb)])
text = text.replace(/\[adverbs\]/, adverbs[randNumber(adverbs)])
text = text.replace(/\[noun\]/, noun[randNumber(noun)])
text = text.replace(/\[adjective\]/, adjective[randNumber(adjective)])
text = text.replace(/\[activities\]/, activities[randNumber(activities)])
text = text.replace(/\[celebrities\]/, celebreties[randNumber(celebreties)])
text = text.replace(/\[countries\]/, countries[randNumber(countries)])
text = text.replace(/\[diseases\]/, diseases[randNumber(diseases)])
text = text.replace(/\[elements\]/, elements[randNumber(elements)])
text = text.replace(/\[hobbies\]/, hobbies[randNumber(hobbies)])
text = text.replace(/\[music\]/, music[randNumber(music)])
text = text.replace(/\[prefixes\]/, prefixes[randNumber(prefixes)])
text = text.replace(/\[pronoun\]/, pronouns[randNumber(pronouns)])
text = text.replace(/\[state\]/, states[randNumber(states)])
text = text.replace(/\[title\]/, titles[randNumber(titles)])
text = text.replace(/\[unit\]/, units[randNumber(units)])
text = text.replace(/\[member\]/, message.guild.members.random().user.username)
text = text.replace(/\[number\]/, Math.floor((Math.random() * 9) + 1))
// Verify if it replaced everything
} while( text.includes('[verb]') || text.includes('[adverbs]') || text.includes('[noun]') || text.includes('[adjective]') || text.includes('[member]') || text.includes('[number]') || text.includes('[activities]') || text.includes('[celebrities]') || text.includes('[countries]') || text.includes('[diseases]') || text.includes('[elements]') || text.includes('[hobbies]') || text.includes('[music]') || text.includes('[prefixes]') || text.includes('[pronoun]') || text.includes('[state]') || text.includes('[title]') || text.includes('[unit]'))
// Send the final text
message.delete();
message.say(text);
}
};

View file

@ -1,58 +0,0 @@
const { Command } = require('discord.js-commando');
const textToSpeech = require('@google-cloud/text-to-speech');
const gclient = new textToSpeech.TextToSpeechClient();
const SelfReloadJSON = require('self-reload-json');
const fs = require('fs');
const blacklist = require('../../json/blacklist.json');
module.exports = class BadMemeCommand extends Command {
constructor(client) {
super(client, {
name: 'tts',
group: 'fun',
memberName: 'tts',
description: `Return what you type in a tts file`,
args: [
{
key: 'text',
prompt: 'What do you want to be said',
type: 'string',
}
]
});
}
async run(message, { text }) {
let blacklistJson = new SelfReloadJSON('./json/blacklist.json');
if(blacklistJson[message.author.id])
return blacklist(blacklistJson[message.author.id] , message)
// Construct the request
const request = {
input: {text: text},
// Select the language and SSML Voice Gender (optional)
voice: {languageCode: 'en-US', ssmlGender: 'NEUTRAL'},
// Select the type of audio encoding
audioConfig: {audioEncoding: 'MP3'},
};
// Performs the Text-to-Speech request
gclient.synthesizeSpeech(request, (err, response) => {
if (err) {
console.error('ERROR:', err);
return;
}
// Write the binary audio content to a local file
fs.writeFile('tts.mp3', response.audioContent, 'binary', err => {
if (err) {
console.error('ERROR:', err);
message.say('An error has occured, the message is probably too long')
return;
}
console.log('Audio content written to file: tts.mp3');
message.say({files: ['./tts.mp3']})
});
});
}}

View file

@ -1,76 +0,0 @@
const { Command } = require('discord.js-commando');
const textToSpeech = require('@google-cloud/text-to-speech');
const gclient = new textToSpeech.TextToSpeechClient();
const SelfReloadJSON = require('self-reload-json');
const fs = require('fs');
const blacklist = require('../../json/blacklist.json');
module.exports = class ttsvcCommand extends Command {
constructor(client) {
super(client, {
name: 'ttsvc',
group: 'fun',
memberName: 'ttsvc',
description: `Play what you write in tts in vc`,
args: [
{
key: 'text',
prompt: 'What do you want to be said',
type: 'string',
}
]
});
}
async run(message, { text }) {
let blacklistJson = new SelfReloadJSON('./json/blacklist.json');
if(blacklistJson[message.author.id])
return blacklist(blacklistJson[message.author.id] , message)
// Construct the request
const request = {
input: {text: text},
// Select the language and SSML Voice Gender (optional)
voice: {languageCode: 'en-US', ssmlGender: 'NEUTRAL'},
// Select the type of audio encoding
audioConfig: {audioEncoding: 'MP3'},
};
// Performs the Text-to-Speech request
gclient.synthesizeSpeech(request, (err, response) => {
if (err) {
console.error('ERROR:', err);
return;
}
// Write the binary audio content to a local file
fs.writeFile('ttsvc.mp3', response.audioContent, 'binary', err => {
if (err) {
console.error('ERROR:', err);
message.say('An error has occured, the message is probably too long')
return;
}
console.log('Audio content written to file: ttsvc.mp3');
const { voiceChannel } = message.member;
// If not in voice channel ask user to join
if (!voiceChannel) {
return message.reply('please join a voice channel first!');
} else
// If user say "stop" make the bot leave voice channel
if (text == 'stop') {
voiceChannel.leave();
message.say('I leaved the channel');
} else
voiceChannel.join().then(connection => {
const dispatcher = connection.playStream('./ttsvc.mp3');
// End at then end of the audio stream
dispatcher.on('end', () => setTimeout(function(){
voiceChannel.leave();
}, 2000));
});
});
});
}}

204
commands/fun/tweet.js Normal file
View file

@ -0,0 +1,204 @@
import { SlashCommandBuilder } from 'discord.js';
import { EmbedBuilder } from 'discord.js';
import { TwitterApi } from 'twitter-api-v2';
import fetch from 'node-fetch';
import os from 'node:os';
import fs from 'node:fs';
import util from 'node:util';
import stream from 'node:stream';
import db from '../../models/index.js';
import wordToCensor from '../../json/censor.json' with {type: 'json'};
const { twiConsumer, twiConsumerSecret, twiToken, twiTokenSecret, twiChannel, twiLogChannel } = process.env;
const Blacklists = db.Blacklists;
export default {
data: new SlashCommandBuilder()
.setName('tweet')
.setDescription('Send tweet from the bot twitter account. Please do not use it for advertisement and keep it english')
.addStringOption(option =>
option.setName('content')
.setDescription('!THIS IS NOT FEEDBACK! The content of the tweet you want to send me.')
.setRequired(false))
.addAttachmentOption(option =>
option.setName('image')
.setDescription('Optional attachment (Image only.)')
.setRequired(false)),
category: 'fun',
ratelimit: 3,
cooldown: 86400,
guildOnly: true,
async execute(interaction, args, client) {
const content = args.content;
const attachment = args.image;
if (!content && !attachment) {
return interaction.reply({ content: 'Uh oh! You are missing any content for me to tweet!', ephemeral: true });
}
await interaction.deferReply({ ephemeral: false });
let tweet = content;
const date = new Date();
// If guild is less than 1 month old don't accept the tweet
if (interaction.guild.createdAt > date.setMonth(date.getMonth() - 1)) {
await interaction.editReply({ content: 'The server need to be 1 month old to be able to use this command!' });
return;
}
// Reset the date for the next check
date.setTime(Date.now());
// If the bot has been in the guild for less than 1 week don't accept the tweet.
if (interaction.guild.createdAt > date.setDate(date.getDate() - 7)) {
await interaction.editReply({ content: 'I need to be in this server for a week to be able to use this command!' });
}
// Reset the date for the next check
date.setTime(Date.now());
// If account is less than 6 months old don't accept the tweet ( alt prevention )
if (interaction.user.createdAt > date.setMonth(date.getMonth() - 6)) {
await interaction.editReply({ content: 'Your account is too new to be able to use this command!' });
return;
}
// Reset the date for the next check
date.setTime(Date.now());
// If account is less than 1 year old don't accept attachment
if (attachment && interaction.user.createdAt > date.setFullYear(date.getFullYear() - 1)) {
await interaction.editReply({ content: 'Your account need to be 1 year or older to be able to send attachment!' });
return;
}
if (tweet) {
// remove zero width space
tweet = tweet.replace('', '');
// This should only happen if someone tweets a zero width space
if (tweet.length === 0) {
return interaction.reply({ content: 'Uh oh! You are missing any content for me to tweet!', ephemeral: true });
}
wordToCensor.forEach(async word => {
if (tweet.toLowerCase().includes(word.toLowerCase())) {
const body = { type:'tweet', uid: interaction.user.id, reason: 'Automatic ban from banned word.' };
Blacklists.create(body);
await interaction.editReply({ content: 'Sike, you just posted cringe! Enjoy the blacklist :)' });
return;
}
});
// Detect banned word (Blacklist the user directly)
/* No worky (I don't remember what the fuck I wrote here)
if (wordToCensor.includes(tweet) || wordToCensor.includes(tweet.substring(0, tweet.length - 1)) || wordToCensor.includes(tweet.substring(1, tweet.length))) {
const body = { type:'tweet', uid: interaction.user.id, reason: 'Automatic ban from banned word.' };
Blacklists.create(body);
await interaction.editReply({ content: 'Sike, you just posted cringe! Enjoy the blacklist :)' });
return;
}
*/
// Very simple link detection
if (new RegExp('([a-zA-Z0-9]+://)?([a-zA-Z0-9_]+:[a-zA-Z0-9_]+@)?([a-zA-Z0-9.-]+\\.[A-Za-z]{2,4})(:[0-9]+)?(/.*)?').test(tweet) && !tweet.includes('twitter.com')) {
await interaction.editReply({ content: 'You may not tweet links outside of twitter.com' });
return;
}
// Do not allow discord invites
if (tweet.includes('discord.gg') || tweet.includes('discord.com/invite/')) {
await interaction.editReply({ content: 'No discord invite allowed.' });
return;
}
}
const userClient = new TwitterApi({
appKey: twiConsumer,
appSecret: twiConsumerSecret,
accessToken: twiToken,
accessSecret: twiTokenSecret,
});
try {
// Make sure there is an attachment and if its an image
if (attachment) {
if (attachment.name.toLowerCase().endsWith('.jpg') || attachment.name.toLowerCase().endsWith('.png') || attachment.name.toLowerCase().endsWith('.gif')) {
const streamPipeline = util.promisify(stream.pipeline);
const res = await fetch(attachment.url);
if (!res.ok) return interaction.editReply('An error has occured while trying to download your image.');
await streamPipeline(res.body, fs.createWriteStream(`${os.tmpdir()}/${attachment.name}`));
const file = fs.statSync(`${os.tmpdir()}/${attachment.name}`);
const fileSize = file.size / 1000000.0;
if ((attachment.name.toLowerCase().endsWith('.jpg') || attachment.name.toLowerCase().endsWith('.png')) && fileSize > 5) {
return interaction.editReply({ content: 'Images can\'t be larger than 5 MB!' });
}
else if (attachment.name.toLowerCase().endsWith('.gif') && fileSize > 15) {
return interaction.editReply({ content: 'Gifs can\'t be larger than 15 MB!' });
}
const image = await userClient.v1.uploadMedia(`${os.tmpdir()}/${attachment.name}`);
Tweet(image);
}
else {
await interaction.editReply({ content: 'File type not supported, you can only send jpg/png/gif' });
return;
}
}
else {
Tweet();
}
}
catch (err) {
console.error(err);
await interaction.editReply({ content: 'Oh no, an error has occurred :(' });
return;
}
async function Tweet(img) {
let options = null;
if (img) {
options = { media: { media_ids: new Array(img) } };
}
const tweeted = await userClient.v2.tweet(tweet, options);
const tweetid = tweeted.data.id;
const FunnyWords = ['oppaGangnamStyle', '69', '420', 'cum', 'funnyMan', 'GUCCISmartToilet', 'TwitterForClowns', 'fart', 'ok', 'hi', 'howAreYou', 'WhatsNinePlusTen', '21'];
const TweetLink = `https://vxtwitter.com/${FunnyWords[Math.floor((Math.random() * FunnyWords.length))]}/status/${tweetid}`;
let channel = await client.channels.resolve(twiChannel);
channel.send(TweetLink);
const Embed = new EmbedBuilder()
.setAuthor({ name: interaction.user.username, iconURL: interaction.user.displayAvatarURL() })
.setDescription(tweet ? tweet : 'No content.')
.addFields(
{ name: 'Link', value: TweetLink, inline: true },
{ name: 'Tweet ID', value: tweetid, inline: true },
{ name: 'Channel ID', value: interaction.channel.id, inline: true },
{ name: 'Message ID', value: interaction.id, inline: true },
{ name: 'Author', value: `${interaction.user.username} (${interaction.user.id})`, inline: true },
)
.setTimestamp();
if (interaction.guild) {
Embed.addFields(
{ name: 'Guild', value: `${interaction.guild.name} (${interaction.guild.id})`, inline: true },
{ name: 'message link', value: `https://discord.com/channels/${interaction.guild.id}/${interaction.channel.id}/${interaction.id}`, inline: true },
);
}
else {
Embed.addFields({ name: 'message link', value: `https://discord.com/channels/@me/${interaction.channel.id}/${interaction.id}` });
}
if (attachment) Embed.setImage(attachment.url);
channel = await client.channels.resolve(twiLogChannel);
channel.send({ embeds: [Embed] });
return interaction.editReply({ content: `Go see ur epic tweet ${TweetLink}` });
}
},
};

90
commands/fun/ytp.js Normal file
View file

@ -0,0 +1,90 @@
import { SlashCommandBuilder } from 'discord.js';
import fs from 'node:fs';
import os from 'node:os';
import YTPGenerator from 'ytpplus-node';
export default {
data: new SlashCommandBuilder()
.setName('ytp')
.setDescription('Generate a YTP')
.addBooleanOption(option =>
option.setName('force')
.setDescription('Force the generation of the video in non-nsfw channel.')
.setRequired(false)),
category: 'fun',
ratelimit: 2,
cooldown: 60,
parallelLimit: 30,
async execute(interaction, args) {
if (!interaction.channel.nsfw && !args.force) return interaction.reply(`Please execute this command in an NSFW channel ( Content might not be NSFW but since the video are user submitted better safe than sorry ) OR do \`\`${interaction.prefix}ytp --force\`\` to make the command work outside of nsfw channel BE AWARE THAT IT WON'T CHANGE THE FINAL RESULT SO NSFW CAN STILL HAPPEN`);
// Read userVid folder and select random vid and only take .mp4
const mp4 = [];
const asset = [];
// Count number of total vid
fs.readdirSync('./asset/ytp/userVid/').forEach(file => {
if (file.endsWith('mp4')) {
mp4.push(file);
}
});
const MAX_CLIPS = 20;
// Select random vid depending on the amount of MAX_CLIPS
for (let i = 0; i < MAX_CLIPS; i++) {
const random = Math.floor(Math.random() * mp4.length);
const vid = `./asset/ytp/userVid/${mp4[random]}`;
if (mp4[random].endsWith('mp4')) {
if (!asset.includes(vid)) {
asset.push(vid);
}
}
}
const loadingmsg = await interaction.reply(`Processing, this can take a ***long*** time, i'll ping you when I finished <a:loadingmin:527579785212329984>\nSome info: There are currently ${mp4.length} videos, why not add yours? You can do so with the \`\`addytp\`\` command.\nLike ytp? Why not check out https://ytp.namejeff.xyz/`);
const options = {
debug: false,
MAX_STREAM_DURATION: Math.floor((Math.random() * 3) + 1),
sources: './asset/ytp/sources/',
sounds: './asset/ytp/sounds/',
music: './asset/ytp/music/',
resources: './asset/ytp/resources/',
temp: os.tmpdir(),
sourceList: asset,
intro: args.force ? './asset/ytp/intro.mp4' : null,
outro: './asset/ytp/outro.mp4',
OUTPUT_FILE: `${os.tmpdir()}/${interaction.id}_YTP.mp4`,
MAX_CLIPS: MAX_CLIPS,
transitions: true,
showFileNames: true,
effects: {
effect_RandomSound: true,
effect_RandomSoundMute: true,
effect_Reverse: true,
effect_Chorus: true,
effect_Vibrato: true,
effect_HighPitch: true,
effect_LowPitch: true,
effect_SpeedUp: true,
effect_SlowDown: true,
effect_Dance: true,
effect_Squidward: true,
effect_How: true,
},
};
await new YTPGenerator().configurateAndGo(options)
.then(() => {
loadingmsg.delete();
return interaction.followUp({ content: 'Here is your YTP! Remember, it might contain nsfw, so be careful!', files: [`${os.tmpdir()}/${interaction.id}_YTP.mp4`] })
.catch(err => {
console.error(err);
return interaction.followUp({ files: [`./asset/ytp/error${Math.floor(Math.random() * 2) + 1}.mp4`] });
});
})
.catch(err => {
console.error(err);
loadingmsg.delete();
return interaction.followUp({ files: [`./asset/ytp/error${Math.floor(Math.random() * 2) + 1}.mp4`] });
});
},
};

View file

@ -1,52 +0,0 @@
const { Command } = require('discord.js-commando');
const Discord = require('discord.js');
const { createCanvas, loadImage, getContext } = require('canvas')
const superagent = require('superagent')
const SelfReloadJSON = require('self-reload-json');
const blacklist = require('../../json/blacklist.json');
module.exports = class fetishCommand extends Command {
constructor(client) {
super(client, {
name: 'fetish',
group: 'images',
memberName: 'fetish',
description: `My fetish`,
});
}
async run(message) {
let blacklistJson = new SelfReloadJSON('./json/blacklist.json');
if(blacklistJson[message.author.id])
return blacklist(blacklistJson[message.author.id] , message)
let Attachment = (message.attachments).array();
let image = null
if (!Attachment[0])
image = message.author.displayAvatarURL
else if(Attachment[0] && Attachment[0].url.endsWith('gif'))
return message.say('Gif dosent work, sorry')
else
image = Attachment[0].url
const canvas = createCanvas(528, 559)
const ctx = canvas.getContext('2d')
const background = await loadImage('https://image.noelshack.com/fichiers/2018/42/2/1539644291-my-fetish-5910119d988512.png').catch(error => {
return message.say('An error as occured, please try again')
})
ctx.drawImage(background, 0, 0, canvas.width, canvas.height);
const { body: buffer } = await superagent.get(image);
const bg = await loadImage(buffer);
ctx.drawImage(bg, 50, 50, 450, 450);
const attachment = new Discord.Attachment(canvas.toBuffer(), 'myfetish.png');
message.say(attachment).catch(error => {
message.say('an error as occured. Check the bot/channel permissions')
})
}
};

View file

@ -1,52 +0,0 @@
const { Command } = require('discord.js-commando');
const Discord = require('discord.js');
const { createCanvas, loadImage, getContext } = require('canvas')
const superagent = require('superagent')
const SelfReloadJSON = require('self-reload-json');
const blacklist = require('../../json/blacklist.json');
module.exports = class godCommand extends Command {
constructor(client) {
super(client, {
name: 'god',
group: 'images',
memberName: 'god',
description: `Retweet if you aren't afraid to have a picture of god on your timeline`,
});
}
async run(message) {
let blacklistJson = new SelfReloadJSON('./json/blacklist.json');
if(blacklistJson[message.author.id])
return blacklist(blacklistJson[message.author.id] , message)
let Attachment = (message.attachments).array();
let image = null
if (!Attachment[0])
image = message.author.displayAvatarURL
else if(Attachment[0] && Attachment[0].url.endsWith('gif'))
return message.say('Gif dosent work, sorry')
else
image = Attachment[0].url
const canvas = createCanvas(310, 400)
const ctx = canvas.getContext('2d')
const background = await loadImage(image);
ctx.drawImage(background, 20, 80, 275, 250);
const { body: buffer } = await superagent.get('https://image.noelshack.com/fichiers/2018/42/1/1539555260-untitled.png').catch(error => {
return message.say('An error as occured, please try again')
})
const bg = await loadImage(buffer);
ctx.drawImage(bg, 0, 0, canvas.width, canvas.height);
const attachment = new Discord.Attachment(canvas.toBuffer(), 'god.png');
message.say(attachment).catch(error => {
message.say('an error as occured. Check the bot/channel permissions')
})
}
};

View file

@ -1,52 +0,0 @@
const { Command } = require('discord.js-commando');
const Discord = require('discord.js');
const { createCanvas, loadImage, getContext } = require('canvas')
const superagent = require('superagent')
const SelfReloadJSON = require('self-reload-json');
const blacklist = require('../../json/blacklist.json');
module.exports = class humanCommand extends Command {
constructor(client) {
super(client, {
name: 'human',
group: 'images',
memberName: 'human',
description: `HUMAN ?! YOU DARE CALL THAT THING HUMAN?!?!`,
});
}
async run(message) {
let blacklistJson = new SelfReloadJSON('./json/blacklist.json');
if(blacklistJson[message.author.id])
return blacklist(blacklistJson[message.author.id] , message)
let Attachment = (message.attachments).array();
let image = null
if (!Attachment[0])
image = message.author.displayAvatarURL
else if(Attachment[0] && Attachment[0].url.endsWith('gif'))
return message.say('Gif dosent work, sorry')
else
image = Attachment[0].url
const canvas = createCanvas(578, 400)
const ctx = canvas.getContext('2d')
const background = await loadImage('https://image.noelshack.com/fichiers/2018/42/1/1539594726-untitled.png').catch(error => {
return message.say('An error as occured, please try again')
})
ctx.drawImage(background, 0, 0, canvas.width, canvas.height);
const { body: buffer } = await superagent.get(image);
const bg = await loadImage(buffer);
ctx.drawImage(bg, 420, 120, 150, 150);
const attachment = new Discord.Attachment(canvas.toBuffer(), 'human.png');
message.say(attachment).catch(error => {
message.say('an error as occured. Check the bot/channel permissions')
})
}
};

View file

@ -1,79 +0,0 @@
const { Command } = require('discord.js-commando');
const Discord = require('discord.js');
const { createCanvas, loadImage, getContext } = require('canvas')
const superagent = require('superagent')
const SelfReloadJSON = require('self-reload-json');
const blacklist = require('../../json/blacklist.json');
module.exports = class idubbbzCommand extends Command {
constructor(client) {
super(client, {
name: 'idubbbz',
aliases: ['idubbz', 'edups'],
group: 'images',
memberName: 'idubbbz',
description: `Put the text you send in idubbbz piece of paper`,
args: [
{
key: 'text',
prompt: 'What do you the paper to say?',
type: 'string',
default: 'Nigger Faggot'
}
]
});
}
async run(message, { text }) {
let blacklistJson = new SelfReloadJSON('./json/blacklist.json');
if(blacklistJson[message.author.id])
return blacklist(blacklistJson[message.author.id] , message)
let Attachment = (message.attachments).array();
let image = null
if (!Attachment[0])
image = message.author.displayAvatarURL
else if(Attachment[0] && Attachment[0].url.endsWith('gif'))
return message.say('Gif dosent work, sorry')
else
image = Attachment[0].url
const canvas = createCanvas(1281, 627)
const applyText = (canvas, text) => {
const ctx = canvas.getContext('2d');
// Declare a base size of the font
let fontSize = 50;
do {
// Assign the font to the context and decrement it so it can be measured again
ctx.font = `${fontSize -= 10}px ubuntu`;
} while (ctx.measureText(text).width > 700 - 300);
// Return the result to use in the actual canvas
return ctx.font;
};
const ctx = canvas.getContext('2d')
const background = await loadImage(image);
ctx.drawImage(background, 620, 100, 200, 200);
const { body: buffer } = await superagent.get('https://image.noelshack.com/fichiers/2018/41/7/1539510207-untitled.png').catch(error => {
return message.say('An error as occured, please try again')
})
const bg = await loadImage(buffer);
ctx.drawImage(bg, 0, 0, canvas.width, canvas.height);
ctx.font = applyText(canvas, text)
ctx.fillStyle = '#000000';
ctx.fillText(text, canvas.width / 2.1, canvas.height / 1.5);
const attachment = new Discord.Attachment(canvas.toBuffer(), 'edups.png');
message.say(attachment).catch(error => {
message.say('an error as occured. Check the bot/channel permissions')
})
}
};

View file

@ -1,79 +0,0 @@
const { Command } = require('discord.js-commando');
const Discord = require('discord.js');
const { createCanvas, loadImage, getContext } = require('canvas')
const superagent = require('superagent')
const SelfReloadJSON = require('self-reload-json');
const blacklist = require('../../json/blacklist.json');
module.exports = class idubbbzpaintCommand extends Command {
constructor(client) {
super(client, {
name: 'idubbbzpaint',
aliases: ['idubbzpaint', 'edupspaint'],
group: 'images',
memberName: 'painting',
description: `Put the image you send or you in idubbbz painting`,
args: [
{
key: 'text',
prompt: 'What do you the paper to say?',
type: 'string',
default: 'Perfection'
}
]
});
}
async run(message, { text }) {
let blacklistJson = new SelfReloadJSON('./json/blacklist.json');
if(blacklistJson[message.author.id])
return blacklist(blacklistJson[message.author.id] , message)
let Attachment = (message.attachments).array();
let image = null
if (!Attachment[0])
image = message.author.displayAvatarURL
else if(Attachment[0] && Attachment[0].url.endsWith('gif'))
return message.say('Gif dosent work, sorry')
else
image = Attachment[0].url
const canvas = createCanvas(1024, 544)
const applyText = (canvas, text) => {
const ctx = canvas.getContext('2d');
// Declare a base size of the font
let fontSize = 100;
do {
// Assign the font to the context and decrement it so it can be measured again
ctx.font = `${fontSize -= 10}px ubuntu`;
} while (ctx.measureText(text).width > 800 - 300);
// Return the result to use in the actual canvas
return ctx.font;
};
const ctx = canvas.getContext('2d')
const background = await loadImage(image);
ctx.drawImage(background, 140, 40, 400, 340);
const { body: buffer } = await superagent.get('https://image.noelshack.com/fichiers/2018/41/7/1539533685-untitled.png').catch(error => {
return message.say('An error as occured, please try again')
})
const bg = await loadImage(buffer);
ctx.drawImage(bg, 0, 0, canvas.width, canvas.height);
ctx.font = applyText(canvas, text)
ctx.fillStyle = '#ffffff';
ctx.fillText(text, canvas.width / 3, canvas.height / 1.1);
const attachment = new Discord.Attachment(canvas.toBuffer(), 'edupspaint.png');
message.say(attachment).catch(error => {
message.say('an error as occured. Check the bot/channel permissions')
})
}
};

View file

@ -1,51 +0,0 @@
const { Command } = require('discord.js-commando');
const Discord = require('discord.js');
const { createCanvas, loadImage, getContext } = require('canvas')
const superagent = require('superagent')
const SelfReloadJSON = require('self-reload-json');
const blacklist = require('../../json/blacklist.json');
module.exports = class likeCommand extends Command {
constructor(client) {
super(client, {
name: 'like',
group: 'images',
memberName: 'like',
description: `What the hell is this and why did my grandsone like it`,
});
}
async run(message) {
let blacklistJson = new SelfReloadJSON('./json/blacklist.json');
if(blacklistJson[message.author.id])
return blacklist(blacklistJson[message.author.id] , message)
let Attachment = (message.attachments).array();
let image = null
if (!Attachment[0])
image = message.author.displayAvatarURL
else if(Attachment[0] && Attachment[0].url.endsWith('gif'))
return message.say('Gif dosent work, sorry')
else
image = Attachment[0].url
const canvas = createCanvas(386, 399)
const ctx = canvas.getContext('2d')
const background = await loadImage(image);
ctx.drawImage(background, 40, 0, 300, 255);
const { body: buffer } = await superagent.get('https://image.noelshack.com/fichiers/2018/41/7/1539547403-untitled.png').catch(error => {
return message.say('An error as occured, please try again')
})
const bg = await loadImage(buffer);
ctx.drawImage(bg, 0, 0, canvas.width, canvas.height);
const attachment = new Discord.Attachment(canvas.toBuffer(), 'like.png');
message.say(attachment).catch(error => {
message.say('an error as occured. Check the bot/channel permissions')
})
}
};

View file

@ -1,51 +0,0 @@
const { Command } = require('discord.js-commando');
const Discord = require('discord.js');
const { createCanvas, loadImage, getContext } = require('canvas')
const superagent = require('superagent')
const SelfReloadJSON = require('self-reload-json');
const blacklist = require('../../json/blacklist.json');
module.exports = class uglyCommand extends Command {
constructor(client) {
super(client, {
name: 'ugly',
group: 'images',
memberName: 'ugly',
description: `You are very ugly!`,
});
}
async run(message) {
let blacklistJson = new SelfReloadJSON('./json/blacklist.json');
if(blacklistJson[message.author.id])
return blacklist(blacklistJson[message.author.id] , message)
let Attachment = (message.attachments).array();
let image = null
if (!Attachment[0])
image = message.author.displayAvatarURL
else if(Attachment[0] && Attachment[0].url.endsWith('gif'))
return message.say('Gif dosent work, sorry')
else
image = Attachment[0].url
const canvas = createCanvas(323, 400)
const ctx = canvas.getContext('2d')
const background = await loadImage('https://image.noelshack.com/fichiers/2018/42/1/1539598678-untitled.png').catch(error => {
return message.say('An error as occured, please try again')
})
ctx.drawImage(background, 0, 0, canvas.width, canvas.height);
const { body: buffer } = await superagent.get(image);
const bg = await loadImage(buffer);
ctx.drawImage(bg, 40, 100, 250, 250);
const attachment = new Discord.Attachment(canvas.toBuffer(), 'ugly.png');
message.say(attachment).catch(error => {
message.say('an error as occured. Check the bot/channel permissions')
})
}
};

View file

@ -1,50 +0,0 @@
const { Command } = require('discord.js-commando');
const fs = require('fs');
module.exports = class BlacklistCommand extends Command {
constructor(client) {
super(client, {
name: 'blacklist',
aliases: ['niggerlist'],
group: 'owner',
memberName: 'blacklist',
description: `To blacklist a user from the bot`,
ownerOnly: true,
args: [
{
key: 'user',
prompt: 'Who do you want to blacklist',
type: 'user',
},
{
key: 'reasons',
prompt: 'Who do you want to blacklist',
type: 'string',
default: 'Didin\'t provide any reasons'
}
]
});
}
async run(message, { user, reasons }) {
let blacklist = {}
let json = JSON.stringify(blacklist)
if(user) {
fs.readFile('json/blacklist.json', 'utf8', function readFileCallback(err, data){
if (err){
console.log(err);
} else {
blacklist = JSON.parse(data); //now it an object
blacklist [user] = reasons
json = JSON.stringify(blacklist); //convert it back to json
json = json.replace(/[<@!>]/g, '')
fs.writeFile('json/blacklist.json', json, 'utf8', function(err) {
if(err) {
return console.log(err);
}
})}});
return message.say(`User ${user} have been blacklisted`);
}
}
};

View file

@ -1,31 +0,0 @@
const { Command } = require('discord.js-commando');
module.exports = class BotavatarCommand extends Command {
constructor(client) {
super(client, {
name: 'botavatar',
group: 'owner',
memberName: 'botavatar',
description: 'Change the avatar of the bot',
ownerOnly: true,
args: [
{
key: 'pic',
prompt: 'Wich avatar should i have?',
type: 'string',
default: ''
}
]
});
}
async run(message, { pic }) {
let Attachment = (message.attachments).array();
let image = null
if (!Attachment[0])
return message.say('You didint provide any images')
else
image = Attachment[0].url
this.client.user.setAvatar(image);
message.say('The avatar have been changed succesfully');
}
};

View file

@ -1,17 +0,0 @@
const { Command } = require('discord.js-commando');
module.exports = class DedCommand extends Command {
constructor(client) {
super(client, {
name: 'ded',
aliases: ['shutdown', 'dead', 'restart', 'reboot'],
group: 'owner',
memberName: 'ded',
description: 'Reboot the bot',
ownerOnly: true,
});
}
async run(message) {
await message.say('k bye thx\nhttps://i.redd.it/lw8hrvr0l4f11.jpg');
process.exit();
}}

View file

@ -0,0 +1,38 @@
// TODO
// Switch to 'twitter-api-v2'
import { SlashCommandBuilder } from 'discord.js';
import Twit from 'twit';
const { twiConsumer, twiConsumerSecret, twiToken, twiTokenSecret } = process.env;
export default {
data: new SlashCommandBuilder()
.setName('deletetweet')
.setDescription('Delete a tweet')
.addStringOption(option =>
option.setName('tweetid')
.setDescription('The id of the tweet you wish to delete.')
.setRequired(true)),
category: 'owner',
ownerOnly: true,
async execute(interaction, args) {
await interaction.deferReply();
try {
const T = new Twit({
consumer_key: twiConsumer,
consumer_secret: twiConsumerSecret,
access_token: twiToken,
access_token_secret: twiTokenSecret,
});
T.post('statuses/destroy', {
id: args.tweetid,
});
return interaction.editReply('Tweet have been deleted!');
}
catch (err) {
console.error(err);
return interaction.editReply('Oh no, an error has occurred :(');
}
},
};

17
commands/owner/die.js Normal file
View file

@ -0,0 +1,17 @@
import { SlashCommandBuilder } from 'discord.js';
export default {
data: new SlashCommandBuilder()
.setName('die')
.setDescription('Kill the bot'),
category: 'owner',
ownerOnly: true,
async execute(interaction) {
console.log('\x1b[31m\x1b[47m\x1b[5mSHUTING DOWN!!!!!\x1b[0m');
await interaction.reply({ content: 'Good bye', ephemeral: true })
.then(() => {
console.log('\x1b[31m\x1b[47m\x1b[5mSHUTING DOWN!!!!!\x1b[0m');
process.exit(1);
});
},
};

View file

@ -1,37 +1,69 @@
const { Command } = require('discord.js-commando'); import { SlashCommandBuilder, EmbedBuilder } from 'discord.js';
module.exports = class dmCommand extends Command { // const feedbackID = [];
constructor(client) {
super(client, {
name: 'dm',
group: 'owner',
memberName: 'dm',
aliases: ['pm'],
description: 'Dm the user id',
ownerOnly: true,
args: [
{
key: 'user',
prompt: 'Wich user would you like to dm?',
type: 'user',
},
{
key: 'text',
prompt: 'What do you want to say to the user',
type: 'string',
}
]
});
}
async run(message, { user, text }) { export default {
let Attachment = (message.attachments).array(); data: new SlashCommandBuilder()
if (Attachment[0]) { .setName('dm')
user.send(`**Message from the dev:**\n${text}\n${Attachment[0].url}`) .setDescription('Replies with Pong!')
message.say(`DM sent to ${user.username}`) .addStringOption(option =>
} option.setName('userid')
else { .setDescription('The user to who you want to send the message to.')
user.send(`**Message from the dev:**\n${text}`) .setRequired(true))
message.say(`DM sent to ${user.username}`) .addStringOption(option =>
} option.setName('message')
} .setDescription('What do you want to tell them?')
}; .setRequired(true))
.addAttachmentOption(option =>
option.setName('image')
.setDescription('Optional attachment.')
.setRequired(false)),
category: 'owner',
ownerOnly: true,
async execute(interaction, args, client) {
/* Too lazy to implement that now (Watch it rest untouched for months)
async function uuidv4() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
const r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
const uuid = uuidv4();
feedbackID[uuid] = args.message;
*/
await client.users.fetch(args.userid);
const user = client.users.resolve(args.userid);
if (!user) return interaction.reply('Not a valid ID');
const text = args.message;
const Embed = new EmbedBuilder()
.setTitle('You received a message from the developer!')
.setDescription(text)
.setFooter({ text: `If you wish to respond use the following command: ${interaction.prefix}feedback <message>` })
.setTimestamp();
user.send({ embeds: [Embed] });
return interaction.reply({ content: `DM sent to ${user.username} (${user.id})` });
/*
const Attachment = (message.attachments).array();
if (Attachment[0]) {
client.users.resolve(user).send(Embed, { files: [Attachment[0].url] })
.then(() => {
return interaction.reply(`DM sent to ${user.username}`);
})
.catch(() => {
return interaction.reply(`Could not send a DM to ${user.username}`);
});
}
else {
client.users.resolve(user).send(Embed)
.then(() => {
return interaction.reply(`DM sent to ${user.username}`);
})
.catch(() => {
return interaction.reply(`Could not send a DM to ${user.username}`);
});
}
*/
},
};

View file

@ -0,0 +1,30 @@
import { SlashCommandBuilder } from 'discord.js';
import util from 'node:util';
import stream from 'node:stream';
import fs from 'node:fs';
export default {
data: new SlashCommandBuilder()
.setName('downloadandload')
.setDescription('Download a command and load it.')
.addAttachmentOption(option =>
option.setName('file')
.setDescription('The .js file that will be loaded by the bot.')
.setRequired(true)),
category: 'owner',
ownerOnly: true,
async execute(interaction, args, client) {
await interaction.deferReply();
const streamPipeline = util.promisify(stream.pipeline);
const res = await fetch(args.file.url);
if (!res.ok) return interaction.editReply('An error has occured while trying to download the command.');
await streamPipeline(res.body, fs.createWriteStream(`./tmp/${args.file.name}`));
let command = await import(`../../tmp/${args.file.name}`);
command = command.default;
client.commands.set(command.data.name, command);
return await interaction.editReply(`${command.data.name} has been loaded.`);
},
};

View file

@ -1,24 +0,0 @@
const { Command } = require('discord.js-commando');
module.exports = class dmCommand extends Command {
constructor(client) {
super(client, {
name: 'emit',
group: 'owner',
memberName: 'emit',
aliases: ['event', 'emitevent'],
description: 'Trigger an event',
ownerOnly: true,
args: [
{
key: 'event',
prompt: 'Wich event do you want to trigger?',
type: 'string',
}
]
});
}
async run(message, { event }) {
this.client.emit(`${event}`);
}
};

22
commands/owner/load.js Normal file
View file

@ -0,0 +1,22 @@
import { SlashCommandBuilder } from 'discord.js';
export default {
data: new SlashCommandBuilder()
.setName('load')
.setDescription('load a command.')
.addStringOption(option =>
option.setName('file')
.setDescription('File location of the command.')
.setRequired(true)),
category: 'owner',
ownerOnly: true,
async execute(interaction, args, client) {
await interaction.deferReply();
let command = await import(`../../${args.file}`);
command = command.default;
client.commands.set(command.data.name, command);
return await interaction.editReply(`${command.data.name} has been loaded.`);
},
};

View file

@ -1,24 +0,0 @@
const { Command } = require('discord.js-commando');
module.exports = class StatusCommand extends Command {
constructor(client) {
super(client, {
name: 'status',
group: 'owner',
memberName: 'status',
description: 'Change the status of the bot',
ownerOnly: true,
args: [
{
key: 'status',
prompt: 'Wich status should i have?',
type: 'string',
}
]
});
}
async run(message, { status }) {
this.client.user.setActivity(status);
message.say(`Status have been set to ${status}`);
}
};

View file

@ -0,0 +1,89 @@
import { ButtonStyle, SlashCommandBuilder, ButtonBuilder, ActionRowBuilder } from 'discord.js';
import db from '../../models/index.js';
const Blacklists = db.Blacklists;
export default {
data: new SlashCommandBuilder()
.setName('ublacklist')
.setDescription('Blacklist a user from the bot')
.addStringOption(option =>
option.setName('command')
.setDescription('Which command do you want to get a user blacklisted from?')
.setRequired(true))
.addStringOption(option =>
option.setName('userid')
.setDescription('Who do you want to blacklist?')
.setRequired(true))
.addStringOption(option =>
option.setName('reason')
.setDescription('The reason of the blacklist.')
.setRequired(false)),
category: 'owner',
ownerOnly: true,
async execute(interaction, args) {
await interaction.deferReply({ ephemeral: true });
const client = interaction.client;
const command = args.command;
const userid = args.userid;
const reason = args.reason ? args.reason : 'No reason has been specified.';
const blacklist = await Blacklists.findOne({ where: { type:command, uid:userid } });
if (!blacklist) {
const body = { type:command, uid: userid, reason: reason };
Blacklists.create(body);
if (command === 'guild') {
const guildid = userid;
await client.guilds.fetch(guildid);
const guild = client.guilds.resolve(guildid).name;
return interaction.editReply(`The guild ${guild} (${guildid}) has been blacklisted with the following reason \`${reason}\``);
}
else {
let user = userid;
await client.users.fetch(userid);
user = client.users.resolve(userid).username;
return interaction.editReply(`${user} (${userid}) has been blacklisted from ${command} with the following reason \`${reason}\``);
}
}
else {
const row = new ActionRowBuilder()
.addComponents(
new ButtonBuilder()
.setCustomId(`yes${interaction.user.id}${interaction.id}`)
.setLabel('Yes')
.setStyle(ButtonStyle.Primary),
)
.addComponents(
new ButtonBuilder()
.setCustomId(`no${interaction.user.id}${interaction.id}`)
.setLabel('No')
.setStyle(ButtonStyle.Danger),
);
await interaction.editReply({ content: 'This user is already blacklisted, do you want to unblacklist him?', ephemeral: true, components: [row] });
return listenButton(client, interaction, command, userid, interaction.user);
}
},
};
async function listenButton(client, interaction, command, userid, user = interaction.user, originalId = interaction.id) {
client.once('interactionCreate', async (interactionMenu) => {
if (user !== interactionMenu.user) return listenButton(client, interaction, command, userid, user, originalId);
if (!interactionMenu.isButton()) return;
await interactionMenu.update({ components: [] });
if (interactionMenu.customId === `yes${interaction.user.id}${originalId}`) {
Blacklists.destroy({ where: { type:command, uid:userid } });
return interaction.editReply(`The following ID have been unblacklisted from ${command}: ${userid}`);
}
else {
return interaction.editReply('No one has been unblacklisted.');
}
});
}

50
commands/owner/unload.js Normal file
View file

@ -0,0 +1,50 @@
import { SlashCommandBuilder } from 'discord.js';
import fs from 'node:fs';
export default {
data: new SlashCommandBuilder()
.setName('unload')
.setDescription('Unload a command and replace it with a placeholder')
.addStringOption(option =>
option.setName('commandname')
.setDescription('The command to unload.')
.setRequired(true))
.addStringOption(option =>
option.setName('placeholder')
.setDescription('The placeholder message you want for the command.'))
.addBooleanOption(option =>
option.setName('nofile')
.setDescription('Don\'t create the placeholder file')),
category: 'owner',
ownerOnly: true,
async execute(interaction, args, client) {
await interaction.deferReply();
if (!client.commands.has(args.commandname)) return await interaction.editReply('Command not found.');
if (!args.placeholder) args.placeholder = 'This command is unloaded, please check back later.';
if (!args.nofile) {
fs.writeFileSync(`./unloaded/${args.commandname}.js`, `
import { SlashCommandBuilder } from 'discord.js';
export default {
data: ${JSON.stringify(client.commands.get(args.commandname).data)},
category: '${client.commands.get(args.commandname).category}',
async execute(interaction) {
return interaction.reply('${args.placeholder.replace(/'/g, '\\\'')}');
},
};
`);
}
client.commands.delete(args.commandname);
if (!args.nofile) {
let command = await import(`../../unloaded/${args.commandname}.js`);
command = command.default;
client.commands.set(args.commandname, command);
}
return await interaction.editReply(`${args.commandname} has been unloaded.`);
},
};

View file

@ -1,25 +0,0 @@
const { Command } = require('discord.js-commando');
module.exports = class UsernameCommand extends Command {
constructor(client) {
super(client, {
name: 'username',
group: 'owner',
memberName: 'username',
description: 'Change the username of the bot',
ownerOnly: true,
args: [
{
key: 'username',
prompt: 'Wich status should i have?',
type: 'string',
}
]
});
}
async run(message, { username }) {
this.client.user.setUsername(username);
message.say(`The username have been changed sucessfully to ${username}`);
}
};

View file

@ -1,40 +0,0 @@
const { Command } = require('discord.js-commando');
module.exports = class BSEspamCommand extends Command {
constructor(client) {
super(client, {
name: 'bsespam',
group: 'reserved',
memberName: 'bsespam',
description: `FOR Big Snow Energy only\nSpam the text you send`,
throttling: {
usages: 2,
duration: 3600,
},
args: [
{
key: 'number',
prompt: 'How many times do you want to repeat it?',
type: 'integer',
validate: number => number < 11,
default: '1'
},
{
key: 'text',
prompt: 'What do you want me to say',
type: 'string',
}
]
});
}
async run(message, { number, text }) {
if (message.author.id != "428387534842626048")
return message.say('Command only available to **Big Snow Energy**')
for(let i = 0; i < number; i++) {
message.say(text);
}
message.say('Finished :)');
}
};

90
commands/secret/s.js Normal file
View file

@ -0,0 +1,90 @@
/* eslint-disable no-case-declarations */
import { SlashCommandBuilder } from 'discord.js';
const { ownerId } = process.env;
export default {
data: new SlashCommandBuilder()
.setName('s')
.setDescription('What could this be 🤫')
.addStringOption(option =>
option.setName('something')
.setDescription('🤫')
.setRequired(true))
.addStringOption(option =>
option.setName('somethingelse')
.setDescription('🤫')
.setRequired(false)),
category: 'secret',
async execute(interaction, args, client) {
const command = args.something;
switch (command) {
case 'levertowned':
return interaction.reply('Hello buddy bro <:youngtroll:488559163832795136> <@434762632004894746>');
case 'owned':
const epicMessage = ['You cheated not ONLY the GAME, BUT yourself. You didn\'t GROW. You didn\'t IMPROVE. You TOOK a SHORTCUT and gained NOTHING. You EXPERIENCED a HOLLOW victory. NOTHING WAS risked and NOTHING WAS gained. It\'s SAD that you don\'t KNOW the DIFFERENCE.', 'TROLOLOLO OWNED EPIC STYLE', 'Owned noob', 'HAHA BRO YOU JUST GOT OOOOOOOOWNED HAHAHAHAHHAHA NOOOB NOOOOB NOOOB OWNED NOOB <:youngtroll:488559163832795136>', '<a:op:516341492982218756> op op op owned epic style <a:op:516341492982218756>', 'HAHAHA BRO YOU HAVE BEEN OWNED TROLL BRO STYLE', 'OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED YOU JUST GOT OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED YOU JUST GOT OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED YOU JUST GOT OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED OWNED YOU JUST GOT OWNED', 'OWNED\nFUCKING OWNED', 'OWNED!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!', 'You just got owned <a:troll:525724709833277442>', 'you just been....epicly trolled <:trole:241942993022615552>', 'I hope you have a nice day, just a simple reminder that I love you and I think you\'re pretty epic!!!!'];
const ownedMessage = epicMessage[Math.floor(Math.random() * epicMessage.length)];
await interaction.guild.members.fetch();
let owned = args.somethingelse ? interaction.guild.members.cache.find(u => u.user.username.toLowerCase().includes(args.somethingelse.toLowerCase())) : null;
if (interaction.isMessage) {
if (interaction.mentions.members.first()) {
console.log('test');
owned = interaction.mentions.members.first();
}
}
if (args.somethingelse) {
if (owned.id === client.user.id) {
return interaction.reply('You really thought you could own me?, pathetic...');
}
else if (owned.id === ownerId) {
return interaction.reply('You really thought you could own him?, pathetic...');
}
else if (owned.id === '286054184623538177' || owned.id === '172112210863194113') {
owned = interaction.user;
}
if (ownedMessage === epicMessage[0]) {
return interaction.reply(ownedMessage);
}
return interaction.reply(`${owned}, ${ownedMessage}`);
}
else {
return interaction.reply(ownedMessage);
}
case 'fartpiss':
if (interaction.guild.id != '240843640375607296') {
return;
}
await interaction.guild.members.fetch();
const member = args.somethingelse ? interaction.guild.members.cache.find(u => u.user.username.toLowerCase().includes(args.somethingelse.toLowerCase())) : null;
if (member) {
return await member.setNickname('fart piss')
.then(() => interaction.reply(`sucessfully fart pissed on ${member.user.username} <:youngtroll:488559163832795136>`))
.catch((error) => {
if (process.env.NODE_ENV === 'development') console.error(error);
interaction.reply(`Sorry i could not fart piss on ${member.user.username} :(`);
});
}
else {
return await interaction.member.setNickname('fart piss')
.then(() => interaction.reply('sucessfully fart pissed on you <:youngtroll:488559163832795136>'))
.catch((error) => {
if (process.env.NODE_ENV === 'development') console.error(error);
interaction.reply('Sorry i could not fart piss on you :(');
});
}
default:
break;
}
},
};

63
commands/utility/about.js Normal file
View file

@ -0,0 +1,63 @@
import { SlashCommandBuilder } from 'discord.js';
import { EmbedBuilder } from 'discord.js';
import { execFile } from 'node:child_process';
import db from '../../models/index.js';
const donator = db.donator;
const { ownerId, uptimePage } = process.env;
export default {
data: new SlashCommandBuilder()
.setName('about')
.setDescription('About me (The bot)'),
category: 'utility',
async execute(interaction) {
const Donator = await donator.findAll({ order: ['id'] });
const client = interaction.client;
const tina = await client.users.fetch('336492042299637771');
const creator = await client.users.fetch('267065637183029248');
const maintainer = await client.users.fetch(ownerId);
let description = 'I\'m a fun multipurpose bot made using [discord.js](https://github.com/discordjs/discord.js)'
+ '\nFor a better experience use the slash commands!\n\nThe people who donated for the bot <3\n';
if (Donator[0]) {
for (let i = 0; i < Donator.length; i++) {
const user = await client.users.fetch(Donator[i].get('userID').toString());
if (user !== null) {
description += `**${user.username} (${user.id}) | ${Donator[i].get('comment')}**\n`;
}
else {
description += `**A user of discord (${user.id}) | ${Donator[i].get('comment')} (This user no longer share a server with the bot)**\n`;
}
}
}
else {
description += 'No one :(\n';
}
description += `\nThanks to ${tina.username} (336492042299637771) for inspiring me for making this bot!`;
// description += '\nThanks to Jetbrains for providing their IDE!';
execFile('git', ['rev-parse', '--short', 'HEAD'], (err, stdout) => {
const aboutEmbed = new EmbedBuilder()
.setColor(interaction.member ? interaction.member.displayHexColor : 'Navy')
.setAuthor({ name: client.user.username, iconURL: client.user.displayAvatarURL(), url: 'https://libtar.de' })
.setTitle('About me')
.setDescription(description)
.addFields(
{ name: 'Current commit', value: stdout },
{ name: 'Current maintainer', value: `${maintainer.username} (${ownerId})` },
{ name: 'Gitea (Main)', value: 'https://git.namejeff.xyz/Supositware/Haha-Yes', inline: true },
{ name: 'Github (Mirror)', value: 'https://github.com/Supositware/Haha-yes', inline: true },
{ name: 'Privacy Policy', value: 'https://libtar.de/discordprivacy.txt', inline: true },
{ name: 'Status page', value: uptimePage.toString(), inline: true },
)
.setFooter({ text: `Original bot made by ${creator.username} (267065637183029248)` });
interaction.reply({ embeds: [aboutEmbed] });
});
},
};

View file

@ -0,0 +1,99 @@
import { SlashCommandBuilder, EmbedBuilder } from 'discord.js';
import utils from '../../utils/videos.js';
import fs from 'node:fs';
import os from 'node:os';
const { ytpChannelId } = process.env;
export default {
data: new SlashCommandBuilder()
.setName('addytp')
.setDescription('Add a video to the pool of ytps. You can add 5 per day.')
.addStringOption(option =>
option.setName('url')
.setDescription('URL of the video you want to add.')
.setRequired(true)),
category: 'utility',
ratelimit: 5,
cooldown: 86400,
async execute(interaction, args) {
const url = args.url;
// This is rather rudementary, a proper way would be using yt-dlp to know if it is a playlist
if (url.includes('list=')) {
return interaction.reply({ content: '❌ Playlists are not allowed!', ephemeral: true });
}
if (!await utils.stringIsAValidurl(url)) {
console.error(`Not a url!!! ${url}`);
return interaction.reply({ content: '❌ This does not look like a valid url!', ephemeral: true });
}
await interaction.deferReply({ ephemeral: true });
utils.downloadVideo(url, interaction.id, 'bestvideo[height<=?480]+bestaudio/best')
.then(async () => {
const file = fs.readdirSync(os.tmpdir()).filter(fn => fn.startsWith(interaction.id));
const output = `${os.tmpdir()}/${file}`;
const fileStat = fs.statSync(output);
const fileSize = fileStat.size / 1000000.0;
if (fileSize > 50) {
// await interaction.deleteReply();
await interaction.editReply({ content: '❌ Uh oh! The video is too big!', ephemeral: true });
}
else {
// CopyFile instead of rename in case you have /tmp and the asset folder on different a disk.
fs.copyFileSync(output, `./asset/ytp/userVid/${file}`);
const mp4 = [];
fs.readdirSync('./asset/ytp/userVid/').forEach(f => {
if (f.endsWith('mp4')) {
mp4.push(f);
}
});
// (Hopefully) limit video to 2k
if (mp4.length > 2000) {
const f = mp4.sort((a, b) => {
const time1 = fs.statSync(`./asset/ytp/userVid/${b}`).ctime;
const time2 = fs.statSync(`./asset/ytp/userVid/${a}`).ctime;
if (time1 < time2) return 1;
if (time1 > time2) return -1;
return 0;
}).slice(0, 1);
fs.unlinkSync(`./asset/ytp/userVid/${f[0]}`);
}
interaction.editReply({ content: `Video successfully added to the pool! There is now ${mp4.length} videos`, ephemeral: true });
const Embed = new EmbedBuilder()
.setAuthor({ name: interaction.user.username, iconURL: interaction.user.displayAvatarURL() })
.addFields([
{ name: 'Channel ID', value: interaction.channel.id.toString(), inline: true },
{ name: 'Message ID', value: interaction.id.toString(), inline: true },
{ name: 'Author', value: `${interaction.user.username} (${interaction.user.id})`, inline: true },
])
.setTimestamp();
if (interaction.guild) {
Embed.addFields([
{ name: 'Guild', value: `${interaction.guild.name} (${interaction.guild.id})`, inline: true },
{ name: 'Message link', value: `https://discord.com/channels/${interaction.guild.id}/${interaction.channel.id}/${interaction.id}` },
]);
}
else {
Embed.addFields([
{ name: 'Message link', value: `https://discord.com/channels/@me/${interaction.channel.id}/${interaction.id}` },
]);
}
const channel = interaction.client.channels.resolve(ytpChannelId);
// Send as 2 separate message otherwise the url won't get embedded.
channel.send({ content: url });
return channel.send({ embeds: [Embed] });
}
});
},
};

View file

@ -1,34 +1,49 @@
const { Command } = require('discord.js-commando'); import { EmbedBuilder, SlashCommandBuilder } from 'discord.js';
const SelfReloadJSON = require('self-reload-json');
const blacklist = require('../../json/blacklist.json'); export default {
data: new SlashCommandBuilder()
.setName('avatar')
.setDescription('Show user avatar')
.addMentionableOption(option =>
option.setName('member')
.setDescription('Who do you want to fake?')
.setRequired(false)),
category: 'utility',
async execute(interaction, args) {
const avatarEmbed = new EmbedBuilder()
.setColor(interaction.member ? interaction.member.displayHexColor : 'Navy')
.setTitle('Avatar');
module.exports = class AvatarCommand extends Command { if (!args.member) {
constructor(client) { const format = interaction.user.displayAvatarURL({ dynamic: true }).substr(interaction.user.displayAvatarURL({ dynamic: true }).length - 3);
super(client, { if (format == 'gif') {
name: 'avatar', avatarEmbed.setAuthor({ name: interaction.user.username });
group: 'utility', avatarEmbed.setDescription(`[gif](${interaction.user.displayAvatarURL({ format: 'gif', size: 2048 })})`);
memberName: 'avatar', avatarEmbed.setImage(interaction.user.displayAvatarURL({ format: 'gif', size: 2048 }));
description: 'Send the avatar of the mentionned user.', }
args: [ else {
{ avatarEmbed.setAuthor({ name: interaction.user.username });
key: 'user', avatarEmbed.setDescription(`[png](${interaction.user.displayAvatarURL({ format: 'png', size: 2048 })}) | [jpeg](${interaction.user.displayAvatarURL({ format: 'jpg', size: 2048 })}) | [webp](${interaction.user.displayAvatarURL({ format: 'webp', size: 2048 })})`);
prompt: 'What do you want me to say', avatarEmbed.setImage(interaction.user.displayAvatarURL({ format: 'png', size: 2048 }));
type: 'user', }
default: '' return interaction.reply({ embeds: [avatarEmbed] });
} }
] else {
}); await interaction.guild.members.fetch();
} const format = args.member.displayAvatarURL({ dynamic: true }).substr(args.member.displayAvatarURL({ dynamic: true }).length - 3);
if (format == 'gif') {
avatarEmbed.setAuthor({ name: args.member.user.username });
avatarEmbed.setDescription(`[gif](${args.member.displayAvatarURL({ format: 'gif', size: 2048 })})`);
avatarEmbed.setImage(args.member.displayAvatarURL({ format: 'gif', size: 2048 }));
}
else {
avatarEmbed.setAuthor({ name: args.member.user.username });
avatarEmbed.setDescription(`[png](${args.member.displayAvatarURL({ format: 'png', size: 2048 })}) | [jpeg](${args.member.displayAvatarURL({ format: 'jpg', size: 2048 })}) | [webp](${args.member.displayAvatarURL({ format: 'webp', size: 2048 })})`);
avatarEmbed.setImage(args.member.displayAvatarURL({ format: 'png', size: 2048 }));
}
return interaction.reply({ embeds: [avatarEmbed] });
}
async run(message, { user }) { },
let blacklistJson = new SelfReloadJSON('./json/blacklist.json'); };
if(blacklistJson[message.author.id])
return blacklist(blacklistJson[message.author.id] , message)
if (!user)
return message.say(`Your avatar:\n${message.author.displayAvatarURL}`);
else
return message.say(`${user.username}'s avatar:\n${user.displayAvatarURL}`);
}
};

View file

@ -0,0 +1,23 @@
import { SlashCommandBuilder } from 'discord.js';
import { EmbedBuilder } from 'discord.js';
import donations from '../../json/donations.json' with {type: 'json'};
export default {
data: new SlashCommandBuilder()
.setName('donate')
.setDescription('Show donation link for the bot.'),
category: 'utility',
async execute(interaction) {
let desc = 'If you decide to donate, please do /feedback to let the owner know about it so he can put you in the about and donator command.';
donations.forEach(m => {
desc += `\n${m}`;
});
const Embed = new EmbedBuilder()
.setColor(interaction.member ? interaction.member.displayHexColor : 'Navy')
.setTitle('Donation link')
.setDescription(desc);
return interaction.reply({ embeds: [Embed] });
},
};

View file

@ -0,0 +1,31 @@
import { SlashCommandBuilder } from 'discord.js';
import db from '../../models/index.js';
const donator = db.donator;
export default {
data: new SlashCommandBuilder()
.setName('donator')
.setDescription('All the people who donated for this bot <3'),
category: 'utility',
async execute(interaction) {
await interaction.deferReply();
const client = interaction.client;
const Donator = await donator.findAll({ order: ['id'] });
let donatorMessage = 'Thanks to:\n';
if (Donator[0]) {
for (let i = 0; i < Donator.length; i++) {
const user = await client.users.fetch(Donator[i].get('userID').toString());
if (user !== null) {donatorMessage += `**${user.username} (${user.id}) | ${Donator[i].get('comment')}**\n`;}
else {donatorMessage += `**A user of discord (${user.id}) | ${Donator[i].get('comment')} (This user no longer share a server with the bot)**\n`;}
}
}
else {
donatorMessage += 'No one :(';
}
return interaction.editReply(donatorMessage);
},
};

View file

@ -1,53 +1,334 @@
const { Command } = require('discord.js-commando'); import { SlashCommandBuilder, EmbedBuilder, ActionRowBuilder, StringSelectMenuBuilder } from 'discord.js';
const fs = require('fs'); import { execFile } from 'node:child_process';
const youtubedl = require('youtube-dl'); import fs from 'node:fs';
const SelfReloadJSON = require('self-reload-json'); import os from 'node:os';
const { fbuser, fbpasswd } = require('../../config.json'); import utils from '../../utils/videos.js';
const blacklist = require('../../json/blacklist.json');
let client;
let maxFileSize;
module.exports = class downloadCommand extends Command { let { ytdlpMaxResolution } = process.env;
constructor(client) { const { proxy } = process.env;
super(client, { // Convert to number as process.env is always a string
name: 'download', ytdlpMaxResolution = Number(ytdlpMaxResolution);
group: 'utility',
memberName: 'download',
description: `Download any video from the link you provided.`,
args: [
{
key: 'link',
prompt: 'Wich video would you like to download?',
type: 'string',
default: 'https://www.youtube.com/watch?v=6n3pFFPSlW4'
}
]
});
}
async run(message, { link }) { export default {
let blacklistJson = new SelfReloadJSON('./json/blacklist.json'); data: new SlashCommandBuilder()
if(blacklistJson[message.author.id]) .setName('download')
return blacklist(blacklistJson[message.author.id] , message) .setDescription('Download a video.')
.addStringOption(option =>
if(link.includes("http") || link.includes("www")) { option.setName('url')
message.say('Downloading...').then(msg => { .setDescription('url of the video you want to download.')
video.on('end', function() { .setRequired(true))
msg.delete() .addBooleanOption(option =>
}) option.setName('format')
}) .setDescription('Choose the quality of the video.')
let video = youtubedl(link, [`--username=${fbuser}`,`--password=${fbpasswd}`]) .setRequired(false))
video.pipe(fs.createWriteStream('./video.mp4')) .addBooleanOption(option =>
video.on('error', function error(err) { option.setName('compress')
console.log('error 2:', err); .setDescription('Compress the video.')
message.say("An error has occured, i can't download from the link you provided.") .setRequired(false))
}); .addBooleanOption(option =>
video.on('end', function() { option.setName('autocrop')
message.delete(); .setDescription('Autocrop borders on videos. Ignored when using compress option.')
message.channel.send(`Downloaded by ${message.author.username}`, {files: ["./video.mp4"]}) .setRequired(false))
.catch(error => message.say('File too big')) .addBooleanOption(option =>
}) option.setName('description')
} else .setDescription('Include the video description.')
message.say("You need to input a valid link") .setRequired(false)),
} category: 'utility',
alias: ['dl'],
integration_types: [0, 1],
async execute(interaction, args, c) {
client = c;
const url = args.url;
const format = args.format;
maxFileSize = await utils.getMaxFileSize(interaction.guild);
interaction.doCompress = args.compress;
interaction.doAutocrop = args.autocrop;
await interaction.deferReply({ ephemeral: false });
if (interaction.isMessage) {
interaction.delete();
}
if (!await utils.stringIsAValidurl(url)) {
console.error(`Not a url!!! ${url}`);
return interaction.editReply({ content: '❌ This does not look like a valid url!', ephemeral: true });
}
if (format) {
let qualitys = await new Promise((resolve, reject) => {
const options = [url, '--print', '%()j'];
if (proxy) {
options.push('--proxy');
options.push(proxy);
};
execFile('./bin/yt-dlp', options, (err, stdout, stderr) => {
if (err) {
reject(stderr);
}
if (stderr) {
console.error(stderr);
}
resolve(stdout);
});
});
qualitys = JSON.parse(qualitys);
const options = [];
qualitys.formats.forEach(f => {
if (f.format.includes('storyboard')) return;
options.push({
label: f.resolution ? f.resolution : 'Unknown format',
description: `${f.format} V: ${f.vcodec} A: ${f.acodec}`,
value: f.format_id,
});
});
if (options.length < 2) {
await interaction.deleteReply();
return interaction.followUp({ content: '❌ There is no other quality option for this video!', ephemeral: true });
}
if (options.length > 25) {
// Reverse so the higher quality formats are first
options.reverse();
while (options.length > 25) {
// Remove the lower quality formats
options.pop();
}
// Reverse again so the lower quality appears first
options.reverse();
}
const row = new ActionRowBuilder()
.addComponents(
new StringSelectMenuBuilder()
.setCustomId(`downloadQuality${interaction.user.id}${interaction.id}`)
.setPlaceholder('Nothing selected')
.setMinValues(1)
.setMaxValues(2)
.addOptions(options),
);
await interaction.deleteReply();
await interaction.followUp({ content: 'Which quality do you want?', ephemeral: true, components: [row] });
client.on('interactionCreate', async (interactionMenu) => {
if (interaction.user !== interactionMenu.user) return;
if (!interactionMenu.isSelectMenu()) return;
if (interactionMenu.customId === `downloadQuality${interaction.user.id}${interaction.id}`) {
await interactionMenu.deferReply({ ephemeral: false });
await checkSize(url, interactionMenu.values[0], args, interaction);
return download(url, interactionMenu, interaction, undefined, true);
}
});
return;
}
const newFormat = await checkSize(url, undefined, args, interaction);
return download(url, interaction, interaction, newFormat, args.description);
},
};
async function download(url, interaction, originalInteraction, format = undefined, description = false) {
let embedColour = 'Navy';
if (interaction.member) {
if (interaction.member.displayHexColor) {
embedColour = interaction.member.displayHexColor;
}
}
const Embed = new EmbedBuilder()
.setColor(embedColour)
.setAuthor({ name: `Downloaded by ${interaction.user.username}`, iconURL: interaction.user.displayAvatarURL(), url: url })
.setFooter({ text: `You can get the original video by clicking on the "Downloaded by ${interaction.user.username}" message!` });
if (description) {
Embed.setDescription(await getVideoDescription(url));
}
if (interaction.customId === `downloadQuality${interaction.user.id}${originalInteraction.id}` && !format) {
format = interaction.values[0];
if (interaction.values[1]) format += '+' + interaction.values[1];
}
utils.downloadVideo(url, interaction.id, format)
.then(async () => {
const file = fs.readdirSync(os.tmpdir()).filter(fn => fn.startsWith(interaction.id));
let output = `${os.tmpdir()}/${file}`;
const compressInteraction = originalInteraction ? originalInteraction : interaction;
if (compressInteraction.doCompress) {
const presets = [ 'Social 25 MB 5 Minutes 360p60', 'Social 25 MB 2 Minutes 540p60', 'Social 25 MB 1 Minute 720p60', 'Social 25 MB 30 Seconds 1080p60' ];
const options = [];
presets.forEach(p => {
options.push({
label: p,
value: p,
});
});
const row = new ActionRowBuilder()
.addComponents(
new StringSelectMenuBuilder()
.setCustomId(`preset${interaction.user.id}${interaction.id}`)
.setPlaceholder('Nothing selected')
.addOptions(options),
);
await interaction.deleteReply();
await interaction.followUp({ content: 'Which compression preset do you want?', ephemeral: true, components: [row] });
client.on('interactionCreate', async (interactionMenu) => {
if (interaction.user !== interactionMenu.user) return;
if (!interactionMenu.isSelectMenu()) return;
if (interactionMenu.customId === `preset${interaction.user.id}${interaction.id}`) {
await interactionMenu.deferReply({ ephemeral: false });
compress(file, interactionMenu, Embed);
if (interaction.isMessage) {
interaction.deleteReply();
interaction.cleanUp();
}
}
});
return;
}
// If the video format is not one compatible with Discord, reencode it unless autocrop is choosen in which case it gets reencoded anyway.
if (!interaction.doAutocrop) {
const bannedFormats = ['av1'];
const codec = await utils.getVideoCodec(output);
if (bannedFormats.includes(codec)) {
const oldOutput = output;
output = `${os.tmpdir()}/264${file}`;
await utils.ffmpeg(['-i', oldOutput, '-vcodec', 'libx264', '-acodec', 'aac', output]);
}
}
else if (interaction.doAutocrop && !compressInteraction.doCompress) {
const oldOutput = output;
output = `${os.tmpdir()}/autocrop${file}`;
await utils.autoCrop(oldOutput, output);
}
const fileStat = fs.statSync(output);
const fileSize = fileStat.size / 1000000.0;
Embed.setAuthor({ name: `${Embed.data.author.name} (${fileSize.toFixed(2)} MB)`, iconURL: Embed.data.author.icon_url, url: Embed.data.author.url });
let message = null;
if (interaction.isMessage && interaction.reference !== null) {
const channel = client.channels.resolve(interaction.reference.channelId);
message = await channel.messages.fetch(interaction.reference.messageId);
}
if (fileSize > 100) {
await interaction.deleteReply();
await interaction.followUp('Uh oh! The video you tried to download is too big!', { ephemeral: true });
}
else if (fileSize > maxFileSize) {
const fileurl = await utils.upload(output)
.catch(err => {
console.error(err);
});
await interaction.editReply({ content: `File was bigger than ${maxFileSize} mb. It has been uploaded to an external site.`, embeds: [Embed], ephemeral: false });
if (interaction.isMessage && message) {
await message.reply({ content: fileurl });
}
else {
await interaction.followUp({ content: fileurl, ephemeral: false });
}
}
else if (interaction.isMessage && message) {
await message.reply({ embeds: [Embed], files: [output] });
}
else {
await interaction.editReply({ embeds: [Embed], files: [output], ephemeral: false });
}
if (interaction.isMessage) {
interaction.deleteReply();
interaction.cleanUp();
}
})
.catch(async err => {
console.error(err);
await interaction.deleteReply();
await interaction.followUp({ content: 'Uh oh! An error has occured!', ephemeral: true });
});
return;
}
async function compress(input, interaction, embed) {
const output = `compressed${input}.mp4`;
// Delete the file as it apparently don't overwrite?
if (fs.existsSync(output)) {
fs.rmSync(output);
}
utils.compressVideo(`${os.tmpdir()}/${input}`, output, interaction.values[0])
.then(async () => {
const fileStat = fs.statSync(`${os.tmpdir()}/${output}`);
const fileSize = fileStat.size / 1000000.0;
embed.setAuthor({ name: `${embed.data.author.name} (${fileSize.toFixed(2)} MB)`, iconURL: embed.data.author.icon_url, url: embed.data.author.url });
if (fileSize > maxFileSize) {
await interaction.editReply({ content: `File was bigger than ${maxFileSize} mb. It has been uploaded to an external site.`, ephemeral: false });
}
else {
await interaction.editReply({ embeds: [embed], files: [`${os.tmpdir()}/${output}`], ephemeral: false });
}
});
}
async function checkSize(url, format, args, interaction, tries = 0) {
const resolutions = [144, 240, 360, 480, 720, 1080, 1440, 2160];
while (tries < 4) {
format = `bestvideo[height<=?${resolutions[resolutions.indexOf(ytdlpMaxResolution) - tries]}]+bestaudio/best`;
const aproxFileSize = await utils.getVideoSize(url, format);
if (isNaN(aproxFileSize)) return format;
if (format || tries >= 4) {
if (aproxFileSize > 100 && !args.compress && tries > 4) {
return await interaction.followUp(`Uh oh! The video you tried to download is larger than 100 mb (is ${aproxFileSize} mb)! Try again with a lower resolution format.`);
}
else if (aproxFileSize > 500 && tries > 4) {
return await interaction.followUp(`Uh oh! The video you tried to download is larger than 500 mb (is ${aproxFileSize} mb)! Try again with a lower resolution format.`);
}
}
if (aproxFileSize < 100) {
return format;
}
if (tries < 4 && aproxFileSize > 100) {
tries++;
}
}
}
async function getVideoDescription(urlArg) {
return await new Promise((resolve, reject) => {
const options = [urlArg, '--no-warnings', '-O', '%(description)s'];
if (proxy) {
options.push('--proxy');
options.push(proxy);
};
execFile('./bin/yt-dlp', options, (err, stdout, stderr) => {
if (err) {
reject(stderr);
}
if (stderr) {
console.error(stderr);
}
resolve(stdout.slice(0, 240));
});
});
} }

View file

@ -1,38 +1,42 @@
const { Command } = require('discord.js-commando'); import { SlashCommandBuilder } from 'discord.js';
const { feedbackChannel } = require('../../config.json'); import { EmbedBuilder } from 'discord.js';
const SelfReloadJSON = require('self-reload-json');
const blacklist = require('../../json/blacklist.json');
const { feedbackChannelId } = process.env;
const fs = require('fs'); export default {
module.exports = class feedbackCommand extends Command { data: new SlashCommandBuilder()
constructor(client) { .setName('feedback')
super(client, { .setDescription('Send a feedback to the developer.')
name: 'feedback', .addStringOption(option =>
group: 'utility', option.setName('feedback')
memberName: 'feedback', .setDescription('The message you want to send me.')
description: `Send feedback ( if you abuse you will get blacklisted )`, .setRequired(true))
throttling: { .addAttachmentOption(option =>
usages: 2, option.setName('image')
duration: 60, .setDescription('Optional attachment.')
}, .setRequired(false)),
args: [ category: 'utility',
{ async execute(interaction, args) {
key: 'text', const Embed = new EmbedBuilder()
prompt: 'What would you want to send as feedback?', .setAuthor({ name: `${interaction.user.username} (${interaction.user.id})`, iconURL: interaction.user.avatarURL() })
type: 'string', .setTimestamp();
}
]
});
}
async run(message, { text }) { if (interaction.guild) Embed.addFields({ name: 'Guild', value: `${interaction.guild.name} (${interaction.guild.id})`, inline: true });
let blacklistJson = new SelfReloadJSON('./json/blacklist.json'); Embed.addFields({ name: 'Feedback', value: args.feedback, inline: true });
if(blacklistJson[message.author.id])
return blacklist(blacklistJson[message.author.id] , message) // Don't let new account use this command to prevent spam
const date = new Date();
const channel = this.client.channels.get(feedbackChannel); if (interaction.user.createdAt > date.setDate(date.getDate() - 7)) {
channel.send(`from ${message.author.username} (${message.author.id}) : ${text}`); return interaction.reply({ content: '❌ Your account is too new to be able to use this command!', ephemeral: true });
message.say('Your feedback has been sent!'); }
}
}; const channel = interaction.client.channels.resolve(feedbackChannelId);
if (args.image) {
channel.send({ embeds: [Embed], files: [args.image] });
}
else {
channel.send({ embeds: [Embed] });
}
await interaction.reply({ content: 'Your feedback has been sent! Don\'t forget to have dm open if you want to get an answer from the dev!', ephemeral: true });
},
};

164
commands/utility/help.js Normal file
View file

@ -0,0 +1,164 @@
import { SlashCommandBuilder, EmbedBuilder, AttachmentBuilder, PermissionsBitField } from 'discord.js';
import fs from 'node:fs';
import ratelimiter from '../../utils/ratelimiter.js';
const { ownerId, prefix } = process.env;
const prefixs = prefix.split(',');
export default {
data: new SlashCommandBuilder()
.setName('help')
.setDescription('Displays a list of commands or information about a command.')
.addStringOption(option =>
option.setName('command')
.setDescription('The command you want more details about.')),
category: 'utility',
async execute(interaction, args, client) {
if (args.command) {
const command = client.commands.get(args.command);
if (!command) return interaction.reply(`Did not found any command named \`\`${args.command}\`\`. Please make sure it is a valid command and not an alias.`);
const description = Object.assign({
content: 'No description available.',
usage: '',
examples: [],
fields: [],
}, command.data);
const usage = command.data.options.map(cmd => {
let type = 'String';
const constructorName = cmd.constructor.name.toLowerCase();
if (constructorName.includes('boolean')) {
if (interaction.isMessage) {
type = `--${cmd.name}`;
}
else {
type = 'True/False';
}
}
else if (constructorName.includes('mentionable')) {
type = 'User';
}
else if (constructorName.includes('attachment')) {
type = 'Attachment';
}
return `[${cmd.name}: ${type}]`;
});
let p = '/';
if (interaction.isMessage) {
p = prefixs[0];
}
const embed = new EmbedBuilder()
.setColor(interaction.member ? interaction.member.displayHexColor : 'Navy')
.setTitle(`\`${p}${command.data.name} ${usage.join(' ')}\``)
.addFields(
{ name: 'Description', value: description.description },
)
.setFooter({ text: `All the available prefix: ${prefixs.join(' | ')}` });
for (const field of description.fields) embed.addFields({ name: field.name, value: field.value });
if (description.examples.length) {
const text = `${prefixs[0]}${command.alias[0]}`;
embed.addFields({ name: 'Examples', value: `\`${text} ${description.examples.join(`\`\n\`${text} `)}\``, inline: true });
}
else {
const example = command.data.options.map(cmd => {
let string = '"lorem ipsum"';
const constructorName = cmd.constructor.name.toLowerCase();
if (constructorName.includes('boolean')) {
if (interaction.isMessage) {
string = `--${cmd.name}`;
}
else {
string = 'True/False';
}
}
else if (constructorName.includes('mentionable')) {
string = `@${interaction.user.username}`;
}
else if (constructorName.includes('attachment')) {
string = 'Attachment';
}
if (!interaction.isMessage) {
string = `\`\`${cmd.name}:${string}\`\``;
}
return string;
});
embed.addFields({ name: 'Example', value: `${p}${command.data.name} ${example.join(' ')}`, inline: true });
}
if (command.alias) {
if (command.alias.length >= 1) {
embed.addFields({ name: 'Aliases', value: `\`${command.alias.join('` `')}\``, inline: true });
}
}
if (command.userPermissions) {
const perm = [];
command.userPermissions.forEach(permission => {
perm.push(new PermissionsBitField(permission).toArray());
});
embed.addFields({ name: 'User permission', value: `\`${perm.join('` `')}\``, inline: true });
}
if (command.clientPermissions) {
const perm = [];
command.clientPermissions.forEach(permission => {
perm.push(new PermissionsBitField(permission).toArray());
});
embed.addFields({ name: 'Bot permission', value: `\`${perm.join('` `')}\``, inline: true });
}
if (command.parallelLimit) {
const paralellimit = ratelimiter.checkParallel(interaction.user, command.data.name, command);
embed.addFields({ name: 'Current number of executions', value: `\`${paralellimit.current}\``, inline: false });
embed.addFields({ name: 'Maximum number of executions', value: `\`${command.parallelLimit}\``, inline: true });
}
if (fs.existsSync(`./asset/img/command/${command.category}/${command.data.name}.png`)) {
const file = new AttachmentBuilder(`./asset/img/command/${command.category}/${command.data.name}.png`);
embed.setImage(`attachment://${command.data.name}.png`);
return interaction.reply({ embeds: [embed], files: [file] });
}
return interaction.reply({ embeds: [embed] });
}
else {
const embed = new EmbedBuilder()
.setColor(interaction.member ? interaction.member.displayHexColor : 'Navy')
.addFields({ name: 'Command List', value: `This is a list of commands.\nTo view details for a command, do \`${prefixs[0]}help <command>\`.` })
.setFooter({ text: `All the available prefix: ${prefixs.join('| ')}` });
const object = { };
for (const command of client.commands.values()) {
if (command.category === 'secret') continue;
if (interaction.user.id !== ownerId && command.category === 'owner') continue;
if (object[command.category]) {
object[command.category].push(command.data.name);
}
else {
object[command.category] = [ command.data.name ];
}
}
for (const category in object) {
const title = {
fun: '🎉\u2000Fun',
utility: '🔩\u2000Utility',
admin: '⚡\u2000Admin',
owner: '🛠️\u2000Owner',
voice: '🗣️\u2000Voice',
AI: '🦾\u2000AI',
}[category];
embed.addFields({ name: title, value: `\`${object[category].join('` `')}\`` });
}
return interaction.reply({ embeds: [embed] });
}
},
};

View file

@ -1,47 +0,0 @@
const { Command } = require('discord.js-commando');
const Discord = require('discord.js');
const fetch = require('node-fetch')
const SelfReloadJSON = require('self-reload-json');
const blacklist = require('../../json/blacklist.json');
module.exports = class InfoCommand extends Command {
constructor(client) {
super(client, {
name: 'info',
group: 'fun',
memberName: 'info',
description: `Search DuckDuckGo for answer`,
args: [
{
key: 'search',
prompt: 'What do you want me to search',
type: 'string',
}
]
});
}
async run(message, { search }) {
let blacklistJson = new SelfReloadJSON('./json/blacklist.json');
if(blacklistJson[message.author.id])
return blacklist(blacklistJson[message.author.id] , message)
let searchURL = encodeURI(search)
fetch("https://api.duckduckgo.com/?q=" + searchURL + "&format=json").then((response) => {
return response.json();
}).then((response) => {
if (response.unsafe == 1)
return message.say("No nsfw sorry...")
const ddgEmbed = new Discord.RichEmbed()
.setColor("#ff9900")
.setTitle(response.Heading)
.setURL(response.AbstractURL)
.setDescription(response.Abstract)
.addField("Topic", response.meta.topic)
.setImage(response.Image)
.setTimestamp()
message.say(ddgEmbed);
});
}};

View file

@ -1,25 +1,27 @@
const { Command } = require('discord.js-commando'); import { SlashCommandBuilder } from 'discord.js';
const { supportServer } = require('../../config.json'); export default {
const SelfReloadJSON = require('self-reload-json'); data: new SlashCommandBuilder()
const blacklist = require('../../json/blacklist.json'); .setName('invite')
.setDescription('Generate invite link for the bot or another')
.addMentionableOption(option =>
module.exports = class InviteCommand extends Command { option.setName('bot')
constructor(client) { .setDescription('The bot you want to make an invite link for.')
super(client, { .setRequired(false)),
name: 'invite', category: 'utility',
group: 'utility', integration_types: [0, 1],
memberName: 'invite', async execute(interaction, args, client) {
description: 'Send invite to add the bot', if (args.bot) {
}); if (args.bot.user.bot) {
} return interaction.reply(`You can add the bot you mentioned with this link: https://discordapp.com/oauth2/authorize?client_id=${args.bot.id}&permissions=2684406848&scope=bot%20applications.commands\n\`Note: The invite will not work if the bot is not public\``);
}
async run(message) { else {
let blacklistJson = new SelfReloadJSON('./json/blacklist.json'); return interaction.reply('I\'m sorry but the user you mentioned is not a bot!');
if(blacklistJson[message.author.id]) }
return blacklist(blacklistJson[message.author.id] , message) }
else {
message.say('Check your dm') return interaction.reply(`
return message.author.send(`You can add me from here: https://discordapp.com/oauth2/authorize?client_id=${this.client.user.id}&scope=bot&permissions=0\nYou can also join my support server over here: ${supportServer} come and say hi :)`); You can add me for your server from here: https://discord.com/oauth2/authorize?client_id=${client.user.id}&permissions=2684406848&scope=bot%20applications.commands` +
} `\nIf you want to use my commands no matter the server you can install me as a user applications from here: https://discord.com/oauth2/authorize?client_id=${client.user.id}`);
}; }
},
};

View file

@ -0,0 +1,68 @@
import { SlashCommandBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle } from 'discord.js';
import db from '../../models/index.js';
export default {
data: new SlashCommandBuilder()
.setName('optout')
.setDescription('Opt out of the non commands features and arguments logging (for debugging purposes)'),
category: 'utility',
integration_types: [0, 1],
async execute(interaction, args, client) {
const isOptOut = await db.optout.findOne({ where: { userID: interaction.user.id } });
if (!isOptOut) {
const body = { userID: interaction.user.id };
await db.optout.create(body);
await interaction.reply({ content: 'You have successfully been opt out.', ephemeral: true });
}
else {
const row = new ActionRowBuilder()
.addComponents(
new ButtonBuilder()
.setCustomId(`yes${interaction.user.id}${interaction.id}`)
.setLabel('Yes')
.setStyle(ButtonStyle.Primary),
)
.addComponents(
new ButtonBuilder()
.setCustomId(`no${interaction.user.id}${interaction.id}`)
.setLabel('No')
.setStyle(ButtonStyle.Danger),
);
await interaction.reply({ content: 'You are already opt out, do you wish to opt in?', components: [row], ephemeral: true });
listenButton(client, interaction, interaction.user);
}
return interaction.followUp({
content:
'As a reminder here what opting out does:\n'
+ '- Your user ID will no longer be used for debug logging.\n'
+ '- servers will no longer be shown in added/kicked stats.\n'
+ '- Your messages won\'t be quoted.\n'
+ '- Won\'t show the arguments from commands.',
ephemeral: true,
},
);
},
};
async function listenButton(client, interaction, user = interaction.user, originalId = interaction.id) {
client.once('interactionCreate', async (interactionMenu) => {
if (user !== interactionMenu.user) return listenButton(client, interaction, user, originalId);
if (!interactionMenu.isButton()) return;
await interactionMenu.update({ components: [] });
if (interactionMenu.customId === `yes${interaction.user.id}${originalId}`) {
db.optout.destroy({ where: { userID: interaction.user.id } });
return interaction.editReply({ content: 'You have successfully been opt in', ephemeral: true });
}
else {
return interaction.editReply({ content: 'Nothing has been changed.', ephemeral: true });
}
});
}

View file

@ -1,41 +1,22 @@
const { oneLine } = require('common-tags'); import { SlashCommandBuilder, ButtonBuilder, ActionRowBuilder, ButtonStyle } from 'discord.js';
const { Command } = require('discord.js-commando'); const { uptimePage } = process.env;
const SelfReloadJSON = require('self-reload-json'); export default {
const blacklist = require('../../json/blacklist.json'); data: new SlashCommandBuilder()
.setName('ping')
.setDescription('Replies with Pong!'),
category: 'utility',
integration_types: [0, 1],
async execute(interaction) {
const row = new ActionRowBuilder()
.addComponents(
new ButtonBuilder()
.setLabel('Status page')
.setURL(uptimePage)
.setStyle(ButtonStyle.Link),
);
module.exports = class PingCommand extends Command { await interaction.reply({ content: `Pong! \`${Math.round(interaction.client.ws.ping)} ms\``, components: [row] });
constructor(client) { },
super(client, {
name: 'ping',
group: 'util',
memberName: 'ping',
description: 'Checks the bot\'s ping to the Discord server.',
throttling: {
usages: 5,
duration: 10
}
});
}
async run(message) {
let blacklistJson = new SelfReloadJSON('./json/blacklist.json');
if(blacklistJson[message.author.id])
return blacklist(blacklistJson[message.author.id] , message)
if(!message.editable) {
const pingMsg = await message.say('Pinging...');
return pingMsg.edit(oneLine`
${message.channel.type !== 'dm' ? `${message.author},` : ''}
<:ping:499226870047571978> Pong! The message round-trip took **${pingMsg.createdTimestamp - message.createdTimestamp}**ms.
${this.client.ping ? `The heartbeat ping is **${Math.round(this.client.ping)}**ms.` : ''}
`);
} else {
await message.edit('Pinging...');
return message.edit(oneLine`
Pong! The message round-trip took **${message.editedTimestamp - message.createdTimestamp}**ms.
${this.client.ping ? `The heartbeat ping is **${Math.round(this.client.ping)}**ms.` : ''}
`);
}
}
}; };

View file

@ -1,42 +0,0 @@
const { Command } = require('discord.js-commando');
const SelfReloadJSON = require('self-reload-json');
const blacklist = require('../../json/blacklist.json');
module.exports = class ServerCommand extends Command {
constructor(client) {
super(client, {
name: 'server',
group: 'utility',
guildOnly: 'true',
memberName: 'server',
description: 'Show some stats about the server',
guildOnly: true,
});
}
async run(message) {
let blacklistJson = new SelfReloadJSON('./json/blacklist.json');
if(blacklistJson[message.author.id])
return blacklist(blacklistJson[message.author.id] , message)
try {
let customresponse = new SelfReloadJSON(`./tag/${message.guild.id}.json`);
var count = Object.keys(customresponse).length
} catch {
var count = 'None'
}
const addEmbed = {
color: 0x0099ff,
title: 'Stats of the server',
thumbnail: {
url: `${message.guild.iconURL}`,
},
description: `Member: **${message.guild.memberCount}** \nChannel number: **${message.guild.channels.size}**\nGuild created at **${message.guild.createdAt}**\nOwner: **${message.guild.owner}**\nTag number: **${count}**`,
};
message.say({ embed: addEmbed });
}
};

View file

@ -0,0 +1,33 @@
import { SlashCommandBuilder, EmbedBuilder } from 'discord.js';
export default {
data: new SlashCommandBuilder()
.setName('serverinfo')
.setDescription('Show info about the server'),
category: 'utility',
alias: ['server'],
async execute(interaction, args, client) {
await interaction.guild.members.fetch();
const botCount = interaction.guild.members.cache.filter(member => member.user.bot).size;
const guildOwner = await client.users.fetch(interaction.guild.ownerId);
const addEmbed = new EmbedBuilder()
.setColor(interaction.member ? interaction.member.displayHexColor : 'NAVY')
.setTitle(interaction.guild.name)
.setThumbnail(interaction.guild.iconURL())
.addFields(
{ name: 'Number of users', value: (interaction.guild.memberCount - botCount).toString(), inline: true },
{ name: 'Number of bots', value: botCount.toString(), inline: true },
{ name: 'Total number of members', value: interaction.guild.memberCount.toString(), inline: true },
{ name: 'Number of channels', value: interaction.guild.channels.cache.size.toString(), inline: true },
{ name: '', value:'' },
{ name: 'Date when guild created', value: interaction.guild.createdAt.toString(), inline: true },
{ name: 'Owner', value: guildOwner.toString(), inline: true },
)
.setTimestamp();
interaction.reply({ embeds: [addEmbed] });
},
};

View file

@ -1,30 +1,55 @@
const { Command } = require('discord.js-commando'); import { SlashCommandBuilder } from 'discord.js';
const SelfReloadJSON = require('self-reload-json'); import { EmbedBuilder, version } from 'discord.js';
const blacklist = require('../../json/blacklist.json'); import os from 'node:os';
export default {
data: new SlashCommandBuilder()
.setName('stats')
.setDescription('Show some stats about the bot'),
category: 'utility',
async execute(interaction) {
const client = interaction.client;
const uptime = process.uptime();
const date = new Date(uptime * 1000);
const days = date.getUTCDate() - 1,
hours = date.getUTCHours(),
minutes = date.getUTCMinutes(),
seconds = date.getUTCSeconds();
module.exports = class statsCommand extends Command { const segments = [];
constructor(client) {
super(client, {
name: 'stats',
group: 'utility',
memberName: 'stats',
description: 'Show bot stats.',
});
}
async run(message) { // Format the uptime string.
let blacklistJson = new SelfReloadJSON('./json/blacklist.json'); if (days > 0) segments.push(days + ' day' + ((days == 1) ? '' : 's'));
if(blacklistJson[message.author.id]) if (hours > 0) segments.push(hours + ' hour' + ((hours == 1) ? '' : 's'));
return blacklist(blacklistJson[message.author.id] , message) if (minutes > 0) segments.push(minutes + ' minute' + ((minutes == 1) ? '' : 's'));
if (seconds > 0) segments.push(seconds + ' second' + ((seconds == 1) ? '' : 's'));
let totalSeconds = (this.client.uptime / 1000); const dateString = segments.join(', ');
let days = Math.floor(totalSeconds / 86400);
let hours = Math.floor(totalSeconds / 3600); const bytesToSize = (bytes) => {
totalSeconds %= 3600; const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
let minutes = Math.floor(totalSeconds / 60); if (bytes == 0) return '0 Byte';
let seconds = totalSeconds.toFixed(0) % 60; const i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
let uptime = `${days} days, ${hours} hours, ${minutes} minutes and ${seconds} seconds`; return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
return message.channel.send(`Servers: \`${this.client.guilds.size}\`\nChannels: \`${this.client.channels.size}\`\nUsers: \`${this.client.users.size}\`\nBot uptime: \`${uptime}\``); };
}
}; const statsEmbed = new EmbedBuilder()
.setColor(interaction.member ? interaction.member.displayHexColor : 'Navy')
.setTitle('Bot stats')
.setAuthor({ name: client.user.username, iconURL: client.user.displayAvatarURL(), url: 'https://libtar.de' })
.addFields(
{ name: 'Servers', value: client.guilds.cache.size.toString(), inline: true },
{ name: 'Channels', value: client.channels.cache.size.toString(), inline: true },
{ name: 'Users', value: client.users.cache.size.toString(), inline: true },
{ name: 'Ram usage', value: `${bytesToSize(process.memoryUsage().heapUsed)}/${bytesToSize(os.totalmem)}`, inline: true },
{ name: 'CPU', value: `${os.cpus()[0].model} (${os.cpus().length} core) (${os.arch()})`, inline: true },
{ name: 'OS', value: `${os.platform()} ${os.release()}`, inline: true },
{ name: 'Nodejs version', value: process.version, inline: true },
{ name: 'Discord.js version', value: version, inline: true },
{ name: 'Uptime', value: dateString, inline: true },
)
.setTimestamp();
return interaction.reply({ embeds: [statsEmbed] });
},
};

View file

@ -1,23 +0,0 @@
const { Command } = require('discord.js-commando');
const SelfReloadJSON = require('self-reload-json');
const blacklist = require('../../json/blacklist.json');
module.exports = class supportMeCommand extends Command {
constructor(client) {
super(client, {
name: 'supportme',
group: 'utility',
memberName: 'supportme',
description: `Support me and my bot`,
});
}
async run(message, { text }) {
let blacklistJson = new SelfReloadJSON('./json/blacklist.json');
if(blacklistJson[message.author.id])
return blacklist(blacklistJson[message.author.id] , message)
message.say('If you want to support me and my bot you can donate here\nhttps://donatebot.io/checkout/487640086859743232\nor here on patreon: https://patreon.com/user?u=15330358&utm_medium=social&utm_source=twitter&utm_campaign=creatorshare\n(This is totally optional dont feel forced to do it)');
}
};

View file

@ -1,48 +0,0 @@
const { Command } = require('discord.js-commando');
const blacklist = require('../../json/blacklist.json');
const Discord = require('discord.js');
const SelfReloadJSON = require('self-reload-json');
const fs = require('fs');
module.exports = class taglistCommand extends Command {
constructor(client) {
super(client, {
name: 'taglist',
group: 'utility',
memberName: 'taglist',
description: `List all the tag`
});
}
async run(message) {
if(blacklist[message.author.id])
return message.channel.send("You are blacklisted")
try {
let customresponse = new SelfReloadJSON(`./tag/${message.guild.id}.json`);
let count = Object.keys(customresponse).length
fs.readFile(`./tag/${message.guild.id}.json`, 'utf8', function readFileCallback(err, data){
if (err) {
console.log(err);
}
let json = JSON.stringify(data)
json = json.replace(/[{}"\\]+/g, '')
json = json.replace(/,+/g, '\n')
const tagEmbed = new Discord.RichEmbed()
.setColor("#ff9900")
.setTitle('Tags list')
.setDescription(`Trigger:Response\n\n${json}`)
.setFooter(`You have ${count} tags on this server`)
message.say(tagEmbed);
});
} catch {
message.say('An error has occured, do you have any tags on the server?')
}
}
};

View file

@ -1,59 +0,0 @@
const { Command } = require('discord.js-commando');
const fetch = require('node-fetch')
const SelfReloadJSON = require('self-reload-json');
const blacklist = require('../../json/blacklist.json');
const Discord = require('discord.js');
const { yandexAPI } = require('../../config.json');
module.exports = class translationCommand extends Command {
constructor(client) {
super(client, {
name: 'translation',
aliases: ['trn', 'translate'],
group: 'utility',
memberName: 'translation',
description: `Translate what you say in english`,
args: [
{
key: 'language',
prompt: 'In what language do you want me to translate to? ( You can get the list here https://tech.yandex.com/translate/doc/dg/concepts/api-overview-docpage/)',
type: 'string',
default: 'en',
oneOf: ["az","ml","sq","mt","am","mk","en","mi","ar","mr","hy","mhr","af","mn","eu","de","ba","ne","be","no","bn","pa","my","pap","bg","fa","bs","pl","cy","pt","hu","ro","vi","ru","ht","ceb","gl","sr","nl","si","mrj","sk","el","sl","ka","sw","gu","su","da","tg","he","th","yi","tl","id","ta","ga","tt","it","te","is","tr","es","udm","kk","uz","kn","uk","ca","ur","ky","fi","zh","fr","ko","hi","xh","hr","km","cs","lo","sv","la","gd","lv","et","lt","eo","lb","jv","mg","ja","ms"]
},
{
key: 'text',
prompt: 'What do you want me to translate',
type: 'string',
}
]
});
}
async run(message, { text, language }) {
let blacklistJson = new SelfReloadJSON('./json/blacklist.json');
if(blacklistJson[message.author.id])
return blacklist(blacklistJson[message.author.id] , message)
let textURI = encodeURI(text)
fetch(`https://translate.yandex.net/api/v1.5/tr.json/translate?key=${yandexAPI}&text=${textURI}&lang=${language}&options=1`,{
}).then((response) => {
return response.json();
}).then((response) => {
if (response.code != '200')
return message.say('An error has occured')
const translationEmbed = new Discord.RichEmbed()
.setColor('#0099ff')
.setTitle('Asked for the following translation:')
.setAuthor(message.author.username)
.setDescription(response.text[0])
.addField('Original text', text)
.addField('Translated from', response.detected.lang)
.setTimestamp()
.setFooter('Powered by Yandex.Translate ');
message.say(translationEmbed)
});
}};

View file

@ -1,36 +0,0 @@
const { Command } = require('discord.js-commando');
const SelfReloadJSON = require('self-reload-json');
const blacklist = require('../../json/blacklist.json');
module.exports = class UpDootCommand extends Command {
constructor(client) {
super(client, {
name: 'updoot',
aliases: ['vote'],
group: 'utility',
memberName: 'updoot',
description: 'Send link to updoot my bot :D.',
});
}
async run(message) {
let blacklistJson = new SelfReloadJSON('./json/blacklist.json');
if(blacklistJson[message.author.id])
return blacklist(blacklistJson[message.author.id] , message)
const upDoot = {
color: 0x93C54B,
title: 'Vote for my bot',
url: 'https://discordbots.org/bot/377563711927484418/vote',
description: 'You can vote for my bot if you think the bot is awesome!',
timestamp: new Date(),
footer: {
text: 'Thanks for the updoots',
icon_url: 'https://cdn.discordapp.com/avatars/377563711927484418/1335d202aa466dbeaa4ed2e4b616484a.png?size=2048',
},
};
message.channel.send({ embed: upDoot });
}
};

View file

@ -0,0 +1,69 @@
import { SlashCommandBuilder, EmbedBuilder } from 'discord.js';
export default {
data: new SlashCommandBuilder()
.setName('userinfo')
.setDescription('Show info about a user')
.addMentionableOption(option =>
option.setName('user')
.setDescription('Which user you want to see the info of?')
.setRequired(false)),
category: 'utility',
alias: ['user'],
async execute(interaction, args, client) {
await interaction.guild.members.fetch();
let member = interaction.member;
let user = interaction.user;
if (args.user) {
user = client.users.resolve(args.user);
member = interaction.guild.members.resolve(args.user);
}
const Embed = new EmbedBuilder()
.setColor(member ? member.displayHexColor : 'Navy')
.setAuthor({ name: `${user.username} (${user.id})`, iconURL: user.displayAvatarURL() })
.addFields(
{ name: 'Current rank hex color', value: member ? member.displayHexColor : 'No rank color', inline: true },
{ name: 'Joined guild at', value: member ? member.joinedAt.toString() : 'Not in this guild', inline: true },
{ name: 'Date when account created', value: user.createdAt.toString(), inline: true },
)
.setTimestamp();
Embed.addFields({ name: '', value: '' });
// Show user status
/* Missing presence intent.
if (user.presence.activities[0]) {
Embed.addField('Presence', user.presence.activities[0], true);
if (user.presence.activities[0].details) Embed.addField('', user.presence.activities[0].details, true);
if (user.presence.activities[0].state) Embed.addField('', user.presence.activities[0].state, true);
}
*/
// Is the user a bot?
if (user.bot) Embed.addFields({ name: 'Is a bot?', value: '✅', inline: true });
// Show on which platform they are using discord from if its not a bot
/* Missing presence intent.
if (user.presence.clientStatus && !user.bot) {
Embed.addFields({ name: '', value: '' });
if (user.presence.clientStatus.mobile) Embed.addFields({ name: 'Using discord on', value: '📱 ' + user.presence.clientStatus.mobile, inline: true });
if (user.presence.clientStatus.desktop) Embed.addFields({ name: 'Using discord on', value: '💻 ' + user.presence.clientStatus.desktop, inline: true });
if (user.presence.clientStatus.web) Embed.addFields({ name: 'Using discord on', value: '☁️ ' + user.presence.clientStatus.web, inline: true });
}
*/
if (member) {
// Show since when this user have been boosting the current guild
if (member.premiumSince) Embed.addFields({ name: 'Boosting this guild since', value: member.premiumSince.toString(), inline: true });
// Show guild nickname
if (member.nickname) Embed.addFields({ name: 'Nickname', value: member.nickname, inline: true });
// Show member roles
if (member.roles) {
Embed.addFields({ name: 'Roles', value: `${[...member.roles.cache.values()].join(', ')}` });
Embed.addFields({ name: 'Permissions', value: `\`${member.permissions.toArray().join(', ')}\`` });
}
}
return interaction.reply({ embeds: [Embed] });
},
};

166
commands/utility/vid2gif.js Normal file
View file

@ -0,0 +1,166 @@
import { SlashCommandBuilder } from 'discord.js';
import utils from '../../utils/videos.js';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { execFile } from 'node:child_process';
const { NODE_ENV } = process.env;
const ytdlpFormat = 'bestvideo[height<=?480]/best';
export default {
data: new SlashCommandBuilder()
.setName('vid2gif')
.setDescription('Convert your video into a gif.')
.addStringOption(option =>
option.setName('url')
.setDescription('URL of the video you want to convert')
.setRequired(true))
.addIntegerOption(option =>
option.setName('quality')
.setDescription('Quality of the gif conversion. Default 70. Number between 1 and 100')
.setRequired(false))
.addIntegerOption(option =>
option.setName('fps')
.setDescription('Change the speed at which the gif play at. Number between 1 and 100.')
.setRequired(false))
.addBooleanOption(option =>
option.setName('autocrop')
.setDescription('Autocrop borders on gif.')
.setRequired(false))
.addBooleanOption(option =>
option.setName('noloop')
.setDescription('Stop the gif from looping')
.setRequired(false)),
category: 'utility',
alias: ['v2g', 'togif'],
integration_types: [0, 1],
async execute(interaction, args) {
await interaction.deferReply({ ephemeral: false });
const maxFileSize = await utils.getMaxFileSize(interaction.guild);
const url = args.url;
let quality = args.quality;
if (quality) {
if (quality <= 0) {
quality = 1;
}
else if (quality > 100) {
quality = 100;
}
}
if (args.fps) {
if (args.fps <= 0) {
args.fps = 1;
}
else if (args.fps > 100) {
args.fps = 100;
}
}
if (!await utils.stringIsAValidurl(url)) {
console.error(`Not a url!!! ${url}`);
return interaction.editReply({ content: '❌ This does not look like a valid url!', ephemeral: true });
}
const aproxFileSize = await utils.getVideoSize(url, ytdlpFormat);
console.log(aproxFileSize);
if (aproxFileSize > 4) {
return interaction.editReply('The file you are trying to convert is too big! Limit is 4 MB');
};
utils.downloadVideo(url, interaction.id, ytdlpFormat)
.then(async () => {
const file = fs.readdirSync(os.tmpdir()).filter(fn => fn.startsWith(interaction.id));
let output = `${os.tmpdir()}/${file}`;
if (args.autocrop) {
const oldOutput = output;
output = `${os.tmpdir()}/autocrop${file}`;
await utils.autoCrop(oldOutput, output);
}
// Get the fps of the original video
if (!args.fps) {
args.fps = getVideoFramerate(output);
}
const gifskiOutput = output.replace(path.extname(output), '.gif');
const gifsicleOutput = output.replace(path.extname(output), 'gifsicle.gif');
// Extract every frame for gifski
await utils.ffmpeg(['-i', output, `${os.tmpdir()}/frame${interaction.id}%04d.png`]);
// Make it look better
await gifski(gifskiOutput, `${os.tmpdir()}/frame${interaction.id}*`, quality, await args.fps);
// Optimize it
await gifsicle(gifskiOutput, gifsicleOutput, args.noloop);
const fileStat = fs.statSync(gifsicleOutput);
const fileSize = fileStat.size / 1000000.0;
if (fileSize > 25) {
await interaction.deleteReply();
await interaction.followUp('❌ Uh oh! The video once converted is too big!', { ephemeral: true });
}
else if (fileSize > maxFileSize) {
const fileURL = await utils.upload(gifsicleOutput)
.catch(err => {
console.error(err);
});
await interaction.editReply({ content: ` File was bigger than ${maxFileSize} mb. It has been uploaded to an external site.\n${fileURL}`, ephemeral: false });
}
else {
await interaction.editReply({ files: [gifsicleOutput], ephemeral: false });
}
});
},
};
async function gifski(output, input, quality, fps) {
return await new Promise((resolve, reject) => {
// Shell: true should be fine as no user input is being passed
execFile('gifski', ['--quality', quality ? quality : 70, '--fps', fps ? fps : 20, '-o', output, input], { shell: true }, (err, stdout, stderr) => {
if (err) {
reject(stderr);
}
if (stderr) {
console.error(stderr);
}
console.log(NODE_ENV === 'development' ? stdout : null);
resolve();
});
});
}
async function gifsicle(input, output, loop = false) {
return await new Promise((resolve, reject) => {
// Shell: true should be fine as no user input is being passed
execFile('gifsicle', ['--colors', '256', loop ? '--no-loopcount' : '', '-i', input, '-o', output], { shell: true }, (err, stdout, stderr) => {
if (err) {
reject(stderr);
}
if (stderr) {
console.error(stderr);
}
console.log(NODE_ENV === 'development' ? stdout : null);
resolve();
});
});
}
async function getVideoFramerate(input) {
return await new Promise((resolve, reject) => {
execFile('ffprobe', ['-v', 'error', '-of', 'csv=p=0', '-select_streams', 'v:0', '-show_entries', 'stream=r_frame_rate', input], (err, stdout, stderr) => {
if (err) {
reject(stderr);
}
if (stderr) {
console.error(stderr);
}
const tempfps = stdout.trim().split('/');
const fps = tempfps[0] / tempfps[1];
return resolve(fps);
});
});
}

43
commands/voice/dectalk.js Normal file
View file

@ -0,0 +1,43 @@
import { SlashCommandBuilder } from 'discord.js';
import { rand } from '../../utils/rand.js';
import { execFile } from 'node:child_process';
export default {
data: new SlashCommandBuilder()
.setName('dectalk')
.setDescription('Send a .wav sound file of what you wrote with dectalk')
.addStringOption(option =>
option.setName('message')
.setDescription('Write something so I can talk it back with dectalk.')
.setRequired(true)),
category: 'voice',
async execute(interaction, args) {
args.message = rand(args.message, interaction);
const output = `${interaction.id}_dectalk.wav`;
const message = '[:phoneme on]' + args.message;
await interaction.deferReply({ ephemeral: false });
if (process.platform === 'win32') {
// Untested, most likely do not work.
execFile('say.exe', ['-w', output, `${message}`], { cwd: './bin/dectalk/' }, (error, stdout, stderr) => {
sendMessage(output, error, stdout, stderr);
});
}
else if (process.platform === 'linux' || process.platform === 'darwin') {
execFile('wine', ['say.exe', '-w', output, `${message}`], { cwd: './bin/dectalk/' }, (error, stdout, stderr) => {
sendMessage(`./bin/dectalk/${output}`, error, stdout, stderr);
});
}
async function sendMessage(file, error, stdout, stderr) {
if (error) {
console.error(stderr);
console.error(error);
return interaction.editReply('Oh no! an error has occurred!');
}
return interaction.editReply({ files: [file] });
}
},
};

View file

@ -1,13 +0,0 @@
{
"token": "Your token",
"prefix": "Your prefix ",
"ownerID": "Id of the owner ( probably you )",
"botID": "id of the bot",
"statsChannel": "channel where the bot send his stats",
"supportServer": "Invite to the support server of the bot",
"feedbackChannel": "id of the channel where the feedback goes",
"printChannel": "Channel of where it will send the id of people who asked for print",
"fbuser": "Facebook email",
"fbpasswd": "Facebook passwd",
"yandexAPI": "yandex api key"
}

View file

@ -0,0 +1,14 @@
{
"development": {
"dialect": "sqlite",
"storage": "./database.sqlite3"
},
"test": {
"dialect": "sqlite",
"storage": ":memory"
},
"production": {
"dialect": "sqlite",
"storage": "./database.sqlite3"
}
}

View file

@ -1 +0,0 @@
["abduct", "abolish", "align", "amend", "amputate", "annihilate", "announce", "appreciate", "apprehend", "articulate", "assault", "associate", "attack", "authenticate", "bake", "bang", "barbeque", "bathe", "bawl", "beep", "behead", "belly-flop", "bind", "bite", "blacken", "blast", "bleed", "bless", "bloat", "bloom", "blossom", "blow", "bludgeon", "boil", "breastfeed", "breathe", "bubble", "burn", "burp", "cackle", "call", "caress", "chew", "chill", "choke", "chomp", "chop", "chow", "churn", "clean", "click", "clip", "commandeer", "conserve", "convict", "cook", "crack", "cram", "crank", "crash", "crawl", "cremate", "cripple", "croak", "crouch", "crumple", "crunch", "crush", "cry", "cuddle", "cultivate", "customize", "cut", "cut + in half", "dangle", "darken", "decapitate", "declare", "decorate", "deep-fry", "defecate", "defy", "deny", "despise", "dice", "dig", "discipline", "dishonor", "dislike", "dismantle", "dissect", "dominate", "donate", "draft", "drain", "dramatize", "drip", "dry-freeze", "dye", "eat", "ejaculate", "eject", "elect", "electrocute", "eliminate", "embrace", "enforce", "examine", "exclaim", "explode", "exploit", "extend", "extrapolate", "extrude", "fabricate", "fall apart", "falsify", "fart", "feed", "fester", "fiddle", "fight", "fistfight", "fizz", "flap", "flash", "flatten", "flick", "floss", "flutter", "fly", "force", "forecast", "freeze", "froth", "fume", "gallop", "gargle", "gleam", "glorify", "glow", "glue", "gnaw", "gouge", "grab", "grate", "grind", "grip", "groom", "grow", "grunt", "gulp", "guzzle", "gyrate", "hack", "hammer", "handle", "hang", "harass", "harden", "headbutt", "hiccup", "hiss", "hog-tie", "hoist", "hoot", "hug", "hunt", "hurl", "hypnotize", "impale", "impeach", "impede", "implode", "inaugurate", "infest", "ingest", "inject", "injure", "invigorate", "iron", "jargogle", "jerk", "jet-spray", "jimmy", "jingle", "joust", "kick", "kidnap", "kill", "kiss", "knead", "knock + out", "lather", "laugh", "lay", "lecture", "legalize", "lick", "lighten", "like", "liquefy", "liquidate", "loathe", "loosen", "maim", "make fun of", "mangle", "manhandle", "manipulate", "march", "marinate", "massage", "masticate", "maul", "mist", "misuse", "moan", "moisten", "move", "mumble", "mutilate", "mutter", "nab", "nail", "need", "nip", "obfuscate", "oil", "organize", "paint", "palpitate", "penetrate", "pepper", "petition", "pickle", "pierce", "pillage", "pinch", "piss", "plaster", "pluck", "plunge", "poke", "polish", "pop", "pour", "pray", "preen", "press", "probe", "prod", "prosecute", "prove", "puff", "pull", "pump", "punch", "punish", "purify", "push", "put up with", "quaff", "quantify", "radiate", "ram", "rapture", "ratify", "rattle", "rearrange", "recycle", "report", "ride", "rip", "ripple", "rise", "roar", "rob", "roll", "rot", "rub", "run", "run + over", "run after", "rustle", "salt", "sanitize", "savor", "say", "scold", "scorch", "scratch", "scream", "screech", "screw", "scrub", "scrunch", "sculpt", "season", "serve", "set + on fire", "shake", "sharpen", "shatter", "shave", "shimmer", "shine", "shiver", "shoot", "shout", "shove", "shower", "shred", "shriek", "shrink", "shudder", "sit", "skewer", "skip", "slam", "slap", "slash", "slay", "sleepwalk", "slip", "slit", "slouch", "slurp", "smack", "smear", "smoke", "smolder", "snap", "snicker", "sniff", "snip", "snoop", "snort", "snuffle", "snuggle", "soak", "soften", "solidify", "spank", "sparkle", "spelunk", "spit", "splash", "splatter", "spray", "sprinkle", "sprint", "spurt", "sputter", "square dance", "squat", "squeal", "squeeze", "squelch", "squirt", "squish", "stab", "stampede", "stand", "staple", "steam", "stew", "stick", "stimulate", "stir", "stomp", "strain", "strangle", "strap", "strategize", "streamline", "stress-test", "strike", "strut", "stuff", "suckle", "sue", "superglue", "swallow", "swear", "swipe", "tap", "tape", "throttle", "throw", "tickle", "tighten", "tinkle", "tiptoe", "toast", "toke", "tongue", "touch", "transcribe", "tremble", "trot", "tune", "twang", "twinkle", "twist", "undermine", "undress", "undulate", "uproot", "urinate", "vaporize", "venerate", "verify", "veto", "vibrate", "vomit", "waddle", "wail", "walk", "want", "waste", "wave", "wedge", "whimper", "whine", "whip", "whisper", "whiten", "wiggle", "wilt", "withdraw", "wrinkle", "yank", "yell", "zip"]

View file

@ -1,12 +0,0 @@
module.exports = {
a: '<a:a:493014525226778624>', b: '<a:b:493014525696802817>', c: '<a:c:493014525457596417>', d: '<a:d:493014526791254026>',
e: '<a:e:493014525373710339>', f: '<a:f:493014525788946443>', g: '<a:g:493014525151543297>', h: '<a:h:493014525256138763>',
i: '<a:i:493014525566648321>', j: '<a:j:493014525738614806>', k: '<a:k:493014525336092673>', l: '<a:l:493014525134635039>',
m: '<a:m:493014525927227392>', n: '<a:n:493014525746872323>', o: '<a:o:493014525847797761>', p: '<a:p:493014525788815371>',
q: '<a:q:493014525344219137>', r: '<a:r:493014525914775562>', s: '<a:s:493014525335961601>', t: '<a:t:493014525818306560>',
u: '<a:u:493014525466116097>', v: '<a:v:493014525432561666>', w: '<a:w:493014525885546497>', x: '<a:x:493014525801660426>',
y: '<a:y:493014525042360329>', z: '<a:z:493014525856055306>', 1: '<a:1:493096650160472065>', 2: '<a:2:493096650160603140>',
3: '<a:3:493096650039099412>', 4: '<a:4:493096650005544960>', 5: '<a:5:493096650395353099>', 6: '<a:6:493096649908944906>',
7: '<a:7:493096649833578508>', 8: '<a:8:493096650491822090>', 9: '<a:9:493096649619668993>', 0: '<a:0:493096650202546208>',
' ': ' ', '?': '<a:question:493448821020426243>', '!': '<a:exclamation:493448903459471360>'
};

101
eslint.config.mjs Normal file
View file

@ -0,0 +1,101 @@
import globals from "globals";
import babelParser from "@babel/eslint-parser";
import path from "node:path";
import { fileURLToPath } from "node:url";
import js from "@eslint/js";
import { FlatCompat } from "@eslint/eslintrc";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const compat = new FlatCompat({
baseDirectory: __dirname,
recommendedConfig: js.configs.recommended,
allConfig: js.configs.all
});
export default [...compat.extends("eslint:recommended"), {
ignores: ["models/*", "migrations/*", "eslint.config.mjs"],
languageOptions: {
globals: {
...globals.node,
},
parser: babelParser,
ecmaVersion: 2022,
sourceType: "module",
parserOptions: {
requireConfigFile: false,
babelOptions: {
plugins: ["@babel/plugin-syntax-import-assertions"],
},
},
},
rules: {
"arrow-spacing": ["warn", {
before: true,
after: true,
}],
"brace-style": ["error", "stroustrup", {
allowSingleLine: true,
}],
"comma-dangle": ["error", "always-multiline"],
"comma-spacing": "error",
"comma-style": "error",
curly: ["error", "multi-line", "consistent"],
"dot-location": ["error", "property"],
"handle-callback-err": "off",
indent: ["error", "tab"],
"keyword-spacing": "error",
"max-nested-callbacks": ["error", {
max: 4,
}],
"max-statements-per-line": ["error", {
max: 2,
}],
"no-console": "off",
"no-empty-function": "error",
"no-floating-decimal": "error",
"no-inline-comments": "error",
"no-lonely-if": "error",
"no-multi-spaces": "error",
"no-multiple-empty-lines": ["error", {
max: 2,
maxEOF: 1,
maxBOF: 0,
}],
"no-shadow": ["error", {
allow: ["err", "resolve", "reject"],
}],
"no-trailing-spaces": ["error"],
"no-var": "error",
"object-curly-spacing": ["error", "always"],
"prefer-const": "error",
quotes: ["error", "single"],
semi: ["error", "always"],
"space-before-blocks": "error",
"space-before-function-paren": ["error", {
anonymous: "never",
named: "never",
asyncArrow: "always",
}],
"space-in-parens": "error",
"space-infix-ops": "error",
"space-unary-ops": "error",
"spaced-comment": "error",
yoda: "error",
},
}];

Some files were not shown because too many files have changed in this diff Show more