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

402
unneyon/hikka-mods/LICENSE Normal file
View File

@@ -0,0 +1,402 @@
Attribution-NonCommercial-NoDerivatives 4.0 International
=======================================================================
Creative Commons Corporation ("Creative Commons") is not a law firm and
does not provide legal services or legal advice. Distribution of
Creative Commons public licenses does not create a lawyer-client or
other relationship. Creative Commons makes its licenses and related
information available on an "as-is" basis. Creative Commons gives no
warranties regarding its licenses, any material licensed under their
terms and conditions, or any related information. Creative Commons
disclaims all liability for damages resulting from their use to the
fullest extent possible.
Using Creative Commons Public Licenses
Creative Commons public licenses provide a standard set of terms and
conditions that creators and other rights holders may use to share
original works of authorship and other material subject to copyright
and certain other rights specified in the public license below. The
following considerations are for informational purposes only, are not
exhaustive, and do not form part of our licenses.
Considerations for licensors: Our public licenses are
intended for use by those authorized to give the public
permission to use material in ways otherwise restricted by
copyright and certain other rights. Our licenses are
irrevocable. Licensors should read and understand the terms
and conditions of the license they choose before applying it.
Licensors should also secure all rights necessary before
applying our licenses so that the public can reuse the
material as expected. Licensors should clearly mark any
material not subject to the license. This includes other CC-
licensed material, or material used under an exception or
limitation to copyright. More considerations for licensors:
wiki.creativecommons.org/Considerations_for_licensors
Considerations for the public: By using one of our public
licenses, a licensor grants the public permission to use the
licensed material under specified terms and conditions. If
the licensor's permission is not necessary for any reason--for
example, because of any applicable exception or limitation to
copyright--then that use is not regulated by the license. Our
licenses grant only permissions under copyright and certain
other rights that a licensor has authority to grant. Use of
the licensed material may still be restricted for other
reasons, including because others have copyright or other
rights in the material. A licensor may make special requests,
such as asking that all changes be marked or described.
Although not required by our licenses, you are encouraged to
respect those requests where reasonable. More considerations
for the public:
wiki.creativecommons.org/Considerations_for_licensees
=======================================================================
Creative Commons Attribution-NonCommercial-NoDerivatives 4.0
International Public License
By exercising the Licensed Rights (defined below), You accept and agree
to be bound by the terms and conditions of this Creative Commons
Attribution-NonCommercial-NoDerivatives 4.0 International Public
License ("Public License"). To the extent this Public License may be
interpreted as a contract, You are granted the Licensed Rights in
consideration of Your acceptance of these terms and conditions, and the
Licensor grants You such rights in consideration of benefits the
Licensor receives from making the Licensed Material available under
these terms and conditions.
Section 1 -- Definitions.
a. Adapted Material means material subject to Copyright and Similar
Rights that is derived from or based upon the Licensed Material
and in which the Licensed Material is translated, altered,
arranged, transformed, or otherwise modified in a manner requiring
permission under the Copyright and Similar Rights held by the
Licensor. For purposes of this Public License, where the Licensed
Material is a musical work, performance, or sound recording,
Adapted Material is always produced where the Licensed Material is
synched in timed relation with a moving image.
b. Copyright and Similar Rights means copyright and/or similar rights
closely related to copyright including, without limitation,
performance, broadcast, sound recording, and Sui Generis Database
Rights, without regard to how the rights are labeled or
categorized. For purposes of this Public License, the rights
specified in Section 2(b)(1)-(2) are not Copyright and Similar
Rights.
c. Effective Technological Measures means those measures that, in the
absence of proper authority, may not be circumvented under laws
fulfilling obligations under Article 11 of the WIPO Copyright
Treaty adopted on December 20, 1996, and/or similar international
agreements.
d. Exceptions and Limitations means fair use, fair dealing, and/or
any other exception or limitation to Copyright and Similar Rights
that applies to Your use of the Licensed Material.
e. Licensed Material means the artistic or literary work, database,
or other material to which the Licensor applied this Public
License.
f. Licensed Rights means the rights granted to You subject to the
terms and conditions of this Public License, which are limited to
all Copyright and Similar Rights that apply to Your use of the
Licensed Material and that the Licensor has authority to license.
g. Licensor means the individual(s) or entity(ies) granting rights
under this Public License.
h. NonCommercial means not primarily intended for or directed towards
commercial advantage or monetary compensation. For purposes of
this Public License, the exchange of the Licensed Material for
other material subject to Copyright and Similar Rights by digital
file-sharing or similar means is NonCommercial provided there is
no payment of monetary compensation in connection with the
exchange.
i. Share means to provide material to the public by any means or
process that requires permission under the Licensed Rights, such
as reproduction, public display, public performance, distribution,
dissemination, communication, or importation, and to make material
available to the public including in ways that members of the
public may access the material from a place and at a time
individually chosen by them.
j. Sui Generis Database Rights means rights other than copyright
resulting from Directive 96/9/EC of the European Parliament and of
the Council of 11 March 1996 on the legal protection of databases,
as amended and/or succeeded, as well as other essentially
equivalent rights anywhere in the world.
k. You means the individual or entity exercising the Licensed Rights
under this Public License. Your has a corresponding meaning.
Section 2 -- Scope.
a. License grant.
1. Subject to the terms and conditions of this Public License,
the Licensor hereby grants You a worldwide, royalty-free,
non-sublicensable, non-exclusive, irrevocable license to
exercise the Licensed Rights in the Licensed Material to:
a. reproduce and Share the Licensed Material, in whole or
in part, for NonCommercial purposes only; and
b. produce and reproduce, but not Share, Adapted Material
for NonCommercial purposes only.
2. Exceptions and Limitations. For the avoidance of doubt, where
Exceptions and Limitations apply to Your use, this Public
License does not apply, and You do not need to comply with
its terms and conditions.
3. Term. The term of this Public License is specified in Section
6(a).
4. Media and formats; technical modifications allowed. The
Licensor authorizes You to exercise the Licensed Rights in
all media and formats whether now known or hereafter created,
and to make technical modifications necessary to do so. The
Licensor waives and/or agrees not to assert any right or
authority to forbid You from making technical modifications
necessary to exercise the Licensed Rights, including
technical modifications necessary to circumvent Effective
Technological Measures. For purposes of this Public License,
simply making modifications authorized by this Section 2(a)
(4) never produces Adapted Material.
5. Downstream recipients.
a. Offer from the Licensor -- Licensed Material. Every
recipient of the Licensed Material automatically
receives an offer from the Licensor to exercise the
Licensed Rights under the terms and conditions of this
Public License.
b. No downstream restrictions. You may not offer or impose
any additional or different terms or conditions on, or
apply any Effective Technological Measures to, the
Licensed Material if doing so restricts exercise of the
Licensed Rights by any recipient of the Licensed
Material.
6. No endorsement. Nothing in this Public License constitutes or
may be construed as permission to assert or imply that You
are, or that Your use of the Licensed Material is, connected
with, or sponsored, endorsed, or granted official status by,
the Licensor or others designated to receive attribution as
provided in Section 3(a)(1)(A)(i).
b. Other rights.
1. Moral rights, such as the right of integrity, are not
licensed under this Public License, nor are publicity,
privacy, and/or other similar personality rights; however, to
the extent possible, the Licensor waives and/or agrees not to
assert any such rights held by the Licensor to the limited
extent necessary to allow You to exercise the Licensed
Rights, but not otherwise.
2. Patent and trademark rights are not licensed under this
Public License.
3. To the extent possible, the Licensor waives any right to
collect royalties from You for the exercise of the Licensed
Rights, whether directly or through a collecting society
under any voluntary or waivable statutory or compulsory
licensing scheme. In all other cases the Licensor expressly
reserves any right to collect such royalties, including when
the Licensed Material is used other than for NonCommercial
purposes.
Section 3 -- License Conditions.
Your exercise of the Licensed Rights is expressly made subject to the
following conditions.
a. Attribution.
1. If You Share the Licensed Material, You must:
a. retain the following if it is supplied by the Licensor
with the Licensed Material:
i. identification of the creator(s) of the Licensed
Material and any others designated to receive
attribution, in any reasonable manner requested by
the Licensor (including by pseudonym if
designated);
ii. a copyright notice;
iii. a notice that refers to this Public License;
iv. a notice that refers to the disclaimer of
warranties;
v. a URI or hyperlink to the Licensed Material to the
extent reasonably practicable;
b. indicate if You modified the Licensed Material and
retain an indication of any previous modifications; and
c. indicate the Licensed Material is licensed under this
Public License, and include the text of, or the URI or
hyperlink to, this Public License.
For the avoidance of doubt, You do not have permission under
this Public License to Share Adapted Material.
2. You may satisfy the conditions in Section 3(a)(1) in any
reasonable manner based on the medium, means, and context in
which You Share the Licensed Material. For example, it may be
reasonable to satisfy the conditions by providing a URI or
hyperlink to a resource that includes the required
information.
3. If requested by the Licensor, You must remove any of the
information required by Section 3(a)(1)(A) to the extent
reasonably practicable.
Section 4 -- Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights that
apply to Your use of the Licensed Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
to extract, reuse, reproduce, and Share all or a substantial
portion of the contents of the database for NonCommercial purposes
only and provided You do not Share Adapted Material;
b. if You include all or a substantial portion of the database
contents in a database in which You have Sui Generis Database
Rights, then the database in which You have Sui Generis Database
Rights (but not its individual contents) is Adapted Material; and
c. You must comply with the conditions in Section 3(a) if You Share
all or a substantial portion of the contents of the database.
For the avoidance of doubt, this Section 4 supplements and does not
replace Your obligations under this Public License where the Licensed
Rights include other Copyright and Similar Rights.
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
c. The disclaimer of warranties and limitation of liability provided
above shall be interpreted in a manner that, to the extent
possible, most closely approximates an absolute disclaimer and
waiver of all liability.
Section 6 -- Term and Termination.
a. This Public License applies for the term of the Copyright and
Similar Rights licensed here. However, if You fail to comply with
this Public License, then Your rights under this Public License
terminate automatically.
b. Where Your right to use the Licensed Material has terminated under
Section 6(a), it reinstates:
1. automatically as of the date the violation is cured, provided
it is cured within 30 days of Your discovery of the
violation; or
2. upon express reinstatement by the Licensor.
For the avoidance of doubt, this Section 6(b) does not affect any
right the Licensor may have to seek remedies for Your violations
of this Public License.
c. For the avoidance of doubt, the Licensor may also offer the
Licensed Material under separate terms or conditions or stop
distributing the Licensed Material at any time; however, doing so
will not terminate this Public License.
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
License.
Section 7 -- Other Terms and Conditions.
a. The Licensor shall not be bound by any additional or different
terms or conditions communicated by You unless expressly agreed.
b. Any arrangements, understandings, or agreements regarding the
Licensed Material not stated herein are separate from and
independent of the terms and conditions of this Public License.
Section 8 -- Interpretation.
a. For the avoidance of doubt, this Public License does not, and
shall not be interpreted to, reduce, limit, restrict, or impose
conditions on any use of the Licensed Material that could lawfully
be made without permission under this Public License.
b. To the extent possible, if any provision of this Public License is
deemed unenforceable, it shall be automatically reformed to the
minimum extent necessary to make it enforceable. If the provision
cannot be reformed, it shall be severed from this Public License
without affecting the enforceability of the remaining terms and
conditions.
c. No term or condition of this Public License will be waived and no
failure to comply consented to unless expressly agreed to by the
Licensor.
d. Nothing in this Public License constitutes or may be interpreted
as a limitation upon, or waiver of, any privileges and immunities
that apply to the Licensor or You, including from the legal
processes of any jurisdiction or authority.
=======================================================================
Creative Commons is not a party to its public
licenses. Notwithstanding, Creative Commons may elect to apply one of
its public licenses to material it publishes and in those instances
will be considered the “Licensor.” The text of the Creative Commons
public licenses is dedicated to the public domain under the CC0 Public
Domain Dedication. Except for the limited purpose of indicating that
material is shared under a Creative Commons public license or as
otherwise permitted by the Creative Commons policies published at
creativecommons.org/policies, Creative Commons does not authorize the
use of the trademark "Creative Commons" or any other trademark or logo
of Creative Commons without its prior written consent including,
without limitation, in connection with any unauthorized modifications
to any of its public licenses or any other arrangements,
understandings, or agreements concerning use of licensed material. For
the avoidance of doubt, this paragraph does not form part of the
public licenses.
Creative Commons may be contacted at creativecommons.org.

