Commited backup

This commit is contained in:
2025-07-10 21:02:34 +03:00
parent 952c1001e3
commit da0b80823e
1310 changed files with 254133 additions and 41 deletions

View File

@@ -0,0 +1,24 @@
name: Generate full.txt
on: [push]
jobs:
generate:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Configure Git
run: |
git config --global user.name "Github Actions"
git config --global user.email "actions@github.com"
- name: Generate full.txt
run: |
echo "Generating full.txt"
python _gen_full_txt.py || echo "Error"
- name: Commit & Push changes
run: |
echo "Committing changes"
git commit -a -m "Update full.txt"
echo "Pushing changes to repository"
git push origin main

View File

@@ -0,0 +1,111 @@
"""
░██████╗░██████╗░██╗░░░░░███╗░░░███╗███████╗██████╗░██████╗░
██╔════╝██╔═══██╗██║░░░░░████╗░████║██╔════╝██╔══██╗██╔══██╗
╚█████╗░██║██╗██║██║░░░░░██╔████╔██║█████╗░░██████╔╝██████╔╝
░╚═══██╗╚██████╔╝██║░░░░░██║╚██╔╝██║██╔══╝░░██╔══██╗██╔══██╗
██████╔╝░╚═██╔═╝░███████╗██║░╚═╝░██║███████╗██║░░██║██║░░██║
╚═════╝░░░░╚═╝░░░╚══════╝╚═╝░░░░░╚═╝╚══════╝╚═╝░░╚═╝╚═╝░░╚═╝
"""
# meta developer: @sqlmerr_m
# meta icon: https://github.com/sqlmerr/hikka_mods/blob/main/assets/icons/FastChangeTgStatus.png?raw=true
from hikkatl.tl.types import MessageEntityCustomEmoji
import logging
from .. import loader, utils
logger = logging.getLogger(__name__)
# сам класс модуля
@loader.tds
class FCTS(loader.Module):
"""Change your status fast. Only for premium users | Изменяйте ваш статус быстро. Только для премиум пользователей"""
# нужные переменные
strings = {
"name": "FastChangeTgStatus",
"no_args": "<b>You didn't enter any arguments!</b>",
"status_changed": "<b>Your status successfully changed to {}!</b>",
"status_is_none": "<b>This status does not exist!</b>",
"list": "<emoji document_id=5836898273666798437>⭐️</emoji> <b>List of your statuses</b>:",
"emoji_added": "<b>Emoji added to status list successfully</b>",
"indexerror": "<emoji document_id=5447644880824181073>⚠️</emoji> <b>You have entered too few arguments!</b>",
}
strings_ru = {
"no_args": "<b>Вы не ввели аргументы!</b>",
"status_changed": "<b>Ваш статус успешно изменен на {}!</b>",
"status_is_none": "<b>Такого статуса не существует!</b>",
"list": "<emoji document_id=5836898273666798437>⭐️</emoji> <b>Список ваших статусов</b>:",
"emoji_added": "<b>Эмодзи успешно добавлен в список статусов</b>",
"indexerror": "<emoji document_id=5447644880824181073>⚠️</emoji> <b>Вы ввели слишком мало аргументов!</b>",
}
async def client_ready(self):
if not self._client.hikka_me.premium:
raise loader.LoadError(
"This module is for Telegram Premium only!"
) # Немного взял кода из модуля TgStatus от @hikarimods
self.default = {
"sleep": "5875318886433295705",
"game": "5877201954714684742",
"heart": "5875452644599795072",
"do not disturb": "5877477244938489129",
"plane": "5877464772353460958",
"home": "5877506824378257176",
}
@loader.command(
ru_doc="[имя статуса] - поставить этот статус | .statuslist для просмотра ваших установленных статусов"
)
async def statuschange(self, m):
"[status name] - set this status | .statuslist to view your downloaded statuses"
args = utils.get_args_raw(m)
if not args:
return await utils.answer(m, self.strings("no_args"))
default = self.default
s = self.get("s", default)
status = s.get(args)
if status is None:
return await utils.answer(m, self.strings("status_is_none"))
await self._client.set_status(int(status))
await utils.answer(m, self.strings("status_changed").format(args))
@loader.command(ru_doc="Посмотреть список всех статусов")
async def statuslist(self, m):
"See list of all your statuses"
s = self.get("s", self.default)
statuses = f"{self.strings('list')}\n"
for j in s:
emoji = f"<emoji document_id={s.get(j)}>▫️</emoji>"
statuses += f"{emoji} {j}\n"
await utils.answer(m, statuses)
@loader.command(ru_doc="[эмодзи] [короткое имя] Добавить кастомный статус")
async def statusadd(self, m):
"[emoji] [short name] Add a custom status"
s = self.get("s", self.default)
args = utils.get_args_raw(m).split()
if not args:
return await utils.answer(m, self.strings("no_args"))
try:
# emoji = m.text.split()[1]
name = args[1]
except IndexError:
return await utils.answer(m, self.strings("indexerror"))
for emoji in m.entities:
if isinstance(emoji, MessageEntityCustomEmoji):
e = str(emoji.document_id)
s[name] = e
self.set("s", s)
await utils.answer(m, self.strings("emoji_added"))
@loader.command(ru_doc="Очистить все кастомные статусы")
async def statusclear(self, m):
"Clear all custom statuses"
self.set("s", self.default)
await utils.answer(m, "<emoji document_id=5206607081334906820>✔️</emoji>")

674
sqlmerr/hikka_mods/LICENSE 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>.

View File

@@ -0,0 +1 @@
# My modules for hikka

View File

@@ -0,0 +1,9 @@
import os
modules = filter(
lambda f: f.endswith(".py") and not f.startswith("_"),
os.listdir(".")
)
with open("full.txt", "w") as file:
file.write("\n".join(m.rstrip(".py") for m in modules))

View File

@@ -0,0 +1,79 @@
"""
░██████╗░██████╗░██╗░░░░░███╗░░░███╗███████╗██████╗░██████╗░
██╔════╝██╔═══██╗██║░░░░░████╗░████║██╔════╝██╔══██╗██╔══██╗
╚█████╗░██║██╗██║██║░░░░░██╔████╔██║█████╗░░██████╔╝██████╔╝
░╚═══██╗╚██████╔╝██║░░░░░██║╚██╔╝██║██╔══╝░░██╔══██╗██╔══██╗
██████╔╝░╚═██╔═╝░███████╗██║░╚═╝░██║███████╗██║░░██║██║░░██║
╚═════╝░░░░╚═╝░░░╚══════╝╚═╝░░░░░╚═╝╚══════╝╚═╝░░╚═╝╚═╝░░╚═╝
"""
# meta developer: @sqlmerr_m
# meta icon: https://github.com/sqlmerr/hikka_mods/blob/main/assets/icons/addlinktosymbols.png?raw=true
# meta banner: https://github.com/sqlmerr/hikka_mods/blob/main/assets/sqlmerrmodules_example.png?raw=true
from hikkatl.tl.types import Message
from .. import loader, utils
@loader.tds
class AddLinkToSymbols(loader.Module):
"""Add link to symbols in text"""
strings = {
"name": "AddLinkToSymbols",
"noargs": "<emoji document_id=5240241223632954241>🚫</emoji> <b>You didn't enter any arguments</b>",
"IndexError": "<emoji document_id=5431571841892228467>😟</emoji> <b>You have entered too few arguments</b>",
"wait": "<emoji document_id=5411225014148014586>🔴</emoji> <b>Please wait a second...</b>",
"none": "<emoji document_id=5210952531676504517>❌</emoji> <b>ERROR</b>",
}
strings_ru = {
"noargs": "<emoji document_id=5240241223632954241>🚫</emoji> <b>Вы не ввели аргументы</b>",
"IndexError": "<emoji document_id=5431571841892228467>😟</emoji> <b>Вы ввели слишком мало аргументов</b>",
"wait": "<emoji document_id=5411225014148014586>🔴</emoji> <b>Подождите немного...</b>",
"none": "<emoji document_id=5210952531676504517>❌</emoji> <b>ОШИБКА</b>",
"_cls_doc": "Добавить ссылку на определённые символы в тексте"
}
@loader.command(
ru_doc="[символы] [ссылка] [текст или реплай] Добавить ссылку на символы\n\nПример: .addlinktosymbols ап.ев https://example.com привет. Еееее хай\nСимволы пишите без пробелов. "
)
async def addlinktosymbols(self, m: Message):
"""
[symbols] [link] [text or reply] Add link to symbols
Example: .addlinktosymbols ah.e https://example.com hi hello. YOOOOOOO
Write characters without spaces.
"""
args = utils.get_args_raw(m).split()
if not args:
return await utils.answer(m, self.strings("noargs"))
reply = await m.get_reply_message()
try:
symbols = args[0]
link = args[1]
text = args[2:]
if reply is not None:
text = reply.raw_text
except IndexError:
return await utils.answer(m, self.strings("IndexError"))
await utils.answer(m, self.strings("wait"))
txt = ""
for t in text:
if reply:
txt += t
else:
txt += t + " "
real_txt = ""
for _ in range(len(txt)):
if txt[_] in symbols:
symbol = txt[_]
real_txt += f'<a href="{link}">{symbol}</a>'
else:
real_txt += txt[_]
if real_txt is None:
return await utils.answer(m, self.strings("none"))
await utils.answer(m, real_txt)

View File

@@ -0,0 +1,151 @@
# ░██████╗░██████╗░██╗░░░░░███╗░░░███╗███████╗██████╗░██████╗░
# ██╔════╝██╔═══██╗██║░░░░░████╗░████║██╔════╝██╔══██╗██╔══██╗
# ╚█████╗░██║██╗██║██║░░░░░██╔████╔██║█████╗░░██████╔╝██████╔╝
# ░╚═══██╗╚██████╔╝██║░░░░░██║╚██╔╝██║██╔══╝░░██╔══██╗██╔══██╗
# ██████╔╝░╚═██╔═╝░███████╗██║░╚═╝░██║███████╗██║░░██║██║░░██║
# ╚═════╝░░░░╚═╝░░░╚══════╝╚═╝░░░░░╚═╝╚══════╝╚═╝░░╚═╝╚═╝░░╚═╝
# ---------------------------------------------------------------------------------------------
# Name: AnimatedProfile
# Description: Модуль для анимации вашего профиля (имя, био)
# Author: sqlmerr
# Commands:
# .animatedname (.aname) | .animatedbio (.abio) | .stopanimatedname (.stopaname) | .stopanimatedbio (.stopabio)
# ---------------------------------------------------------------------------------------------
# meta icon: https://github.com/sqlmerr/hikka_mods/blob/main/assets/icons/animatedprofile.png?raw=true
# meta developer: @sqlmerr_m
# only hikka
import asyncio
from hikkatl.tl.types import Message
from hikkatl import functions
import logging
from .. import loader, utils
logger = logging.getLogger(__name__)
@loader.tds
class AnimatedProfile(loader.Module):
"""Module for your profile animation (name, bio) look in the config"""
strings = {
"name": "AnimatedProfile",
"name_delay": "Time between frames of name animation",
"animated_name_frames": "Name animation frames",
"not_name_frames": "<emoji document_id=5447644880824181073>⚠️</emoji> See the config! In the animated_name_frames parameter, put your animation frames by name",
"name_is_enabled": "<emoji document_id=5447644880824181073>⚠️</emoji> Name animation is already enabled, use <code>.astopname</code> to turn it off.",
"name_is_disabled": "<emoji document_id=5447644880824181073>⚠️</emoji> Name animation is already turned off.",
"name_turned_off": "<emoji document_id=5447644880824181073>⚠️</emoji> Name animation is disabled.",
"bio_status": "Is the bio animation enabled or not",
"bio_delay": "Time between frames of bio animation",
"animated_bio_frames": "Bio animation frames",
"not_bio_frames": "<emoji document_id=5447644880824181073>⚠️</emoji> See the config! In the animated_bio_frames parameter, put your animation frames bio",
"bio_is_enabled": "<emoji document_id=5447644880824181073>⚠️</emoji> Bio animation is already enabled, use <code>.astopname</code> to turn it off.",
"bio_is_disabled": "<emoji document_id=5447644880824181073>⚠️</emoji> Bio animation is already turned off.",
"bio_turned_off": "<emoji document_id=5447644880824181073>⚠️</emoji> Bio animation is disabled.",
}
strings_ru = {
"name_delay": "Время между кадрами анимации имени",
"animated_name_frames": "Кадры анимации имени",
"not_name_frames": "<emoji document_id=5447644880824181073>⚠️</emoji> Смотрите конфиг! В параметре animated_name_frames, поставьте ваши кадры анимации имени",
"name_is_enabled": "<emoji document_id=5447644880824181073>⚠️</emoji> Анимация имени уже включена, используйте <code>.stopaname</code>, чтобы выключить.",
"name_is_disabled": "<emoji document_id=5447644880824181073>⚠️</emoji> Анимация имени уже выключена.",
"name_turned_off": "<emoji document_id=5447644880824181073>⚠️</emoji> Анимация имени выключена.",
"bio_status": "Включена ли анимация био или нет",
"bio_delay": "Время между кадрами анимации био",
"animated_bio_frames": "Кадры анимации био",
"not_bio_frames": "<emoji document_id=5447644880824181073>⚠️</emoji> Смотрите конфиг! В параметре animated_bio_frames, поставьте ваши кадры анимации био",
"bio_is_enabled": "<emoji document_id=5447644880824181073>⚠️</emoji> Анимация био уже включена, используйте <code>.stopabio</code>, чтобы выключить.",
"bio_is_disabled": "<emoji document_id=5447644880824181073>⚠️</emoji> Анимация био уже выключена.",
"bio_turned_off": "<emoji document_id=5447644880824181073>⚠️</emoji> Анимация био выключена.",
"_cls_doc": "Модуль для анимации вашего профиля (имя, био) смотрите конфиг"
}
def __init__(self):
self.aname = False
self.abio = False
self.config = loader.ModuleConfig(
loader.ConfigValue(
"animated_name_frames",
[],
lambda: self.strings("animated_name_frames"),
validator=loader.validators.Series(
loader.validators.Union(loader.validators.String())
),
),
loader.ConfigValue(
"name_delay",
1.0,
lambda: self.strings("name_delay"),
validator=loader.validators.Float(),
),
loader.ConfigValue(
"animated_bio_frames",
[],
lambda: self.strings("animated_bio_frames"),
validator=loader.validators.Series(
loader.validators.Union(loader.validators.String())
),
),
loader.ConfigValue(
"bio_delay",
2.0,
lambda: self.strings("bio_delay"),
validator=loader.validators.Float(),
),
)
@loader.command(alias="aname", ru_doc="""(aname) Включить анимацию имени""")
async def animatedname(self, message: Message):
"""(aname) Turn on name animation"""
if not self.config["animated_name_frames"]:
return await utils.answer(message, self.strings("not_name_frames"))
if self.aname is False:
self.aname = True
await message.delete()
while self.aname:
for n in self.config["animated_name_frames"]:
await asyncio.sleep(self.config["name_delay"])
await self.client(
functions.account.UpdateProfileRequest(first_name=n)
)
else:
return await utils.answer(message, self.strings("name_is_enabled"))
@loader.command(alias="abio", ru_doc="""(abio) Включить анимацию био""")
async def animatedbio(self, message: Message):
"""(abio) Turn on bio animation"""
if not self.config["animated_bio_frames"]:
return await utils.answer(message, self.strings("not_bio_frames"))
if self.abio is False:
self.abio = True
await message.delete()
while self.abio:
for n in self.config["animated_bio_frames"]:
await asyncio.sleep(self.config["bio_delay"])
await self.client(functions.account.UpdateProfileRequest(about=n))
else:
return await utils.answer(message, self.strings("bio_is_enabled"))
@loader.command(
alias="stopaname", ru_doc="""(stopaname) Выключить анимацию имени"""
)
async def stopanimatedname(self, message: Message):
"""(stopaname) Turn off name animation"""
if self.aname is False:
return await utils.answer(message, self.strings("name_is_disabled"))
await utils.answer(message, self.strings("name_turned_off"))
self.aname = False
@loader.command(alias="stopabio", ru_doc="""(stopabio) Выключить анимацию био""")
async def stopanimatedbio(self, message: Message):
"""(stopabio) Turn off bio animation"""
if self.abio is False:
return await utils.answer(message, self.strings("bio_is_disabled"))
await utils.answer(message, self.strings("bio_turned_off"))
self.abio = False

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 177 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 174 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 166 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 171 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 167 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 153 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 683 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 165 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 173 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 160 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 171 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 175 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 168 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 163 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 171 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 175 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 242 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 70 KiB

