Initial Commit

This commit is contained in:
Anon 2022-08-16 23:45:26 -07:00
commit 6c277d8187
12 changed files with 2611 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>.

179
README.md Normal file
View File

@ -0,0 +1,179 @@
# 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](https://www.gnu.org/licenses/gpl-3.0.en.html). See 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
# Generate the default folder structure.
mkdir ./md5
mkdir -p ./rsc/{safe,nsfw}
cp -vn ./default/cfg.py ./src/cfg.py
./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.
```
source ./venv/bin/activate
./src/create_app.py
# Follow the interactive prompts.
deactivate
```
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:]
```

451
default/cfg.py Normal file
View File

@ -0,0 +1,451 @@
from collections import OrderedDict
def setup_episode(profile_name, path, frames, _skip, _nsfw, output_name, message, message_nsfw):
return {
"profile_name": profile_name,
"path": path,
"frames": frames,
"skip": _skip,
"nsfw": _nsfw,
"output_name": output_name,
"message": (message,),
"message_nsfw": (message_nsfw,),
"render_script": "./src/render_script.sh"
}
# 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", "generate from create_app.py"),
("api_base_url", "generate from create_app.py"),
("client_id", "generate from create_app.py"),
("client_secret", "generate from create_app.py"),
("access_token", "generate from create_app.py")
])
settings_reminder = "07/05/2023 01:39AM"
# 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": ""
}
# Basic settings to configure Yandere Bot's behavior
settings_behavior = {
"visibility": "private",
"feature_set": "pleroma",
"sleep_seconds": 20*60,
"uploads_per_post": 1,
"retry_seconds": 15,
"delete_after_upload": True,
"target": None,
"content_type": "text/plain",
"content_newline": "\n",
"post_image_link": False,
"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",
"datetime": "%Y.%m.%d_%I.%M.%S%p"
}
# The final frame (in seconds)
end_frame = {
"fd_ep01": 25*60+20.019000000,
"fd_ep02": 23*60+47.969000000,
"fd_ep03": 25*60+33.866000000,
"fd_ep04": 23*60+49.095000000,
"fd_ep05": 23*60+47.969000000,
"fd_ep06": 23*60+50.096000000,
"fd_ep07": 23*60+49.095000000,
"fd_ep08": 23*60+48.094000000,
"fd_ep09": 25*60+09.675000000,
"fd_ep10": 23*60+49.095000000,
"fd_ep11": 23*60+47.969000000,
"fd_ep12": 23*60+50.096000000,
"fd_ep13": 23*60+49.095000000,
"fd_ep14": 23*60+47.927000000,
"fd_ep15": 24*60+58.164000000,
"fd_ep16": 23*60+49.095000000,
"fd_ep17": 25*60+02.551000000,
"fd_ep18": 23*60+50.096000000,
"fd_ep19": 25*60+33.199000000,
"fd_ep20": 25*60+38.370000000,
"fd_ep21": 25*60+53.052000000,
"fd_ep22": 25*60+56.055000000,
"fd_ep23": 25*60+24.482000000,
"fd_ep24": 23*60+50.096000000,
"fd_ep25": 23*60+49.261000000,
"fd_ep26": 24*60+44.692000000,
"ova": 30*60+00.174000000
}
# Tuple of time ranges to skip (in seconds)
skip = {
"fd_ep01": (
(40.958, 134), # OP
(656.99, 661.995), # Mid
(1349.014, 1427.009), # ED
(1504.003, end_frame["fd_ep01"]) # Credits
),
"fd_ep02": (
(36.035000, 130.964), # OP
(756.005, 761.01), # Mid
(1238.988, 1328.911), # ED
(1412.995, end_frame["fd_ep02"]) # Credits
),
"fd_ep03": (
(67.025000, 161.995), # OP
(601.976, 606.94), # Mid
(1323.948, 1413.954), # ED
(1517.766, end_frame["fd_ep03"]) # Credits
),
"fd_ep04": (
(91.049000, 185.977), # OP
(744.035, 749.04), # Mid
(1242.032, 1331.956), # ED
(1413.037, end_frame["fd_ep04"]) # Credits
),
"fd_ep05": (
(33.033000, 128.21), # OP
(741.991, 746.996), # Mid
(1204.954, 1294.96), # ED
(1412.995, end_frame["fd_ep05"]) # Credits
),
"fd_ep06": (
(19.019000, 114.031), # OP
(1005.046, 1010.009), # Mid
(1178.094, 1268.017), # ED
(1414.079, end_frame["fd_ep06"]) # Credits
),
"fd_ep07": (
(76.035000, 171.004), # OP
(619.994, 624.958), # Mid
(1235.067, 1325.908), # ED
(1412.995, end_frame["fd_ep07"]) # Credits
),
"fd_ep08": (
(29.196, 125.083), # OP
(705.121, 710.084), # Mid
(1189.146, 1279.069), # ED
(1412.62, end_frame["fd_ep08"]) # Credits
),
"fd_ep09": (
(137.012, 232.023), # OP
(743.117, 749.04), # Mid
(1323.989, 1413.996), # ED
(1493.617, end_frame["fd_ep09"]) # Credits
),
"fd_ep10": (
(29.446, 125.042), # OP
(612.07, 617.033), # Mid
(1250.082, 1340.005), # ED
(1413.078, end_frame["fd_ep10"]) # Credits
),
"fd_ep11": (
(58.058, 152.986), # OP
(734.984, 739.948), # Mid
(1180.012, 1270.019), # ED
(1412.995, end_frame["fd_ep11"]) # Credits
),
"fd_ep12": (
(37.037, 131.965), # OP
(560.018, 565.023), # Mid
(1215.715, 1307.014), # ED
(1414.038, end_frame["fd_ep12"]) # Credits
),
"fd_ep13": (
(48.048, 142.976), # OP
(615.115, 615.99), # Mid
(1226.6, 1300.424), # ED
(1412.995, end_frame["fd_ep13"]) # Credits
),
"fd_ep14": (
(57.057, 151.985), # OP
(504.963, 509.926), # Mid
(1191.857, 1283.908), # ED
(1399.106, end_frame["fd_ep14"]) # Credits
),
"fd_ep15": (
(40.04, 135.01), # OP
(606.981, 611.945), # Mid
(1323.948, 1413.954), # ED
(1482.064, end_frame["fd_ep15"]) # Credits
),
"fd_ep16": (
(20.02, 115.032), # OP
(530.03, 534.993), # Mid
(1235.067, 1324.99), # ED
(1413.078, end_frame["fd_ep16"]) # Credits
),
"fd_ep17": (
(15.265, 20.229), # OP - Episode Name
(407.032, 496.955), # OP
(705.997, 710.96), # Mid
(1320.82, 1412.995), # ED
(1489.738, end_frame["fd_ep17"]) # Credits
),
"fd_ep18": (
(19.019, 109.026), # OP
(590.882, 601.976), # Mid
(1247.788, 1340.965), # ED
(1414.038, end_frame["fd_ep18"]) # Credits
),
"fd_ep19": (
(107.065, 202.035), # OP
(778.069, 783.116), # Mid
(1319.026, 1413.037), # ED
(1517.182, end_frame["fd_ep19"]) # Credits
),
"fd_ep20": (
(93.051, 187.979), # OP
(740.031, 744.994), # Mid
(1322.988, 1412.995), # ED
(1523.397, end_frame["fd_ep20"]) # Credits
),
"fd_ep21": (
(106.064, 200.992), # OP
(590.006, 594.969), # Mid
(1323.989, 1413.996), # ED
(1536.91, end_frame["fd_ep21"]) # Credits
),
"fd_ep22": (
(44.878, 140.974), # OP
(636.01, 640.974), # Mid
(1322.947, 1412.953), # ED
(1539.997, end_frame["fd_ep22"]) # Credits
),
"fd_ep23": (
(58.058, 147.981), # OP
(788.997, 793.96), # Mid
(1322.988, 1412.995), # ED
(1509.508, end_frame["fd_ep23"]) # Credits
),
"fd_ep24": (
(182.683, 274.983), # OP
(617.242, 622.997), # Mid
(1179.303, 1269.226), # ED
(1414.038, end_frame["fd_ep24"]) # Credits
),
"fd_ep25": (
(21.021, 116.033), # OP
(649.065, 654.028), # Mid
(1218.092, 1308.098), # ED
(1413.12, end_frame["fd_ep25"]) # Credits
),
"fd_ep26": (
(55.055, 149.983), # OP
(645.019, 649.983), # Mid
(1305.012, 1397.396), # ED
(1477.726, end_frame["fd_ep26"]) # Credits
),
"ova": (
(179.012, 273.356), # OP
(1700.073, end_frame["ova"]) # ED
)
}
# Tuple of time ranges to mark as sensative (in seconds)
nsfw = {
"fd_ep01": (tuple()),
"fd_ep02": (
# Yuno locker room
(252.669, 258.592),
),
"fd_ep03": (
# Minane strips from cosplay after escaping the high school
(373.248, 386.052),
# Yuno loses swimming top
(537.37, 539.456), (542.042, 543.918), (552.927, 554.929),
(566.316, 569.861)
),
"fd_ep04": (
# Omakata cult, Minane tits
(853.311, 859.776), (865.782, 871.454), (873.289, 887.512),
(995.578, 1000.666), (1021.812, 1023.272), (1097.388, 1100.308),
(1107.732, 1119.327), (1128.753, 1140.514), (1147.021, 1152.61),
(1161.41, 1164.372), (1218.217, 1222.304)
),
"fd_ep05": (
# Tsubaki's rape
(128.253, 135.218), (209, 220.721), (224.516, 238.238),
# Minane's tits again
(313.605, 323.365), (343.051, 347.013), (353.061, 359.776),
(367.284, 368.41),
# Tsubaki's rape
(717.634, 721.012), (857.065, 861.819),
# Tsubaki strips yuno
(965.84, 967.925), (984.233, 985.943), (1033.449, 1035.159),
(1035.535, 1037.119), (1039.455, 1041.874), (1045.92, 1050.883),
(1073.322, 1077.41), (1086.21, 1089.63), (1097.972, 1101.267),
(1102.602, 1106.022), (1122.455, 1124.415)
),
"fd_ep06": (
# Yuno finds Yukki's porno stash
(383.55, 386.052), (387.554, 389.681), (394.269, 394.477),
(395.353, 396.313),
# Yukki's baby pictures, just to be safe
(615.74, 619.953), (623.623, 632.048), (633.758, 634.425),
# Yuno shower
(800.133, 803.303), (825.325, 832.415), (842.8, 845.47),
(852.518, 856.481), (869.66, 876.209)
),
"fd_ep07": (
# Yuno shower, almost electrocuted by Fifth
(356.69, 367.576), (379.588, 380.714), (390.807, 392.142),
(399.357, 404.029), (404.279, 407.991)
),
"fd_ep08": (
# Yukki trips, exposes Hinata's panties
(328.328, 333.875), (340.257, 346.346)
),
"fd_ep09": (tuple()),
"fd_ep10": (
# Minane and detective bathroom scene + changing into cosplay
(391.224, 392.142), (434.976, 435.936),
# Brief shot of detective grabbing Minane's breast
(496.037, 496.621)
),
"fd_ep11": (
# Yuno peeing at hospital
(802.135, 802.719), (811.144, 815.231),
),
"fd_ep12": (tuple()),
"fd_ep13": (
# Hinata in spa
(270.604, 271.438), (271.605, 286.453), (302.636, 314.856),
(318.652, 322.072), (322.948, 330.038), (335.085, 345.22),
# Yandere Yuno, captured Yuki
(1222.93, 1226.559),
# Omake - Hinata fan service
(1305.429, 1311.727), (1313.229, 1327.827), (1332.873, 1336.919),
(1337.336, 1341.757),
# Omake - Mao fan service
(1344.093, 1350.391), (1352.351, 1365.99), (1370.661, 1378.878),
(1385.885, 1386.552), (1391.473, 1395.394), (1397.813, 1412.953)
),
"fd_ep14": (
# Yandere Yuno naked feeding Yukki
(34.701, 40.666), (42.209, 53.136), (186.019, 190.941),
(192.901, 199.741), (235.944, 238.864), (241.908, 244.661),
(248.999, 258.175), (265.97, 268.894), (270.061, 272.647),
(352.31, 355.856), (369.494, 374.457), (405.447, 406.907),
(431.681, 434.1), (545.754, 552.343), (587.712, 596.638),
(598.598, 601.476), (610.777, 611.444), (619.953, 624.165),
(643.852, 646.312), (691.149, 694.36), (698.907, 700.825),
(714.631, 718.843), (722.847, 729.062), (773.398, 777.61),
(786.911, 790.623), (800.758, 810.476), (815.523, 819.986),
(837.211, 839.13), (867.95, 869.41), (873.331, 873.998),
(886.26, 890.223), (912.286, 924.757), (938.062, 943.484),
(943.985, 944.819), (947.488, 948.364), (949.073, 950.867),
(952.034, 953.995), (959.542, 964.13), (969.427, 977.643),
(981.439, 983.316), (1003.044, 1011.677), (1040.79, 1059.475),
),
"fd_ep15": (
# Yukki flashback of slapping Yuno
(231.606, 233.483), (241.283, 244.077),
# Ai's bra (just going to censor the close-up)
(766.557, 768.393), (769.686, 771.187)
),
"fd_ep16": (tuple()),
"fd_ep17": (
# Ai Rape
(282.657, 285.744), (288.663, 290.665), (368.994, 391.975),
# Omake - Marco's ass
(1422.838, 1431.764)
),
"fd_ep18": (tuple()),
"fd_ep19": (
# Yuno changes into casual
(410.285, 422.38), (427.01, 427.677),
# Yuno panties
(452.452, 453.37), (461.92, 465.674), (488.196, 491.658)
),
"fd_ep20": (
# Minane showering
(35.827, 39.414), (66.358, 79.371),
# Minane and Nishijima's baby lol
(386.845, 389.055)
),
"fd_ep21": (
# Yuno fanservice after Bacchus towers
(1105.021, 1113.571), (1117.533, 1123.247)
),
"fd_ep22": (tuple()),
"fd_ep23": (
# Yuno and Yuki come together
(619.911, 623.873), (626.668, 634.384), (640.932, 645.895),
(687.854, 700.867), (713.421, 726.392), (746.996, 748.581),
(753.878, 757.09), (769.978, 771.02), (776.276, 785.576),
(798.214, 800.591), (813.438, 815.189), (836.794, 838.254),
(923.089, 933.558), (1310.226, 1314.021), (1316.816, 1319.777),
# Yuno Omake
(1422.796, 1433.015), (1451.2, 1461.919), (1466.715, 1474.682)
),
"fd_ep24": (
(1.001, 5.005), (141.058, 144.519), (150.4, 152.611),
(275.025, 277.235), (310.894, 318.36), (324.574, 325.575),
(337.587, 351.476), (371.955, 391.308), (395.478, 398.94),
(409.242, 414.581), (431.431, 433.725)
),
"fd_ep25": (
# Ai sleeping
(732.982, 736.611),
# Yuno illusion world, Wakabe
(930.972, 934.016), (940.064, 942.4), (942.984, 944.61)
),
"fd_ep26": (tuple()),
"ova": (tuple())
}
# Regular episodes
start_episode = 1
end_episode = 26
profile_name = "fd_ep{}"
rsc_name = "./rsc/fd{}.mkv"
screenshot_folder = "/tmp/Future_Diary_EP{}_${{frame}}.png"
msg = "#Future_Diary #yandere"
msg_nsfw = "#Future_Diary #yandere #nsfw"
# Use a list comprehension and convert it to a tuple since
# regular episodes are named in ascending order
regular_episodes = tuple((
setup_episode(
profile_name .format(i),
rsc_name .format(i),
end_frame [profile_name.format(i)],
skip [profile_name.format(i)],
nsfw [profile_name.format(i)],
screenshot_folder .format(i),
msg .format(i),
msg_nsfw .format(i)
) for i in (str(x).zfill(2) for x in range(start_episode, end_episode + 1))
))
# Future diary OVA
ova = setup_episode(
"ova",
"./rsc/ova.mkv",
end_frame ["ova"],
skip ["ova"],
nsfw ["ova"],
"/tmp/Future_Diary_Redial_${frame}.png",
msg .format("ova"),
msg_nsfw .format("ova")
)
# The actual post setting (tuple)
settings_post = regular_episodes + (ova,)

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
#
# 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

156
src/create_app.py Executable file
View File

@ -0,0 +1,156 @@
#! /usr/bin/env python3
# Yandere Lewd Bot, an image posting bot for Pleroma
# Copyright (C) 2022 Anon
#
# 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 getpass
import re
import sys
import datetime
import importlib
from mastodon import Mastodon, MastodonIllegalArgumentError, MastodonAPIError, MastodonIOError
from collections import OrderedDict
import yanlib
class CreateAppError(Exception):
pass
def get_client_id_and_secret(app, permissions, domain):
try:
return Mastodon.create_app(app, scopes=permissions, api_base_url=domain)
except MastodonIOError:
raise CreateAppError("An error occurred. Make sure the domain name is correct.")
def get_api(client_id, client_secret, domain):
api = Mastodon(client_id, client_secret, api_base_url=domain)
return api
def get_token(api, email, password, permissions):
try:
token = api.log_in(email, password, scopes=permissions)
return token
except MastodonIllegalArgumentError:
raise CreateAppError("Username or Password is incorrect.")
except MastodonAPIError:
raise CreateAppError("Could not grant scopes:", ", ".join(permissions))
def get_cfg(cfg_name):
try:
cfg = importlib.import_module(cfg_name)
return cfg
except ImportError:
raise CreateAppError("Cannot import module:", cfg_name, "Make sure you omitted the .py extension and try again")
def package_settings(app, domain, client_id, client_secret, token):
settings_server = OrderedDict([
("app_name", app),
("api_base_url", domain),
("client_id", client_id),
("client_secret", client_secret),
("access_token", token)
])
return settings_server
def get_setting_reminder(fmt):
dt_now = datetime.datetime.now()
dt_now = dt_now.replace(year=dt_now.year + 1)
settings_reminder = dt_now.strftime(fmt)
return settings_reminder
def main():
# Create App
print("Generate and register Mastodon App")
print("You can just hit enter to accept the default for prompts that have them")
print("Ctrl+C to Quit\n")
try:
# Get instance information
app = input("Enter your app name (Default: app): ") or "app"
domain = input("URL of Instance (Default: https://yandere.cc): ") or "https://yandere.cc"
email = input("Enter your email: ")
password = getpass.getpass("Enter password: ")
print("Scopes: read, write, follow, push")
print("Separate each scope with a comma (example above).")
print("!!! Accept the default unless you intend to modify Yandere Lewd Bot !!!")
ans = input("Scopes (Default: write): ") or "write"
ans = re.sub(r"\s+", "", ans, flags=re.UNICODE)
permissions = ans.split(",")
print("Granting:", permissions)
# Begin logging in
client_id, client_secret = get_client_id_and_secret(app, permissions, domain)
api = get_api(client_id, client_secret, domain)
token = get_token(api, email, password, permissions)
# Get user setting for settings_time["long_date_format"]
# Needed for setting_reminder
print("What is the name of your main configuration file? Exclude the '.py' extension.")
ans = input("(Default: cfg): ") or "cfg"
cfg = get_cfg(ans)
# Credentials (unencrypted)
encrypt, salt = False, ""
settings_server = package_settings(app, domain, client_id, client_secret, token)
reminder = get_setting_reminder(cfg.settings_time["long_date_format"])
# Encrypt
ans = input("Do you want to encrypt your credentials (y/N)? ")
if ans.upper() in ("Y", "YES"):
import encryption
encrypt = True
salt, settings_server = encryption.settings_server_encrypt_cfg(settings_server)
settings_encrypt = OrderedDict([
("encrypt", encrypt),
("salt", salt),
])
# Output the user's new credentials
print("Copy to your config file!!!")
yanlib.pp_ordered_dict("settings_server", settings_server)
print('\nsettings_reminder = "{}"\n'.format(reminder))
yanlib.pp_dict("settings_encrypt", settings_encrypt)
return 0
except (KeyboardInterrupt, EOFError):
print("Quitting...")
return 1
except CreateAppError as e:
print(e)
return 2
except Exception as e:
print("Unhandled Exception!!", e)
return 3
if __name__ == "__main__":
status_code = main()
status_msg = {
0: "Success :)",
1: "User Quit :|",
2: "Error :(",
3: "Unhandled Exception ¯\\_(ツ)_/¯"
}
print(status_msg[status_code])
sys.exit(status_code)

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
#
# 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
import yanlib
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)
])
yanlib.pp_ordered_dict("settings_server", settings_server)
yanlib.pp_dict("settings_encrypt", settings_encrypt)
return 0
if __name__ == "__main__":
sys.exit(main())

281
src/main.py Executable file
View File

@ -0,0 +1,281 @@
#! /usr/bin/env python3
# Yandere Lewd Bot, an image posting bot for Pleroma
# Copyright (C) 2022 Anon
#
# 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 yanlib
import yandereBot
import datetime
import contextlib
# A class that inherits from either YandereBot from yandereBot 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(yandereBot.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, 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)
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 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 = yanlib.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 = yanlib.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
def print_gpl():
print("Yandere Lewd Bot, an image posting bot for Pleroma")
print("Copyright (C) 2022 Anon")
print("")
print("This program is free software: you can redistribute it and/or modify")
print("it under the terms of the GNU General Public License as published by")
print("the Free Software Foundation, either version 3 of the License, or")
print("(at your option) any later version.")
print("")
print("This program is distributed in the hope that it will be useful,")
print("but WITHOUT ANY WARRANTY; without even the implied warranty of")
print("MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the")
print("GNU General Public License for more details.")
print("")
print("You should have received a copy of the GNU General Public License")
print("along with this program. If not, see <https://www.gnu.org/licenses/>.")
# 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("-c", "--config", help="Set custom config file (Default: {})".format(default_cfg), default=default_cfg)
parser.add_argument("-l", "--license", help="Display GPL license", 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()
# Display gpl license
if arguments.license:
print_gpl()
return 0
# Redirect stdout when the bot first initializes if the bot is not going to run normally
redirect_stdout = None if 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.help)
with contextlib.redirect_stdout(redirect_stdout):
prime_bot = not arguments.help
yandere = YandereBot(
yandere_config,
debug_mode,
prime_bot,
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
# 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 yandereBot.Debug:
sys.exit(6)
except yandereBot.BadCfgFile:
sys.exit(4)
except yandereBot.FailedLogin:
sys.exit(2)

38
src/render_script.sh Executable file
View File

@ -0,0 +1,38 @@
#! /usr/bin/env sh
# src/render_script.sh
# ISSUES:
# - https://github.com/mpv-player/mpv/issues/5498
# MPV has an issue when outputting to jpg.
# Colors look washed out and faded compared to png screenshots.
# As a workaround this script will output to png then convert to jpg.
#
# - https://trac.ffmpeg.org/ticket/2391
# I want to just use ffmpeg for this script, however it
# does not support dvd subtitles. For now, I have to
# rely on mpv to render dvdsubs correctly :(
# TODO:
# - Tidy up this script and add some safety checks
# - Add some logic to the bot to detect if this script failed
# - Research more mpv options to avoid having to use mpv + convert
# Requiered args supplied by the bot
INPUT_PATH="$1"
OUTPUT_PATH="$2"
PICKED_FRAME="$3"
PNG_PATH="${OUTPUT_PATH%.*}.png"
echo "$INPUT_PATH"
echo "$OUTPUT_PATH"
echo "$PICKED_FRAME"
mkdir -p "$(dirname "$OUTPUT_PATH")"
mkdir -p "$(dirname "$PNG_PATH")"
mpv "$INPUT_PATH" --sid=1 "--start=${PICKED_FRAME}" --frames=1 -o "$PNG_PATH"
convert -quality 95 "$PNG_PATH" "$OUTPUT_PATH"
rm -fv "$PNG_PATH"

430
src/yandereBot.py Normal file
View File

@ -0,0 +1,430 @@
#! /usr/bin/env python3
# Yandere Lewd Bot, an image posting bot for Pleroma
# Copyright (C) 2022 Anon
#
# 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 yanlib
import os
import datetime
import contextlib
import fnmatch
import math
import random
import subprocess
from threading import Event
from mastodon import Mastodon, MastodonIllegalArgumentError, MastodonAPIError, MastodonVersionError
# A class that contains all of the rendering information for a single post
class YandereFrame:
# From Config File
profile_name = ""
path = ""
frames = 0
skip = tuple()
nsfw = tuple()
output_name = ""
output_name_tr = ""
translation = {}
message = ""
message_nsfw = ""
render_script = ""
# Picked
picked_frame = None
def __init__(self, picked):
self.profile_name = picked["profile_name"]
self.path = picked["path"]
self.frames = picked["frames"]
self.skip = picked["skip"]
self.nsfw = picked["nsfw"]
self.output_name = picked["output_name"]
self.output_name_tr = self.output_name
self.message = picked["message"]
self.message_nsfw = picked["message_nsfw"]
self.render_script = picked["render_script"]
self.add_translation("profile_name", self.profile_name)
def add_translation(self, k, v):
self.translation.update({k: v})
def pick(self):
random.seed(os.urandom(16))
picked_frame = None
while picked_frame is None:
picked_frame = random.random() * self.frames
for skip in self.skip:
begin, end = skip
if begin <= picked_frame <= end:
print("Cannot pick frame:", picked_frame, "from:", self.profile_name)
picked_frame = None
break
self.picked_frame = picked_frame
self.add_translation("frame", str(picked_frame))
return picked_frame
def is_nsfw(self):
for nsfw in self.nsfw:
begin, end = nsfw
if begin <= self.picked_frame <= end:
return True
return False
def translate_basename(self):
output_name = self.output_name
output_name_tr = output_name
for k,v in self.translation.items():
replace_token = "${" + k + "}"
output_name_tr = output_name_tr.replace(replace_token, v)
self.output_path_tr = output_name_tr
return output_name_tr
# TODO: Add translation keywords to the message
def get_message(self):
return self.message_nsfw if self.is_nsfw() else self.message
def render(self):
self.translate_basename()
args = [
self.render_script,
self.path,
self.output_path_tr,
self.translation["frame"]
]
subprocess.run(args)
return self.output_path_tr
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_encrypt = None
# Class variables
mastodon_api = None
listPictures = []
failed_uploads = 0
currentSessionCount = 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_encrypt"
)
_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, yandere_frame, date_selection, date_next_selection):
profile, frame, nsfw, path = None, None, None, None
if yandere_frame:
profile = yandere_frame.profile_name
frame = yandere_frame.picked_frame
nsfw = yandere_frame.is_nsfw()
path = yandere_frame.output_path_tr
print("\n==== PLEROMA ====")
print("Profile: {} | Frame: {} | NSFW: {}".format(
profile, frame, nsfw
))
print("Path:", path)
next_selection_seconds = max(0, int(yanlib.time_diff_seconds(date_next_selection, date_selection)))
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 tuples that contain the media list path and media mastodon dictionary
def upload_media_list(self, path_list):
media_list = []
for ele in path_list:
if not self.debug_mode:
media = self.mastodon_api.media_post(ele, description=os.path.basename(ele))
media_list.append((ele, media))
return media_list
def get_post_text(self, yandere_frame, media_list):
content_type = self.settings_behavior["content_type"]
content_newline = self.settings_behavior["content_newline"]
static_message = content_newline.join(yandere_frame.get_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, yandere_frame):
media_list = self.upload_media_list([yandere_frame.output_path_tr])
content_type, message = self.get_post_text(yandere_frame, media_list)
if self.debug_mode:
return yandere_frame
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=yandere_frame.is_nsfw(),
content_type=content_type
)
return yandere_frame
def render_frame(self, picked_profile):
yandere_frame = YandereFrame(picked_profile)
yandere_frame.add_translation("datetime", datetime.datetime.strftime(datetime.datetime.now(), self.cfg.settings_time["datetime"]))
yandere_frame.pick()
yandere_frame.render()
if not os.path.isfile(yandere_frame.output_path_tr):
raise FileNotFoundError("Could not generate screenshot:", yandere_frame.output_path_tr)
return yandere_frame
# 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
picked_profile = random.choice(self.cfg.settings_post)
picked = self.render_frame(picked_profile)
self._post(picked)
if os.path.isfile(picked.output_path_tr):
os.remove(picked.output_path_tr)
else:
raise FileNotFoundError("Unable to render {}".format(picked.output_path_tr))
# 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 as e:
print(e)
# 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
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 = yanlib.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 = yanlib.time_diff_seconds(self.dateNextSelection, datetime.datetime.now())
self.eventSleep.wait(max(0, seconds))
# [BEGIN THE PROGRAM]
def prime_bot(self):
random.seed(os.urandom(16))
if not self.debug_mode:
self.decrypt_settings()
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(yanlib.time_diff_seconds(self.dateNextSelection, start_time) + delay, delay)
delay_time = yanlib.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. 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()
# Custom Exceptions for YandereBot
class Debug(Exception):
pass
class FailedLogin(Exception):
pass
class BadCfgFile(Exception):
pass

90
src/yanlib.py Normal file
View File

@ -0,0 +1,90 @@
#! /usr/bin/env python3
# Yandere Lewd Bot, an image posting bot for Pleroma
# Copyright (C) 2022 Anon
#
# 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/>.
# yanlib.py is required by yandereBot.py
# This file contains functions and utilities that may be useful to external tools and programs that interface with
# yandereBot, or manipulate hash files in some way. Typically instantiating a yandereBot object is unnecessary for this.
import os
import datetime
import shutil
import contextlib
# ------------------------------- 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()
def input_time_format(s):
return s.replace("-", "")
def humanize_time_delta(total_seconds):
m, s = divmod(int(total_seconds), 60)
h, m = divmod(m, 60)
d, h = divmod(h, 24)
return d, h, m, s
# -------------------------------- Pretty Print Functions ------------------------------------
# If value is a subclass of string, return it in parentheses (used for generating a python configuration file)
def _pp_str(v):
if issubclass(str, type(v)):
return '"{}"'.format(v)
else:
return "{}".format(v)
# Prints out a dictionary in pretty print form as valid python code.
# setting_dict should consist of string formats with key value pairs defined in setting_dict ex. '{key} {value}'.
def _pp_dict(head, setting_dict, fmt, tail):
if head:
print(head)
last_index = len(setting_dict) - 1
# i, k -> index and key value of setting_dict
for i, k in enumerate(setting_dict):
_fmt = fmt
_k = _pp_str(k)
_v = _pp_str(setting_dict[k])
# Add comma separator on all but the last value setting
if i < last_index:
_fmt += ","
print(_fmt.format(_k, _v))
if tail:
print(tail)
def pp_ordered_dict(setting, setting_dict):
_pp_dict(
"{} = OrderedDict([".format(setting),
setting_dict,
'\t({},\t{})',
"])")
def pp_dict(setting, setting_dict):
_pp_dict(
"{} = {{".format(setting),
setting_dict,
'\t{}:\t{}',
"}")