View File

@@ -0,0 +1,28 @@
# 🌘 Hikka Userbot Mods by @unneyon
This repository contains a some list of modules for the Hikka Userbot. To install a module, simply copy the raw file link.
## 😼 About Me
You can contact me on Telegram: [@unneyon](https://t.me/unneyon). Feel free to reach out with any questions or inquiries. ❤<br>
My Telegram channel with modules: [@unneyon_hmods](https://t.me/unneyon_hmods).<br>
My modules also have comfortable web interface: [mods.unneyon.ru](https://mods.unneyon.ru).
## 📥 How install
You can install my modules using raw links. For example:
```
.dlm https://raw.githubusercontent.com/unneyon/hikka-mods/main/<module_name>
```
And you can use my repository, just add my repo:
```
.addrepo https://raw.githubusercontent.com/unneyon/hikka-mods/main/
```
Or, you can add my web repo:
```
.addrepo https://mods.unneyon.ru/
```
After this you will can install mod simple:
```
.dlm <module_name>
```

Binary file not shown.

After

Width:  |  Height:  |  Size: 552 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 593 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 592 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 579 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 612 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 584 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 166 KiB

View File

@@ -0,0 +1,147 @@
__version__ = (1, 0, 0)
# █▄▀ ▄▀█ █▀▄▀█ █▀▀ █▄▀ █ █ █▀█ █▀█
# █ █ █▀█ █ ▀ █ ██▄ █ █ ▀▄▄▀ █▀▄ █▄█ ▄
# © Copyright 2025
# ✈ https://t.me/kamekuro
# 🔒 Licensed under CC-BY-NC-ND 4.0 unless otherwise specified.
# 🌐 https://creativecommons.org/licenses/by-nc-nd/4.0
# + attribution
# + non-commercial
# + no-derivatives
# You CANNOT edit, distribute or redistribute this file without direct permission from the author.
# meta banner: https://raw.githubusercontent.com/kamekuro/hikka-mods/main/banners/caliases.png
# meta pic: https://raw.githubusercontent.com/kamekuro/hikka-mods/main/icons/caliases.png
# meta developer: @kamekuro_hmods
# scope: hikka_only
# scope: hikka_min 1.6.3
import logging
from telethon import types
from .. import loader, utils
logger = logging.getLogger(__name__)
@loader.tds
class CustomAliasesMod(loader.Module):
"""Module for custom aliases"""
strings = {
"name": "CAliases",
"c404": "<emoji document_id=5312526098750252863>❌</emoji> <b>Command <code>{}</code> not found!</b>",
"a404": "<emoji document_id=5312526098750252863>❌</emoji> <b>Custom alias <code>{}</code> not found!</b>",
"no_args": "<emoji document_id=5312526098750252863>❌</emoji> <b>You must specify two args: alias name and command</b>",
"added": (
"<emoji document_id=5314250708508220914>✅</emoji> <b>Custom alias <i>{alias}</i> for command "
"<code>{prefix}{cmd}</code> successfully added!</b>\n<b>Use it like:</b> <code>{prefix}{alias}{args}</code>"
),
"argsopt": " [args (optional)]",
"deleted": "<emoji document_id=5314250708508220914>✅</emoji> <b>Custom alias <code>{}</code> successfully deleted</b>",
"list": "<emoji document_id=5974492756494519709>🔗</emoji> <b>Custom aliases ({len}):</b>\n",
"no_aliases": "<emoji document_id=5312526098750252863>❌</emoji> <b>You have no custom aliases!</b>"
}
strings_ru = {
"c404": "<emoji document_id=5312526098750252863>❌</emoji> <b>Команда <code>{}</code> не найдена!</b>",
"a404": "<emoji document_id=5312526098750252863>❌</emoji> <b>Кастомный алиас <code>{}</code> не найден!</b>",
"no_args": "<emoji document_id=5312526098750252863>❌</emoji> <b>Вы должны указать как минимум два аргумента: имя алиаса и команду</b>",
"added": (
"<emoji document_id=5314250708508220914>✅</emoji> <b>Успешно добавил алиас с названием <i>{alias}</i> "
"для команды <code>{prefix}{cmd}</code></b>\n<b>Используй его так:</b> <code>{prefix}{alias}{args}</code>"
),
"argsopt": " [аргументы (необязательно)]",
"deleted": "<emoji document_id=5314250708508220914>✅</emoji> <b>Кастомный алиас <code>{}</code> успешно удалён</b>",
"list": "<emoji document_id=5974492756494519709>🔗</emoji> <b>Кастомные алиасы (всего {len}):</b>\n",
"no_aliases": "<emoji document_id=5312526098750252863>❌</emoji> <b>У вас нет кастомных алиасов!</b>"
}
@loader.command(
ru_doc="👉 Получить список всех алиасов",
alias="calist"
)
async def caliasescmd(self, message: types.Message):
"""👉 Get all aliases"""
aliases = self.get("aliases", {})
if not aliases:
return await utils.answer(message, self.strings['no_aliases'])
out = self.strings['list'].format(len=len(aliases.keys()))
for alias in aliases.keys():
cmd = aliases[alias]['command']
if aliases[alias]['args']:
cmd += f" {aliases[alias]['args']}"
out += f" <emoji document_id=5280726938279749656>▪️</emoji> <code>{alias}</code> " \
f"<emoji document_id=5960671702059848143>👈</emoji> <code>{cmd}</code>\n"
await utils.answer(message, out)
@loader.command(
ru_doc="<имя> 👉 Удалить алиас"
)
async def rmcaliascmd(self, message: types.Message):
"""<name> 👉 Remove alias"""
args = utils.get_args(message)
aliases = self.get("aliases", {})
if args[0] not in aliases:
return await utils.answer(message, self.strings['a404'])
del aliases[args[0]]
self.set("aliases", aliases)
await utils.answer(message, self.strings['deleted'].format(args[0]))
@loader.command(
ru_doc="<имя> <команда> [аргументы] 👉 Добавить новый алиас (может содержать ключевое слово {args})"
)
async def caliascmd(self, message: types.Message):
"""<name> <command> [args] 👉 Add new alias (may contain {args} keyword)"""
rargs = " ".join(utils.get_args_raw(message).split(' ')[2:])
args = utils.get_args(message)
if len(args) < 2:
return await utils.answer(message, self.strings['no_args'])
name = args[0]
cmd = args[1]
cmdargs = rargs
if cmd not in self.allmodules.commands.keys():
return await utils.answer(message, self.strings['c404'].format(cmd))
aliases = self.get("aliases", {})
aliases[str(args[0])] = {"command": cmd, "args": cmdargs}
self.set("aliases", aliases)
await utils.answer(message, self.strings['added'].format(
alias=name,
prefix=self.get_prefix(),
cmd=cmd+' '+cmdargs if cmdargs else cmd,
args=self.strings["argsopt"] if "{args}" in cmdargs else ""
))
@loader.tag(
only_messages=True, no_media=True, no_inline=True,
out=True
)
async def watcher(self, message):
aliases = self.get("aliases", {})
command = message.raw_text.lower().split()[0]
if (command[0] == self.get_prefix()) and (command[1:] in aliases.keys()):
text = message.raw_text.lower()
args = utils.get_args_raw(message)
ass = aliases[command[1:]]
await self.allmodules.commands[ass['command']](
await utils.answer(
message,
(self.get_prefix() + ass['command'] + '@me ' + ass['args']).format(args=args)
)
)

View File

@@ -0,0 +1,141 @@
__version__ = (1, 0, 0)
# █▄▀ ▄▀█ █▀▄▀█ █▀▀ █▄▀ █ █ █▀█ █▀█
# █ █ █▀█ █ ▀ █ ██▄ █ █ ▀▄▄▀ █▀▄ █▄█ ▄
# © Copyright 2025
# ✈ https://t.me/kamekuro
# 🔒 Licensed under CC-BY-NC-ND 4.0 unless otherwise specified.
# 🌐 https://creativecommons.org/licenses/by-nc-nd/4.0
# + attribution
# + non-commercial
# + no-derivatives
# You CANNOT edit, distribute or redistribute this file without direct permission from the author.
# meta banner: https://raw.githubusercontent.com/kamekuro/hikka-mods/main/banners/deleter.png
# meta pic: https://raw.githubusercontent.com/kamekuro/hikka-mods/main/icons/deleter.png
# meta developer: @kamekuro_hmods
# scope: hikka_only
# scope: hikka_min 1.6.3
import logging
from telethon import types
from .. import loader, utils
logger = logging.getLogger(__name__)
@loader.tds
class DeleterMod(loader.Module):
"""Module for delete your messages"""
strings = {
"name": "Deleter",
"_cfg_trigger": "Trigger for delete messages",
"_cfg_edit_msgs": "Is need to edit messages before delete them?",
"_cfg_edit_text": "Text for edit messages"
}
strings_ru = {
"_cfg_trigger": "Триггер-команда для удаления сообщений",
"_cfg_edit_msgs": "Нужно ли редактировать сообщения перед удалением?",
"_cfg_edit_text": "Текст для редактирования сообщений",
"_cls_doc": "Модуль для удаления своих сообщений"
}
def __init__(self):
self.config = loader.ModuleConfig(
loader.ConfigValue(
"trigger",
"дд",
lambda: self.strings["_cfg_trigger"]
),
loader.ConfigValue(
"edit_msgs",
True,
lambda: self.strings["_cfg_edit_msgs"],
validator=loader.validators.Boolean()
),
loader.ConfigValue(
"edit_text",
"\xad",
lambda: self.strings["_cfg_edit_text"]
)
)
@loader.command(
ru_doc="[число] 👉 Удалить сообщения (можно использовать значение из конфига: «{значение}{число}», без пробела!)"
)
async def delmsgcmd(self, message: types.Message):
"""[count] 👉 Delete messages (you can use your trigger from config: «{value}{count}» and write them only together!)"""
args = utils.get_args(message)
count = 1
if args:
count = int(args[0]) if args[0].isnumeric() else 1
dmsgs = []
msgs = await self._client.get_messages(
message.chat_id, limit=50+count
)
for i in msgs:
if i.id == message.id:
continue
if i.sender_id == self._client.tg_id:
dmsgs.append(i)
if self.config["edit_msgs"]:
await message.edit(self.config["edit_text"])
await message.delete()
for i in dmsgs:
if count == 0:
break
if self.config["edit_msgs"]:
try:
await i.edit(self.config["edit_text"])
except:
pass
await i.delete()
count -= 1
@loader.tag(
only_messages=True, no_media=True, no_inline=True,
out=True
)
async def watcher(self, message: types.Message):
if not message.raw_text.startswith(self.config['trigger']):
return
p = message.raw_text.partition(self.config['trigger'])[2]
count = int(p) if p.isdigit() else 1
dmsgs = []
msgs = await self._client.get_messages(
message.chat_id, limit=50+count
)
for i in msgs:
if i.id == message.id:
continue
if i.sender_id == self._client.tg_id:
dmsgs.append(i)
if self.config["edit_msgs"]:
await message.edit(self.config["edit_text"])
await message.delete()
for i in dmsgs:
if count == 0:
break
if self.config["edit_msgs"]:
try:
await i.edit(self.config["edit_text"])
except:
pass
await i.delete()
count -= 1

View File

@@ -0,0 +1,6 @@
caliases
deleter
privacy
tidal
warpigs
yamusic

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 109 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

View File

@@ -0,0 +1,397 @@
__version__ = (1, 0, 0)
# █▄▀ ▄▀█ █▀▄▀█ █▀▀ █▄▀ █ █ █▀█ █▀█
# █ █ █▀█ █ ▀ █ ██▄ █ █ ▀▄▄▀ █▀▄ █▄█ ▄
# © Copyright 2025
# ✈ https://t.me/kamekuro
# 🔒 Licensed under CC-BY-NC-ND 4.0 unless otherwise specified.
# 🌐 https://creativecommons.org/licenses/by-nc-nd/4.0
# + attribution
# + non-commercial
# + no-derivatives
# You CANNOT edit, distribute or redistribute this file without direct permission from the author.
# meta banner: https://raw.githubusercontent.com/kamekuro/hikka-mods/main/banners/privacy.png
# meta pic: https://raw.githubusercontent.com/kamekuro/hikka-mods/main/icons/privacy.png
# meta developer: @kamekuro_hmods
# scope: heroku_only
# scope: hikka_min 1.6.3
import logging
import re
import typing
import telethon
from telethon import types
from .. import loader, utils, inline
logger = logging.getLogger(__name__)
@loader.tds
class PrivacyMod(loader.Module):
"""Module for fastly changing privacy settings"""
_privacy_types = {
"phone": types.InputPrivacyKeyPhoneNumber,
"add_by_phone": types.InputPrivacyKeyAddedByPhone,
"online": types.InputPrivacyKeyStatusTimestamp,
"photos": types.InputPrivacyKeyProfilePhoto,
"forwards": types.InputPrivacyKeyForwards,
"calls": types.InputPrivacyKeyPhoneCall,
"p2p": types.InputPrivacyKeyPhoneP2P,
"voices": types.InputPrivacyKeyVoiceMessages,
# "messages": None,
"birthdate": getattr(types, "InputPrivacyKeyBirthday", None),
"gifts": getattr(types, "InputPrivacyKeyStarGiftsAutoSave", None),
"bio": getattr(types, "InputPrivacyKeyAbout", None),
"invites": types.InputPrivacyKeyChatInvite
}
_privacy_rules = {
types.PrivacyValueAllowAll: types.InputPrivacyValueAllowAll,
getattr(types, "PrivacyValueAllowBots", None): getattr(types, "InputPrivacyValueAllowBots", None),
types.PrivacyValueAllowChatParticipants: types.InputPrivacyValueAllowChatParticipants,
getattr(types, "PrivacyValueAllowCloseFriends", None): getattr(types, "InputPrivacyValueAllowCloseFriends", None),
types.PrivacyValueAllowContacts: types.InputPrivacyValueAllowContacts,
getattr(types, "PrivacyValueAllowPremium", None): getattr(types, "InputPrivacyValueAllowPremium", None),
types.PrivacyValueAllowUsers: types.InputPrivacyValueAllowUsers,
types.PrivacyValueDisallowAll: types.InputPrivacyValueDisallowAll,
getattr(types, "PrivacyValueDisallowBots", None): getattr(types, "InputPrivacyValueDisallowBots", None),
types.PrivacyValueDisallowChatParticipants: types.InputPrivacyValueDisallowChatParticipants,
types.PrivacyValueDisallowContacts: types.InputPrivacyValueDisallowContacts,
types.PrivacyValueDisallowUsers: types.InputPrivacyValueDisallowUsers
}
strings = {
"name": "Privacy",
"privacy_types": (
"<emoji document_id=5974492756494519709>🔗</emoji> <b>Types of privacy settings:</b>\n"
),
"no_user": "<emoji document_id=5312383351217201533>⚠️</emoji> <b>You haven't specified user</b>",
"u_silly": (
"<emoji document_id=5449682572223194186>🥺</emoji> <b>You can't set privacy settings "
"exceptions for yourself, silly.</b>"
),
"choose_type": "🔑 <b>Select the type of settings to set exceptions</b>",
"not_supported_type": (
"<emoji document_id=5312383351217201533>⚠️</emoji> <b>It is not possible to set exceptions "
"for the [{}] type of settings</b>"
),
"allowed": (
"<emoji document_id=5298609004551887592>💕</emoji> <b>{user} was added to the allowed "
"users for the [{pr}] type of settings</b>"
),
"disallowed": (
"<emoji document_id=5224379368242965520>💔</emoji> <b>{user} was added to the disallowed "
"users for the [{pr}] type of settings</b>"
),
"privacy": {
"phone": "Phone Number",
"add_by_phone": "Who can find you by your number",
"p2p": "Using Peer-to-Peer in calls",
"online": "Last Seen & Online",
"photos": "Profile Photos",
"forwards": "Forwarded Messages",
"calls": "Calls",
"voices": "Voice Messages",
# "messages": "Messages" if _privacy_types.get("messages") else None,
"birthdate": "Date of Birth" if _privacy_types.get("birthdate") else None,
"gifts": "Gifts" if _privacy_types.get("gifts") else None,
"bio": "Bio" if _privacy_types.get("bio") else None,
"invites": "Invites"
}
}
strings_ru = {
"_cls_doc": "Модуль для быстрого изменения настроек конфиденциальности",
"privacy_types": (
"<emoji document_id=5974492756494519709>🔗</emoji> <b>Типы настроек приватности:</b>\n"
),
"no_user": "<emoji document_id=5312383351217201533>⚠️</emoji> <b>Вы не указали пользователя</b>",
"u_silly": (
"<emoji document_id=5449682572223194186>🥺</emoji> <b>Ты не можешь выставить исключения "
"настроек приватности для самого себя, глупенький</b>"
),
"choose_type": "🔑 <b>Выберите тип настроек для выставления исключений</b>",
"not_supported_type": (
"<emoji document_id=5312383351217201533>⚠️</emoji> <b>Для типа настроек [{}] "
"невозможно выставить исключения</b>"
),
"allowed": (
"<emoji document_id=5298609004551887592>💕</emoji> <b>{user} добавлен в разрешённых "
"пользователей для настройки [{pr}]</b>"
),
"disallowed": (
"<emoji document_id=5224379368242965520>💔</emoji> <b>{user} добавлен в запрещённых "
"пользователей для настройки [{pr}]</b>"
),
"privacy": {
"phone": "Номер телефона",
"add_by_phone": "Кто может найти Вас по номеру",
"p2p": "Использование peer-to-peer в звонках",
"online": "Время захода",
"photos": "Фотографии профиля",
"forwards": "Пересылка сообщений",
"calls": "Звонки",
"voices": "Голосовые сообщения",
# "messages": "Сообщения" if _privacy_types.get("messages") else None,
"birthdate": "Дата рождения" if _privacy_types.get("birthdate") else None,
"gifts": "Подарки" if _privacy_types.get("gifts") else None,
"bio": "О себе" if _privacy_types.get("bio") else None,
"invites": "Приглашения"
}
}
async def client_ready(self, client, db):
self._client: telethon.TelegramClient = client
self._db = db
@loader.command(
ru_doc="👉 Список типов настроек для указания их в командах",
alias="ptypes"
)
async def privacytypescmd(self, message: types.Message):
"""👉 List of setting types to pass it in commands"""
out = self.strings("privacy_types")
for key, item in self.strings("privacy").items():
if not item: continue
out += f" <code>{key}</code> — {item}\n"
await utils.answer(
message, out
)
@loader.command(
ru_doc="<пользователь> [настройка (необязательно)] 👉 Добавить пользователя в разрешённых для какой-либо настройки"
)
async def allowusercmd(self, message: types.Message):
"""<user> [setting (optional)] 👉 Add user to includes for some setting"""
uid = await self.getID(message)
if (not uid) or (uid < 0):
return await utils.answer(message, self.strings("no_user"))
elif uid == (await self._client.get_me()).id:
return await utils.answer(message, self.strings("u_silly"))
args = utils.get_args(message)[(0 if message.is_reply else 1):]
new_allow_user: types.User = await self._client.get_entity(uid)
if (len(args) < 1) or (not self._privacy_types.get(args[0])):
return await self.inline.form(
message=message,
text=self.strings("choose_type"),
reply_markup=self.gen_kb_action(new_allow_user, "allow")
)
pr = self.strings('privacy').get(args[0])
if args[0] == "add_by_phone":
return await utils.answer(
message, self.strings("not_supported_type").format(pr)
)
key: types.TypeInputPrivacyKey = self._privacy_types.get(args[0])
rules = (await self._client(telethon.functions.account.GetPrivacyRequest(
key=key()
))).rules
await self.allow_user(new_allow_user, key, rules, "allow")
await utils.answer(
message, self.strings("allowed").format(
user=telethon.utils.get_display_name(new_allow_user), pr=pr
)
)
@loader.command(
ru_doc="<пользователь> [настройка (необязательно)] 👉 Добавить пользователя в запрещённых для какой-либо настройки"
)
async def disallowusercmd(self, message: types.Message):
"""<user> [setting (optional)] 👉 Add user to excludes for some setting"""
uid = await self.getID(message)
if (not uid) or (uid < 0):
return await utils.answer(message, self.strings("no_user"))
elif uid == (await self._client.get_me()).id:
return await utils.answer(message, self.strings("u_silly"))
args = utils.get_args(message)[(0 if message.is_reply else 1):]
new_allow_user: types.User = await self._client.get_entity(uid)
if (len(args) < 1) or (not self._privacy_types.get(args[0])):
return await self.inline.form(
message=message,
text=self.strings("choose_type"),
reply_markup=self.gen_kb_action(new_allow_user, "disallow")
)
pr = self.strings('privacy').get(args[0])
if args[0] == "add_by_phone":
return await utils.answer(
message, self.strings("not_supported_type").format(pr)
)
key: types.TypeInputPrivacyKey = self._privacy_types.get(args[0])
rules = (await self._client(telethon.functions.account.GetPrivacyRequest(
key=key()
))).rules
await self.allow_user(new_allow_user, key, rules, "disallow")
await utils.answer(
message, self.strings("disallowed").format(
user=telethon.utils.get_display_name(new_allow_user), pr=pr
)
)
async def allow_by_kb(
self,
call: inline.types.InlineCall,
new_user: types.User,
key: types.TypeInputPrivacyKey
):
pr = "[Unknown]"
for i in self._privacy_types.keys():
if self._privacy_types[i] == key:
pr = self.strings('privacy').get(i); break
rules = (await self._client(telethon.functions.account.GetPrivacyRequest(
key=key()
))).rules
await self.allow_user(new_user, key, rules, "allow")
await call.edit(
text=self.strings("allowed").format(
user=telethon.utils.get_display_name(new_user), pr=pr
)
)
async def disallow_by_kb(
self,
call: inline.types.InlineCall,
new_user: types.User,
key: types.TypeInputPrivacyKey
):
pr = "[Unknown]"
for i in self._privacy_types.keys():
if self._privacy_types[i] == key:
pr = self.strings('privacy').get(i); break
rules = (await self._client(telethon.functions.account.GetPrivacyRequest(
key=key()
))).rules
await self.allow_user(new_user, key, rules, "disallow")
await call.edit(
text=self.strings("disallowed").format(
user=telethon.utils.get_display_name(new_user), pr=pr
)
)
async def allow_user(
self,
new_allow_user: types.User,
key: types.TypeInputPrivacyKey,
rules: list,
action: str = "allow" # allow/disallow
):
new_rules = []
f_all = [x for x in rules if type(x) in [types.PrivacyValueAllowAll, types.PrivacyValueDisallowAll]]
f_all = f_all[0] if f_all else None
allow_users, disallow_users = [], []
allow_chats, disallow_chats = [], []
if (action == "allow") and (type(f_all) != types.PrivacyValueAllowAll):
allow_users.append(types.InputUser(new_allow_user.id, new_allow_user.access_hash))
elif (action == "disallow") and (type(f_all) != types.PrivacyValueDisallowAll):
disallow_users.append(types.InputUser(new_allow_user.id, new_allow_user.access_hash))
need_to_set = True
for rule in rules:
rule_type = type(rule)
if rule_type == types.PrivacyValueAllowUsers:
for user in rule.users:
if (user == new_allow_user.id) and (action == "allow"):
need_to_set = False; break
if (user == new_allow_user.id) and (action == "disallow"):
continue
us: types.User = await self._client.get_entity(user)
allow_users.append(types.InputUser(us.id, us.access_hash))
elif rule_type == types.PrivacyValueDisallowUsers:
for user in rule.users:
if (user == new_allow_user.id) and (action == "disallow"):
need_to_set = False; break
if (user == new_allow_user.id) and (action == "allow"): continue
us: types.User = await self._client.get_entity(user)
disallow_users.append(types.InputUser(us.id, us.access_hash))
elif rule_type == types.PrivacyValueAllowChatParticipants:
for chat in rule.chats:
allow_chats.append(chat)
elif rule_type == types.PrivacyValueDisallowChatParticipants:
for chat in rule.chats:
disallow_chats.append(chat)
else:
new_rules.append(self._privacy_rules[rule_type]())
if allow_users:
new_rules.append(types.InputPrivacyValueAllowUsers(allow_users))
if disallow_users:
new_rules.append(types.InputPrivacyValueDisallowUsers(disallow_users))
if allow_chats:
new_rules.append(types.InputPrivacyValueAllowChatParticipants(allow_chats))
if disallow_chats:
new_rules.append(types.InputPrivacyValueDisallowChatParticipants(disallow_chats))
if need_to_set:
await self._client(telethon.functions.account.SetPrivacyRequest(
key=key(), rules=new_rules
))
def gen_kb_action(
self,
new_user: types.User,
action: str # allow/disallow
):
return self.split_list([
{
"text": self.strings("privacy").get(key),
"callback": self.allow_by_kb if action == "allow" else self.disallow_by_kb,
"args": (new_user, item)
} for key, item in self._privacy_types.items() if item
], 2)
async def getID(self, message: types.Message):
reply: types.Message = await message.get_reply_message()
if reply:
return reply.sender_id
args: list = utils.get_args(message)
if not args: return None
username = args[0] if args else ""
match = re.search(r"(?:t\.me/|@|^(\w+)\.t\.me$)([a-zA-Z0-9_\.]+)", username)
if match:
username = match.group(1) or match.group(2)
try:
response = await self._client(telethon.functions.contacts.ResolveUsernameRequest(username))
except telethon.errors.rpcbaseerrors.RPCError:
response = None
try:
user_entity = await self._client.get_entity(username)
except Exception:
user_entity = None
if response and response.users:
return response.users[0].id
if user_entity:
return getattr(user_entity, "user_id", None)
return None
def split_list(self, input_list: typing.List, chunk_size: int):
return [input_list[i:i+chunk_size] for i in range(0, len(input_list), chunk_size)]

370
unneyon/hikka-mods/tidal.py Normal file
View File

@@ -0,0 +1,370 @@
__version__ = (1, 0, 2)
# █ █ ▀ █▄▀ ▄▀█ █▀█ ▀
# █▀█ █ █ █ █▀█ █▀▄ █
# © Copyright 2022
#
# https://t.me/hikariatama
#
# 🔒 Licensed under the GNU AGPLv3
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
# █▄▀ ▄▀█ █▀▄▀█ █▀▀ █▄▀ █ █ █▀█ █▀█
# █ █ █▀█ █ ▀ █ ██▄ █ █ ▀▄▄▀ █▀▄ █▄█ ▄
# © Copyright 2025
# ✈ https://t.me/kamekuro
#
# 🔒 Licensed under CC-BY-NC-ND 4.0 unless otherwise specified.
# 🌐 https://creativecommons.org/licenses/by-nc-nd/4.0
# + attribution
# + non-commercial
# + no-derivatives
#
# You CANNOT edit, distribute or redistribute this file without direct permission from the author.
# ORIGINAL MODULE: https://raw.githubusercontent.com/hikariatama/ftg/master/tidal.py
# meta banner: https://raw.githubusercontent.com/kamekuro/hikka-mods/main/banners/tidal.png
# meta pic: https://raw.githubusercontent.com/kamekuro/hikka-mods/main/icons/tidal.png
# meta developer: @kamekuro_hmods
# scope: hikka_only
# scope: hikka_min 1.6.3
# requires: git+https://github.com/tamland/python-tidal
import asyncio
import base64
import io
import json
import logging
import re
import requests
import tidalapi
from telethon import types
from .. import loader, utils
logger = logging.getLogger(__name__)
@loader.tds
class TidalMod(loader.Module):
"""API wrapper over TIDAL Hi-Fi music streaming service
Thanks @hikarimods for original module: t.me/hikarimods/764"""
strings = {
"name": "Tidal",
"_cfg_quality": "Select the desired quality for the tracks",
"args": "<emoji document_id=5312526098750252863>❌</emoji> <b>Specify search query</b>",
"404": "<emoji document_id=5312526098750252863>❌</emoji> <b>No results found</b>",
"oauth": (
"<emoji document_id=5773798959206108871>🔑</emoji> <b>Login to TIDAL</b>\n\n<i>This link will expire in 5 minutes</i>"
),
"oauth_btn": "🔑 Login",
"success": "<emoji document_id=5314250708508220914>✅</emoji> <b>Successfully logged in!</b>",
"error": "<emoji document_id=5312526098750252863>❌</emoji> <b>Error logging in</b>",
"search": "<emoji document_id=5438616889632761336>🎧</emoji> <b>{artist}{title}</b>\n<emoji document_id=5359582743992737342>🎵</emoji> <b><a href=\"https://tidal.com/track/{track_id}\">TIDAL</a> | <a href=\"https://song.link/t/{track_id}\">song.link</a></b>",
"downloading_file": "\n\n<emoji document_id=5325617665874600234>🕔</emoji> <i>Downloading audio…</i>",
"searching": "<emoji document_id=5309965701241379366>🔍</emoji> <b>Searching…</b>",
"auth_first": "<emoji document_id=5312526098750252863>❌</emoji> <b>You need to login first</b>",
}
strings_ru = {
"_cfg_quality": "Выберите желаемое качество для треков",
"args": "<emoji document_id=5312526098750252863>❌</emoji> <b>Укажите поисковый запрос</b>",
"404": "<emoji document_id=5312526098750252863>❌</emoji> <b>Ничего не найдено</b>",
"oauth": (
"<emoji document_id=5773798959206108871>🔑</emoji> <b>Авторизуйтесь в TIDAL</b>\n\n<i>Эта ссылка будет действительна в"
" течение 5 минут</i>"
),
"oauth_btn": "🔑 Авторизоваться",
"success": "<emoji document_id=5314250708508220914>✅</emoji> <b>Успешно авторизованы!</b>",
"error": "<emoji document_id=5312526098750252863>❌</emoji> <b>Ошибка авторизации</b>",
"search": "<emoji document_id=5438616889632761336>🎧</emoji> <b>{artist}{title}</b>\n<emoji document_id=5359582743992737342>🎵</emoji> <b><a href=\"https://tidal.com/track/{track_id}\">TIDAL</a> | <a href=\"https://song.link/t/{track_id}\">song.link</a></b>",
"downloading_file": "\n\n<emoji document_id=5325617665874600234>🕔</emoji> <i>Загрузка аудио…</i>",
"searching": "<emoji document_id=5309965701241379366>🔍</emoji> <b>Ищем…</b>",
"auth_first": "<emoji document_id=5312526098750252863>❌</emoji> <b>Сначала нужно авторизоваться</b>",
"_cls_doc": (
"""Модуль для музыкального сервиса TIDAL Hi-Fi
Спасибо @hikarimods за оригинальный модуль: t.me/hikarimods/764"""
)
}
def __init__(self):
self.qualities = {
"Low (96kbps)": tidalapi.Quality.low_96k,
"Low (320kbps)": tidalapi.Quality.low_320k,
"High": tidalapi.Quality.high_lossless,
"Max": tidalapi.Quality.hi_res_lossless
}
self.tags_files = {
"Low (96kbps)": "mp3",
"Low (320kbps)": "mp3",
"High": "m4a",
"Max": "flac"
}
self.config = loader.ModuleConfig(
loader.ConfigValue(
"quality",
"High",
lambda: self.strings["_cfg_quality"],
validator=loader.validators.Choice(['Low (96kbps)', 'Low (320kbps)', 'High', 'Max']),
)
)
def tidalLogin(self):
login_credits = (
self.get("token_type"),
self.get("access_token"),
self.get("refresh_token"),
self.get("session_id")
)
tidal = tidalapi.Session()
if not all(login_credits):
return tidal
try:
tidal.load_oauth_session(*login_credits)
if tidal.check_login():
tidal.audio_quality = self.qualities.get(self.config['quality'], "High")
return tidal
return tidalapi.Session()
except:
logger.exception("Error loading OAuth session")
return tidalapi.Session()
@loader.command(
ru_doc="👉 Авторизация в TIDAL",
alias="tauth"
)
async def tlogincmd(self, message: types.Message):
"""👉 Open OAuth window to login into TIDAL"""
tidal_session = self.tidalLogin()
result, future = tidal_session.login_oauth()
form = await self.inline.form(
message=message,
text=self.strings("oauth"),
reply_markup={
"text": self.strings("oauth_btn"),
"url": f"https://{result.verification_uri_complete}",
},
gif="https://0x0.st/oecP.MP4",
)
outer_loop = asyncio.get_event_loop()
def callback(*args, **kwargs):
nonlocal form, outer_loop
if tidal_session.check_login():
asyncio.ensure_future(
form.edit(
self.strings("success"),
gif="https://x0.at/dg3A.mp4",
),
loop=outer_loop,
)
self.set("token_type", tidal_session.token_type)
self.set("session_id", tidal_session.session_id)
self.set("access_token", tidal_session.access_token)
self.set("refresh_token", tidal_session.refresh_token)
else:
asyncio.ensure_future(
form.edit(
self.strings("error"),
gif="https://i.gifer.com/8Z2a.gif",
),
loop=outer_loop
)
future.add_done_callback(callback)
@loader.command(
ru_doc="<запрос> 👉 Поиск трека в TIDAL",
alias="tq"
)
async def tidalcmd(self, message: types.Message):
"""<query> 👉 Search track in TIDAL"""
tidal_session = self.tidalLogin()
if not await utils.run_sync(tidal_session.check_login):
await utils.answer(message, self.strings("auth_first"))
return
query = utils.get_args_raw(message)
if not query:
await utils.answer(message, self.strings("args"))
return
message = await utils.answer(message, self.strings("searching"))
result = tidal_session.search(query=query)
if not result or not result.get('tracks'):
await utils.answer(message, self.strings("404"))
return
track = result['tracks'][0]
track_res = {
"url": None, "id": track.id,
"artists": [], "name": track.name,
"tags": [], "duration": track.duration
}
meta = (
tidal_session.request.request(
"GET",
f"tracks/{track_res['id']}",
)
).json()
for i in meta["artists"]:
if i['name'] not in track_res['artists']:
track_res['artists'].append(i['name'])
tags = track_res['tags']
if meta.get("explicit"):
tags += ["#explicit🤬"]
if isinstance(meta.get("audioModes"), list):
for tag in meta["audioModes"]:
tags += [f"#{tag}🎧"]
if tags:
track_res['tags'] = tags
text = self.strings("search").format(
artist=", ".join(track_res['artists']),
title=track_res['name'],
track_id=track_res['id']
)
message = await utils.answer(
message, text + self.strings("downloading_file")
)
q = self.qualities.get(self.config['quality'], "HIGH")
q = q.value if type(q) != str else q
t = tidal_session.request.request(
"GET",
f"tracks/{track_res['id']}/playbackinfopostpaywall",
{
"audioquality": q,
"playbackmode": "STREAM",
"assetpresentation": "FULL"
}
).json()
man = json.loads(base64.b64decode(t['manifest']).decode('utf-8'))
track_res['url'] = man['urls'][0]
track_res['tags'].append(f"#{q}🔈")
with requests.get(track_res['url']) as r:
audio = io.BytesIO(r.content)
audio.name = f"audio.{self.tags_files.get(self.config['quality'], 'mp3')}"
audio.seek(0)
text += f"\n\n{', '.join(track_res['tags'])}"
await utils.answer_file(
message, audio, text,
attributes=([
types.DocumentAttributeAudio(
duration=track_res['duration'],
title=track_res['name'],
performer=', '.join(track_res['artists'])
)
])
)
@loader.command(
ru_doc="<ID/ссылка> 👉 Поиск трека в TIDAL по ID или ссылке",
alias="tid"
)
async def turlcmd(self, message: types.Message):
"""<ID/url> 👉 Search track in TIDAL by ID or url"""
tidal_session = self.tidalLogin()
if not await utils.run_sync(tidal_session.check_login):
await utils.answer(message, self.strings("auth_first"))
return
args = utils.get_args(message)
if (not args):
return await utils.answer(message, self.strings("args"))
res = re.findall(r"tidal\.com\/(?:track|browse\/track)\/(\d+)", args[0])
if (not res) and (not args[0].isdigit()):
return await utils.answer(message, self.strings("args"))
message = await utils.answer(message, self.strings("searching"))
try:
track = tidal_session.track(int(args[0]) if args[0].isdigit() else int(res[0]))
except tidalapi.exceptions.ObjectNotFound:
return await utils.answer(message, self.strings("404"))
track_res = {
"url": None, "id": track.id,
"artists": [], "name": track.name,
"tags": [], "duration": track.duration
}
meta = (
tidal_session.request.request(
"GET",
f"tracks/{track_res['id']}",
)
).json()
for i in meta["artists"]:
if i['name'] not in track_res['artists']:
track_res['artists'].append(i['name'])
tags = track_res['tags']
if meta.get("explicit"):
tags += ["#explicit🤬"]
if isinstance(meta.get("audioModes"), list):
for tag in meta["audioModes"]:
tags += [f"#{tag}🎧"]
if tags:
track_res['tags'] = tags
text = self.strings("search").format(
artist=", ".join(track_res['artists']),
title=track_res['name'],
track_id=track_res['id']
)
message = await utils.answer(
message, text + self.strings("downloading_file")
)
q = self.qualities.get(self.config['quality'], "HIGH")
q = q.value if type(q) != str else q
t = tidal_session.request.request(
"GET",
f"tracks/{track_res['id']}/playbackinfopostpaywall",
{
"audioquality": q,
"playbackmode": "STREAM",
"assetpresentation": "FULL"
}
).json()
man = json.loads(base64.b64decode(t['manifest']).decode('utf-8'))
track_res['url'] = man['urls'][0]
track_res['tags'].append(f"#{q}🔈")
with requests.get(track_res['url']) as r:
audio = io.BytesIO(r.content)
audio.name = f"audio.{self.tags_files.get(self.config['quality'], 'mp3')}"
audio.seek(0)
text += f"\n\n{', '.join(track_res['tags'])}"
await utils.answer_file(
message, audio, text,
attributes=([
types.DocumentAttributeAudio(
duration=track_res['duration'],
title=track_res['name'],
performer=', '.join(track_res['artists'])
)
])
)

View File

@@ -0,0 +1,183 @@
__version__ = (1, 0, 0)
# █▄▀ ▄▀█ █▀▄▀█ █▀▀ █▄▀ █ █ █▀█ █▀█
# █ █ █▀█ █ ▀ █ ██▄ █ █ ▀▄▄▀ █▀▄ █▄█ ▄
# © Copyright 2025
# ✈ https://t.me/kamekuro
# 🔒 Licensed under CC-BY-NC-ND 4.0 unless otherwise specified.
# 🌐 https://creativecommons.org/licenses/by-nc-nd/4.0
# + attribution
# + non-commercial
# + no-derivatives
# You CANNOT edit, distribute or redistribute this file without direct permission from the author.
# meta banner: https://raw.githubusercontent.com/kamekuro/hikka-mods/main/banners/warpigs.png
# meta pic: https://raw.githubusercontent.com/kamekuro/hikka-mods/main/icons/warpigs.png
# meta developer: @kamekuro_hmods
# scope: hikka_only
# scope: hikka_min 1.6.3
import asyncio
import logging
import traceback
from telethon import types
from .. import loader, utils
logger = logging.getLogger(__name__)
@loader.tds
class WarPigsMod(loader.Module):
"""Some auto-functions for your pig in @warpigs_bot"""
strings = {
"name": "WarPigs",
"dforpm": "<emoji document_id=5312526098750252863>❌</emoji> <b>This command cannot be used in PM.</b>",
"af_started": "<emoji document_id=5454014806950429357>⚔️</emoji> <b>Autofight was enabled for this chat.</b>",
"af_stopped": "<emoji document_id=5462990652943904884>😴</emoji> <b>Autofight was disabled for this chat.</b>",
"ag_started": "<emoji document_id=5463081281048818043>🍕</emoji> <b>Autogrow was enabled for this chat.</b>",
"ag_stopped": "<emoji document_id=5462990652943904884>😴</emoji> <b>Autogrow was disabled for this chat.</b>",
"no_name": "<emoji document_id=5312526098750252863>❌</emoji> <b>You have not specified a new name for your pig.</b>",
"new_name": "<emoji document_id=5463071033256848094>👑</emoji> <b>Now your pig's new name is:</b> {name}"
}
strings_ru = {
"_cls_doc": "Немного авто-функций для вашего хряка в @warpigs_bot",
"dforpm": "<emoji document_id=5312526098750252863>❌</emoji> <b>Эту команду нельзя использовать в ЛС.</b>",
"af_started": "<emoji document_id=5454014806950429357>⚔️</emoji> <b>Автобой был включён для этого чата.</b>",
"af_stopped": "<emoji document_id=5462990652943904884>😴</emoji> <b>Автобой был отключён для этого чата.</b>",
"ag_started": "<emoji document_id=5463081281048818043>🍕</emoji> <b>Автокормёжка была включена для этого чата.</b>",
"ag_stopped": "<emoji document_id=5462990652943904884>😴</emoji> <b>Автокормёжка была отключена для этого чата.</b>",
"no_name": "<emoji document_id=5312526098750252863>❌</emoji> <b>Вы не указали новое имя для вашего хряка.</b>",
"new_name": "<emoji document_id=5463071033256848094>👑</emoji> <b>Теперь новое имя вашего хряка:</b> {name}"
}
bot = "@warpigs_bot"
bot_id = 2028629176
async def client_ready(self, client, db):
self.client = client
self.logger = logging.getLogger(__name__)
self.autofight.start()
self.autogrow.start()
async def message_q(
self,
text: str,
chat_id: int,
mark_read: bool = False,
delete: bool = False,
):
async with self.client.conversation(chat_id, exclusive=False) as conv:
msg = await conv.send_message(text)
while True:
await asyncio.sleep(1)
response = await conv.get_response()
if response.from_id != self.bot_id:
continue
if mark_read:
await conv.mark_read()
if delete:
await msg.delete()
await response.delete()
return response
await conv.cancel_all()
@loader.loop(interval=86400)
async def autofight(self):
chats = self.get("chats", {})
for i in chats.keys():
if chats[i].get("autofight"):
try:
r = await self.message_q(
chat_id=int(i),
text=f"/fight{self.bot}"
)
except Exception as e:
self.logger.error(f"Ошибка отправки сообщения в чат {i}:\n{traceback.format_exc()}")
continue
await asyncio.sleep(1)
@loader.loop(interval=86400)
async def autogrow(self):
chats = self.get("chats", {})
for i in chats.keys():
if chats[i].get("autogrow"):
try:
r = await self.message_q(
chat_id=int(i),
text=f"/grow{self.bot}"
)
except Exception as e:
self.logger.error(f"Ошибка отправки сообщения в чат {i}:\n{traceback.format_exc()}")
continue
await asyncio.sleep(1)
@loader.command(
ru_doc="👉 Включить/отключить автобой"
)
async def afightcmd(self, message: types.Message):
"""👉 Enable/disable autofight"""
if message.is_private:
await utils.answer(message, self.strings("dforpm"))
return
chats = self.get("chats", {})
chat = chats.get(str(message.chat_id), {"autofight": False, "autogrow": False})
chat['autofight'] = not chat.get('autofight', False)
chats[str(message.chat_id)] = chat
self.set("chats", chats)
self.autofight.stop()
await asyncio.sleep(1)
self.autofight.start()
await utils.answer(
message, self.strings("af_started") if chat['autofight'] else self.strings("af_stopped")
)
@loader.command(
ru_doc="👉 Включить/отключить автокормёжку"
)
async def agrowcmd(self, message: types.Message):
"""👉 Enable/disable autogrow"""
if message.is_private:
await utils.answer(message, self.strings("dforpm"))
return
chats = self.get("chats", {})
chat = chats.get(str(message.chat_id), {"autofight": False, "autogrow": False})
chat['autogrow'] = not chat.get('autogrow', False)
chats[str(message.chat_id)] = chat
self.set("chats", chats)
self.autogrow.stop()
await asyncio.sleep(1)
self.autogrow.start()
await utils.answer(
message, self.strings("ag_started") if chat['autogrow'] else self.strings("ag_stopped")
)
@loader.command(
ru_doc="<имя> 👉 Меняет имя вашего хряка"
)
async def setnamecmd(self, message: types.Message):
"""<name> 👉 Changes your pig's name"""
args = utils.get_args_raw(message)
if not args:
return await utils.answer(message, self.strings("no_name"))
r = await self.message_q(chat_id=message.chat_id, text=f"/name{self.bot} {args}")
await utils.answer(message, self.strings("new_name").format(name=args))

View File

@@ -0,0 +1,740 @@
__version__ = (1, 0, 2)
# █▄▀ ▄▀█ █▀▄▀█ █▀▀ █▄▀ █ █ █▀█ █▀█
# █ █ █▀█ █ ▀ █ ██▄ █ █ ▀▄▄▀ █▀▄ █▄█ ▄
# © Copyright 2025
# ✈ https://t.me/kamekuro
# 🔒 Licensed under CC-BY-NC-ND 4.0 unless otherwise specified.
# 🌐 https://creativecommons.org/licenses/by-nc-nd/4.0
# + attribution
# + non-commercial
# + no-derivatives
# You CANNOT edit, distribute or redistribute this file without direct permission from the author.
# meta banner: https://raw.githubusercontent.com/kamekuro/hikka-mods/main/banners/yamusic.png
# meta pic: https://raw.githubusercontent.com/kamekuro/hikka-mods/main/icons/yamusic.png
# meta developer: @kamekuro_hmods
# scope: hikka_only
# scope: hikka_min 1.6.3
# requires: aiohttp asyncio requests pillow==11.2.1 git+https://github.com/MarshalX/yandex-music-api
import aiohttp
import asyncio
import io
import json
import logging
import random
import requests
import string
import yandex_music
import telethon
import textwrap
from PIL import (
Image, ImageDraw, ImageEnhance,
ImageFilter, ImageFont
)
import yandex_music.exceptions
from .. import loader, utils
logger = logging.getLogger(__name__)
@loader.tds
class YaMusicMod(loader.Module):
"""The module for Yandex.Music streaming service"""
strings = {
"name": "YaMusic",
"queue_types": {
"VARIOUS": "Your queue",
"RADIO": "«My Wave»",
"PLAYLIST": "Playlist «{}»",
"ALBUM": "Album «{}»"
},
"guide": (
"<emoji document_id=5956561916573782596>📜</emoji> <b><a "
"href=\"https://github.com/MarshalX/yandex-music-api/discussions/513"
"#discussioncomment-2729781\">Guide for obtaining a Yandex.Music token</a></b>"
),
"no_token": (
"<emoji document_id=5778527486270770928>❌</emoji> <b>You didn't specify "
"the access token in the config!</b>"
),
"autobio_e": "<emoji document_id=5429189857324841688>🎧</emoji> <b>Autobio is on now</b>",
"autobio_d": "<emoji document_id=5429189857324841688>🎧</emoji> <b>Autobio is off now</b>",
"there_is_no_playing": (
"<emoji document_id=5474140048741901455>❌</emoji> <b>You don't "
"listening to anything right now.</b>"
),
"now": (
"<emoji document_id=5474304919651491706>🎧</emoji> <b>{performer}{title}</b>\n\n"
"<emoji document_id={device_eid}>⌨️</emoji> <b>Now is listening on</b> <code>{device}</code> "
"<b>(<emoji document_id=6039454987250044861>🔊</emoji> {volume}%)</b>\n"
"<emoji document_id=5257969839313526622>🗂</emoji> <b>Playing from:</b> {playing_from}\n\n"
"<emoji document_id=5429189857324841688>🎵</emoji> <b><a href=\"https://music.yandex.ru/"
"album/{album_id}/track/{track_id}\">Yandex.Music</a> | "
"<a href=\"https://song.link/ya/{track_id}\">song.link</a></b>"
),
"downloading": "\n\n<emoji document_id=5841359499146825803>🕔</emoji> <i>Downloading audio…</i>",
"downloading_banner": "\n\n<emoji document_id=5841359499146825803>🕔</emoji> <i>Downloading banner…</i>",
"likes": {
"liked": (
"<emoji document_id=6037533152593842454>❤️</emoji> <b>Track "
"<a href=\"https://music.yandex.ru/album/{album_id}/track/{track_id}\">{track}</a> "
"was successfully liked</b>"
),
"unliked": (
"<emoji document_id=5992453811510186287>❤️</emoji> <b>Track "
"<a href=\"https://music.yandex.ru/album/{album_id}/track/{track_id}\">{track}</a> "
"was successfully unliked</b>"
),
"disliked": (
"<emoji document_id=5222400230133081714>💔</emoji> <b>Track "
"<a href=\"https://music.yandex.ru/album/{album_id}/track/{track_id}\">{track}</a> "
"was successfully disliked</b>"
)
},
"lyrics": (
"<emoji document_id=5956561916573782596>📜</emoji> <b>Lyrics of the <a href=\""
"https://music.yandex.ru/album/{album_id}/track/{track_id}\">{track}</a> track:</b>\n"
"<blockquote expandable>{text}</blockquote>\n\n"
"<emoji document_id=5247213725080890199>©️</emoji> <b>Writers:</b> {writers}"
),
"no_lyrics": (
"<emoji document_id=5886285363869126932>❌</emoji> <b>Track "
"<a href=\"https://music.yandex.ru/album/{album_id}/track/{track_id}\">{track}</a> "
"has no lyrics!</b>"
),
"search": (
"<emoji document_id=5474304919651491706>🎧</emoji> <b>{performer}{title}</b>\n"
"<emoji document_id=5429189857324841688>🎵</emoji> <b><a href=\"https://music.yandex.ru/"
"album/{album_id}/track/{track_id}\">Yandex.Music</a> | "
"<a href=\"https://song.link/ya/{track_id}\">song.link</a></b>"
),
"args": "<emoji document_id=5778527486270770928>❌</emoji> <b>Specify search query</b>",
"404": "<emoji document_id=5778527486270770928>❌</emoji> <b>No results found</b>",
"searching": "<emoji document_id=5258274739041883702>🔍</emoji> <b>Searching…</b>",
"_cfg_token": "Your access token of Yandex.Music",
"_cfg_autobio": "Automatic bio template (may contain {artist} and {title})",
"_cfg_no_playing_bio": "Bio that is set when nothing is playing"
}
strings_ru = {
"_cls_doc": "Модуль для стримингового сервиса Яндекс.Музыка",
"queue_types": {
"VARIOUS": "Ваша очередь",
"RADIO": "«Моя Волна»",
"PLAYLIST": "Плейлист «{}»",
"ALBUM": "Альбом «{}»"
},
"guide": (
"<emoji document_id=5956561916573782596>📜</emoji> <b><a "
"href=\"https://github.com/MarshalX/yandex-music-api/discussions/513"
"#discussioncomment-2729781\">Гайд по получению токена Яндекс.Музыки</a></b>"
),
"no_token": (
"<emoji document_id=5312526098750252863>❌</emoji> <b>Ты не "
"указал токен Яндекс.Музыки в конфиге!</b>"
),
"autobio_e": "<emoji document_id=5429189857324841688>🎧</emoji> <b>Автобио включено</b>",
"autobio_d": "<emoji document_id=5429189857324841688>🎧</emoji> <b>Автобио выключено</b>",
"there_is_no_playing": (
"<emoji document_id=5474140048741901455>❌</emoji> <b>Ты ничего "
"не слушаешь сейчас.</b>"
),
"now": (
"<emoji document_id=5474304919651491706>🎧</emoji> <b>{performer}{title}</b>\n\n"
"<emoji document_id={device_eid}>⌨️</emoji> <b>Сейчас слушаю на</b> <code>{device}</code> "
" <b>(<emoji document_id=6039454987250044861>🔊</emoji> {volume}%)</b>\n"
"<emoji document_id=5257969839313526622>🗂</emoji> <b>Откуда играет:</b> {playing_from}\n\n"
"<emoji document_id=5429189857324841688>🎵</emoji> <b><a href=\"https://music.yandex.ru/"
"album/{album_id}/track/{track_id}\">Яндекс.Музыка</a> | "
"<a href=\"https://song.link/ya/{track_id}\">song.link</a></b>"
),
"downloading": "\n\n<emoji document_id=5841359499146825803>🕔</emoji> <i>Загрузка трека…</i>",
"downloading_banner": "\n\n<emoji document_id=5841359499146825803>🕔</emoji> <i>Загрузка баннера…</i>",
"likes": {
"liked": (
"<emoji document_id=6037533152593842454>❤️</emoji> <b>Лайкнул трек "
"<a href=\"https://music.yandex.ru/album/{album_id}/track/{track_id}\">{track}</a></b>"
),
"unliked": (
"<emoji document_id=5992453811510186287>❤️</emoji> <b>Убрал лайк с трека "
"<a href=\"https://music.yandex.ru/album/{album_id}/track/{track_id}\">{track}</a></b>"
),
"disliked": (
"<emoji document_id=5222400230133081714>💔</emoji> <b>Дизлайкнул трек "
"<a href=\"https://music.yandex.ru/album/{album_id}/track/{track_id}\">{track}</a></b>"
)
},
"lyrics": (
"<emoji document_id=5956561916573782596>📜</emoji> <b>Текст трека "
"<a href=\"https://music.yandex.ru/album/{album_id}/track/{track_id}\">{track}</a>:</b>\n"
"<blockquote expandable>{text}</blockquote>\n\n"
"<emoji document_id=5247213725080890199>©️</emoji> <b>Авторы:</b> {writers}"
),
"no_lyrics": (
"<emoji document_id=5886285363869126932>❌</emoji> <b>У трека "
"<a href=\"https://music.yandex.ru/album/{album_id}/track/{track_id}\">{track}</a> "
"нет текста!</b>"
),
"search": (
"<emoji document_id=5474304919651491706>🎧</emoji> <b>{performer}{title}</b>\n"
"<emoji document_id=5429189857324841688>🎵</emoji> <b><a href=\"https://music.yandex.ru/"
"album/{album_id}/track/{track_id}\">Яндекс.Музыка</a> | "
"<a href=\"https://song.link/ya/{track_id}\">song.link</a></b>"
),
"args": "<emoji document_id=5312526098750252863>❌</emoji> <b>Укажите поисковый запрос</b>",
"404": "<emoji document_id=5312526098750252863>❌</emoji> <b>Ничего не найдено</b>",
"searching": "<emoji document_id=5258274739041883702>🔍</emoji> <b>Ищем…</b>",
"_cfg_token": "Твой токен от Яндекс.Музыки",
"_cfg_autobio": "Шаблон автоматического био (может содержать {artist} и {title})",
"_cfg_no_playing_bio": "Био, которое ставится, когда ничего не играет"
}
def __init__(self):
self.config = loader.ModuleConfig(
loader.ConfigValue(
"token",
None,
lambda: self.strings["_cfg_token"],
validator=loader.validators.Hidden()
),
loader.ConfigValue(
"autobio",
"🎧 {artist} - {title}",
lambda: self.strings["_cfg_autobio"],
validator=loader.validators.String()
),
loader.ConfigValue(
"no_playing_bio",
"Hello!",
lambda: self.strings["_cfg_no_playing_bio"],
validator=loader.validators.String()
)
)
async def on_dlmod(self):
if not self.get("guide_send", False):
await self.inline.bot.send_message(
self._tg_id,
self.strings("guide").replace("<emoji document_id=6334657396698253102>📜</emoji>", "📜"),
)
self.set("guide_send", True)
async def client_ready(self, client, db):
self._client = client
self._db = db
me = await self._client.get_me()
self._premium = me.premium if hasattr(me, "premium") else False
self.premium_check.start()
if self.get("autobio", False):
self.autobio.start()
@loader.loop(1800)
async def premium_check(self):
me = await self._client.get_me()
self._premium = me.premium if hasattr(me, "premium") else False
@loader.loop(30)
async def autobio(self):
if not self.config['token']:
self.autobio.stop(); self.set("autobio", False)
return
client = yandex_music.Client(self.config['token']).init()
now = await self.__get_now_playing(self.config['token'], client)
out = self.config['no_playing_bio'][:(140 if self._premium else 70)]
if now and (not now['paused']):
out = self.config['autobio'].format(
title=now['track']['title'],
artist=", ".join(now['track']['artist'])
)[:(140 if self._premium else 70)]
try:
await self._client(
telethon.functions.account.UpdateProfileRequest(about=out)
)
except telethon.errors.rpcerrorlist.FloodWaitError as e:
logger.info(f"Sleeping {max(e.seconds, 60)} because of floodwait")
await asyncio.sleep(max(e.seconds, 60))
@loader.command(
ru_doc="👉 Гайд по получению токена Яндекс.Музыки",
alias="yg"
)
async def yguidecmd(self, message: telethon.types.Message):
"""👉 Guide for obtaining a Yandex.Music token"""
await utils.answer(message, self.strings("guide"))
@loader.command(
ru_doc="👉 Включить/выключить автобио",
alias="yb"
)
async def ybiocmd(self, message: telethon.types.Message):
"""👉 Enable/disable autobio"""
if not self.config['token']:
return await utils.answer(message, self.strings("no_token"))
bio_now = self.get("autobio", False)
self.set("autobio", not bio_now)
if (not bio_now):
self.autobio.start()
else:
self.autobio.stop()
try:
await self._client(
telethon.functions.account.UpdateProfileRequest(
about=self.config['no_playing_bio'][:(140 if self._premium else 70)]
)
)
except: pass
await utils.answer(
message,
self.strings(f"autobio_{'e' if (not bio_now) else 'd'}")
)
@loader.command(
ru_doc="👉 Получить трек, который играет сейчас",
alias="yn"
)
async def ynowcmd(self, message: telethon.types.Message):
"""👉 Get now playing track"""
if not self.config['token']:
return await utils.answer(message, self.strings("no_token"))
client = yandex_music.Client(self.config['token']).init()
now = await self.__get_now_playing(self.config['token'], client)
if (not now) or now['paused']:
return await utils.answer(message, self.strings("there_is_no_playing"))
playlist_name = ""
if now['entity_type'] in ["PLAYLIST", "ALBUM"]:
func = getattr(
client,
"playlists_list" if now['entity_type'] == "PLAYLIST" else "albums"
)
if func:
entity = func(now['entity_id'])[0]
playlist_name = f"<b><a href=\"https://music.yandex.ru/users/" \
f"{client.me.account.login}/playlists/" \
f"{now['entity_id'].split(':')[1]}\">{entity.title}</a></b>"
else:
now['entity_type'] = "RADIO"
device_eid, volume, device = "6039404727542747508", "Unknown Device", ""
if now['device']:
device=now['device']['info']['title']
volume=round(now['device']['volume']*100, 2)
if now['device']['info']['type'] == "ANDROID": device_eid = "5373266788970670174"
if now['device']['info']['type'] == "IOS": device_eid = "5372908412604525258"
out = self.strings("now").format(
title=now['track']['title'],
performer=", ".join(now['track']['artist']),
device=device, volume=volume, device_eid=device_eid,
playing_from=self.strings("queue_types").get(now['entity_type'], "VARIOUS").format(playlist_name),
track_id=now['track']['track_id'],
album_id=now['track']['album_id']
)
await utils.answer(
message, out+self.strings("downloading")
)
audio = io.BytesIO((await utils.run_sync(requests.get, now['track']['download_link'])).content)
audio.name = "audio.mp3"
await utils.answer_file(
message=message, file=audio, caption=out,
attributes=([
telethon.types.DocumentAttributeAudio(
duration=now['track']['duration'],
title=now['track']['title'],
performer=", ".join(now['track']['artist'])
)
])
)
@loader.command(
ru_doc="👉 Получить баннер трека, который играет сейчас",
alias="ynb"
)
async def ynowbcmd(self, message: telethon.types.Message):
"""👉 Get now playing track's banner"""
if not self.config['token']:
return await utils.answer(message, self.strings("no_token"))
client = yandex_music.Client(self.config['token']).init()
now = await self.__get_now_playing(self.config['token'], client)
if (not now) or now['paused']:
return await utils.answer(message, self.strings("there_is_no_playing"))
playlist_name = ""
if now['entity_type'] in ["PLAYLIST", "ALBUM"]:
func = getattr(
client,
"playlists_list" if now['entity_type'] == "PLAYLIST" else "albums"
)
if func:
entity = func(now['entity_id'])[0]
playlist_name = f"<b><a href=\"https://music.yandex.ru/users/" \
f"{client.me.account.login}/playlists/" \
f"{now['entity_id'].split(':')[1]}\">{entity.title}</a></b>"
else:
now['entity_type'] = "RADIO"
device_eid, volume, device = "6039404727542747508", "Unknown Device", ""
if now['device']:
device=now['device']['info']['title']
volume=round(now['device']['volume']*100, 2)
if now['device']['info']['type'] == "ANDROID": device_eid = "5373266788970670174"
if now['device']['info']['type'] == "IOS": device_eid = "5372908412604525258"
out = self.strings("now").format(
title=now['track']['title'],
performer=", ".join(now['track']['artist']),
device=device, volume=volume, device_eid=device_eid,
playing_from=self.strings("queue_types").get(now['entity_type'], "VARIOUS").format(playlist_name),
track_id=now['track']['track_id'],
album_id=now['track']['album_id']
)
await utils.answer(
message, out+self.strings("downloading_banner")
)
file = self.__create_banner(
now['track']['title'], now['track']['artist'],
requests.get(now['track']['img']).content
)
await utils.answer_file(
message=message, file=file, caption=out
)
@loader.command(
ru_doc="👉 Лайкнуть играющий сейчас трек"
)
async def ylikecmd(self, message: telethon.types.Message):
"""👉 Like now playing track's banner"""
if not self.config['token']:
return await utils.answer(message, self.strings("no_token"))
client = yandex_music.Client(self.config['token']).init()
now = await self.__get_now_playing(self.config['token'], client)
if (not now) or now['paused']:
return await utils.answer(message, self.strings("there_is_no_playing"))
client.users_likes_tracks_add(now['track']['track_id'])
await utils.answer(
message, self.strings("likes")['liked'].format(
track_id=now['track']['track_id'], album_id=now['track']['album_id'],
track=f"{', '.join(now['track']['artist'])}{now['track']['title']}"
)
)
@loader.command(
ru_doc="👉 Убрать лайк с играющего сейчас трека"
)
async def yunlikecmd(self, message: telethon.types.Message):
"""👉 Unlike now playing track"""
if not self.config['token']:
return await utils.answer(message, self.strings("no_token"))
client = yandex_music.Client(self.config['token']).init()
now = await self.__get_now_playing(self.config['token'], client)
if (not now) or now['paused']:
return await utils.answer(message, self.strings("there_is_no_playing"))
client.users_likes_tracks_remove(now['track']['track_id'])
await utils.answer(
message, self.strings("likes")['unliked'].format(
track_id=now['track']['track_id'], album_id=now['track']['album_id'],
track=f"{', '.join(now['track']['artist'])}{now['track']['title']}"
)
)
@loader.command(
ru_doc="👉 Дизлайкнуть играющий сейчас трек",
alias="ydis"
)
async def ydislikecmd(self, message: telethon.types.Message):
"""👉 Dislike now playing track"""
if not self.config['token']:
return await utils.answer(message, self.strings("no_token"))
client = yandex_music.Client(self.config['token']).init()
now = await self.__get_now_playing(self.config['token'], client)
if (not now) or now['paused']:
return await utils.answer(message, self.strings("there_is_no_playing"))
client.users_dislikes_tracks_add(now['track']['track_id'])
await utils.answer(
message, self.strings("likes")['disliked'].format(
track_id=now['track']['track_id'], album_id=now['track']['album_id'],
track=f"{', '.join(now['track']['artist'])}{now['track']['title']}"
)
)
@loader.command(
ru_doc="👉 Получить текст играющего сейчас трека"
)
async def ylyricscmd(self, message: telethon.types.Message):
"""👉 Get lyrics of the now playing track"""
if not self.config['token']:
return await utils.answer(message, self.strings("no_token"))
client = yandex_music.Client(self.config['token']).init()
now = await self.__get_now_playing(self.config['token'], client)
if (not now) or now['paused']:
return await utils.answer(message, self.strings("there_is_no_playing"))
try:
lyrics = client.tracks_lyrics(now['track']['track_id'])
await utils.answer(
message, self.strings("lyrics").format(
track_id=now['track']['track_id'], album_id=now['track']['album_id'],
track=f"{', '.join(now['track']['artist'])}{now['track']['title']}",
text=requests.get(lyrics.download_url).text,
writers=", ".join(lyrics.writers)
)
)
except yandex_music.exceptions.NotFoundError:
await utils.answer(
message, self.strings("no_lyrics").format(
track_id=now['track']['track_id'], album_id=now['track']['album_id'],
track=f"{', '.join(now['track']['artist'])}{now['track']['title']}"
)
)
@loader.command(
ru_doc="<запрос> 👉 Поиск трека в Яндекс.Музыке",
alias="yq"
)
async def ysearchcmd(self, message: telethon.types.Message):
"""<query> 👉 Search track in Yandex.Music"""
if not self.config['token']:
return await utils.answer(message, self.strings("no_token"))
client = yandex_music.Client(self.config['token']).init()
query = utils.get_args_raw(message)
if not query:
await utils.answer(message, self.strings("args"))
return
message = await utils.answer(message, self.strings("searching"))
search = client.search(query, type_="track")
if (not search.tracks) or (len(search.tracks.results) == 0):
return await utils.answer(message, self.strings("404"))
out = self.strings("search").format(
title=search.tracks.results[0].title + (
f" ({search.tracks.results[0].version})" if search.tracks.results[0].version else ""
),
performer=", ".join([x.name for x in search.tracks.results[0].artists]),
album_id=search.tracks.results[0].albums[0].id, track_id=search.tracks.results[0].id
)
message = await utils.answer(message, out+self.strings("downloading"))
info = client.tracks_download_info(search.tracks.results[0].id, True)
link = info[0].direct_link
audio = None
audio = io.BytesIO((await utils.run_sync(requests.get, link)).content)
audio.name = "audio.mp3"
await utils.answer_file(
message=message, file=audio, caption=out,
attributes=([
telethon.types.DocumentAttributeAudio(
duration=int(search.tracks.results[0].duration_ms / 1000),
title=search.tracks.results[0].title,
performer=", ".join([x.name for x in search.tracks.results[0].artists])
)
])
)
# Original code: https://raw.githubusercontent.com/MIPOHBOPOHIH/YMMBFA/main/main.py
async def __create_ynison_ws(self, yamusic_token: str, ws_proto: dict) -> dict:
async with aiohttp.ClientSession() as session:
async with session.ws_connect(
"wss://ynison.music.yandex.ru/redirector.YnisonRedirectService/GetRedirectToYnison",
headers={
"Sec-WebSocket-Protocol": f"Bearer, v2, {json.dumps(ws_proto)}",
"Origin": "http://music.yandex.ru",
"Authorization": f"OAuth {yamusic_token}",
},
) as ws:
response = await ws.receive()
return json.loads(response.data)
# Original code: https://raw.githubusercontent.com/MIPOHBOPOHIH/YMMBFA/main/main.py
async def __get_now_playing(self, yamusic_token: str, client: yandex_music.Client):
device_id = ''.join(random.choices(string.ascii_lowercase, k=16))
ws_proto = {
"Ynison-Device-Id": device_id,
"Ynison-Device-Info": json.dumps({"app_name": "Chrome", "type": 1}),
}
data = await self.__create_ynison_ws(yamusic_token, ws_proto)
ws_proto["Ynison-Redirect-Ticket"] = data["redirect_ticket"]
payload = {
"update_full_state": {
"player_state": {
"player_queue": {
"current_playable_index": -1,
"entity_id": "",
"entity_type": "VARIOUS",
"playable_list": [],
"options": {"repeat_mode": "NONE"},
"entity_context": "BASED_ON_ENTITY_BY_DEFAULT",
"version": {"device_id": device_id, "version": 9021243204784341000, "timestamp_ms": 0},
"from_optional": "",
},
"status": {
"duration_ms": 0,
"paused": True,
"playback_speed": 1,
"progress_ms": 0,
"version": {"device_id": device_id, "version": 8321822175199937000, "timestamp_ms": 0},
},
},
"device": {
"capabilities": {"can_be_player": True, "can_be_remote_controller": False, "volume_granularity": 16},
"info": {
"device_id": device_id,
"type": "WEB",
"title": "Chrome Browser",
"app_name": "Chrome",
},
"volume_info": {"volume": 0},
"is_shadow": True,
},
"is_currently_active": False,
},
"rid": "ac281c26-a047-4419-ad00-e4fbfda1cba3",
"player_action_timestamp_ms": 0,
"activity_interception_type": "DO_NOT_INTERCEPT_BY_DEFAULT",
}
async with aiohttp.ClientSession() as session:
async with session.ws_connect(
f"wss://{data['host']}/ynison_state.YnisonStateService/PutYnisonState",
headers={
"Sec-WebSocket-Protocol": f"Bearer, v2, {json.dumps(ws_proto)}",
"Origin": "http://music.yandex.ru",
"Authorization": f"OAuth {yamusic_token}",
}
) as ws:
await ws.send_str(json.dumps(payload))
response = await ws.receive()
ynison: dict = json.loads(response.data)
if len(ynison.get("player_state", {}).get("player_queue", {}).get("playable_list", [])) == 0:
return {}
raw_track = ynison["player_state"]["player_queue"]["playable_list"][
ynison["player_state"]["player_queue"]["current_playable_index"]
]
track = client.tracks(raw_track["playable_id"])[0]
device = [
x for x in ynison['devices'] if x['info']['device_id'] == ynison.get('active_device_id_optional', "")
]
return {
"paused": ynison["player_state"]["status"]["paused"],
"duration_ms": ynison["player_state"]["status"]["duration_ms"],
"progress_ms": ynison["player_state"]["status"]["progress_ms"],
"entity_id": ynison["player_state"]["player_queue"]["entity_id"],
"entity_type": ynison["player_state"]["player_queue"]["entity_type"],
"device": device[0] if len(device) > 0 else None,
"track": {
"track_id": int(track.track_id.split(":")[0]) if track.track_id.split(":")[0].isdigit() else track.track_id,
"album_id": track.albums[0].id,
"title": track.title,
"artist": track.artists_name(),
"img": f"https://{track.cover_uri[:-2]}1000x1000",
"duration": track.duration_ms // 1000,
"minutes": round(track.duration_ms / 1000) // 60,
"seconds": round(track.duration_ms / 1000) % 60,
"download_link": track.get_download_info(get_direct_links=True)[0].direct_link
}
} if raw_track['playable_type'] != "LOCAL_TRACK" else {}
def __create_banner(
self,
title: str, artists: list,
track_cover: bytes
):
w, h = 1920, 768
title_font = ImageFont.truetype(io.BytesIO(requests.get(
"https://raw.githubusercontent.com/kamekuro/assets/master/fonts/Onest-Bold.ttf"
).content), 80)
art_font = ImageFont.truetype(io.BytesIO(requests.get(
"https://raw.githubusercontent.com/kamekuro/assets/master/fonts/Onest-Regular.ttf"
).content), 55)
# Gen banner (bg)
track_cov = Image.open(io.BytesIO(track_cover)).convert("RGBA")
banner = track_cov.resize((w, w)).crop(
(0, (w-h)//2, w, ((w-h)//2)+h)
).filter(ImageFilter.GaussianBlur(radius=14))
banner = ImageEnhance.Brightness(banner).enhance(0.3)
# Gen track cover and put to bg
track_cov = track_cov.resize((banner.size[1]-150, banner.size[1]-150))
mask = Image.new("L", track_cov.size, 0)
ImageDraw.Draw(mask).rounded_rectangle((0, 0, track_cov.size[0], track_cov.size[1]), radius=35, fill=255)
track_cov.putalpha(mask)
track_cov = track_cov.crop(track_cov.getbbox())
banner.paste(track_cov, (75, 75), mask)
# Editing text
title_lines = textwrap.wrap(title, 23)
if len(title_lines) > 1:
title_lines[1] = title_lines[1] + "..." if len(title_lines) > 2 else title_lines[1]
title_lines = title_lines[:2]
artists_lines = textwrap.wrap("".join(artists), width=40)
if len(artists_lines) > 1:
for index, art in enumerate(artists_lines):
if "" in art[-2:]:
artists_lines[index] = art[:art.rfind("") - 1]
# Put title and artists to banner
draw = ImageDraw.Draw(banner)
x, y = 150+track_cov.size[0], 110
for index, line in enumerate(title_lines):
draw.text((x, y), line, font=title_font, fill="#FFFFFF")
if index != len(title_lines)-1:
y += 70
x, y = 150+track_cov.size[0], 110*2
if len(title_lines) > 1: y += 70
for index, line in enumerate(artists_lines):
draw.text((x, y), line, font=art_font, fill="#A0A0A0")
if index != len(artists_lines)-1:
y += 50
by = io.BytesIO()
banner.save(by, format="PNG"); by.seek(0)
by.name = "banner.png"
return by