View File

@@ -0,0 +1,116 @@
# ░██████╗░██████╗░██╗░░░░░███╗░░░███╗███████╗██████╗░██████╗░
# ██╔════╝██╔═══██╗██║░░░░░████╗░████║██╔════╝██╔══██╗██╔══██╗
# ╚█████╗░██║██╗██║██║░░░░░██╔████╔██║█████╗░░██████╔╝██████╔╝
# ░╚═══██╗╚██████╔╝██║░░░░░██║╚██╔╝██║██╔══╝░░██╔══██╗██╔══██╗
# ██████╔╝░╚═██╔═╝░███████╗██║░╚═╝░██║███████╗██║░░██║██║░░██║
# ╚═════╝░░░░╚═╝░░░╚══════╝╚═╝░░░░░╚═╝╚══════╝╚═╝░░╚═╝╚═╝░░╚═╝
# ---------------------------------------------------------------------------------------------
# Name: AutoFormatter
# Description: Automatically formats the text of your messages | Автоматически форматирует текст ваших сообщений | Check The Config | Загляните в конфиг
# Author: sqlmerr
# Commands:
# .textformat
# ---------------------------------------------------------------------------------------------
# meta icon: https://github.com/sqlmerr/hikka_mods/blob/main/assets/icons/autoformatter.png?raw=true
# meta banner: https://github.com/sqlmerr/sqlmerr/blob/main/assets/hikka_mods/sqlmerrmodules_autoformatter.png?raw=true
# meta developer: @sqlmerr_m
# only hikka
from hikkatl.tl.patched import Message
import logging
from .. import loader, utils
logger = logging.getLogger(__name__)
@loader.tds
class AutoFormatter(loader.Module):
"""Automatically formats the text of your messages | Check The Config"""
strings = {
"name": "AutoFormatter",
"status": "Module enabled or disabled",
"format": "Text format. Where {} is the original message text",
"type": "Formatting Type",
"exceptions": "This is exceptions, this text is not formated",
"disabled": "Module is now disabled",
"enabled": "Module is now enabled",
}
strings_ru = {
"status": "Включен или выключен модуль",
"format": "Формат текста. Где {} это исходный текст сообщения",
"type": "Тип форматирования",
"exceptions": "Это исключения, этот текст не будет форматироваться",
"disabled": "Модуль сейчас выключен",
"enabled": "Модуль сейчас включен",
}
def __init__(self):
self.config = loader.ModuleConfig(
loader.ConfigValue(
"status",
False,
lambda: self.strings("status"),
validator=loader.validators.Boolean(),
),
loader.ConfigValue(
"format",
"<b>{}</b>",
lambda: self.strings("format"),
validator=loader.validators.String(),
),
loader.ConfigValue(
"exceptions",
[],
lambda: self.strings("exceptions"),
validator=loader.validators.Series(loader.validators.String()),
),
)
@loader.watcher(
only_messages=True,
no_commands=True,
no_stickers=True,
no_docs=True,
no_audios=True,
no_videos=True,
no_photos=True,
no_forwards=True,
)
async def watcher(self, message):
if not self.config["status"]:
return
exc = self.config["exceptions"]
if message.from_id == self._tg_id:
f = self.config["format"]
text = message.text
if exc != [None]:
for e in exc:
if str(e).strip() == text.strip():
return
else:
if f in text:
return
await utils.answer(message, f"{f.format(text)}")
@loader.command(ru_doc="Включить/выключить модуль")
async def textformat(self, message: Message):
"""Turn on/off The Module"""
self.config["status"] = not self.config["status"]
enable = self.strings("enabled")
disable = self.strings("disabled")
status = (
f"<emoji document_id=5447644880824181073>⚠️</emoji> {enable}"
if self.config["status"]
else f"<emoji document_id=5447644880824181073>⚠️</emoji> {disable}"
)
await utils.answer(message, "<b>{}</b>".format(status))

View File

@@ -0,0 +1,77 @@
# ░██████╗░██████╗░██╗░░░░░███╗░░░███╗███████╗██████╗░██████╗░
# ██╔════╝██╔═══██╗██║░░░░░████╗░████║██╔════╝██╔══██╗██╔══██╗
# ╚█████╗░██║██╗██║██║░░░░░██╔████╔██║█████╗░░██████╔╝██████╔╝
# ░╚═══██╗╚██████╔╝██║░░░░░██║╚██╔╝██║██╔══╝░░██╔══██╗██╔══██╗
# ██████╔╝░╚═██╔═╝░███████╗██║░╚═╝░██║███████╗██║░░██║██║░░██║
# ╚═════╝░░░░╚═╝░░░╚══════╝╚═╝░░░░░╚═╝╚══════╝╚═╝░░╚═╝╚═╝░░╚═╝
# ---------------------------------------------------------------------------------------------
# Name: AutoForward
# Description: Автоматически пересылает сообщения из каналов в один
# Author: sqlmerr
# Commands:
# .autoforward
# ---------------------------------------------------------------------------------------------
# meta developer: @sqlmerr_m
# only hikka
from .. import loader, utils
@loader.tds
class AutoForward(loader.Module):
"""Автоматически пересылает сообщения из каналов в один"""
strings = {
"name": "AutoForward",
"channels_from": "Каналы из которых будут перессылаться сообщения",
"channel_to": "Канал в который будут пересылаться сообщения из каналов",
}
async def client_ready(self, client, db):
self._client = client
self._db = db
self._db.set(__name__, "status", False)
def __init__(self):
self.config = loader.ModuleConfig(
loader.ConfigValue(
"channels_from",
[],
lambda: self.strings("channels_from"),
validator=loader.validators.Series(
validator=loader.validators.Union(
loader.validators.Integer(),
)
),
),
loader.ConfigValue(
"channel_to",
None,
lambda: self.strings("channel_to"),
validator=loader.validators.Integer(),
),
)
@loader.command()
async def autoforward(self, message):
"""- вкл/выкл модуля"""
status = self._db.get(__name__, "status")
self._db.set(__name__, "status", not status)
data = (
"Пересылаю" if self._db.get(__name__, "status") else "Больше не пересылаю"
)
await utils.answer(
message,
"<emoji document_id=5416117059207572332>➡️</emoji> <b>{}</b>".format(data),
)
@loader.watcher(only_channels=True)
async def watcher(self, m):
status = self._db.get(__name__, "status")
if status:
if m.chat_id not in self.config["channels_from"]:
return
await m.forward_to(self.config["channel_to"])

View File

@@ -0,0 +1,38 @@
"""
░██████╗░██████╗░██╗░░░░░███╗░░░███╗███████╗██████╗░██████╗░
██╔════╝██╔═══██╗██║░░░░░████╗░████║██╔════╝██╔══██╗██╔══██╗
╚█████╗░██║██╗██║██║░░░░░██╔████╔██║█████╗░░██████╔╝██████╔╝
░╚═══██╗╚██████╔╝██║░░░░░██║╚██╔╝██║██╔══╝░░██╔══██╗██╔══██╗
██████╔╝░╚═██╔═╝░███████╗██║░╚═╝░██║███████╗██║░░██║██║░░██║
╚═════╝░░░░╚═╝░░░╚══════╝╚═╝░░░░░╚═╝╚══════╝╚═╝░░╚═╝╚═╝░░╚═╝
"""
# meta developer: @sqlmerr_m
# meta banner: https://github.com/sqlmerr/sqlmerr/blob/main/assets/hikka_mods/sqlmerrmodules_codeformat.png?raw=true
from .. import loader, utils
from hikkatl.tl.types import Message
@loader.tds
class CodeFormat(loader.Module):
"""Format your code!"""
strings = {"name": "CodeFormat"}
def __init__(self):
self.config = loader.ModuleConfig(
loader.ConfigValue(
"language", "python", validator=loader.validators.String()
)
)
@loader.command()
async def code(self, message: Message):
args = utils.get_args_raw(message)
language = self.config["language"]
await utils.answer(
message, f"<pre><code class='language-{language}'>{args}</code></pre>"
)

View File

