Initial Commit

This commit is contained in:
Anon 2022-08-29 00:10:06 -07:00
commit 9e93ab73ad
10 changed files with 2018 additions and 0 deletions

31
.gitignore vendored Normal file
View File

@ -0,0 +1,31 @@
# User preferance files
/rsc*/
/md5/
/src/cfg*.py
# Virtual environment
/venv*
/src/__pycache__/
# PyCharm IDE folder
/.idea/
# Editor files
/*~
/*#
# Automation scripts + odds and ends
/notes.txt
/compile.sh
/upload.sh
/balance_2.csv
/DEFAULT.csv
/generate_random.sh
/src/make_master_template.py
/src/make_master_list.py
/src/hash_path_exists.py
/utils/
/cfg_availible/
/profile/
/gnu_header.txt
/backup*

674
LICENSE.txt Normal file
View File

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

180
README.md Normal file
View File

@ -0,0 +1,180 @@
# Readme
Yandere Lewd Bot is a customizable, no frills image-posting bot for Pleroma.
A live example can be viewed at [GNU/Yandere](https://yandere.cc/YandereLewdBot).
Currently the bot will only run on Linux. I believe it should run on most distros but I have only tested it on Arch and Raspbian.
## About
Yandere Lewd Bot is designed to be simple to understand (from a technical perspective) and easy to modify/extend. It relies on GNU formatted hash files to configure and organize posts (from the GNU coreutils package):
Yandere Lewd Bot is licensed under GPLv3. See [LICENSE.txt](./LICENSE.txt).
The bot is still in development and can easily be crashed by writing a poorly configured `cfg.py` file, or messing with the hash files it uses to configure posts. The bot may also crash with encoding errors for files with non-unicode filenames.
## Installing
To setup the python3 environment (for Arch Linux) run the following commands:
```
sudo pacman -Syu
sudo pacman -S --needed python git
git clone 'https://git.yandere.cc/Anon/YandereLewdBot.git'
cd YandereLewdBot/
python -m venv venv
source venv/bin/activate
pip install --upgrade pip
pip install -r requirements.txt
deactivate
mkdir -p md5 rsc/{safe,nsfw}
cp -vn default/cfg.py src/
./run.sh -h
```
If everything worked correctly you should see usage information on Yandere Lewd Bot.
The ./run.sh file will automatically activate and deactive the python virtual environment. You may want add a symlink to `/usr/local/bin` for convienence.
```
sudo ln -s "$(pwd)/run.sh" "/usr/local/bin/yandereLewdBot"
yandereLewdBot -h
```
For Debian or Ubuntu based distros I believe you need to change python with python3 for the package and command name `¯\_(ツ)_/¯`
## Generating your OAuth Tokens
Before you can begin posting from the bot, you must first create an account on the instance of your choice, and then generate your OAuth tokens.
To generate your tokens, run the following commands and follow the interactive prompts.
```
cd ..
git clone 'https://git.yandere.cc/Anon/CreatePleromaApp.git'
ln -s "$(pwd)"/YandereLewdBot/{venv,src/cfg.py} CreatePleromaApp/
cd CreatePleromaApp
./run.sh -c cfg
# Follow the interactive prompts.
```
If you did everything correctly you should see `Success! :)` at the end of the terminal, as well as your credentials in the format below:
```text
settings_server = OrderedDict([
"app_name": "app",
"api_base_url": "https://yandere.cc",
"client_id": "Long String of Text",
"client_secret": "Long String of Text",
"access_token": "Long String of Text"
])
settings_reminder = "09/20/2020 02:58PM"
settings_encrypt = {
"encrypt": False,
"salt": "",
}
```
If you used encryption, everything in the `settings_server` dictionary will be encrypted and you will have to enter your password every time you start the bot. Copy and paste these values from the terminal into your `src/cfg.py` file. **Make sure you paste over or delete the placeholder values with the same names.**
## Posting
To begin posting:
- Put some images in the rsc/ folder (organize by safe and nsfw posts).
- 'safe' posts will be marked with `#yandere`
- 'nsfw' posts will be spoilered and marked as `#nsfw #lewd #yandere`
- Make sure you are in the bot's root directory (the directory with `run.sh`)
- Checksum all the files you added with the following command:
- `find "./rsc" -type f -exec md5sum -b '{}' \; > "./md5/master_file.txt"`
- Start the bot with `./run.sh`
- Enter your password if you encrypted your OAuth tokens.
- If you symlinked the file in the [Installing](#installing) section you can simply run `yandereLewdBot` instead of changing directories and starting the bot with `./run.sh`
- If everything worked correctly, you should see your first image posted to your account.
- Hit Ctrl+C to stop the bot.
- When you start the bot again, it will begin posting from where it last left off.
- It accomplishes this by writing to a `md5/blacklist.txt` file. If you see this file, it worked correctly.
- Keep in mind that the bot's default visibility setting is set to unlisted for testing. You may want to update it to public.
- Read [docs/configuration.md](./docs/configuration.md) to customize the bot for your purposes.
# Donate
XMR: 493HynLQA4z71b3j9ZDXRNQudpdFW8GxeBGD8ahRctKn97RRurMVd35DqVqdAdjv68TcXTJWUwm6ee81ujDXGcmtKFixwQk
BAT: [Basic Attention Token](https://basicattentiontoken.org/)
# Useful Tips
## Installing Screen
Most likely, you will want this bot to run over a long period of time. It is probably best to install the `screen` package for your distro so you don't have to have a terminal window constantly open (especially if you are running it from a remote machine such as a Raspberry Pi or server).
```
sudo pacman -Syu
sudo pacman -S --needed screen
# Screen cheatsheet
# To create a new screen session named 'yandereLewdBot'
screen -S yandereLewdBot
# To detach from the screen session
Ctrl+a d
# To reconnect to the screen session
screen -r yandereLewdBot
# List screen sessions
screen -ls
# Kill the screen session
Ctrl+a k y
# Scroll back
Ctrl+a ESC Page Up
# Cancel scroll back
ESC
```
## A Master Blacklist
The default configuration file has the following settings below (these files will not exist by default. The bot will simply ignore blacklist hash files that it can't open). The `_r` stands for read and the `_w` stands for write. This will ensure that the `master_blacklist.txt` is always read, but is never written to. This is intended for the user to manually add GNU formatted hashes to `master_blacklist.txt` in case they want to make especially sure that hashes and paths that are matched in the list are never uploaded accidentally.
```
"master_blacklist_r": ("./md5/blacklist.txt", "./md5/master_blacklist.txt"),
"master_blacklist_w": ("./md5/blacklist.txt",),
```
## Quickly Create Configuration Files
Configuration files for Yandere Lewd Bot are just python files. Because of this we can easily create multiple configurations by importing the main configuration file, and overriding the values we need. This is useful for creating holiday and debug configurations without needing to create a new configuration file from scratch.
```
# Name: alt.py
# Post to an alt account using the exact same settings as the main configuration file
# Run with the following command: ./run.sh -c alt
# cfg.py is the default configuration.
from cfg import *
settings_server = OrderedDict([
("app_name", "generate from ./bin/create_app.py"),
("api_base_url", "generate from ./bin/create_app.py"),
("client_id", "generate from ./bin/create_app.py"),
("client_secret", "generate from ./bin/create_app.py"),
("access_token", "generate from ./bin/create_app.py")
])
settings_reminder = "generate from ./bin/create_app.py"
settings_encrypt = {
"encrypt": False,
"salt": "generate from ./bin/create_app.py"
}
settings_behavior["master_blacklist_r"] = ("./md5/blacklist_alt.txt", "./md5/master_blacklist.txt")
settings_behavior["master_blacklist_w"] = ("./md5/blacklist_alt.txt",)
# Uncommenting the below might be useful if your alt is used for debugging and testing
# settings_behavior["master_list"] = ("master_file_alt.txt",)
# settings_behavior["visibility"] = "private"
# settings_behavior["debug"] = True
# settings_behavior["master_blacklist_w"] = tuple()
```
```
# Name: xmas.py
# An xmas themed config file!
# Run with the following command: ./run.sh -c xmas
# cfg.py is the default configuration.
from cfg import *
settings_behavior["master_list"] = ("./md5/event_xmas.txt",)
settings_behavior["master_blacklist_r"] = ("./md5/blacklist_xmas.txt", "master_blacklist.txt")
settings_behavior["master_blacklist_w"] = ("./md5/blacklist_xmas.txt",)
# Prepend '#Merry #Christmas' to the beginning of the first line in each post
for setting in settings_post:
if len(setting["message"]) and issubclass(type(setting["message"][0]), str):
new_msg = "#Merry #Christmas {}".format(setting["message"][0])
setting["message"] = (new_msg,) + setting["message"][1:]
```

97
default/cfg.py Normal file
View File

@ -0,0 +1,97 @@
#! /usr/bin/env python3
# Yandere Lewd Bot, an image posting bot for Pleroma
# Copyright (C) 2022 Anon <yanderefedi@proton.me>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
from collections import OrderedDict
def setup_profile(name, backend, tags, *message):
post_setting = {
"name": name,
"backend": backend,
"tags": tags,
"message": message
}
return post_setting
# Client credentials: >>>NEVER GIVE THESE OUT TO ANYONE<<<
# Use the create_app.py script and follow the prompts to generate your tokens. Once generated, copy & paste them below.
settings_server = OrderedDict([
("app_name", "Generated from create_app.py"),
("api_base_url", "Generated from create_app.py"),
("client_id", "Generated from create_app.py"),
("client_secret", "Generated from create_app.py"),
("access_token", "Generated from create_app.py")
])
# settings_reminder = "Generated from create_app.py"
settings_reminder = "08/26/2022 08:16PM"
# Encryption settings: When using encryption the bot will ask you for your password before logging into your instance.
# Use create_app.py and follow the instructions. Select yes when it asks you if you want to encrypt your credentials.
# Paste the output below and never change the values.
# If you want to encrypt or re-encrypt settings_server you can use encryption.py (or just regenerate your tokens)
settings_encrypt = {
"encrypt": False,
"salt": "Generated from create_app.py"
}
settings_credentials = {
"danbooru_backend": {
"username": None,
"password": None
}
}
# Basic settings to configure Yandere Bot's behavior
settings_behavior = {
"max_size": 15*1024*1024,
"visibility": "unlisted",
"feature_set": "pleroma",
"sleep_seconds": 1*60*60,
"uploads_per_post": 1,
"tag_select": "sequential",
"retry_seconds": 15,
"content_type": "text/plain",
"content_newline": "\n",
"post_image_link": False,
"tmp_dir": "/tmp",
"debug": False
}
# Time string formats
settings_time = {
"time_format": "%I:%M%p",
"time_format_seconds": "%I:%M:%S%p",
"date_format": "%m/%d/%Y",
"long_date_format": "%m/%d/%Y %I:%M%p",
"long_date_seconds_format": "%m/%d/%Y %I:%M:%S%p",
"long_date_week": "%m/%d/%Y %I:%M%p, %A"
}
# Apply post settings
settings_post = (
setup_profile("danbooru.random", "danbooru_backend", ("random",), "#random"),
setup_profile("danbooru.yandere", "danbooru_backend", ("yandere",), "#yandere"),
)
# Default post behavior:
# If no profile can be matched in a master_list, it will default to settings_post_default
# If settings_post_default is None, the bot will error out and output the offending line(s)
# If you want the bot to start, set this to a valid settings_post, or create a default setting with setup_profile()
settings_post_default = None

2
requirements.txt Normal file
View File

@ -0,0 +1,2 @@
Mastodon.py
cryptography

35
run.sh Executable file
View File

@ -0,0 +1,35 @@
#! /usr/bin/env bash
# Yandere Lewd Bot, an image posting bot for Pleroma
# Copyright (C) 2022 Anon <yanderefedi@proton.me>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
# Get the runtime path of the bot
ABS_PATH="$(readlink -f "$0")"
RUN_DIR="$(dirname "$ABS_PATH")"
# Relative paths to the virtual environment and main.py
VENV='./venv/bin/activate'
ENTRY='./src/main.py'
# cd into the bot's root path, set up the virtual environment, and run
cd "$RUN_DIR"
[ ! -f "$VENV" ] && echo "Virtual environment not found: ${VENV}" && cd - > /dev/null && exit 1
source "$VENV"
"$ENTRY" "$@"
# Cleanup
deactivate
cd - > /dev/null

92
src/danbooru_backend.py Normal file
View File

@ -0,0 +1,92 @@
#! /usr/bin/env python3
# TODO:
# Update to enable multiple file downloads
# Update to include safe/nsfw filter
import requests
import os
def random_tag(*tags):
if len(tags) == 1 and tags[0].lower() == "random":
return True
return False
def get_most_sever_rating(*ratings):
if "q" in ratings or "e" in ratings:
return True
return False
class downloader:
username = None
password = None
tmp = None
def __init__(self, username=None, password=None, tmp="/tmp"):
self.username = username
self.password = password
self.tmp = tmp
def download(self, profile):
# Search ratings: s=safe, e=explicit
# base_url = "https://danbooru.donmai.us/posts.json?random=true&tags={}&rating=e&limit=1"
tags = profile["tags"]
search_url = "https://danbooru.donmai.us/posts.json?random=true&limit=1"
if tags and not random_tag(*tags):
search_tags = "+".join(tags)
search_url = "{}&tags={}".format(search_url, search_tags)
search_request = None
if self.username and self.password:
search_request = requests.get(search_url,
auth=(self.username, self.password)
)
else:
search_request = requests.get(search_url)
# Return None if the request failed
if search_request.status_code != 200:
print("Search request returned:", search_request.status_code)
return None
# Check to make sure large_file_url key exists in the response
elif "large_file_url" not in search_request.json()[0]:
return None
large_file_url = search_request.json()[0]["file_url"]
explicit = search_request.json()[0]["rating"]
explicit = get_most_sever_rating(explicit)
remote_image = requests.get(large_file_url)
if remote_image.status_code != 200:
print("Remote image request returned:", remote_image.status_code)
return None
basename = large_file_url.rsplit("/", 1)[1]
full_path = os.path.join(self.tmp, basename)
with open(full_path, "wb") as f:
f.write(remote_image.content)
r = {
# Add profile to dictioanry
"name": profile["name"],
"backend": profile["backend"],
"tags": profile["tags"],
"message": profile["message"],
# Query results
"search_url": search_url,
"large_file_url": large_file_url,
"full_path": [full_path],
"explicit": explicit
}
return r

244
src/encryption.py Executable file
View File

@ -0,0 +1,244 @@
#! /usr/bin/env python3
# Yandere Lewd Bot, an image posting bot for Pleroma
# Copyright (C) 2022 Anon <yanderefedi@proton.me>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import sys
import base64
import os
import getpass
from cryptography.fernet import Fernet, InvalidToken
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from collections import OrderedDict
class PasswordMismatch(Exception):
pass
# Salts
def generate_salt():
return os.urandom(16)
# Return string from bytes
def salt_encode(b):
return base64.urlsafe_b64encode(b).decode()
# Return bytes from string
def salt_decode(s):
return base64.urlsafe_b64decode(s.encode())
# Ordered Dictionaries
def change_encoding_dict(settings_server, encoding_type):
return OrderedDict([(k, encoding_type(v)) for k, v in settings_server.items()])
# Return bytes from string
def encode_dict(settings_server):
return change_encoding_dict(settings_server, str.encode)
# Return string from bytes
def decode_dict(settings_server):
return change_encoding_dict(settings_server, bytes.decode)
# password: Bytes
# salt: Bytes
def derive_key(password, salt):
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=salt,
iterations=100000,
backend=default_backend()
)
r_key = base64.urlsafe_b64encode(kdf.derive(password))
return r_key
# Encryption functions
# message: Bytes
# key: Bytes
def encrypt(message, key):
f = Fernet(key)
token = f.encrypt(message)
return token
# token: Bytes
# key: Bytes
def decrypt(token, key):
f = Fernet(key)
message = f.decrypt(token)
return message
# password: bytes()
# salt: bytes()
# settings_server: dict() -> Byte values
# encryption_function: encrypt(message, key) : decrypt(token, key):
# Returns settings_server_decrypted dictionary with Byte() values. Will need to use
# ChangeEncodingDict to make them strings (recommended cfg file friendly)
def __settings_server(password, salt, settings_server, encryption_function):
key = derive_key(password, salt)
settings_server_decrypted = OrderedDict()
for setting in settings_server:
settings_server_decrypted[setting] = encryption_function(settings_server[setting], key)
return settings_server_decrypted
# Returns (salt, settings_server)
def _settings_server_encrypt(settings_server):
salt = generate_salt()
password = getpass.getpass("Enter password: ")
password2 = getpass.getpass("Retype Password: ")
if password != password2:
raise PasswordMismatch
settings_server_encrypted = __settings_server(password.encode(), salt, encode_dict(settings_server), encrypt)
return salt, settings_server_encrypted
# Returns (settings_server)
def _settings_server_decrypt(settings_server, settings_encrypt):
settings_server_encoded = encode_dict(settings_server)
if settings_encrypt["encrypt"]:
salt = salt_decode(settings_encrypt["salt"])
password = getpass.getpass("Enter password: ")
return __settings_server(password.encode(), salt, settings_server_encoded, decrypt)
else:
return settings_server_encoded
# Wrapper function that will catch exceptions and exit
def settings_server_new(function, **kwargs):
try:
return function(**kwargs)
# If the user cancels the login
except KeyboardInterrupt:
print("\nQuitting...")
# If the user passwords do not match (encrypt)
except PasswordMismatch:
print("Passwords do not match...")
# Incorrect password entered (decrypt)
except InvalidToken:
print("Password or Token Incorrect...")
# Probably the salt value got modified
except base64.binascii.Error:
print("Salt is invalid...")
# Some other kind of fuck up
except Exception as e:
print("Unknown exception occurred...")
print(e)
# Exit if an exception was thrown
sys.exit(1)
# Glue functions that package **kwargs automatically
def settings_server_encrypt(settings_server):
kwargs = {"settings_server": settings_server}
return settings_server_new(_settings_server_encrypt, **kwargs)
def settings_server_decrypt(settings_server, settings_encrypt):
kwargs = {
"settings_server": settings_server,
"settings_encrypt": settings_encrypt
}
return settings_server_new(_settings_server_decrypt, **kwargs)
# The _cfg functions should return a regular string
# These are the functions that should interface with the bot a return a plain string
# settings_server ordered dictionary
def settings_server_encrypt_cfg(settings_server):
salt, settings_server = settings_server_encrypt(settings_server)
return salt_encode(salt), decode_dict(settings_server)
def settings_server_decrypt_cfg(settings_server, settings_encrypt):
settings_server = settings_server_decrypt(settings_server, settings_encrypt)
return decode_dict(settings_server)
def main():
import argparse
from pprint import pformat
default_cfg = "cfg"
parser = argparse.ArgumentParser(
description="A class to encrypt server credentials",
epilog="There are no additional parameters.",
add_help=True )
parser.add_argument("--encrypt", help="Generate encrypted authentication.", action="store_true")
parser.add_argument("--decrypt", help="Decrypt encrypted authentication", action="store_true")
parser.add_argument("--recrypt", help="Recrypt encrypted authentication", action="store_true")
parser.add_argument("-c", "--cfg", help="Specify config file.", default=default_cfg)
arguments = parser.parse_args()
if arguments.recrypt:
arguments.encrypt = True
arguments.decrypt = True
if arguments.encrypt or arguments.decrypt:
import importlib
cfg = importlib.import_module(arguments.cfg)
settings_server = cfg.settings_server
settings_encrypt = None
if arguments.decrypt and arguments.encrypt:
print("Re-encrypting")
if arguments.decrypt: # arguments.decrypt
print("Decrypt...")
settings_server = settings_server_decrypt_cfg(cfg.settings_server, cfg.settings_encrypt)
settings_encrypt = OrderedDict([
("encrypt", False),
("salt", cfg.settings_encrypt["encrypt"])
])
if arguments.encrypt:
print("Encrypt...")
salt, settings_server = settings_server_encrypt_cfg(settings_server)
settings_encrypt = OrderedDict([
("encrypt", True),
("salt", salt)
])
print("settings_server = {}".format(pformat(settings_server)))
print("settings_encrypt = {}".format(pformat(settings_encrypt)))
return 0
if __name__ == "__main__":
sys.exit(main())

274
src/main.py Executable file
View File

@ -0,0 +1,274 @@
#! /usr/bin/env python3
# Yandere Lewd Bot, an image posting bot for Pleroma
# Copyright (C) 2022 Anon <yanderefedi@proton.me>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import sys
import argparse
import signal
import yandere_bot
import datetime
import contextlib
# A class that inherits from either YandereBot from yandere_bot module
# This class is used to handle command line arguments gracefully, and extend functionality quickly
# Bot specific changes should be made here (if they are minor enough).
# This will be instantiated from the main() function
class YandereBot(yandere_bot.YandereBot):
# The below settings are required from the configuration module
settings_time = None
settings_reminder = None
# Wait before running
delay_start = 0
def __init__(self, cfg, debug_mode, prime_bot, start_index, delay_d=None, delay_h=None, delay_s=None):
super(YandereBot, self).__init__(cfg, debug_mode, prime_bot=False)
self.load_settings(self.cfg, ("settings_time", "settings_reminder"))
self.set_pretimer(delay_d, delay_h, delay_s)
self.currentIndexCount = start_index
if self.debug_mode:
print("[DEBUG MODE ON - DRY RUN BEGIN]")
# Do not perform sanity test if stdout is None.
# input() will fail if stdout is None, which could happen with the following command
# ./run --dry-run -h -d 'a date in the past'
if sys.stdout is not None and not self.pass_sanity_test():
raise FailedSanityTest
if prime_bot:
self.prime_bot()
def print_date_time_example(self):
print_fmt = " {0:6} {1:10} {2}"
time_fmt = self.settings_time["time_format"]
date_fmt = self.settings_time["date_format"]
current_time = self.dateSelection
print(print_fmt.format(
"TIME", time_fmt, current_time.strftime(time_fmt)
))
print(print_fmt.format(
"DATE", date_fmt, current_time.strftime(date_fmt)
))
def dump_pictures(self):
for ele in self.listPictures:
print(ele.get_full_string())
def set_delay_d(self, d):
try:
t = datetime.datetime.strptime(d, self.settings_time["date_format"])
self.dateNextSelection = self.dateNextSelection.replace(
year=t.year, month=t.month, day=t.day
)
except Exception:
print("Invalid date format: {}\n\nCorrect date/time format examples:".format(d))
self.print_date_time_example()
raise DateWrongFormat
def set_delay_h(self, h, add_24):
try:
t = datetime.datetime.strptime(h, self.settings_time["time_format"])
self.dateNextSelection = self.dateNextSelection.replace(
hour=t.hour, minute=t.minute, second=t.second, microsecond=t.microsecond
)
if self.dateNextSelection < self.dateSelection and add_24:
self.dateNextSelection = yandere_bot.time_add_seconds(self.dateNextSelection, 60 * 60 * 24)
except Exception:
print("Invalid time format: {}\n\nCorrect date/time format examples:".format(h))
self.print_date_time_example()
raise TimeWrongFormat
def set_pretimer(self, d=None, h=None, s=0):
if d:
self.set_delay_d(d)
if h:
self.set_delay_h(h, d is None)
if s:
self.delay_start = max(0, s)
# Check for potential misconfigurations by the user
def pass_sanity_test(self):
# Calculate pre-timer value
seconds_until_next_pos = yandere_bot.time_diff_seconds(self.dateNextSelection, self.dateSelection)
# Possible misconfigurations that will prompt the user to continue
pretimer_less_than_zero = seconds_until_next_pos < 0
pretimer_greater_than_sleep = seconds_until_next_pos > self.settings_behavior["sleep_seconds"]
# Prompt the user
prompt_user = pretimer_less_than_zero or pretimer_greater_than_sleep
# Remind the user to generate new OAuth tokens
dt = datetime.datetime.strptime(self.settings_reminder, self.settings_time["long_date_format"])
if dt < datetime.datetime.now():
print("REMINDER: Generate new tokens!!")
# Check if the bot is back-posting in time and make sure this is what the user wanted to avoid spamming
if pretimer_less_than_zero:
sleep = round(abs(seconds_until_next_pos), 2)
images = round(sleep / (self.settings_behavior["sleep_seconds"] * self.settings_behavior["uploads_per_post"]), 2) + 1
print("WARNING: Pre-timer is less than the current time by: {} seconds. {} images will post immediately".format(
sleep, images
))
# Check if the bot will wait for longer than the default amount of sleep time configured in the cfg.py
elif pretimer_greater_than_sleep:
print("WARNING: Pre-timer will sleep for {} seconds. This is more than the configured amount ({} seconds)".format(
round(seconds_until_next_pos, 2), self.settings_behavior["sleep_seconds"]
))
# Prompt the user if something doesn't seem right
# This must be done before we set up our keyboard interrupts. Otherwise the below exceptions will not work.
try:
if prompt_user:
# Default to 'y' if the user just presses enter
ans = input("Do you want to continue [Y/n]? ") or "y"
return ans.lower() in ("y", "yes")
except (EOFError, KeyboardInterrupt):
print()
return False
# Sanity test passed
return True
def start(self, delay=None):
_delay = delay or self.delay_start
return super(YandereBot, self).start(max(0, _delay))
# Custom exceptions
class TimeWrongFormat(Exception):
pass
class DateWrongFormat(Exception):
pass
class FailedSanityTest(Exception):
pass
class FailedToLoadCfg(Exception):
pass
# Entry point if run from the command line
def main():
# Default config file
default_cfg = "cfg"
# Parser
parser = argparse.ArgumentParser(
description="A bot for posting on Mastodon",
# epilog="All switches can be combined for greater control",
add_help=False)
parser.add_argument("--dry-run", help="Will not login or post to Plemora", action="store_true")
parser.add_argument("--debug", help="Same as --dry-run", action="store_true")
parser.add_argument("-w", "--wait", type=int, help="Wait before posting first image (seconds)", default=0)
parser.add_argument("-t", "--time", help="Wait for time before posting first image", default=None)
parser.add_argument("-d", "--date", help="Wait for date before posting first image", default=None)
parser.add_argument("-i", "--index", help="Start at index (only matters if profile select is set to sequential)", default=0)
parser.add_argument("-c", "--config", help="Set custom config file (Default: {})".format(default_cfg), default=default_cfg)
parser.add_argument("-o", "--output-hashes", help="Output list of hashes", action="store_true")
parser.add_argument("-h", "--help", help="Show this help message and exit", action="store_true")
parser.add_argument("remainder", help=argparse.SUPPRESS, nargs=argparse.REMAINDER)
arguments = parser.parse_args()
# Redirect stdout when the bot first initializes if the bot is not going to run normally
redirect_stdout = None if arguments.output_hashes or arguments.help else sys.stdout
# Yandere Lewd Bot
yandere = None
yandere_config = None
# Configuration file for Yandere Lewd Bot
try:
import importlib
yandere_config = importlib.import_module(arguments.config)
except ImportError:
print("Failed to Load Configuration:", arguments.config)
raise FailedToLoadCfg
# Flag if the bot is running in debug mode
debug_mode = (arguments.dry_run or arguments.debug or arguments.output_hashes or arguments.help)
with contextlib.redirect_stdout(redirect_stdout):
prime_bot = not arguments.help
yandere = YandereBot(
yandere_config,
debug_mode,
prime_bot,
int(arguments.index),
arguments.date,
arguments.time,
arguments.wait
)
# Print Usage Information with Time and Date Formats with Examples
if arguments.help:
parser.print_help()
print()
yandere.print_date_time_example()
print()
return 0
# Output all of the images in the bot's picture list
if arguments.output_hashes:
yandere.dump_pictures()
return 0
# Setup exit calls
# Must be done after we declare our bot(s), otherwise this will be called if quitting on decrypting settings )
def yandere_quit(signo, _frame):
print("\nInterrupted by {}, shutting down...".format(signo))
yandere.exit()
# Setup our exit calls
for sig in ("TERM", "HUP", "INT"):
signal.signal(getattr(signal, "SIG" + sig), yandere_quit)
return yandere.start()
if __name__ == "__main__":
# A return value of 0 or 1 is a normal exit
try:
sys.exit(main())
# Exceptions raised from the main function
except FailedToLoadCfg:
sys.exit(10)
except FailedSanityTest:
sys.exit(9)
except DateWrongFormat:
sys.exit(8)
except TimeWrongFormat:
sys.exit(7)
# Exceptions raised from the bot
except yandere_bot.Debug:
sys.exit(6)
except yandere_bot.MissingMasterList:
sys.exit(5)
except yandere_bot.BadCfgFile:
sys.exit(4)
except yandere_bot.BadPostSettings:
sys.exit(3)
except yandere_bot.FailedLogin:
sys.exit(2)

389
src/yandere_bot.py Normal file
View File

@ -0,0 +1,389 @@
#! /usr/bin/env python3
# Yandere Lewd Bot, an image posting bot for Pleroma
# Copyright (C) 2022 Anon <yanderefedi@proton.me>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import os
import datetime
import contextlib
import fnmatch
import math
import shutil
import importlib
from threading import Event
from mastodon import Mastodon, MastodonIllegalArgumentError, MastodonAPIError, MastodonVersionError
class YandereBot:
# From the threading library. Is responsible for putting the bot to sleep, and exiting when the user quits (Ctrl+C)
eventSleep = Event()
# The configuration module
cfg = None
# The below settings are required from the configuration module
settings_server = None
settings_behavior = None
settings_time = None
settings_post = None
settings_post_default = None
settings_encrypt = None
settings_credentials = None
# Class variables
mastodon_api = None
failed_uploads = 0
currentSessionCount = 0
currentIndexCount = 0
debug_mode = False
primed = False
decrypted = False
# Time variables
dateSelection = None
dateNextSelection = None
# YandereBot.__init__()
# @param cfg A dynamically loaded python module. See yanlib.module_load() for an example
# @param debug_mode Should the bot run in debug mode (do not sign in or post to Pleroma)
# prime_bot Should the bot immediately prime itself (configure picture list and login, but don't post)
def __init__(self, cfg, debug_mode=False, prime_bot=True):
self.dateSelection = datetime.datetime.now()
self.dateNextSelection = self.dateSelection
self.cfg = cfg
self.load_settings(self.cfg)
self.debug_mode = debug_mode or self.settings_behavior["debug"]
if prime_bot:
self.prime_bot()
# Setup Exit Calls
def exit(self):
self.eventSleep.set()
# Decryption settings
# Used to set class attributes with the same name to the value specified in the config file.
def load_settings(self, cfg, settings=None):
try:
default_settings = (
"settings_server",
"settings_behavior",
"settings_time",
"settings_post",
"settings_post_default",
"settings_encrypt",
"settings_credentials"
)
_settings = settings or default_settings
for ele in _settings:
setattr(self, ele, getattr(cfg, ele))
except AttributeError as e:
print(e)
raise BadCfgFile
def decrypt_settings(self):
if self.settings_encrypt["encrypt"] and not self.decrypted and not self.debug_mode:
import encryption
self.settings_server = encryption.settings_server_decrypt_cfg(self.settings_server, self.settings_encrypt)
self.decrypted = True
# Login to Pleroma
def login(self):
skip_login = self.debug_mode or self.mastodon_api is not None
if skip_login:
return
if not self.decrypted:
self.decrypt_settings()
try:
self.mastodon_api = Mastodon(
client_id=self.settings_server["client_id"],
client_secret=self.settings_server["client_secret"],
access_token=self.settings_server["access_token"],
api_base_url=self.settings_server["api_base_url"],
feature_set=self.settings_behavior["feature_set"] # <--- Necessary for Mastodon Version 1.5.1
)
except (MastodonIllegalArgumentError, MastodonVersionError) as e:
print(e)
raise FailedLogin
# Maybe I should remove this from the backend?
def print_header_stats(self, picked, date_selection, date_next_selection):
picked_name = picked["name"] if picked else None
picked_url = picked["large_file_url"] if picked else None
picked_path = picked["full_path"] if picked else None
picked_explicit = picked["explicit"] if picked else None
next_selection_seconds = max(0, int(time_diff_seconds(date_next_selection, date_selection)))
print("[Profile]", picked_name)
print(picked_path)
print(picked_url)
print("Explicit:", picked_explicit)
print("Selection time: {}".format(
date_selection.strftime(self.settings_time["long_date_format"])) )
print("Next selection time: {} ({} seconds)".format(
date_next_selection.strftime(self.settings_time["long_date_format"]), next_selection_seconds) )
print("[ {} Selected during session | {} Failed ]\n".format(
self.currentSessionCount, self.failed_uploads) )
# Returns a list of media paths (without the hashes)
def get_media_list(self, picked):
try:
backend_s = picked["backend"]
backend = importlib.import_module(backend_s)
username = self.settings_credentials[backend_s]["username"]
password = self.settings_credentials[backend_s]["password"]
downloader = backend.downloader(username, password, tmp=self.settings_behavior["tmp_dir"])
img = downloader.download(picked)
return img
except ImportError:
print("Invalid Backend:", picked["backend"])
return None
# Returns a list of tuples that contain the media list path and media mastodon dictionary
def upload_media_list(self, path_list):
if self.debug_mode:
return tuple()
media_list = ((ele, self.mastodon_api.media_post(ele, description=os.path.basename(ele))) for ele in path_list)
return media_list
def get_post_text(self, picked, media_list):
content_type = self.settings_behavior["content_type"]
content_newline = self.settings_behavior["content_newline"]
static_message = content_newline.join(picked["message"])
string_post = ""
string_imglinks = []
if media_list and self.settings_behavior["post_image_link"]:
for ele in media_list:
path, media = ele
if path is None or media is None:
continue
elif content_type == "text/markdown" and not self.debug_mode:
string_imglinks.append(
"[{}]({})".format(os.path.basename(path), media["url"])
)
else:
string_imglinks.append(media["url"])
# Join non empty strings with a newline character
string_imglinks_joined = content_newline.join(filter(None, string_imglinks))
string_post = content_newline.join(filter(None, (static_message, string_imglinks_joined)))
return content_type, string_post
def _post(self, picked):
media_list = self.upload_media_list(picked["full_path"])
content_type, message = self.get_post_text(picked, media_list)
if self.debug_mode:
return picked
self.mastodon_api.status_post(
message,
media_ids=[i[1] for i in media_list if len(i) == 2],
visibility=self.settings_behavior["visibility"],
sensitive=picked["explicit"],
content_type=content_type
)
return picked
def pick_profile(self):
profiles = self.settings_post
tag_select = self.settings_behavior["tag_select"].lower()
pick_index = None
if tag_select == "random":
pick_index = random.randint(0, len(profiles) - 1)
elif tag_select == "sequential":
pick_index = self.currentIndexCount % len(profiles)
return profiles[pick_index]
# The main post function
# This function is responsible for incrementing self.currentSessionCount, as well as posting and blacklisting the
# picked item.
#
# It is also responsible for removing the picked item from self.listPictures, which can be accomplished by simply
# popping it at index 0. This should handle any error that might occur while posting.
#
# This function should return 'None' if a post failed, and the picked item from self.listPictures if it succeeded.
def post(self):
picked = None
# Flags that are set if an upload fails
timeout = False
# Attempt post
try:
# Post
while not picked and self.can_post():
picked_profile = self.pick_profile()
print("Posting...", picked_profile["name"])
picked = self.get_media_list(picked_profile)
self.currentIndexCount += 1
self._post(picked)
for path in picked["full_path"]:
os.remove(path)
# After a successful post
self.currentSessionCount += 1
# The post was successful
return picked
# Attempted to post a file that doesn't exist (immediately repost ignoring retry_seconds)
except FileNotFoundError:
print("File not found:", picked["full_path"])
# Exception flags
timeout = False
# Check if the file limit has been reached
except MastodonAPIError as e:
# Check if the file limit has been reached (413 error)
file_limit_reached = False
with contextlib.suppress(IndexError):
file_limit_reached = (e.args[1] == 413)
print("API Error:", e)
# Exception flags
timeout = True
# Server Errors
# Assume all exceptions are on the server side
# If the connection is timing out it could be for two reasons:
# 1. The error was caused by the user attempting to upload a large file over a slow connection:
# a. FIX: Reduce settings_behavior["max_size"]
# 2. The server is down. Check to verify in a web browser (this is the default assumption since the
# mastodon.py API will not specify why the connection timed out).
# The default assumption is #2
except Exception as e:
print("Unhandled Exception:", e)
# Exception flags
timeout = True
# An exception occurred
self.failed_uploads += 1
self.currentIndexCount += 1
print("[Errors: {}]".format(self.failed_uploads))
if timeout:
self.eventSleep.wait(self.settings_behavior["retry_seconds"])
# The post failed
return None
def schedule_next_post(self):
self.dateSelection = self.dateNextSelection
self.dateNextSelection = time_add_seconds(self.dateSelection, self.settings_behavior["sleep_seconds"])
# Will wait between the current time and the time of next selection
def wait_future_time(self):
seconds = time_diff_seconds(self.dateNextSelection, datetime.datetime.now())
self.eventSleep.wait(max(0, seconds))
# [BEGIN THE PROGRAM]
def prime_bot(self):
if not self.debug_mode:
self.decrypt_settings()
if self.can_post():
self.login()
self.primed = True
def start(self, delay=0):
# Prime bot if not already primed.
if not self.primed:
self.prime_bot()
# Early out if the bot is incapable of posting
if not self.can_post():
print("Bot is incapable of posting!!")
return 1
start_time = self.dateSelection
delay_seconds = max(time_diff_seconds(self.dateNextSelection, start_time) + delay, delay)
delay_time = time_add_seconds(start_time, delay_seconds)
# Print the first image in the list if a delay or pretimer is set
if delay_seconds:
self.print_header_stats(None, start_time, delay_time)
# The delay parameter is different from the dateSelection and dateSelectionNext
# It will literally time out the bot for a given number of seconds regardless of the pre-timer setting
# This is useful if you want to set a delay of 30 seconds, before back-posting several images
self.eventSleep.wait(max(0, delay))
# Check if the pre-timer is set
# dateNextSelection should be greater than dateSelection if it is
# dateSelection and dateNextSelection are both set to the current time when the bot is initialized
if delay_seconds:
self.wait_future_time()
# Begin posting
self.main_loop()
# Return 1 if there are still pictures in the picture list
return 0
# End Conditions:
# 1. User presses Ctrl+C
# 2. There is nothing left in the picture list to select from
# 3. settings_behavior["uploads_per_post"] is less than one for some reason
def can_post(self):
return not self.eventSleep.is_set() and self.settings_behavior["uploads_per_post"] > 0
def main_loop(self):
target_posts = self.settings_behavior["uploads_per_post"]
while self.can_post():
successful_posts = 0
while (successful_posts < target_posts) and self.can_post():
last_picked = self.post()
successful_posts += int(last_picked is not None)
if successful_posts >= target_posts:
self.schedule_next_post()
self.print_header_stats(last_picked, self.dateSelection, self.dateNextSelection)
else:
self.print_header_stats(last_picked, self.dateNextSelection, self.dateNextSelection)
if self.can_post():
self.wait_future_time()
# ------------------------------- TIME FUNCTIONS ---------------------------------------------
def time_add_seconds(dt, seconds):
return dt + datetime.timedelta(0, seconds)
def time_diff_seconds(d1, d2):
return (d1-d2).total_seconds()
# Custom Exceptions for YandereBot
class Debug(Exception):
pass
class BadPostSettings(Exception):
pass
class FailedLogin(Exception):
pass
class BadCfgFile(Exception):
pass
class MissingMasterList(Exception):
pass