@@ -0,0 +1,163 @@
import asyncio
import logging
import aiohttp
from typing import Dict, Tuple, Union, Optional, List
from .. import utils, loader
from hikkatl.tl.patched import Message
from difflib import get_close_matches
from ..inline.types import InlineMessage
# meta developer: @sqlmerr_m
# meta icon: https://github.com/sqlmerr/hikka_mods/blob/main/assets/icons/currencyconverter.png?raw=true
# meta banner: https://github.com/sqlmerr/hikka_mods/blob/main/assets/banners/currencyconverter.png?raw=true
async def find_currency(from_: str, to: str) -> Optional[Tuple[str, str, float]]:
async with aiohttp.ClientSession() as session:
res = await session.get(
"https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@latest/v1/currencies.json"
)
json: Dict[str, str] = await res.json()
close_match = get_close_matches(from_, json.keys(), 1, cutoff=0.1)
if not close_match or close_match[0] == "":
return
from_currency = json[close_match[0]]
if not from_currency:
return
from_currency = close_match[0].upper()
res2 = await session.get(
f"https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@latest/v1/currencies/{close_match[0]}.json"
)
json2: Dict[str, Union[str, Dict[str, str]]] = await res2.json()
close_match2 = get_close_matches(
to, json2[close_match[0]].keys(), 1, cutoff=0.1
)
if close_match2 and close_match2[0] != "":
to_currency = json2[close_match[0]]
if not to_currency:
return
to_currency = close_match2[0].upper()
price = json2[from_currency.lower()][to_currency.lower()]
if not isinstance(price, float):
return
else:
return
return from_currency, to_currency, price
@loader.tds
class CurrencyConverter(loader.Module):
"""Module for converting a large number of currencies to other currencies"""
strings = {
"name": "Currency Converter",
"msg": "<emoji document_id=5364116657499285751>💲</emoji> <b>Convert</b>\n<i>{from_}</i> <b>/</b> <i>{to}</i> <code>{price}</code>",
"no_args": "<emoji document_id=5210952531676504517>❌</emoji> <b>No args!</b>",
"args_too_short": "<emoji document_id=5210952531676504517>❌</emoji> <b>Args are too short!</b>",
"not_found": "<emoji document_id=5210952531676504517>❌</emoji> <b>Currency not found!</b>",
"_cfg_autoupdate": "Auto update message",
"_cfg_update_delay": "Message auto update delay. In hours",
}
strings_ru = {
"msg": "<emoji document_id=5364116657499285751>💲</emoji> <b>Конвертация</b>\n<i>{from_}</i> <b>/</b> <i>{to}</i> <code>{price}</code>",
"no_args": "<emoji document_id=5210952531676504517>❌</emoji> <b>Вы не передали аргументы!</b>",
"args_too_short": "<emoji document_id=5210952531676504517>❌</emoji> <b>Слишком короткие аргументы!</b>",
"not_found": "<emoji document_id=5210952531676504517>❌</emoji> <b>Валюта не найдена!</b>",
"_cls_doc": "Модуль для конвертации большого количества валют в другие валюты",
"_cfg_autoupdate": "Автообновление сообщения",
"_cfg_update_delay": "Кд автообновления сообщения. В часах",
}
def __init__(self):
self.config = loader.ModuleConfig(
loader.ConfigValue(
"autoupdate",
False,
lambda: self.strings("_cfg_autoupdate"),
validator=loader.validators.Boolean(),
),
loader.ConfigValue(
"update_delay",
24,
lambda: self.strings("_cfg_update_delay"),
validator=loader.validators.Integer(),
),
)
@loader.command(ru_doc="[from] [to] Конвертировать одну валюту в другую")
async def cconvert(self, message: Message):
"""[from] [to] Convert currency to other currency"""
args = utils.get_args(message)
if len(args) == 0:
await utils.answer(message, self.strings("no_args"))
return
if len(args) < 2:
await utils.answer(message, self.strings("args_too_short"))
return
from_, to = args[0].lower(), args[1].lower()
result = await find_currency(from_, to)
if result is None:
await utils.answer(message, self.strings("not_found"))
return
if not self.config["autoupdate"]:
await utils.answer(
message,
self.strings["msg"].format(
from_=result[0], to=result[1], price=round(result[2], 2)
),
)
return
msg: InlineMessage = await self.inline.form(
message=message,
text=self.strings["msg"].format(
from_=result[0], to=result[1], price=round(result[2], 2)
),
reply_markup={"text": "\u0020\u2800", "data": "empty"},
)
msgs_to_upd = self.get("msgs", [])
msgs_to_upd.append(
{
"msg_id": msg.inline_message_id,
"unit_id": msg.unit_id,
"from": from_,
"to": to,
}
)
self.set("msgs", msgs_to_upd)
@loader.loop(interval=1, autostart=True)
async def loop(self) -> None:
if not self.config["autoupdate"]:
return
msgs_to_upd: List[dict] = self.get("msgs", [])
for msg in msgs_to_upd:
result = await find_currency(msg["from"], msg["to"])
if result is None:
continue
await self.inline._edit_unit(
text=self.strings["msg"].format(
from_=result[0], to=result[1], price=round(result[2], 2)
),
inline_message_id=msg["msg_id"],
unit_id=msg["unit_id"],
)
logging.info("updated")
await asyncio.sleep(self.config["update_delay"] * 3600)

View File

@@ -0,0 +1,204 @@
"""
░██████╗░██████╗░██╗░░░░░███╗░░░███╗███████╗██████╗░██████╗░
██╔════╝██╔═══██╗██║░░░░░████╗░████║██╔════╝██╔══██╗██╔══██╗
╚█████╗░██║██╗██║██║░░░░░██╔████╔██║█████╗░░██████╔╝██████╔╝
░╚═══██╗╚██████╔╝██║░░░░░██║╚██╔╝██║██╔══╝░░██╔══██╗██╔══██╗
██████╔╝░╚═██╔═╝░███████╗██║░╚═╝░██║███████╗██║░░██║██║░░██║
╚═════╝░░░░╚═╝░░░╚══════╝╚═╝░░░░░╚═╝╚══════╝╚═╝░░╚═╝╚═╝░░╚═╝
"""
# meta developer: @sqlmerr_m
# meta icon: https://github.com/sqlmerr/hikka_mods/blob/main/assets/icons/egsfreegames.png?raw=true
# meta banner: https://github.com/sqlmerr/hikka_mods/blob/main/assets/banners/egsfreegames.png?raw=true
import logging
from typing import Dict, List, Optional
import datetime
import aiohttp
from .. import utils, loader
from hikkatl.tl.patched import Message
@loader.tds
class EGSFreeGames(loader.Module):
"""Module for checking free games in Epic Games Store. Inline bot will send them every day in special chat"""
strings = {
"name": "EGSFreeGames",
"game": (
"- <b>Game</b>: {title}\n"
" <i>Status</i>: {status}\n"
" <i>Promotion started at</i>: <code>{start}</code>\n"
" <i>Promotion will end at</i>: <code>{end}</code>\n"
" <i>Link</i>: {url}\n"
),
"header": "<emoji document_id=5472282432436708545>🎮</emoji> <b>Free games in EGS:</b>",
"header_bot": "🎮 <b>Today's free games in EGS:</b>",
"footer": "<emoji document_id=6028435952299413210></emoji> <i>The </i><code>active</code><i> status means that the game can be picked up now.\nThe </i><code>upcoming</code><i> status means that the game can be picked up later</i>",
"_region_cfg": "Free games check region",
"_schedule_checking_cfg": "Will the bot automatically send the current free games to a special chat room",
}
strings_ru = {
"game": (
"- <b>Игра</b>: {title}\n"
" <i>Статус</i>: {status}\n"
" <i>Акция началась</i>: <code>{start}</code>\n"
" <i>Акция закончится</i>: <code>{end}</code>\n"
" <i>Ссылка</i>: {url}\n"
),
"header": "<emoji document_id=5472282432436708545>🎮</emoji> <b>Бесплатные игры в EGS:</b>",
"header_bot": "🎮 <b>Сегодняшние бесплатные игры в EGS:</b>",
"footer": "<emoji document_id=6028435952299413210></emoji> <i>Статус </i><code>active</code><i> означает, что игру можно забрать уже сейчас.\nСтатус </i><code>upcoming</code><i> означает, что игру можно будет забрать потом.</i>",
"_region_cfg": "Регион проверки бесплатных игр",
"_schedule_checking_cfg": "Будет ли бот автоматически отправлять в специальный чат текущие бесплатные игры",
"_cls_doc": "Модуль для проверки бесплатных игр в Epic Games Store. Инлайн бот будет отправлять их каждый день в специальном чате",
}
async def client_ready(self):
self.chat, _ = await utils.asset_channel(
self._client,
"EGS Free Games",
"There will be free games from epic games every day",
avatar="https://github.com/sqlmerr/hikka_mods/blob/main/assets/icons/egsfreegames_chat.png?raw=true",
invite_bot=True,
_folder="hikka",
)
def __init__(self):
self.config = loader.ModuleConfig(
loader.ConfigValue(
"region",
default="RU",
doc=lambda: self.strings("_region_cfg"),
validator=loader.validators.String(),
),
loader.ConfigValue(
"schedule_checking",
default=True,
doc=lambda: self.strings("_schedule_checking_cfg"),
validator=loader.validators.Boolean(),
),
)
def create_game_info(self, game, offer, status, available_in_russia=None):
price_info = {
"discount": 0,
"RUB": {"original": -1, "current": -1},
"USD": {"original": -1, "current": -1},
}
if game.get("price"):
total_price = game["price"].get("totalPrice", {})
discount = offer["discountSetting"]["discountPercentage"]
original_price = total_price.get("originalPrice", 0) / 100
current_price = total_price.get("discountPrice", original_price) / 100
currency = total_price.get("currencyCode", "USD")
if currency in price_info:
price_info[currency] = {
"original": original_price,
"current": current_price,
}
price_info["discount"] = discount
slug = (
game["productSlug"]
if game["productSlug"]
else game["catalogNs"]["mappings"][0]["pageSlug"]
)
url = "https://store.epicgames.com/ru/p/" + slug
return {
"title": game["title"],
"publisher": game.get("seller", {}).get("name"),
"status": status,
"start_date": offer["startDate"],
"end_date": offer["endDate"],
"url": url,
"image_url": game.get("keyImages", [{}])[0].get("url"),
"price": price_info,
"available_in_russia": available_in_russia,
}
def process_offers(
self, game: Dict, offers: List, status: str, available_in_russia=None
):
games_list = []
if offers:
for offer in offers[0].get("promotionalOffers", []):
if offer["discountSetting"]["discountPercentage"] == 0:
games_list.append(
self.create_game_info(game, offer, status, available_in_russia)
)
return games_list
def get_normal_timestamp(self, date: str) -> str:
dt = datetime.datetime.fromisoformat(date.replace("Z", "+00:00"))
dt = dt.astimezone(datetime.timezone.utc)
formatted_date = dt.strftime("%d.%m.%Y %H:%M (UTC)")
return formatted_date
async def get_free_games(self, region: str = "RU") -> Optional[List]:
url = "https://store-site-backend-static.ak.epicgames.com/freeGamesPromotions"
params = {"locale": "en-US", "country": region, "allowCountries": region}
try:
async with aiohttp.ClientSession() as session:
response = await session.get(url, params=params)
response.raise_for_status()
data = await response.json()
games = []
for game in data["data"]["Catalog"]["searchStore"]["elements"]:
if not game.get("promotions"):
continue
promotions = game["promotions"]
promo = promotions.get("promotionalOffers", [])
upcoming = promotions.get("upcomingPromotionalOffers", [])
games.extend(self.process_offers(game, promo, "active", None))
games.extend(self.process_offers(game, upcoming, "upcoming", None))
return games
except aiohttp.ClientResponseError as e:
return
def gen_text(self, games: List[Dict], bot: bool = False) -> str:
header = self.strings("header") if not bot else self.strings("header_bot")
text = "".join(
[
self.strings("game").format(
title=g["title"],
status=g["status"],
start=self.get_normal_timestamp(g["start_date"]),
end=self.get_normal_timestamp(g["end_date"]),
url=g["url"],
)
+ "\n"
for g in games
]
)
footer = self.strings("footer") if not bot else ""
return f"{header}\n\n{text}{footer}"
@loader.command(ru_doc="Получить бесплатные игры доступные в Epic Games Store")
async def egsgames(self, message: Message):
"""Get free games links available in Epic Games Store"""
games = await self.get_free_games(self.config["region"])
text = self.gen_text(games)
await utils.answer(message, text)
@loader.loop(interval=86400, autostart=True)
async def loop(self, *args, **kwargs):
if not self.config["schedule_checking"]:
return
games = await self.get_free_games(self.config["region"])
text = self.gen_text(games, bot=True)
chat_id = utils.get_entity_id(self.chat)
await self.inline.bot.send_message(chat_id=chat_id, text=text)

View File

@@ -0,0 +1,115 @@
"""
░██████╗░██████╗░██╗░░░░░███╗░░░███╗███████╗██████╗░██████╗░
██╔════╝██╔═══██╗██║░░░░░████╗░████║██╔════╝██╔══██╗██╔══██╗
╚█████╗░██║██╗██║██║░░░░░██╔████╔██║█████╗░░██████╔╝██████╔╝
░╚═══██╗╚██████╔╝██║░░░░░██║╚██╔╝██║██╔══╝░░██╔══██╗██╔══██╗
██████╔╝░╚═██╔═╝░███████╗██║░╚═╝░██║███████╗██║░░██║██║░░██║
╚═════╝░░░░╚═╝░░░╚══════╝╚═╝░░░░░╚═╝╚══════╝╚═╝░░╚═╝╚═╝░░╚═╝
"""
# meta developer: @sqlmerr_m
# meta icon: https://github.com/sqlmerr/hikka_mods/blob/main/assets/icons/fakedata.png?raw=true
# meta banner: https://github.com/sqlmerr/sqlmerr/blob/main/assets/hikka_mods/sqlmerrmodules_fakedata.png?raw=true
import aiohttp
from typing import Dict, Any
from .. import utils, loader
from hikkatl.types import Message
@loader.tds
class FakeData(loader.Module):
"""Just fake data of persons and credit cards"""
strings = {
"name": "FakeData",
"error": "<emoji document_id=5210952531676504517>❌</emoji> <b>Error in api!</b>",
"person_text": (
"<b>{emoji} Person:</b>\n"
" name - {name}\n"
" email - {email}\n"
" phone - {phone}\n"
" birthday - {birthday}\n"
" gender - {gender}\n"
" ip - {ip}\n"
" address - {address}\n\n"
),
"credit_card_text": (
"<b>💳 Credit card:</b>\n"
" type - {type}\n"
" number - {number}\n"
" expiration - {expiration}"
),
}
strings_ru = {
"error": "<emoji document_id=5210952531676504517>❌</emoji> <b>Ошибка в апи!</b>",
"person_text": (
"<b>{emoji} Человек:</b>\n"
" имя - {name}\n"
" почта - {email}\n"
" номер телефона - {phone}\n"
" дата рождения - {birthday}\n"
" пол - {gender}\n"
" айпи - {ip}\n"
" адресс - {address}\n\n"
),
"credit_card_text": (
"<b>💳 Кредитная карта:</b>\n"
" тип - {type}\n"
" номер - {number}\n"
" истекает - {expiration}"
),
"_cls_doc": "Просто фейковые данные о людях и их кредитных карт",
}
def get_formatted_person_text(self, data: Dict[str, Any]) -> str:
address = data["address"]
return self.strings("person_text").format(
emoji="👨" if data["gender"] == "male" else "👩",
name=f"{data['firstname']} {data['lastname']}",
email=data["email"],
phone=data["phone"],
birthday=data["birthday"],
gender=data["gender"],
ip=data["ip"],
address=f"{address['country']}, {address['city']}, {address['street']}",
)
def get_formatted_credit_card_text(self, data: Dict[str, Any]) -> str:
return self.strings("credit_card_text").format(
type=data["type"], number=data["number"], expiration=data["expiration"]
)
@loader.command(
ru_doc='[язык (к примеру: "ru_RU" для Русского или "fr_FR" для французского и т.д.)] - Получить фейковые данные человека и его кредитной карты'
)
async def fakedata(self, message: Message):
"""[locale (for example: "ru_RU" for Russian or "fr_FR" for French)] - Get fake data about person and credit card"""
args = utils.get_args_raw(message).split()
params = {"_quantity": 1}
if args:
params["_locale"] = args[0]
async with aiohttp.ClientSession("https://fakerapi.it") as session:
async with session.get("/api/v1/persons", params=params) as response:
if response.status != 200:
await utils.answer(message, self.strings("error"))
data = await response.json()
person = data["data"][0]
async with session.get("/api/v2/creditCards", params=params) as response:
if response.status != 200:
await utils.answer(message, self.strings("error"))
data = await response.json()
card = data["data"][0]
async with session.get("/api/v1/users", params=params) as response:
if response.status != 200:
await utils.answer(message, self.strings("error"))
data = await response.json()
person["ip"] = data["data"][0]["ip"]
text = self.get_formatted_person_text(
person
) + self.get_formatted_credit_card_text(card)
await utils.answer(message, text)

View File

@@ -0,0 +1,17 @@
autoformatter
triggers
random_emoji
egsfreegames
animatedprofile
addlinktosymbols
silentmessages
numbersfacts
fakedata
upgradedeval
codeformat
inlinetimer
autoforward
FastChangeTgStatus
quicktools
translation_manager
currencyconverter

View File

@@ -0,0 +1,187 @@
"""
░██████╗░██████╗░██╗░░░░░███╗░░░███╗███████╗██████╗░██████╗░
██╔════╝██╔═══██╗██║░░░░░████╗░████║██╔════╝██╔══██╗██╔══██╗
╚█████╗░██║██╗██║██║░░░░░██╔████╔██║█████╗░░██████╔╝██████╔╝
░╚═══██╗╚██████╔╝██║░░░░░██║╚██╔╝██║██╔══╝░░██╔══██╗██╔══██╗
██████╔╝░╚═██╔═╝░███████╗██║░╚═╝░██║███████╗██║░░██║██║░░██║
╚═════╝░░░░╚═╝░░░╚══════╝╚═╝░░░░░╚═╝╚══════╝╚═╝░░╚═╝╚═╝░░╚═╝
"""
# meta developer: @sqlmerr_m
# meta icon: https://github.com/sqlmerr/hikka_mods/blob/main/assets/icons/inlinetimer.png?raw=true
# meta banner: https://github.com/sqlmerr/sqlmerr/blob/main/assets/hikka_mods/sqlmerrmodules_inlinetimer.png?raw=true
import asyncio
from .. import loader
from ..inline.types import InlineCall
@loader.tds
class InlineTimer(loader.Module):
"""Описание нашего модуля"""
strings = {
"name": "InlineTimer",
"text": "⏲ <b>Inline timer</b>\n⏰ <i>Current time</i>: {} seconds",
"successful": "Great, in {} seconds the inline bot will send you a message via PM",
"timer_created": "<b>Timer created!</b>",
"text_cfg": "The text that your inline bot will send when the timer expires",
"below_zero": "Time cannot be below zero",
}
strings_ru = {
"text": "⏲ <b>Inline timer</b>\n⏰ <i>Текущее время</i>: {} секунд",
"successful": "Отлично, через {} секунд инлайн бот отправит вам сообщение в лс",
"timer_created": "<b>Таймер создан!</b>",
"text_cfg": "Текст, который будет писать ваш инлайн бот по истечению времени таймера",
"below_zero": "Время не может быть меньше нуля",
}
def __init__(self):
self.config = loader.ModuleConfig(
loader.ConfigValue(
"text",
"⚠️",
lambda: self.strings("text_cfg"),
validator=loader.validators.String(),
)
)
@loader.command(ru_doc="отправить таймер")
async def timer(self, message):
"""Send timer"""
timer = self.get("timer", 0)
await self.inline.form(
text=self.strings("text").format(timer),
message=message,
reply_markup=[
[
{
"text": "-1 sec",
"callback": self.decrement,
},
{
"text": "✍️ Enter value",
"input": "✍️ Enter new time IN SECONDS",
"handler": self.input_handler,
},
{"text": "+1 sec", "callback": self.increment},
],
[
{"text": "", "callback": self.proceed},
{
"text": "",
"action": "close",
},
],
],
)
async def proceed(self, call: InlineCall):
timer = self.get("timer", 1)
await call.answer(self.strings("successful").format(timer))
await call.edit(self.strings("timer_created"))
self.set("timer", 0)
await asyncio.sleep(timer)
await self.inline.bot.send_message(self.tg_id, self.config["text"])
async def decrement(self, call: InlineCall):
timer = self.get("timer", 0)
if timer == 0:
await call.answer(self.strings("below_zero"))
return
timer -= 1
self.set("timer", timer)
await call.answer()
await call.edit(
text=self.strings("text").format(timer),
reply_markup=[
[
{
"text": "-1 sec",
"callback": self.decrement,
},
{
"text": "✍️ Enter value",
"input": "✍️ Enter new time IN SECONDS",
"handler": self.input_handler,
},
{"text": "+1 sec", "callback": self.increment},
],
[
{"text": "", "callback": self.proceed},
{
"text": "",
"action": "close",
},
],
],
)
async def increment(self, call: InlineCall):
timer = self.get("timer", 0)
timer += 1
self.set("timer", timer)
await call.answer()
await call.edit(
text=self.strings("text").format(timer),
reply_markup=[
[
{
"text": "-1 sec",
"callback": self.decrement,
},
{
"text": "✍️ Enter value",
"input": "✍️ Enter new time IN SECONDS",
"handler": self.input_handler,
},
{"text": "+1 sec", "callback": self.increment},
],
[
{"text": "", "callback": self.proceed},
{
"text": "",
"action": "close",
},
],
],
)
async def input_handler(self, call: InlineCall, query: str):
if not query.isdigit():
await call.answer("Вы ввели не число!")
return
self.set("timer", int(query))
timer = self.get("timer", int(query))
await call.answer()
await call.edit(
text=self.strings("text").format(timer),
reply_markup=[
[
{
"text": "-1 sec",
"callback": self.decrement,
},
{
"text": "✍️ Enter value",
"input": "✍️ Enter new time IN SECONDS",
"handler": self.input_handler,
},
{"text": "+1 sec", "callback": self.increment},
],
[
{"text": "", "callback": self.proceed},
{
"text": "",
"action": "close",
},
],
],
)

View File

@@ -0,0 +1,57 @@
from hikkatl.types import Message
from .. import loader, utils
import requests
# meta developer: @sqlmerr_m
# meta icon: https://github.com/sqlmerr/hikka_mods/blob/main/assets/icons/numberfacts.png?raw=true
# meta banner: https://github.com/sqlmerr/sqlmerr/blob/main/assets/hikka_mods/sqlmerrmodules_numberfacts.png?raw=true
@loader.tds
class NumbersFacts(loader.Module):
"""Interesting facts about numbers | Check the config"""
strings = {
"name": "NumbersFacts",
"noargs": "<emoji document_id=5240241223632954241>🚫</emoji> <b>You didn't enter any arguments</b>",
"indexerror": "<emoji document_id=5240241223632954241>🚫</emoji> <b>You have not entered enough arguments</b>",
"type": "Type of facts about numbers. Trivia is a fact from life, math is a mathematical fact, date and year is a question about a date",
}
string_ru = {
"noargs": "<emoji document_id=5240241223632954241>🚫</emoji> <b>Вы не ввели аргументы</b>",
"indexerror": "<emoji document_id=5240241223632954241>🚫</emoji> <b>Вы ввели недостаточно аргументов</b>",
"type": "Тип фактов о числах. Trivia — факт из жизни, math — математический факт, date и year — вопрос про дату",
}
def __init__(self):
self.config = loader.ModuleConfig(
loader.ConfigValue(
"type",
"math",
lambda: self.strings("type"),
validator=loader.validators.Choice(["date", "math", "year", "trivia"]),
),
)
@loader.command(ru_doc="[число] - получить факт об этом числе")
async def numberfact(self, message: Message):
"""[number] - get fact about number"""
if not (args := utils.get_args_raw(message).split()):
return await utils.answer(message, self.strings("no_args"))
number = args[0]
_type = self.config["type"]
url = f"http://numbersapi.com/{number}/{_type}"
response = await utils.run_sync(requests.get, url)
data = response.text
await utils.answer(
message,
await self._client.translate(
message.peer_id,
message,
to_lang=self._db.get("hikka.translations", "lang")[0:2],
raw_text=data,
entities=message.entities,
),
)

View File

@@ -0,0 +1,130 @@
from hikkatl.tl.types import (
ReplyInlineMarkup,
KeyboardButtonCallback,
KeyboardButtonUrl,
)
from .. import utils, loader
from hikkatl.tl.patched import Message
# meta developer: @sqlmerr_m
# meta icon: https://github.com/sqlmerr/hikka_mods/blob/main/assets/icons/quicktools.png?raw=true
# meta banner: https://github.com/sqlmerr/sqlmerr/blob/main/assets/hikka_mods/quicktools.png?raw=true
@loader.tds
class QuickTools(loader.Module):
"""Module with various quick and useful tools"""
strings = {
"name": "QuickTools",
"id_cmd_text": (
"<emoji document_id=5974526806995242353>🆔</emoji> <b>Id</b>\n"
"<b>·</b> <emoji document_id=5417843850808926945>🫵</emoji> <b>Your id: </b><code>{}</code>\n"
"<b>·</b> <emoji document_id=5443038326535759644>💬</emoji> <b>Chat id:</b> <code>{}</code>\n"
"<b>·</b> <emoji document_id=5366526456274891907>🎈</emoji> <b>User id:</b> <code>{}</code>\n"
"<b>·</b> <emoji document_id=5974187156686507310>💬</emoji> <b>Replied Message id:</b> <code>{}</code>\n"
),
"reply_markup_cmd_text": "<emoji document_id=5397782960512444700>📌</emoji> <b>Buttons:</b>\n{}",
"entity_link_cmd_text": "<emoji document_id=5253577054137362120>🔗</emoji> <b>Your link:</b> {}",
"empty": "Empty",
"no_reply": "<emoji document_id=5210952531676504517>❌</emoji> <b>No reply!</b>",
"no_args": "<emoji document_id=5210952531676504517>❌</emoji> <b>No args!</b>",
"no_reply_markup": "<emoji document_id=5210952531676504517>❌</emoji> No reply markup!",
}
strings_ru = {
"id_cmd_text": (
"<emoji document_id=5974526806995242353>🆔</emoji> <b>Айди</b>\n"
"<b>·</b> <emoji document_id=5417843850808926945>🫵</emoji> <b>Твой айди: </b><code>{}</code>\n"
"<b>·</b> <emoji document_id=5443038326535759644>💬</emoji> <b>Айди чата:</b> <code>{}</code>\n"
"<b>·</b> <emoji document_id=5366526456274891907>🎈</emoji> <b>Айди пользователя:</b> <code>{}</code>\n"
"<b>·</b> <emoji document_id=5974187156686507310>💬</emoji> <b>Айди ответного сообщения:</b> <code>{}</code>\n"
),
"reply_markup_cmd_text": "<emoji document_id=5397782960512444700>📌</emoji> <b>Кнопки:</b>\n{}",
"entity_link_cmd_text": "<emoji document_id=5253577054137362120>🔗</emoji> <b>Ваша ссылка:</b> {}",
"empty": "Отсутствует",
"no_reply": "<emoji document_id=5210952531676504517>❌</emoji> <b>Вы не ответили на сообщение!</b>",
"no_args": "<emoji document_id=5210952531676504517>❌</emoji> <b>Вы не передали аргументы!</b>",
"no_reply_markup": "<emoji document_id=5210952531676504517>❌</emoji> Вы ответили на сообщение, где нет кнопок!",
"_cls_doc": "Модуль с разными быстрыми и полезными инструментами",
}
@loader.command(
ru_doc="<реплай на сообщение> Получить айди пользователя/чата/отправителя/сообщения"
)
async def id(self, message: Message) -> None:
"""<reply to message> Get user/chat/sender/replied message/message ID"""
reply: Message = await message.get_reply_message()
sender_id = message.from_id
chat_id = message.chat_id
user_id = reply.from_id if reply else self.strings("empty")
message_id = reply.id if reply else self.strings("empty")
text = self.strings("id_cmd_text").format(
sender_id, chat_id, user_id, message_id
)
await utils.answer(message, text)
@loader.command(ru_doc="<реплай на сообщение> Получить текст сообщения")
async def text(self, message: Message) -> None:
"""<reply to message> Get replied message text"""
reply: Message = await message.get_reply_message()
text = reply.text if (reply and reply.text) else ""
await utils.answer(message, f"<pre>{utils.escape_html(text)}</pre>")
@loader.command(ru_doc="<реплай на сообщение> Получить кнопки сообщения")
async def reply_markup(self, message: Message) -> None:
"""<reply to message> Get replied message reply markup (buttons)"""
reply: Message = await message.get_reply_message()
if not reply:
await utils.answer(message, self.strings("no_reply"))
return
reply_markup = reply.reply_markup
if not reply_markup or not isinstance(reply_markup, ReplyInlineMarkup):
await utils.answer(message, self.strings("no_reply_markup"))
return
buttons = []
for row in reply_markup.rows:
buttons.extend(row.buttons)
text = ""
for button in buttons:
if isinstance(button, KeyboardButtonCallback):
value = button.data.decode("utf-8")
value_type = "data"
elif isinstance(button, KeyboardButtonUrl):
value = button.url
value_type = "url"
else:
text += f" - <i>{button.text}</i>\n"
continue
text += f" - <i>{button.text}</i> - {value_type}: <code>{value}</code>\n"
await utils.answer(message, self.strings("reply_markup_cmd_text").format(text))
@loader.command()
async def entity_link(self, message: Message) -> None:
"""<bot api entity id> <use open message (optional)> - creates link to entity (chat/user)"""
args = utils.get_args(message)
if len(args) == 0 or not args[0].isdigit() and not args[0].startswith("@"):
await utils.answer(message, self.strings("no_args"))
return
openmessage = bool(args[1]) if len(args) > 1 else False
if args[0].startswith("@"):
entity = await self.client.get_entity(args[0])
else:
entity = await self.client.get_entity(int(args[0]))
link = utils.get_entity_url(entity, openmessage)
await utils.answer(message, self.strings("entity_link_cmd_text").format(link))

View File

@@ -0,0 +1,34 @@
"""
░██████╗░██████╗░██╗░░░░░███╗░░░███╗███████╗██████╗░██████╗░
██╔════╝██╔═══██╗██║░░░░░████╗░████║██╔════╝██╔══██╗██╔══██╗
╚█████╗░██║██╗██║██║░░░░░██╔████╔██║█████╗░░██████╔╝██████╔╝
░╚═══██╗╚██████╔╝██║░░░░░██║╚██╔╝██║██╔══╝░░██╔══██╗██╔══██╗
██████╔╝░╚═██╔═╝░███████╗██║░╚═╝░██║███████╗██║░░██║██║░░██║
╚═════╝░░░░╚═╝░░░╚══════╝╚═╝░░░░░╚═╝╚══════╝╚═╝░░╚═╝╚═╝░░╚═╝
"""
# meta banner: https://github.com/sqlmerr/sqlmerr/blob/main/assets/hikka_mods/sqlmerrmodules_randomemoji.png?raw=true
# meta icon: https://github.com/sqlmerr/hikka_mods/blob/main/assets/icons/random_emoji.png?raw=true
# meta developer: @sqlmerr_m
import requests
from .. import loader, utils
from hikkatl.tl.types import Message
@loader.tds
class RandomEmoji(loader.Module):
"""Just random emojis"""
strings = {"name": "RandomEmoji"}
@loader.command()
async def random_emoji(self, message: Message):
"""Random emoji"""
url = "https://emojihub.yurace.pro/api/random"
emoji = await utils.run_sync(requests.get, url)
emoji = emoji.json()
await utils.answer(message, "".join(html for html in emoji["htmlCode"]))

View File

@@ -0,0 +1,92 @@
"""
░██████╗░██████╗░██╗░░░░░███╗░░░███╗███████╗██████╗░██████╗░
██╔════╝██╔═══██╗██║░░░░░████╗░████║██╔════╝██╔══██╗██╔══██╗
╚█████╗░██║██╗██║██║░░░░░██╔████╔██║█████╗░░██████╔╝██████╔╝
░╚═══██╗╚██████╔╝██║░░░░░██║╚██╔╝██║██╔══╝░░██╔══██╗██╔══██╗
██████╔╝░╚═██╔═╝░███████╗██║░╚═╝░██║███████╗██║░░██║██║░░██║
╚═════╝░░░░╚═╝░░░╚══════╝╚═╝░░░░░╚═╝╚══════╝╚═╝░░╚═╝╚═╝░░╚═╝
"""
# meta developer: @sqlmerr_m
# meta icon: https://github.com/sqlmerr/hikka_mods/blob/main/assets/icons/silentmessages.png?raw=true
# meta banner: https://github.com/sqlmerr/sqlmerr/blob/main/assets/hikka_mods/sqlmerrmodules_silentmessages.png?raw=true
from .. import loader, utils
from hikkatl.tl.patched import Message
@loader.tds
class SilentMessages(loader.Module):
"""With this module you won't miss important messages sent without sound!"""
strings = {
"name": "SilentMessages",
"_cfg_chats": "Chats in which the module will monitor messages without sound",
"_cfg_status": "Is the module working or not?",
"_cfg_text": "The text that will be sent by your inline bot when a silent message is received",
"enabled": "enabled",
"disabled": "disabled",
"toggle_message": "<emoji document_id=5222444124698853913>🔖</emoji> <b>Module {}!</b>",
}
strings_ru = {
"_cfg_chats": "Чаты, в которых модуль будет следить за сообщениями без звука",
"_cfg_status": "Работает ли модуль или нет",
"_cfg_text": "Текст, который будет отправлен вашим инлайн ботом, когда будет получено сообщение без звука",
"enabled": "включен",
"disabled": "выключен",
"toggle_message": "<emoji document_id=5222444124698853913>🔖</emoji> <b>Модуль {}!</b>",
"_cls_doc": "С этим модулем вы не пропустите важные сообщения, отправленные без звука!",
}
def __init__(self):
self.config = loader.ModuleConfig(
loader.ConfigValue(
"chats",
[],
lambda: self.strings("_cfg_chats"),
validator=loader.validators.Series(loader.validators.TelegramID()),
),
loader.ConfigValue(
"status",
False,
lambda: self.strings("_cfg_status"),
validator=loader.validators.Boolean(),
),
loader.ConfigValue(
"text",
"<b>New silent message in chat {chat}:</b> {link}",
lambda: self.strings("_cfg_text"),
validator=loader.validators.String(),
),
)
@loader.command(ru_doc="включить/выключить модуль")
async def silentmessages(self, message: Message):
"""toggle module status"""
self.config["status"] = not self.config["status"]
await utils.answer(
message,
self.strings("toggle_message").format(
self.strings("enabled")
if self.config["status"]
else self.strings("disabled")
),
)
@loader.watcher()
async def watcher(self, message: Message):
if not self.config["status"]:
return
if (
(getattr(message, "chat", None) and message.chat.id in self.config["chats"])
or (
getattr(message, "sender", None)
and message.sender.id in self.config["chats"]
)
) and message.silent is True:
link = await utils.get_message_link(message)
chat_id = utils.get_chat_id(message)
await self.inline.bot.send_message(
self.tg_id, self.config["text"].format(chat=chat_id, link=link)
)

View File

@@ -0,0 +1,167 @@
"""
_
___ __ _| |_ __ ___ ___ _ __ _ __
/ __|/ _` | | '_ ` _ \ / _ \ '__| '__|
\__ \ (_| | | | | | | | __/ | | |
|___/\__, |_|_| |_| |_|\___|_| |_|
|_|
🔒 Licensed under the GNU GPLv3
🌐 https://www.gnu.org/licenses/gpl-3.0.htmla
"""
# meta banner: https://github.com/sqlmerr/hikka_mods/blob/main/assets/banners/translation_manager.png?raw=true
# meta icon: https://github.com/sqlmerr/hikka_mods/blob/main/assets/icons/translation_manager.png?raw=true
# meta developer: @sqlmerr_m
import asyncio
import logging
from .. import loader, utils
from hikkatl.tl.patched import Message
log = logging.getLogger(__name__)
@loader.tds
class TranslationManager(loader.Module):
"""Module for managing external modules translations"""
strings = {
"name": "TranslationManager",
"no_args": "<emoji document_id=5210952531676504517>❌</emoji> No args!",
"get_txt": "<code>`{}`</code> <b>Translation in </b><code>{}</code> <b>module of language </b><code>{}</code><b>:</b>\n<blockquote>{}</blockquote>\n{}",
"custom": "<emoji document_id=5962952497197748583>🔧</emoji> <b>Translation is edited</b>",
"default": "<emoji document_id=5962952497197748583>🔧</emoji> <b>Translation is default</b>",
"404": "<emoji document_id=5210952531676504517>❌</emoji> <b>Module not found!</b>",
"success": "<emoji document_id=5255813619702049821>✅</emoji> <b>Success</b>",
"only_external": "<emoji document_id=5210952531676504517>❌</emoji> <i>You can manage translations in only external mods. To update them use custom language.</i>"
}
strings_ru = {
"no_args": "<emoji document_id=5210952531676504517>❌</emoji> Вы не передали аргументы!",
"get_txt": "<code>`{}`</code> <b>Перевод модуля </b><code>{}</code> <b>в языке </b><code>{}</code><b>:</b>\n<blockquote>{}</blockquote>\n{}",
"custom": "<emoji document_id=5962952497197748583>🔧</emoji> <b>Перевод изменен</b>",
"default": "<emoji document_id=5962952497197748583>🔧</emoji> <b>Перевод стандартный</b>",
"404": "<emoji document_id=5210952531676504517>❌</emoji> <b>Модуль не найден!</b>",
"success": "<emoji document_id=5255813619702049821>✅</emoji> <b>Успешно</b>",
"only_external": "<emoji document_id=5210952531676504517>❌</emoji> <i>Ты можешь управлять переводами только в сторонних модулях. Чтобы изменить их, используй кастомный язык.</i>",
"_cls_doc": "Модуль для управления переводами сторонних модулей"
}
async def client_ready(self):
while not self.lookup("Loader").fully_loaded:
await asyncio.sleep(0.5)
mods = self.get("mods")
if not mods:
return
for mod, tr in mods.items():
module = self.lookup(mod)
if not module:
continue
if module.__origin__.startswith("<core"):
log.info(f"Can't load translations for core module")
continue
for lang, st in tr.items():
for k, v in st.items():
if hasattr(module, f"strings_{lang}"):
strings = getattr(module, f"strings_{lang}")
strings[k] = v
setattr(module, f"strings_{lang}", strings)
else:
module.strings._base_strings[k] = v
log.info("Custom translations loaded")
def get_one(self, mod: str, lang: str, name: str):
if not (strings := self.get("mods", {}).get(mod)) or not strings.get(lang):
module = self.lookup(mod)
if not module:
raise ValueError("404")
if module.__origin__.startswith("<core"):
raise ValueError("only_external")
if hasattr(module, f"strings_{lang}"):
return getattr(module, f"strings_{lang}", {}).get(name)
return module.strings._base_strings.get(name), False
return strings.get(lang, {}).get(name), True
def set_one(self, mod: str, lang: str, name: str, val: str):
module = self.lookup(mod)
if not module:
raise ValueError("404")
if module.__origin__.startswith("<core"):
raise ValueError("only_external")
if hasattr(module, f"strings_{lang}"):
strings = getattr(module, f"strings_{lang}")
strings[name] = val
setattr(module, f"strings_{lang}", strings)
else:
module.strings._base_strings[name] = val
mods = self.get("mods", {})
db_strings = mods.get(mod, {})
lang_strings = db_strings.get(lang, {})
lang_strings[name] = val
db_strings[lang] = lang_strings
mods[mod] = db_strings
self.set("mods", mods)
def del_one(self, mod: str, lang: str, name: str):
mods = self.get("mods", {})
if not ((strings := mods.get(mod)) and strings.get(lang)):
return
lang_strings = strings.get(lang)
if not lang_strings.get(name):
return
del lang_strings[name]
strings[lang] = lang_strings
mods[mod] = strings
self.set("mods", mods)
@loader.command(ru_doc="[модуль] [язык] [ключ] - Получить перевод")
async def trget(self, message: Message):
"""[mod] [lang] [key] - Get current translation"""
if not (args := utils.get_args_raw(message).split()) or len(args) < 3:
await utils.answer(message, self.strings("no_args"))
return
mod, lang, key = args
try:
tr, is_custom = self.get_one(mod, lang, key)
except ValueError as e:
await utils.answer(message, self.strings(e.args[0]))
return
await utils.answer(message, self.strings("get_txt").format(key, mod, lang, utils.escape_html(tr), self.strings("custom") if is_custom else self.strings("default")))
@loader.command(ru_doc="[модуль] [язык] [ключ] [значение] - Изменить перевод")
async def trset(self, message: Message):
"""[mod] [lang] [key] [val] - Set translation"""
if not (args := utils.get_args_raw(message).split(maxsplit=3)) or len(args) < 4:
await utils.answer(message, self.strings("no_args"))
return
mod, lang, key, val = args
try:
self.set_one(mod, lang, key, val)
except ValueError as e:
await utils.answer(message, self.strings(e.args[0]))
return
await utils.answer(message, self.strings("success"))
@loader.command(ru_doc="[модуль] [язык] [ключ] - Удалить кастомный перевод")
async def trdel(self, message: Message):
"""[mod] [lang] [key] - Delete custom translation"""
if not (args := utils.get_args_raw(message).split()) or len(args) < 3:
await utils.answer(message, self.strings("no_args"))
return
mod, lang, key = args
try:
self.del_one(mod, lang, key)
except ValueError as e:
await utils.answer(message, self.strings(e.args[0]))
return
await utils.answer(message, self.strings("success"))

View File

@@ -0,0 +1,930 @@
"""
_
___ __ _| |_ __ ___ ___ _ __ _ __
/ __|/ _` | | '_ ` _ \ / _ \ '__| '__|
\__ \ (_| | | | | | | | __/ | | |
|___/\__, |_|_| |_| |_|\___|_| |_|
|_|
🔒 Licensed under the GNU GPLv3
🌐 https://www.gnu.org/licenses/gpl-3.0.htmla
"""
# meta banner: https://github.com/sqlmerr/hikka_mods/blob/main/assets/banners/triggers.png?raw=true
# meta icon: https://github.com/sqlmerr/hikka_mods/blob/main/assets/icons/triggers.png?raw=true
# meta developer: @sqlmerr_m
# requires: cachetools
import ast
import logging
import asyncio
import json
from contextlib import suppress
from typing import Dict, List, TypedDict, Any, Callable, Optional, Tuple, Union
from meval import meval
from .. import loader, utils
from hikkatl.tl.patched import Message
from cachetools import TTLCache
from ..inline.types import InlineCall
from ..types import JSONSerializable
try:
from ..types import HikkaReplyMarkup
except ImportError:
from ..types import HerokuReplyMarkup as HikkaReplyMarkup
logger = logging.getLogger(__name__)
class Action(TypedDict):
type: str
data: Dict[str, str]
ACTION_TYPES = ["callback", "invoke", "answer", "delete"]
class Filters(TypedDict, total=False):
from_users: List[int]
chats: List[int]
is_admin: bool
contains: bool
ignorecase: bool
class Trigger(TypedDict):
id: int
m: str
action: Action
filters: Filters
delay: float
def dict_updater(obj: Dict[str, Union[dict, Any]], query: str, value: Any) -> None:
keys = query.split(".")
current = obj
for key in keys[:-1]:
if not isinstance(current, dict) or key not in current:
raise ValueError(f"key {key} not found")
current = current[key]
if not isinstance(current, dict) or keys[-1] not in current:
raise ValueError(f"key {keys[-1]} not found")
if not isinstance(current[keys[-1]], type(value)):
raise ValueError(f"value in dict must be the same type as value")
current[keys[-1]] = value
def dict_getter(obj: Dict[str, Union[dict, Any]], query: str) -> Any:
keys = query.split(".")
current = obj
for key in keys[:-1]:
if not isinstance(current, dict) or key not in current:
raise ValueError(f"key {key} not found")
current = current[key]
return current.get(keys[-1])
class TriggerManager:
def __init__(
self,
getter_func: Callable[[str, Optional[JSONSerializable]], JSONSerializable],
setter_func: Callable[[str, JSONSerializable], bool],
) -> None:
self.getter = getter_func
self.setter = setter_func
def get_triggers(self) -> List[Trigger]:
return self.getter("triggers", [])
def get_trigger(self, t_id: int) -> Optional[Trigger]:
triggers = self.get_triggers()
for t in triggers:
if t["id"] == t_id:
return t
def get_trigger_with_index(self, t_id: int) -> Optional[Tuple[int, Trigger]]:
triggers = self.get_triggers()
for i, t in enumerate(triggers):
if t["id"] == t_id:
return i, t
def set_triggers(self, value: List[Trigger]) -> bool:
return self.setter("triggers", value)
def add_trigger(self, value: Trigger) -> bool:
triggers = self.get_triggers()
triggers.append(value)
return self.set_triggers(triggers)
def set_trigger(self, trigger: Trigger) -> bool:
response = self.get_trigger_with_index(trigger["id"])
if not response:
return self.add_trigger(trigger)
i, t = response
triggers = self.get_triggers()
triggers[i] = trigger
return self.set_triggers(triggers)
class Configuration:
def __init__(self, manager: TriggerManager) -> None:
self.manager = manager
def _triggers_menu_markup(self, triggers: List[Trigger]) -> HikkaReplyMarkup:
if len(triggers) > 96:
triggers = triggers[:95]
butttons = [
{
"text": f"ID-{t['id']}",
"callback": self._open_trigger_config,
"kwargs": {"trigger": t},
}
for t in triggers
]
return utils.chunks(butttons, 3)
def _main_menu_markup(self) -> HikkaReplyMarkup:
return [
[{"text": "🔀 Triggers", "callback": self._open_triggers_menu}],
[{"text": "❌ Close", "action": "close"}],
]
def _trigger_config_markup(self, trigger: Trigger) -> HikkaReplyMarkup:
buttons = [
self._input_button(trigger, "m", "message"),
self._input_button(trigger, "delay", "delay"),
{
"text": "🛡 Filters",
"callback": self._open_filters_config_menu,
"kwargs": {"trigger": trigger},
},
{
"text": "💊 Action",
"callback": self._open_action_config_menu,
"kwargs": {"trigger": trigger},
},
{
"text": "⬅️ Back",
"callback": self._open_triggers_menu,
},
]
return utils.chunks(buttons, 2)
def _trigger_filters_markup(self, trigger: Trigger) -> HikkaReplyMarkup:
types = Filters.__annotations__.items()
f = []
for k, v in types:
if v == bool:
f.append(self._bool_filter_config(trigger, k))
elif v == List[int]:
f.append(self._list_int_filter_config(trigger, k))
f.append(
[
{
"text": "⬅️ Back",
"callback": self._open_trigger_config,
"kwargs": {"trigger": trigger},
}
]
)
return f
def _bool_filter_config(self, trigger: Trigger, key: str) -> HikkaReplyMarkup:
async def callback(call: InlineCall) -> None:
val: Optional[bool] = trigger["filters"].get(key)
if val is None:
await call.answer("error: filter not found")
return
trigger["filters"][key] = not val
self.manager.set_trigger(trigger)
await call.answer("")
await self._open_filters_config_menu(call, trigger)
v: Optional[bool] = trigger["filters"].get(key)
if v is None:
trigger["filters"][key] = False
return [
{
"text": f"{'' if not v else ''} {key}",
"callback": callback,
}
]
def _list_int_filter_config(self, trigger: Trigger, key: str) -> HikkaReplyMarkup:
async def callback(call: InlineCall, query: str, action: str) -> None:
val: List[int] = trigger["filters"].get(key)
if val is None:
await call.answer("filter not found")
return
if action == "append":
if not query.isdigit():
logger.error("input value to append must be an integer")
return
val.append(int(query))
elif action == "set":
try:
query = ast.literal_eval(query)
if isinstance(query, int):
val = [query]
elif iter(query) and isinstance(query[0], int):
val = list(query)
else:
raise ValueError(
"input value must be list of integers or integers. For example: [-123, 456, 678]; 123"
)
except (ValueError, TypeError) as e:
logger.warning(f"{query}, {type(query)}")
logger.error(e)
return
elif action == "delete":
try:
query = ast.literal_eval(query)
if not isinstance(query, int):
raise ValueError("input value must be an integer")
with suppress(ValueError):
val.remove(query)
except ValueError as e:
logger.error(e)
return
trigger["filters"][key] = val
self.manager.set_trigger(trigger)
await open_configuration(call)
async def open_configuration(call: InlineCall) -> None:
val: Optional[List[int]] = trigger["filters"].get(key)
if val is None:
val = []
trigger["filters"][key] = val
await call.edit(
text=f"<b>Configuring </b><code>{key}</code><b> of trigger </b><code>{trigger['id']}</code>: \n<code>{val}</code>",
reply_markup=[
[
{
"text": f" Add value",
"input": "✍️ Enter value to append",
"handler": callback,
"kwargs": {"action": "append"},
},
],
[
{
"text": f" Delete value",
"input": "✍️ Enter value to delete",
"handler": callback,
"kwargs": {"action": "delete"},
},
],
[
{
"text": f"✍️ Set",
"input": "✍️ Enter list to replace",
"handler": callback,
"kwargs": {"action": "set"},
}
],
[
{
"text": "⬅️ Back",
"callback": self._open_filters_config_menu,
"kwargs": {"trigger": trigger},
}
],
],
)
return [
{
"text": f"{key} - list[int]",
"callback": open_configuration,
}
]
def _input_button(
self, trigger: Trigger, path: str, title: str
) -> HikkaReplyMarkup:
return {
"text": f"✍️ {title.capitalize()}",
"input": f"✍️ Enter new value for '{title}'",
"handler": self._update_trigger_input_handler,
"kwargs": {
"path": path,
"trigger": trigger,
},
}
def _trigger_config_text(self, trigger: Trigger) -> str:
return f"🛠 <b>Editing trigger with id {trigger['id']}</b>\n\n<code>{utils.escape_html(str(trigger))}</code>"
async def _update_trigger_input_handler(
self, call: InlineCall, query: str, path: str, trigger: Trigger
) -> None:
try:
val = dict_getter(trigger, path)
except ValueError:
await call.answer("error")
return
if val is None:
with suppress(Exception):
value = ast.literal_eval(query)
else:
if not isinstance(val, str):
value = ast.literal_eval(query)
else:
value = query
try:
dict_updater(trigger, path, value)
self.manager.set_trigger(trigger)
except ValueError:
return
await call.edit(
text=self._trigger_config_text(trigger),
reply_markup=self._trigger_config_markup(trigger),
)
async def _open_filters_config_menu(
self, call: InlineCall, trigger: Trigger
) -> None:
markup = self._trigger_filters_markup(trigger)
await call.edit(text="⚙️ <b>Filter configuration</b>", reply_markup=markup)
async def __change_action_type(
self, call: InlineCall, val: str, trigger: Trigger
) -> None:
if val not in ACTION_TYPES:
await call.answer("error")
return
trigger["action"]["type"] = val
self.manager.set_trigger(trigger)
await call.answer("")
await self._open_action_type_config_menu(call, trigger)
async def _open_action_type_config_menu(
self, call: InlineCall, trigger: Trigger
) -> None:
markup = utils.chunks(
[
{
"text": f"{'⚫️' if trigger['action']['type'] == t else '⚪️'} {t}",
"callback": self.__change_action_type,
"kwargs": {"val": t, "trigger": trigger},
}
for t in ACTION_TYPES
],
2,
)
markup.append(
[
{
"text": "⬅️ Back",
"callback": self._open_action_config_menu,
"kwargs": {"trigger": trigger},
}
]
)
await call.edit("⚙️ <b>Select action type:</b>", reply_markup=markup)
async def _open_action_config_menu(
self, call: InlineCall, trigger: Trigger
) -> None:
markup = [
[
{
"text": "♦️ Type",
"callback": self._open_action_type_config_menu,
"kwargs": {"trigger": trigger},
}
],
[self._input_button(trigger, "action.data", "data")],
[
{
"text": "⬅️ Back",
"callback": self._open_trigger_config,
"kwargs": {"trigger": trigger},
}
],
]
await call.edit(
text=f"⚙️ <b>Action configuration</b>\n<code>{utils.escape_html(str(trigger['action']))}</code>",
reply_markup=markup,
)
async def _open_triggers_menu(self, call: InlineCall) -> None:
triggers = self.manager.get_triggers()
markup = self._triggers_menu_markup(triggers)
await call.edit(
text="☰ <b>Select trigger to configure:</b>", reply_markup=markup
)
async def _open_trigger_config(self, call: InlineCall, trigger: Trigger):
markup = self._trigger_config_markup(trigger)
await call.edit(text=self._trigger_config_text(trigger), reply_markup=markup)
async def render_specified_trigger(self, form: Any, message: Message, trigger: Trigger) -> None:
markup = self._trigger_config_markup(trigger)
await form(
text=self._trigger_config_text(trigger),
message=message,
reply_markup=markup
)
async def render(self, form: Any, message: Message) -> None:
await form(
text="⚙️ <b>Triggers Configuration Menu</b>",
message=message,
reply_markup=self._main_menu_markup(),
)
@loader.tds
class Triggers(loader.Module):
"""Triggers watch chat messages and can do anything, reply to a message with a given text, delete a message, execute any userbot command. Overall, a very cool module"""
strings = {
"name": "Triggers",
"_cfg_status": "module working or not",
"_cfg_allow_invoke": "can triggers run ANY userbot commands?",
"_cfg_allow_callback": "can triggers run ANY python code?",
"_cfg_throttle_time": "cooldown between trigger executions",
"no_reply": "<emoji document_id=5210952531676504517>❌</emoji> No reply!",
"no_args": "<emoji document_id=5210952531676504517>❌</emoji> No args!",
"text_add": (
"<emoji document_id=5427009714745517609>✅</emoji> <b>Trigger successfully added</b>\n"
"<i>id:</i> <code>{id}</code>"
),
"empty": " <emoji document_id=5411324253662356461>🫗</emoji> Empty\n",
"text_all": (
"<emoji document_id=5443038326535759644>💬</emoji> <b>Your triggers:</b>\n"
"{triggers}\n"
"<i>in {chats} chats</i>"
),
"chat_added": "<emoji document_id=5456140674028019486>⚡️</emoji> <b>Chat {chat} successfully added</b>",
"chat_removed": "<emoji document_id=5440660757194744323>‼️</emoji> <b>Chat {chat} successfully removed</b>",
"success": "<emoji document_id=5427009714745517609>✅</emoji> <b>Success</b>",
"not_found": "<emoji document_id=5210952531676504517>❌</emoji> <b>Trigger not found!</b>",
"not_valid": "<emoji document_id=5210952531676504517>❌</emoji> <b>Trigger is not valid!</b>",
"error": "<emoji document_id=5210952531676504517>❌</emoji> <b>Unexpected error: {e}</b>",
}
strings_ru = {
"_cfg_status": "Модуль работает или нет",
"_cfg_allow_invoke": "могут ли триггеры запускать ЛЮБЫЕ команды юзербота?",
"_cfg_allow_callback": "могут ли триггеры запускать АБСОЛЮТНО любой код на python?",
"_cfg_throttle_time": "Кд между выполнением триггеров. Для применения изменений требуется перезагрузить модуль/юзербота",
"no_reply": "<emoji document_id=5210952531676504517>❌</emoji> Нет реплая!",
"no_args": "<emoji document_id=5210952531676504517>❌</emoji> Нет аргументов!",
"text_add": (
"<emoji document_id=5427009714745517609>✅</emoji> <b>Триггер успешно добавлен</b>\n"
"<i>id:</i> <code>{id}</code>"
),
"empty": " <emoji document_id=5411324253662356461>🫗</emoji> Пусто\n",
"text_all": (
"<emoji document_id=5443038326535759644>💬</emoji> <b>Ваши триггеры:</b>\n"
"{triggers}\n"
"<i>в {chats} чатах</i>"
),
"chat_added": "<emoji document_id=5456140674028019486>⚡️</emoji> <b>Чат {chat} успешно добавлен</b>",
"chat_removed": "<emoji document_id=5440660757194744323>‼️</emoji> <b>Чат {chat} успешно убран</b>",
"success": "<emoji document_id=5427009714745517609>✅</emoji> <b>Успешно</b>",
"not_found": "<emoji document_id=5210952531676504517>❌</emoji> <b>Триггер не найден!</b>",
"not_valid": "<emoji document_id=5210952531676504517>❌</emoji> <b>Триггер не валиден!</b>",
"error": "<emoji document_id=5210952531676504517>❌</emoji> <b>Неожиданная ошибка. Обратитесь к разработчику модуля или попробуйте изменить данные: {e}</b>",
"_cls_doc": "Триггеры следят за сообщениями в чате и могут сделать что угодно, ответить на сообщение заданным текстом, удалить сообщение, выполнить любую команду юзербота. В общем очень крутой модуль",
}
def __init__(self):
self.config = loader.ModuleConfig(
loader.ConfigValue(
"status",
False,
lambda: self.strings("_cfg_status"),
validator=loader.validators.Boolean(),
),
loader.ConfigValue(
"allow_invoke",
False,
lambda: self.strings("_cfg_allow_invoke"),
validator=loader.validators.Boolean(),
),
loader.ConfigValue(
"allow_callback",
True,
lambda: self.strings("_cfg_allow_callback"),
validator=loader.validators.Boolean(),
),
loader.ConfigValue(
"throttle_time",
1.0,
lambda: self.strings("_cfg_throttle_time"),
validator=loader.validators.Float(minimum=0),
),
)
self.cache = TTLCache(maxsize=10_000, ttl=float(self.config["throttle_time"]))
self.manager = TriggerManager(self.get, self.set)
def increment_trigger_id(self) -> int:
triggers: List[Trigger] = self.get("triggers", [])
if triggers:
return triggers[-1]["id"] + 1
return 0
async def _execute_callback(
self, callback_id: str, message: Message, trigger: Trigger
) -> None:
callbacks: Dict[str, int] = self.get("callbacks", {})
if not (asset_id := callbacks.get(callback_id)):
logger.error("callback with id %s not found", callback_id)
return
asset: Optional[Message] = await self.db.fetch_asset(asset_id)
if not asset:
logger.error("callback code not found", asset_id)
return
code = asset.text
reply = await message.get_reply_message()
kwargs = {
"client": self.client,
"c": self.client,
"message": message,
"m": message,
"reply": reply,
"r": reply,
"trigger": trigger,
"t": trigger,
"utils": utils,
}
try:
await meval(code, globals(), **kwargs)
except Exception as e:
logger.exception("callback code error: %s", e)
@loader.command(
ru_doc="[текст, на который будет тригеррится модуль] <реплай на текст ответа> - Добавить базовый триггер",
alias="taddbase",
)
async def triggeraddbase(self, message: Message):
"""[text that the module will trigger on] <reply on the response text> - Add base trigger"""
triggers = self.get("triggers", [])
args = utils.get_args_raw(message)
if not args:
await utils.answer(message, self.strings("no_args"))
return
reply = await message.get_reply_message()
if not reply or not reply.text:
await utils.answer(message, self.strings("no_reply"))
return
trigger = Trigger(
m=args,
id=self.increment_trigger_id(),
action=Action(type="answer", data={"text": reply.text}),
delay=0,
filters=Filters(),
)
triggers.append(trigger)
self.set("triggers", triggers)
text = self.strings("text_add").format(id=trigger["id"])
await utils.answer(message, text)
@loader.command(ru_doc="[триггер] - Добавить триггер из сырых данных", alias="tadd")
async def triggeradd(self, message: Message):
"""[trigger] - Add a trigger from raw data"""
args = utils.get_args_raw(message)
if not args:
await utils.answer(message, self.strings("no_args"))
return
trigger = json.loads(args)
if (
not isinstance(trigger, dict)
or not trigger.get("m")
or not trigger.get("action")
or not trigger.get("filters")
):
return
trigger["id"] = self.increment_trigger_id()
if not trigger.get("delay") or trigger["delay"] < 0:
trigger["delay"] = 0
self.manager.add_trigger(trigger)
text = self.strings("text_add").format(id=trigger["id"])
await utils.answer(message, text)
@loader.command(ru_doc="Посмотреть все триггеры")
async def triggers(self, message: Message):
"""View all triggers"""
triggers = self.manager.get_triggers()
t = ""
if not triggers:
t = self.strings("empty")
else:
for trigger in triggers:
t += f"{trigger['m']} {trigger['id']} action={trigger['action']['type'].lower()};\n"
text = self.strings("text_all").format(
triggers=t, chats=len(self.get("chats", []))
)
await utils.answer(message, text)
@loader.command(ru_doc="Добавить чат, где будут работать триггеры", alias="tchat")
async def triggerchat(self, message: Message):
"""Add chat, where triggers will work"""
chats = self.get("chats", [])
chat_id = utils.get_chat_id(message)
flag = False
if chat_id not in chats:
chats.append(chat_id)
flag = True
else:
chats.remove(chat_id)
self.set("chats", chats)
text = (
self.strings("chat_added").format(chat=chat_id)
if flag
else self.strings("chat_removed").format(chat=chat_id)
)
await utils.answer(message, text)
@loader.command(ru_doc="[необязятельно: айди триггера] - Конфиг модуля")
async def tconfig(self, message: Message):
"""[optional: trigger id] - Triggers config."""
config = Configuration(self.manager)
args = utils.get_args(message)
if len(args) < 1 or not args[0].isdigit():
await config.render(self.inline.form, message)
return
tid = int(args[0])
trigger = self.manager.get_trigger(tid)
if not trigger:
await config.render(self.inline.form, message)
return
await config.render_specified_trigger(self.inline.form, message, trigger)
@loader.command(ru_doc="[айди триггера] - Удалить триггер", alias="tdel")
async def triggerdel(self, message: Message):
"""[trigger's id] - Delete trigger"""
args = utils.get_args_raw(message).split()
if not args:
await utils.answer(message, self.strings("no_args"))
return
if not args[0].isdigit():
await utils.answer(
message, self.strings("error").format("Input id must be an integer")
)
return
triggers = self.manager.get_triggers()
for trigger in triggers:
if trigger["id"] == int(args[0]):
triggers.remove(trigger)
self.manager.set_triggers(triggers)
await utils.answer(message, self.strings("success"))
return
await utils.answer(message, self.strings("not_found"))
@loader.command(ru_doc="[айди колбека: str] <реплай на пайтон код> - Добавить колбек, который триггер сможет выполнить")
async def tcallback(self, message: Message):
"""[callback_id: str] <reply to python code> - Add a callback that trigger can execute"""
args = utils.get_args_raw(message).split()
if not args:
await utils.answer(message, self.strings("no_args"))
return
callback_id = args[0]
reply = await message.get_reply_message()
if not reply or not reply.raw_text:
await utils.answer(message, self.strings("no_reply"))
return
asset_id = await self.db.store_asset(reply)
callbacks = self.get("callbacks", {})
callbacks[callback_id] = asset_id
self.set("callbacks", callbacks)
await utils.answer(message, self.strings("success"))
@loader.command(ru_doc="[айди триггера] - Получить триггер", alias="tget")
async def triggerget(self, message: Message):
"""[trigger's id] - Get trigger"""
args = utils.get_args_raw(message).split()
if not args:
await utils.answer(message, self.strings("no_args"))
return
if not args[0].isdigit():
await utils.answer(
message, self.strings("error").format("Input id must be an integer")
)
return
trigger = self.manager.get_trigger(int(args[0]))
if trigger:
await utils.answer(message, f"<code>{trigger}</code>")
return
await utils.answer(message, self.strings("not_found"))
@loader.command(
ru_doc="[айди триггера] [измененный триггер] - Изменить триггер", alias="tset"
)
async def triggerset(self, message: Message):
"""[trigger's id] [edited trigger] - Edit trigger"""
args = utils.get_args_raw(message).split(maxsplit=1)
if not args:
await utils.answer(message, self.strings("no_args"))
return
if len(args) < 2:
await utils.answer(message, self.strings("no_args"))
return
if not args[0].isdigit():
await utils.answer(
message, self.strings("error").format("Input id must be an integer")
)
return
trigger_id = int(args[0])
trigger = self.manager.get_trigger(trigger_id)
if not trigger:
await utils.answer(message, self.strings("not_found"))
return
try:
new_trigger = json.loads(args[1])
keys = new_trigger.keys()
if not isinstance(new_trigger, dict) or not any(k in keys for k in keys):
raise ValueError(
"trigger must be in JSON format and must have 'm' and 'action'"
)
new_trigger["id"] = trigger["id"]
if not new_trigger.get("delay") or new_trigger["delay"] < 0:
new_trigger["delay"] = 0
self.manager.set_trigger(new_trigger)
except Exception as e:
await utils.answer(message, self.strings("error").format(e=e))
return
await utils.answer(message, self.strings("success"))
@loader.command(
ru_doc="[айди триггера] [путь] [значение] - Изменить одно значение триггера",
alias="tupd",
)
async def triggerupdate(self, message: Message):
"""[trigger's id] [path] [value] - Edit trigger"""
args = utils.get_args_raw(message).split(maxsplit=2)
if not args or len(args) < 3:
await utils.answer(message, self.strings("no_args"))
return
if not args[0].isdigit():
await utils.answer(
message, self.strings("error").format("Input id must be an integer")
)
return
trigger = self.manager.get_trigger(int(args[0]))
if not trigger:
await utils.answer(message, self.strings("not_found"))
return
path = args[1]
value = args[2]
try:
tvalue = dict_getter(trigger, "value")
except Exception as e:
await utils.answer(message, self.strings("error").format(e=e))
return
if tvalue is None:
with suppress(Exception):
value = ast.literal_eval(value)
else:
if not isinstance(tvalue, str):
value = ast.literal_eval(tvalue)
try:
dict_updater(trigger, path, value)
self.manager.set_trigger(trigger)
except Exception as e:
await utils.answer(message, self.strings("error").format(e=e))
return
await utils.answer(message, self.strings("success"))
@loader.watcher()
async def triggers_handler(self, message: Message):
if not self.config["status"]:
return
if not message.text:
return
chats = self.get("chats", [])
chat_id = utils.get_chat_id(message)
if chat_id not in chats:
return
triggers = self.manager.get_triggers()
if not triggers:
return
t = []
for trigger in triggers:
if (
trigger["filters"].get("chats") is not None
and chat_id not in trigger["filters"]["chats"]
):
continue
if (
trigger["filters"].get("from_users") is not None
and message.from_id not in trigger["filters"]["from_users"]
):
continue
if trigger["filters"].get("ignorecase"):
message.text = message.text.lower()
trigger["m"] = trigger["m"].lower()
if message.text == trigger["m"]:
t.append(trigger)
continue
if trigger["filters"].get("contains") and trigger["m"] in message.text:
t.append(trigger)
for trigger in t:
if trigger["id"] in self.cache:
continue
else:
self.cache[trigger["id"]] = None
action_type = trigger["action"]["type"]
if trigger["delay"] != 0:
await asyncio.sleep(trigger["delay"])
if action_type == "answer":
await message.reply(
trigger["action"]["data"]["text"].format(text=message.text)
)
elif action_type == "delete":
await message.delete()
elif action_type == "invoke":
if self.config["allow_invoke"]:
await self.invoke(
trigger["action"]["data"].get("command"),
trigger["action"]["data"].get("args", ""),
message=message,
)
elif action_type == "callback":
if self.config["allow_callback"]:
callback_id = trigger["action"].get("data", {}).get("callback_id")
if not callback_id:
logger.warning(
"callback_id not set in trigger %s", trigger["id"]
)
continue
await self._execute_callback(callback_id, message, trigger)
else:
logger.error(
f"unknown action type {action_type} of trigger {trigger['id']}"
)

View File

@@ -0,0 +1,459 @@
import datetime
import io
import contextlib
import logging
import sys
import typing
import aiohttp
from enum import Enum
from meval import meval
from dataclasses import dataclass, field
from hikkatl.errors.rpcerrorlist import MessageIdInvalidError
from hikkatl.types import Message
from .. import loader, utils
from ..inline.types import InlineCall
from ..log import HikkaException
try:
from ..types import HikkaReplyMarkup
except ImportError:
from ..types import HerokuReplyMarkup as HikkaReplyMarkup
# meta banner: https://github.com/sqlmerr/hikka_mods/blob/main/assets/banners/upgradedeval.png?raw=true
# meta icon: https://github.com/sqlmerr/hikka_mods/blob/main/assets/icons/upgradedeval.png?raw=true
# meta developer: @sqlmerr_m
ITEMS_PER_PAGE = 6
EMOJIS = {
"python": "<emoji document_id=5197646705813634076>🐍</emoji>",
"kotlin": "<emoji document_id=5278725341785889330>👩‍💻</emoji>",
"rust": "<emoji document_id=5278586051701514918>🦀</emoji>",
"go": "<emoji document_id=5278401118999682984>🐹</emoji>",
}
class LanguageEnum(str, Enum):
python = "python"
rust = "rust"
kotlin = "kotlin"
go = "go"
@dataclass(frozen=True)
class EvaluationInfo:
code: str
language: LanguageEnum = field(default=LanguageEnum.python)
result: typing.Optional[str] = field(default=None)
error: typing.Optional[typing.Union[HikkaException, str]] = field(default=None)
is_error: bool = field(default=False)
date: datetime.datetime = field(default_factory=datetime.datetime.now)
@loader.tds
class UpgradedEval(loader.Module):
"""Just eval with customizable text and stdout"""
strings = {
"name": "UpgradedEval",
"_cfg_text_result": "Text for result",
"_cfg_text_error": "Text for error",
"_cfg_text_result_and_error": "Text containing both error and result",
"_cfg_mode": "Code run mode. stdout is when print works. return, this is standard .e; auto is just a mode that automatically selects stdout or return",
}
strings_ru = {
"_cfg_text_result": "Текст результата",
"_cfg_text_error": "Текст ошибки",
"_cfg_text_result_and_error": "Текст содержащий и ошибку и результат",
"_cfg_mode": "Режим запуска кода. stdout, это когда работает print. return, это стандартный .e; auto - это просто режим, который автоматически выбирает stdout или return",
}
def __init__(self):
self.config = loader.ModuleConfig(
loader.ConfigValue(
"text_result",
(
"<b><i>Language:</i></b> <code>{lang}</code>\n"
"{emoji} <b><i>Code:</i></b>\n"
"<code><pre class='language-{lang}'>{code}</pre></code>\n\n"
"<emoji document_id=5895231943955451762>✅</emoji> <b><i>Result:</i></b>\n"
"<code><pre class='language-{lang}'>{result}</pre></code>"
),
lambda: self.strings("_cfg_text_result"),
validator=loader.validators.String(),
),
loader.ConfigValue(
"text_error",
(
"<b><i>Language:</i></b> <code>{lang}</code>\n"
"{emoji} <b><i>Code:</i></b>\n"
"<code><pre>{code}</pre></code>\n\n"
"<emoji document_id=5465665476971471368>❌</emoji> <b><i>Error:</i></b>\n"
"<code><pre class='language-{lang}'>{error}</pre></code>"
),
lambda: self.strings("_cfg_text_error"),
validator=loader.validators.String(),
),
loader.ConfigValue(
"text_result_and_error",
(
"<b><i>Language:</i></b> <code>{lang}</code>\n"
"{emoji} <b><i>Code:</i></b>\n"
"<code><pre>{code}</pre></code>\n\n"
"<emoji document_id=5895231943955451762>✅</emoji> <b><i>Result:</i></b>\n"
"<code><pre class='language-{lang}'>{result}</pre></code>\n\n"
"<emoji document_id=5465665476971471368>❌</emoji> <b><i>Error:</i></b>\n"
"<code><pre class='language-{lang}'>{error}</pre></code>"
),
lambda: self.strings("_cfg_text_result_and_error"),
validator=loader.validators.String()
),
loader.ConfigValue(
"mode",
"auto",
lambda: self.strings("_cfg_mode"),
validator=loader.validators.Choice(["stdout", "return", "auto"]),
),
)
self._evals: typing.List[EvaluationInfo] = []
async def __inline_open_eval(self, call: InlineCall, eval_info: EvaluationInfo, current_page: int):
if not eval_info.is_error:
text = self.config["text_result"].format(
emoji=EMOJIS[eval_info.language.lower()],
lang=eval_info.language.lower(),
code=utils.escape_html(eval_info.code) if eval_info.code else "None",
result=eval_info.result if eval_info.result else "None",
)
else:
if eval_info.language == LanguageEnum.python and isinstance(eval_info.error, HikkaException):
error = (
self.lookup("Evaluator").censor(
(
"\n".join(eval_info.error.full_stack.splitlines()[:-1])
+ "\n\n"
+ "🚫 "
+ eval_info.error.full_stack.splitlines()[-1]
)
),
)
text = self.config["text_error"].format(
emoji=EMOJIS["python"], lang="python", code=utils.escape_html(eval_info.code), error=error[0]
)
else:
error = eval_info.error
text = self.config["text_result_and_error"].format(
lang=eval_info.language.lower(), code=utils.escape_html(eval_info.code), result=eval_info.result, error=error
)
await call.edit(
text=text,
reply_markup={
"text": "",
"callback": self.__inline_open,
"args": (current_page,)
}
)
async def __inline_open(self, call: InlineCall, page: int = 0):
await call.edit(
text="📋 <b>Evaluation history</b>",
reply_markup=self.__inline_generate_keyboard(self._evals, page),
)
def __inline_generate_keyboard(self, evals: typing.List[EvaluationInfo], page: int = 0):
if len(evals) == 0:
return []
# Sort evals in descending order based on date to ensure newest first
sorted_evals = sorted(evals, key=lambda x: x.date, reverse=True)
offset = page * ITEMS_PER_PAGE
if offset < 0 or offset >= len(sorted_evals):
page = 0
offset = 0
# Slice evaluations for the current page
page_evals = sorted_evals[offset:offset + ITEMS_PER_PAGE]
buttons = []
# Generate buttons for evaluations on current page (no reverse)
for e in page_evals:
buttons.append(
[{
"text": f"{e.date.strftime('%Y-%m-%d %H:%M:%S')} {'' if not e.is_error else ''} {e.language.capitalize()}",
"callback": self.__inline_open_eval,
"args": (e, page)
}]
)
# Navigation buttons
nav_buttons = []
if offset > 0:
nav_buttons.append({
"text": "<",
"callback": self.__inline_open,
"args": (page - 1,)
})
else:
nav_buttons.append({
"text": "X",
"data": "empty"
})
nav_buttons.append({
"text": f"{page + 1}/{(len(evals) + ITEMS_PER_PAGE - 1) // ITEMS_PER_PAGE}",
"data": "empty"
})
if offset + ITEMS_PER_PAGE < len(sorted_evals):
nav_buttons.append({
"text": ">",
"callback": self.__inline_open,
"args": (page + 1,)
})
else:
nav_buttons.append({
"text": "X",
"data": "empty"
})
if nav_buttons:
buttons.append(nav_buttons)
return buttons
@loader.command(ru_doc="Получить историю (с рестарта юзербота)")
async def ehistory(self, message: Message):
"""Get history (since userbot restart)"""
await self.inline.form(
text="📋 <b>Evaluation history</b>",
message=message,
reply_markup=self.__inline_generate_keyboard(self._evals),
)
@loader.command(ru_doc="Улучшенный eval")
async def ie(self, message: Message):
"""Upgraded eval"""
args = utils.get_args_raw(message)
try:
attrs = await self.lookup("Evaluator").getattrs(message)
stdout = io.StringIO()
with contextlib.redirect_stdout(stdout):
result = await meval(
utils.escape_html(args),
globals(),
**attrs,
)
output = stdout.getvalue()
except Exception:
item = HikkaException.from_exc_info(*sys.exc_info())
error = (
self.lookup("Evaluator").censor(
(
"\n".join(item.full_stack.splitlines()[:-1])
+ "\n\n"
+ "🚫 "
+ item.full_stack.splitlines()[-1]
)
),
)
await utils.answer(
message,
self.config["text_error"].format(
emoji=EMOJIS["python"],
lang="python",
code=utils.escape_html(utils.get_args_raw(message)), error=error[0]
),
)
self._evals.append(EvaluationInfo(
args,
error=item,
is_error=True,
))
return
mode = self.config["mode"]
if mode == "stdout":
result = output
elif mode == "auto" and output.strip():
result = output
if callable(getattr(result, "stringify", None)):
with contextlib.suppress(Exception):
result = str(result.stringify())
with contextlib.suppress(MessageIdInvalidError):
await utils.answer(
message,
self.config["text_result"].format(
emoji=EMOJIS["python"],
lang="python",
code=utils.escape_html(args) if args else "None",
result=result if result else "None",
),
)
self._evals.append(EvaluationInfo(
args,
result=result,
))
@loader.command(ru_doc="Запустить код на Rust")
async def erust(self, message: Message):
"""Evaluate Rust code"""
code = utils.get_args_raw(message)
url = "https://play.rust-lang.org/execute"
payload = {
"channel": "stable",
"mode": "debug",
"edition": "2024",
"crateType": "bin",
"tests": False,
"code": code
}
headers = {"Content-Type": "application/json"}
async with aiohttp.ClientSession() as session:
async with session.post(url, json=payload, headers=headers, timeout=10) as response:
response.raise_for_status()
result = await response.json()
output = result.get("stdout", "")
errors = result.get("stderr", "")
with contextlib.suppress(MessageIdInvalidError):
await utils.answer(
message,
self.config["text_result_and_error"].format(
emoji=EMOJIS["rust"],
lang="rust",
code=utils.escape_html(code) if code else "None",
result=output,
error=errors,
),
)
self._evals.append(EvaluationInfo(code, LanguageEnum.rust, result=output, error=errors, is_error=errors!=""))
@loader.command(ru_doc="Запустить код на Go")
async def ego(self, message: Message):
"""Evaluate Go code"""
code = utils.get_args_raw(message)
url = "https://play.golang.org/compile"
payload = {
"version": 2,
"body": code,
"withVet": False
}
headers = {"Content-Type": "application/x-www-form-urlencoded"}
async with aiohttp.ClientSession() as session:
async with session.post(url, data=payload, headers=headers, timeout=10) as response:
response.raise_for_status()
result = await response.json()
output = ""
if result.get("Events"):
for event in result["Events"]:
if event.get("Kind") == "stdout":
output += event.get("Message", "")
errors = result.get("Errors", "")
if errors:
with contextlib.suppress(MessageIdInvalidError):
await utils.answer(
message,
self.config["text_result_and_error"].format(
emoji=EMOJIS["go"],
lang="go",
code=utils.escape_html(code) if code else "None",
result=output,
error=errors,
),
)
else:
with contextlib.suppress(MessageIdInvalidError):
await utils.answer(
message,
self.config["text_result"].format(
emoji=EMOJIS["go"],
lang="go",
code=utils.escape_html(code) if code else "None",
result=output,
),
)
self._evals.append(EvaluationInfo(code, LanguageEnum.go, result=output, error=errors, is_error=errors!=""))
@loader.command(ru_doc="Запустить код на Kotlin")
async def ekt(self, message: Message):
"""Evaluate Kotlin code"""
code = utils.get_args_raw(message)
url = "https://api.kotlinlang.org/api/2.1.20/compiler/run"
payload = {
"args": "",
"conftype": "java",
"files": [
{
"name": "Main.kt",
"publicId": "",
"text": code
}
]
}
headers = {"Content-Type": "application/json"}
async with aiohttp.ClientSession() as session:
async with session.post(url, json=payload, headers=headers, timeout=10) as response:
response.raise_for_status()
result = await response.json()
output = result.get("text", "")
errors = result.get("errors", {}).get("Main.kt", [])
error = ""
for err in errors:
error += f"- {err.get('message')}\n"
if errors:
with contextlib.suppress(MessageIdInvalidError):
await utils.answer(
message,
self.config["text_result_and_error"].format(
emoji=EMOJIS["kotlin"],
lang="kotlin",
code=utils.escape_html(code) if code else "None",
result=output,
error=error,
),
)
else:
with contextlib.suppress(MessageIdInvalidError):
await utils.answer(
message,
self.config["text_result"].format(
emoji=EMOJIS["kotlin"],
lang="kotlin",
code=utils.escape_html(code) if code else "None",
result=output,
),
)
self._evals.append(EvaluationInfo(code, LanguageEnum.kotlin, result=output, error=errors, is_error=errors!=[]))