Compare commits

...

61 Commits

Author SHA1 Message Date
github-actions[bot]
430f49f345 Updated modules.json after parse 2026-02-14 06:58:27 2026-02-14 06:58:27 +00:00
54229a8266 nvm 2026-02-14 09:54:25 +03:00
Zahar Vanilovv
6cb625acd8 Merge pull request #183 from MuRuLOSE/update-submodules_61ebb7fa472caa2abd4d6c7523bcf8830258167c
Update of repositories 2026-02-09 01:29:55
2026-02-09 17:25:41 +03:00
github-actions[bot]
bf03595075 Updated modules.json after parse 2026-02-09 01:29:33 2026-02-09 01:29:33 +00:00
github-actions[bot]
8bef604170 Added and updated repositories 2026-02-09 01:29:03 2026-02-09 01:29:03 +00:00
61ebb7fa47 Legacy version is here! 2026-02-08 20:17:50 +03:00
Zahar Vanilovv
2702cd2356 Merge pull request #182 from MuRuLOSE/update-submodules_ab5aaf579b3117a79d44591859b2cd30a6fcd5a1
Update of repositories 2026-02-08 01:59:39
2026-02-08 08:01:47 +03:00
github-actions[bot]
37f53375bc Updated modules.json after parse 2026-02-08 01:59:16 2026-02-08 01:59:16 +00:00
github-actions[bot]
23dade9b9e Added and updated repositories 2026-02-08 01:58:46 2026-02-08 01:58:46 +00:00
Macsim
ab5aaf579b Merge pull request #181 from MuRuLOSE/update-submodules_78a9b0cb76b2d495a5ff23a25614d91699a8757d
Update of repositories 2026-02-07 07:57:35
2026-02-07 11:05:32 +03:00
github-actions[bot]
170809519a Updated modules.json after parse 2026-02-07 07:57:13 2026-02-07 07:57:13 +00:00
78a9b0cb76 added full tds attribute 2026-02-07 10:54:30 +03:00
Macsim
c1d407f885 Merge pull request #180 from MuRuLOSE/update-submodules_7cda8f2685159651f9c2c9ff238215f2b5894d6c
Update of repositories 2026-02-07 07:41:22
2026-02-07 10:43:12 +03:00
github-actions[bot]
cf230d2922 Updated modules.json after parse 2026-02-07 07:41:02 2026-02-07 07:41:02 +00:00
7cda8f2685 fix f-strings while parsing 2026-02-07 10:35:19 +03:00
Macsim
92bdd1510d Merge pull request #179 from MuRuLOSE/update-submodules_a7b8c740b42879d9b3c0d577d275d5b42e4db254
Update of repositories 2026-02-07 01:23:55
2026-02-07 10:34:25 +03:00
github-actions[bot]
52f6fc53c3 Updated modules.json after parse 2026-02-07 01:23:38 2026-02-07 01:23:38 +00:00
github-actions[bot]
5c25eaad81 Added and updated repositories 2026-02-07 01:23:08 2026-02-07 01:23:08 +00:00
a7b8c740b4 Now index locking should be not a problem 2026-02-06 12:27:31 +03:00
44ca8633c6 Merge branch 'main' of https://github.com/MuRuLOSE/limoka 2026-02-06 12:03:00 +03:00
e076d4ab28 lang and dev_username hotfix 2026-02-06 12:02:48 +03:00
Macsim
634861943a Merge pull request #177 from MuRuLOSE/update-submodules_f68d97d09b6ca907775228791cde9446509954c8
Update of repositories 2026-02-06 01:25:04
2026-02-06 07:43:55 +03:00
github-actions[bot]
d20d019c32 Updated modules.json after parse 2026-02-06 01:24:40 2026-02-06 01:24:40 +00:00
github-actions[bot]
041e6ec5f7 Added and updated repositories 2026-02-06 01:24:12 2026-02-06 01:24:12 +00:00
f68d97d09b bolded some text 2026-02-05 20:30:35 +03:00
e624861b64 Blacklisted some module 2026-02-05 20:17:09 +03:00
Macsim
d3f035ec58 Merge pull request #176 from MuRuLOSE/update-submodules_5c2de322d31171b50a220dcbb9862aea611ab15a
Update of repositories 2026-02-05 01:23:39
2026-02-05 20:07:37 +03:00
Macsim
1ced5efae6 Update SpotifyMod.py 2026-02-05 20:01:13 +03:00
github-actions[bot]
3bf476c8a9 Updated modules.json after parse 2026-02-05 01:23:15 2026-02-05 01:23:15 +00:00
github-actions[bot]
abff91c013 Added and updated repositories 2026-02-05 01:22:45 2026-02-05 01:22:45 +00:00
5c2de322d3 new developer 2026-01-30 20:29:03 +03:00
5b2fe145ff b 2026-01-30 17:17:10 +03:00
64d8ceb354 clear histroy 2026-01-30 16:58:22 +03:00
537ae4c485 againfix 2026-01-30 16:50:55 +03:00
52018c8e14 fix not found PeerUser bcs of id 2026-01-30 15:42:57 +03:00
6f95292df1 hotfix again 2026-01-30 15:31:04 +03:00
4a5d4883a9 version bump 2026-01-30 15:22:55 +03:00
ce59b13c94 Merge branch 'main' of https://github.com/MuRuLOSE/limoka 2026-01-30 15:22:26 +03:00
91351cb83d hotfix (i am scared...) 2026-01-30 15:22:01 +03:00
Macsim
118a800856 Merge pull request #170 from MuRuLOSE/update-submodules_51bbb98711dbacc9d018d87706b7f28c77463cc4
Update of repositories 2026-01-30 11:59:59
2026-01-30 15:00:33 +03:00
github-actions[bot]
f14a99c640 Updated modules.json after parse 2026-01-30 11:59:36 2026-01-30 11:59:36 +00:00
github-actions[bot]
c76dcc0fc1 Added and updated repositories 2026-01-30 11:59:07 2026-01-30 11:59:07 +00:00
51bbb98711 Merge branch 'main' of https://github.com/MuRuLOSE/limoka 2026-01-30 14:56:57 +03:00
edd70ad020 бь 2026-01-30 14:56:48 +03:00
Macsim
2c33b08ea0 Merge pull request #169 from MuRuLOSE/update-submodules_88ab2657552874370ef8600b9655bbfe90c2decd
Update of repositories 2026-01-30 11:50:56
2026-01-30 14:52:28 +03:00
github-actions[bot]
e9bb89cf62 Updated modules.json after parse 2026-01-30 11:50:33 2026-01-30 11:50:33 +00:00
github-actions[bot]
51055e6427 Added and updated repositories 2026-01-30 11:50:03 2026-01-30 11:50:03 +00:00
88ab265755 fixed workflow 2026-01-30 14:46:22 +03:00
Macsim
baada2d019 Merge pull request #168 from MuRuLOSE/update-submodules_2dd772b52d052144384a8e0c71f2d33b7c21ff1d
Update of repositories 2026-01-30 11:40:55
2026-01-30 14:42:26 +03:00
github-actions[bot]
ad782a6f46 Updated modules.json after parse 2026-01-30 11:40:21 2026-01-30 11:40:21 +00:00
github-actions[bot]
2435df880e Added and updated repositories 2026-01-30 11:39:54 2026-01-30 11:39:54 +00:00
2dd772b52d fix (wrong json structure) 2026-01-30 14:38:18 +03:00
c9ed00bb78 removed categories 2026-01-30 14:28:51 +03:00
504d1f32e9 Limoka 1.4.0 2026-01-30 14:24:43 +03:00
48d3e46d79 replaced wrong keyword 2026-01-29 19:36:37 +03:00
d48c269916 cooking update... 2026-01-27 19:15:25 +03:00
Macsim
8f52e0c18c Merge pull request #166 from MuRuLOSE:update-submodules_7cb3c70695a897525680a149b0a9e66c751ded33
Update of repositories 2026-01-27 01:19:05
2026-01-27 13:15:07 +03:00
github-actions[bot]
ae00dc0199 Updated modules.json after parse 2026-01-27 01:18:43 2026-01-27 01:18:43 +00:00
github-actions[bot]
c670c44a7a Added and updated repositories 2026-01-27 01:17:35 2026-01-27 01:17:36 +00:00
7cb3c70695 not needed anymore 2026-01-11 19:49:49 +03:00
8a98c79856 Added parsing repositories links from JSON file and removed static list from script 2026-01-11 13:29:58 +03:00
96 changed files with 91917 additions and 49211 deletions

View File

@@ -10,8 +10,10 @@ on:
pull_request:
branches:
- main
types: [opened, synchronize, reopened, closed]
workflow_dispatch: # Allows manual triggering from GitHub UI
# Environment variables available to all jobs
env:
BRANCH_NAME: "update-submodules_${{ github.sha }}"
@@ -137,9 +139,8 @@ jobs:
python3 -m venv venv
source venv/bin/activate
pip install --upgrade pip
pip install requests scikit-learn tqdm
pip install requests
python3 parse.py
python3 categories.py
git add modules.json
git commit -m "Updated modules.json after parse $(date +'%Y-%m-%d %H:%M:%S')" || echo "No changes for modules.json"
git remote set-url origin "https://x-access-token:${GITHUB_TOKEN}@${REPO_URL}"
@@ -206,61 +207,54 @@ jobs:
echo "Branch ${{ env.BRANCH_NAME }} does not exist in remote repository, skipping PR creation."
fi
notify_diffs:
runs-on: ubuntu-latest
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
needs: parse
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Configure Git
run: |
git config --global user.email "github-actions[bot]@users.noreply.github.com"
git config --global user.name "github-actions[bot]"
- name: Set up Python 3.9
uses: actions/setup-python@v5
with:
python-version: '3.9'
- name: Install dependencies
run: pip install aiohttp
- name: Send module diffs to channel
env:
TELEGRAM_BOT_TOKEN: ${{ secrets.TELEGRAM_BOT_TOKEN }}
TELEGRAM_CHAT_ID: ${{ secrets.TELEGRAM_CHAT_ID_UPDATE }}
run: |
LAST_COMMIT_MESSAGE=$(git log -1 --pretty=%B)
if [[ "$LAST_COMMIT_MESSAGE" == Merge* ]]; then
python3 update_diffs.py --token ${{ secrets.TELEGRAM_BOT_TOKEN }} --chat_id ${{ secrets.TELEGRAM_CHAT_ID_UPDATE }} --base_commit HEAD~1
fi
backup:
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/main' || github.event_name == 'workflow_dispatch'
needs: parse
steps:
- name: Configure Git for github-actions[bot]
run: |
git config --global user.email "github-actions[bot]@users.noreply.github.com"
git config --global user.name "github-actions[bot]"
git config --global --list
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: ${{ env.GIT_DEPTH }}
- name: Create and send backup to Telegram
- name: Set up Python 3.9
uses: actions/setup-python@v5
with:
python-version: '3.9'
- name: Install Python dependencies
run: pip install aiohttp
- name: Run backup script
env:
TELEGRAM_BOT_TOKEN: ${{ secrets.TELEGRAM_BOT_TOKEN }}
TELEGRAM_CHAT_ID: ${{ secrets.TELEGRAM_CHAT_ID }}
run: |
echo "Creating .zip file of the repository with maximum compression..."
git archive --format=zip --output=repository-original.zip HEAD
zip -9 repository.zip repository-original.zip
rm repository-original.zip
echo "File size of the created .zip file:"
du -sh repository.zip
echo "Splitting the .zip file into 8 parts..."
split -b 49M repository.zip repository-part-
echo "Files created after split:"
ls repository-part-*
COMMIT_MESSAGE="$(git log -1 --pretty=%B)"
COMMIT_DATE="$(date --date="$(git log -1 --pretty=%ci)" +'%Y-%m-%d %H:%M:%S')"
COMMIT_HASH="$(git rev-parse --short=6 HEAD)"
COMMIT_URL="https://${REPO_URL}/commit/$(git rev-parse HEAD)"
MESSAGE="Commit Date: $COMMIT_DATE, Commit Message: $COMMIT_MESSAGE, Commit Hash: [\`$COMMIT_HASH\`]($COMMIT_URL)"
echo "Sending .zip file parts to Telegram..."
FIRST_PART=true
for part in $(ls repository-part-* | sort); do
if $FIRST_PART; then
TELEGRAM_API_URL="https://api.telegram.org/bot$TELEGRAM_BOT_TOKEN/sendDocument"
echo "Sending first file to Telegram: $TELEGRAM_API_URL"
curl -X POST "$TELEGRAM_API_URL" \
-F chat_id=$TELEGRAM_CHAT_ID \
-F document=@$part \
-F caption="$MESSAGE" \
-F parse_mode="Markdown"
FIRST_PART=false
else
TELEGRAM_API_URL="https://api.telegram.org/bot$TELEGRAM_BOT_TOKEN/sendDocument"
echo "Sending file to Telegram: $TELEGRAM_API_URL"
curl -X POST "$TELEGRAM_API_URL" \
-F chat_id=$TELEGRAM_CHAT_ID \
-F document=@$part
fi
done
echo "Files sent to Telegram successfully!"
python backup.py --token ${{ secrets.TELEGRAM_BOT_TOKEN }} --chat_id ${{ secrets.TELEGRAM_CHAT_ID }}

1101
Limoka.py

File diff suppressed because it is too large Load Diff

1420
LimokaLegacy.py Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -23,4 +23,4 @@ class K(loader.Module):
"""K"""
raise Exception("Testing error handling")
await utils.answer(message, "K")
# why
# why FUCK YOU BILL GATES ЛЛЛЛ

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,267 @@
#░░░███░███░███░███░███
#░░░░░█░█░░░░█░░█░░░█░█
#░░░░█░░███░░█░░█░█░█░█
#░░░█░░░█░░░░█░░█░█░█░█
#░░░███░███░░█░░███░███
# meta developer: @nullmod
__version__ = (1, 0, 1)
import io
import math
from PIL import Image, ImageDraw
from herokutl.tl.custom import Message
from herokutl.tl.functions.help import (
GetPeerProfileColorsRequest
)
from herokutl.tl.types import (
EmojiStatusCollectible
)
from .. import loader, utils
def resize_image(image: Image.Image, max_size: int = 1280) -> Image.Image:
w, h = image.size
if max(w, h) <= max_size:
return image
else:
scale = max_size / max(w, h)
new_w = int(w * scale)
new_h = int(h * scale)
return image.resize((new_w, new_h), Image.LANCZOS)
# Source: https://gist.github.com/weihanglo/1e754ec47fdd683a42fdf6a272904535#file-draw_gradient_pillow-py
def get_gradient(size: tuple, color1: tuple, color2: tuple, gradient_type: str = "linear") -> Image.Image:
def interpolate(f_co, t_co, interval):
if interval <= 1:
yield list(t_co)
return
det_co = [(t - f) / (interval - 1) for f, t in zip(f_co, t_co)]
for i in range(interval):
yield [round(f + det * i) for f, det in zip(f_co, det_co)]
gradient = Image.new('RGB', size, color=(0, 0, 0))
draw = ImageDraw.Draw(gradient)
if gradient_type == "linear":
top_color, bottom_color = color1, color2
for y, color in enumerate(interpolate(top_color, bottom_color, max(1, size[1]))):
draw.line([(0, y), (size[0], y)], fill=tuple(color), width=1)
elif gradient_type == "radial":
center_color, edge_color = color1, color2
max_radius = math.hypot(size[0], size[1]) / 2.0
interval = max(1, int(math.ceil(max_radius)) + 1)
colors = list(interpolate(center_color, edge_color, interval))
cx = size[0] / 2
cy = size[1] / 2
for r_index, color in enumerate(colors):
r = interval - 1 - r_index
if r < 0:
continue
bbox = [
int(round(cx - r)),
int(round(cy - r)),
int(round(cx + r)),
int(round(cy + r))
]
draw.ellipse(bbox, fill=tuple(color))
return gradient
def set_gradient(im: io.BytesIO, gradient: Image.Image) -> io.BytesIO:
img = resize_image(Image.open(im).convert('RGBA'))
max_size = max(img.width, img.height)
gradient = gradient.resize((max_size, max_size), Image.LANCZOS).convert('RGBA')
left = (max_size - img.width) // 2
top = (max_size - img.height) // 2
gradient.paste(img, (left, top), img)
buffer = io.BytesIO()
gradient.save(buffer, format='PNG')
buffer.seek(0)
return buffer
def crop_by_bbox(img: Image.Image, bbox: tuple = None):
img_w, img_h = img.size
x, y, w, h = bbox or BBOX_TGA_TGD
left = int(round(x * img_w))
top = int(round(y * img_h))
right = int(round((x + w) * img_w))
bottom = int(round((y + h) * img_h))
return img.crop((left, top, right, bottom))
def hex_to_rgb(value: int):
return ((value >> 16) & 255, (value >> 8) & 255, value & 255)
def hexes_to_rgbs(value: list):
if len(value) > 1:
res = list()
for i in value:
res.append(hex_to_rgb(i))
return tuple(res)
else:
res = hex_to_rgb(value[0])
return (res, res)
SHAPES = {
# TODO: фигуры для создания масок на авы
}
BBOX_TGA_TGD = (
2894 / 8268,
1260 / 8268,
2504 / 8268,
2504 / 8268,
)
@loader.tds
class Gradientor(loader.Module):
strings = {
"name": "Gradientor",
"_cls_doc": "A module to create your profile picture with a background from your profile",
"gradient_creating": "<tg-emoji emoji-id=5886667040432853038>🔁</tg-emoji> Creating gradient...",
"gradient_created": "<tg-emoji emoji-id=5818804345247894731>✅</tg-emoji> Gradient created!",
}
strings_ru = {
"_cls_doc": "Модуль для создания вашей аватарки на фоне из вашего профиля",
"gradient_creating": "<tg-emoji emoji-id=5886667040432853038>🔁</tg-emoji> Создание градиента...",
"gradient_created": "<tg-emoji emoji-id=5818804345247894731>✅</tg-emoji> Градиент создан!",
}
async def client_ready(self):
self.colors = self.get("PROFILE_COLORS", None)
if not self.colors or not self.colors.get("light", None):
raw_colors = (await self.client(GetPeerProfileColorsRequest(0))).colors
self.colors = {
"dark": {
str(col.color_id): hexes_to_rgbs(col.dark_colors.bg_colors) for col
in raw_colors
},
"light": {
str(col.color_id): hexes_to_rgbs(col.colors.bg_colors) for col
in raw_colors
},
}
self.set("PROFILE_COLORS", self.colors)
@loader.command(
ru_doc="[фотография/reply] - создать аватарку с градиентом из цвета профиля\n"
"--update-cache - обновить кеш профиля, если вы только что сменили фон профиля\n"
"--linear - использовать линейный градиент\n"
"--light - использовать светлую тему"
)
async def makepp(self, message: Message):
"""[photo/reply] - create a profile picture with a gradient from profile color\n
--update-cache - update profile cache if you just changed profile background\n
--linear - use linear gradient\n
--light - use light theme"""
reply: Message = await message.get_reply_message()
args = utils.get_args(message)
if "--update-cache" in args:
upd_cache = True
args.remove("--update-cache")
else:
upd_cache = False
if "--linear" in args:
force_linear = True
args.remove("--linear")
else:
force_linear = False
if "--light" in args:
theme = "light"
args.remove("--light")
else:
theme = "dark"
if "--full" in args:
_full = True
args.remove("--full")
else:
_full = False
user = None
background_only = False
if args:
user = await self.client.get_entity(int(args[0]) if args[0].isdigit() else args[0])
photo_source = (
message
if (not reply or not (reply.photo or reply.document and "image/" in getattr(reply.document, "mime_type", "")))
else reply
)
if not (photo_source.photo or photo_source.document and "image/" in getattr(photo_source.document, "mime_type", "")):
background_only = True
if not user:
if upd_cache:
user = self.client.hikka_me = await self.client.get_me()
elif reply:
user = reply.sender
else:
user = self.client.hikka_me
if not user.premium:
color1, color2 = (28, 28, 28), (28, 28, 28)
elif user.emoji_status and isinstance(user.emoji_status, EmojiStatusCollectible):
color1, color2 = (
user.emoji_status.edge_color, user.emoji_status.center_color
)
color1 = hex_to_rgb(color1)
color2 = hex_to_rgb(color2)
elif user.profile_color:
color_variant = user.profile_color.color
color1, color2 = self.colors.get(theme).get(
str(color_variant),
((28, 28, 28), (28, 28, 28))
)
else:
color1, color2 = (28, 28, 28), (28, 28, 28)
await utils.answer(message, self.strings["gradient_creating"])
gradient = get_gradient((1280, 1280), color1, color2, "linear" if force_linear else "radial")
if not _full:
gradient = crop_by_bbox(gradient)
if not background_only and not _full:
p_b = await photo_source.download_media(bytes)
p_b_io = io.BytesIO(p_b)
p_b_io.seek(0)
result = set_gradient(p_b_io, gradient)
else:
result = io.BytesIO()
gradient.save(result, format='PNG')
result.seek(0)
result.name = "grad @nullmod.png"
await utils.answer(message, self.strings["gradient_created"], file=result, force_document=True)

View File

@@ -1,3 +1,4 @@
Chess
HaremManager
SchedulePlus
SchedulePlus
Gradientor

View File

@@ -168,10 +168,10 @@ class DaysToMyBirthday(loader.Module):
await asyncio.sleep(60)
@loader.command(
ru_doc="Выставить таймер дней в ник (нестабильно)",
en_doc="Set the timer of days in the nickname (unstable)",
ru_doc="Включить таймер дней в ник (нестабильно)",
en_doc="Enable timer of days in nickname (unstable)",
)
async def btname(self, message):
async def btnameon(self, message):
try:
user = await self.client(GetFullUserRequest(self.client.hikka_me.id))
name = user.users[0].last_name or ""
@@ -181,25 +181,32 @@ class DaysToMyBirthday(loader.Module):
return
self.db.set(__name__, "last_name", name)
self.db.set(__name__, "change_name", True)
await utils.answer(message, self.strings("btname_yes"))
@loader.command(
ru_doc="Выключить таймер дней в ник",
en_doc="Disable timer of days in nickname",
)
async def btnameoff(self, message):
change_name = self.db.get(__name__, "change_name", False)
if change_name:
self.db.set(__name__, "change_name", False)
if not change_name:
await utils.answer(message, self.strings("btname_no"))
try:
await self.client(
UpdateProfileRequest(last_name=self.db.get(__name__, "last_name"))
)
await utils.answer(message, self.strings("name_not_changed"))
except UserPrivacyRestrictedError:
await utils.answer(message, self.strings("name_privacy_error"))
except Exception as e:
logger.error(f"Error removing name: {e}")
await utils.answer(message, self.strings("error"))
return
else:
self.db.set(__name__, "change_name", True)
await utils.answer(message, self.strings("btname_yes"))
self.db.set(__name__, "change_name", False)
await utils.answer(message, self.strings("btname_no"))
try:
await self.client(
UpdateProfileRequest(last_name=self.db.get(__name__, "last_name"))
)
await utils.answer(message, self.strings("name_not_changed"))
except UserPrivacyRestrictedError:
await utils.answer(message, self.strings("name_privacy_error"))
except Exception as e:
logger.error(f"Error removing name: {e}")
await utils.answer(message, self.strings("error"))
@loader.command(
ru_doc="Вывести таймер",

View File

@@ -35,6 +35,7 @@ from telethon.types import MessageMediaDocument
logger = logging.getLogger(__name__)
@loader.tds
class CodeShareMod(loader.Module):
"""Uploads your code at the kmi.aeza.net (Pastebin and GitHub Gist alternative)"""
@@ -55,16 +56,16 @@ class CodeShareMod(loader.Module):
async def upload_to_kmi(self, content: str) -> str:
url = "https://kmi.aeza.net"
data = aiohttp.FormData()
data.add_field('kmi', content)
data.add_field("kmi", content)
async with aiohttp.ClientSession() as session:
async with session.post(url, data=data) as response:
if response.status == 200:
link = await response.text()
return link
else:
logger.error(f"Error occurred! Status code: {response.status}")
return
async with session.post(url, data=data) as response:
if response.status == 200:
link = await response.text()
return link
else:
logger.error(f"Error occurred! Status code: {response.status}")
return
@loader.command(
ru_doc="Загрузка кода на сайт",
@@ -75,20 +76,14 @@ class CodeShareMod(loader.Module):
reply = await message.get_reply_message()
if args:
link = await self.upload_to_kmi(args)
await utils.answer(message, self.strings['link_ready'].format(link))
await utils.answer(message, self.strings["link_ready"].format(link))
return
if reply and isinstance(reply.media, MessageMediaDocument):
file_name = await reply.download_media()
async with aiofiles.open(file_name, mode='r') as f:
async with aiofiles.open(file_name, mode="r") as f:
content = await f.read()
link = await self.upload_to_kmi(content)
os.remove(file_name)
await utils.answer(message, self.strings['link_ready'].format(link))
await os.remove(file_name)
await utils.answer(message, self.strings["link_ready"].format(link))
return
await utils.answer(message, self.strings['invalid_args'])
await utils.answer(message, self.strings["invalid_args"])

View File

@@ -31,7 +31,6 @@ import re
from typing import Optional, Set
from telethon.errors import FloodWaitError, MessageDeleteForbiddenError
from telethon.tl.functions.messages import DeleteMessagesRequest
from telethon.tl.types import Message, MessageMediaDocument
from .. import loader, utils
@@ -82,17 +81,20 @@ class EmojiStickerBlocker(loader.Module):
self.blocked_packs: Set[str] = set()
self.blocked_stickers: Set[str] = set()
self.blocked_emojis: Set[str] = set()
self._client = None
self._db = None
async def client_ready(self, client, db):
self._client = client
self._db = db
self._load_blocklists()
def _load_blocklists(self):
"""Load blocklists from database"""
self.blocked_packs = set(self._db.get(__name__, "blocked_packs", []))
self.blocked_stickers = set(self._db.get(__name__, "blocked_stickers", []))
self.blocked_emojis = set(self._db.get(__name__, "blocked_emojis", []))
def _save_blocklists(self):
"""Save blocklists to database"""
self._db.set(__name__, "blocked_packs", list(self.blocked_packs))
self._db.set(__name__, "blocked_stickers", list(self.blocked_stickers))
self._db.set(__name__, "blocked_emojis", list(self.blocked_emojis))
@@ -107,9 +109,15 @@ class EmojiStickerBlocker(loader.Module):
return message.sticker.set_name.lower()
if isinstance(message.media, MessageMediaDocument):
if hasattr(message.media.document, "attributes"):
if hasattr(message.media, "document") and hasattr(
message.media.document, "attributes"
):
for attr in message.media.document.attributes:
if hasattr(attr, "stickerset") and attr.stickerset:
if (
hasattr(attr, "stickerset")
and hasattr(attr.stickerset, "title")
and attr.stickerset.title
):
return attr.stickerset.title.lower()
return None
@@ -126,19 +134,18 @@ class EmojiStickerBlocker(loader.Module):
if emojis:
return emojis[0]
else:
return None
return None
async def _delete_message(self, message: Message) -> bool:
"""Delete message with error handling"""
try:
await self._client(DeleteMessagesRequest([message.id]))
await self._client.delete_messages(message.to_id, [message.id])
return True
except MessageDeleteForbiddenError:
await utils.answer(message, self.strings["no_permission"])
logger.warning("No permission to delete message")
return False
except FloodWaitError as e:
logger.warning(f"Flood wait when deleting message: {e}")
logger.warning(f"Flood wait when deleting message: {e.seconds}s")
return False
except Exception as e:
logger.error(f"Error deleting message: {e}")
@@ -146,19 +153,23 @@ class EmojiStickerBlocker(loader.Module):
async def _should_block_message(self, message: Message) -> tuple[bool, str]:
"""Check if message should be blocked and return reason"""
pack_name = self._extract_pack_name(message)
emoji_text = self._extract_emoji_text(message)
try:
pack_name = self._extract_pack_name(message)
emoji_text = self._extract_emoji_text(message)
if pack_name and pack_name in self.blocked_packs:
return True, f"pack: {pack_name}"
if pack_name and pack_name in self.blocked_packs:
return True, f"pack: {pack_name}"
if message.sticker:
sticker_id = str(message.sticker.id)
if sticker_id in self.blocked_stickers:
return True, f"sticker: {sticker_id}"
if message.sticker:
sticker_id = str(message.sticker.id)
if sticker_id in self.blocked_stickers:
return True, f"sticker: {sticker_id}"
if emoji_text and emoji_text in self.blocked_emojis:
return True, f"emoji: {emoji_text}"
if emoji_text and emoji_text in self.blocked_emojis:
return True, f"emoji: {emoji_text}"
except Exception as e:
logger.error(f"Error checking message: {e}")
return False, ""
@@ -174,7 +185,9 @@ class EmojiStickerBlocker(loader.Module):
pack_name = args.lower().strip()
# Add to blocked packs
if pack_name in self.blocked_packs:
return await utils.answer(message, self.strings["not_found"])
self.blocked_packs.add(pack_name)
self._save_blocklists()
@@ -194,6 +207,10 @@ class EmojiStickerBlocker(loader.Module):
return await utils.answer(message, self.strings["no_reply"])
sticker_id = str(reply_msg.sticker.id)
if sticker_id in self.blocked_stickers:
return await utils.answer(message, self.strings["not_found"])
self.blocked_stickers.add(sticker_id)
self._save_blocklists()
@@ -206,6 +223,7 @@ class EmojiStickerBlocker(loader.Module):
async def emojiblock(self, message: Message):
"""Block emoji from reply or input"""
args = utils.get_args_raw(message)
emoji_text = None
if args:
emoji_text = args.strip()
@@ -223,6 +241,9 @@ class EmojiStickerBlocker(loader.Module):
if not emoji_text:
return await utils.answer(message, self.strings["no_reply"])
if emoji_text in self.blocked_emojis:
return await utils.answer(message, self.strings["not_found"])
self.blocked_emojis.add(emoji_text)
self._save_blocklists()
@@ -326,6 +347,8 @@ class EmojiStickerBlocker(loader.Module):
async def watcher(self, message: Message):
"""Monitor messages and block unwanted content"""
if not self._client or not self._db:
return
if message.is_group or message.is_channel:
return

View File

@@ -1,91 +1,184 @@
<div align="center">
<img src="https://github.com/Codwizer/ReModules/blob/main/assets/Vector.png" alt="hikka_mods" width="600">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://github.com/Codwizer/ReModules/blob/main/assets/Vector.png">
<img src="https://github.com/Codwizer/ReModules/blob/main/assets/Vector.png" alt="H:Mods Logo" width="400">
</picture>
</div>
<h1 align="center">H:Mods - Hikka Modules</h1>
<h1 align="center">
<a href="https://github.com/archquise/H.Modules">
<img src="https://readme-typing-svg.herokuapp.com/?lines=H:Mods;Hikka+Modules+Collection&center=true&vCenter=true&width=500&height=80&color=00D9FF&center=true&vCenter=true">
</a>
</h1>
<p align="center">
Enhance your <a href="https://github.com/hikariatama/Hikka">Hikka</a>/<a href="https://github.com/coddrago/Heroku">Heroku</a> experience with a curated collection of community modules.
<a href="https://github.com/hikariatama/Hikka">
<img src="https://img.shields.io/badge/Hikka-Userbot-blue?style=for-the-badge&logo=python" alt="Hikka">
</a>
<a href="https://github.com/coddrago/Heroku">
<img src="https://img.shields.io/badge/Heroku-Userbot-purple?style=for-the-badge&logo=heroku" alt="Heroku">
</a>
</p>
<p align="center">
<a href="https://t.me/hikka_mods">
<img src="https://img.shields.io/badge/Join%20the-Telegram%20Channel-blue?style=flat-square&logo=telegram" alt="Telegram Channel">
<img src="https://img.shields.io/badge/Telegram%20Channel-2CA5E0?style=for-the-badge&logo=telegram&logoColor=white" alt="Telegram Channel">
</a>
<a href="https://github.com/archquise/H.Modules">
<img src="https://img.shields.io/badge/GitHub-Repository-181717?style=for-the-badge&logo=github" alt="GitHub">
</a>
<a href="https://github.com/archquise/H.Modules/stargazers">
<img src="https://img.shields.io/github/stars/archquise/H.Modules?style=for-the-badge&logo=github&color=yellow" alt="Stars">
</a>
</p>
---
## ✨ Installation Guide
## 🚀 Quick Start
### 1. Direct Installation
To install a module directly from the repository, use the following command:
```bash
.dlm https://raw.githubusercontent.com/archquise/H.Modules/main/<module_name>.py
```
**Example:** To install example_module.py, use:
```bash
.dlm https://raw.githubusercontent.com/archquise/H.Modules/main/example_module.py
```
### 2. Repository Installation (Recommended)
For easier module management and updates, install the entire repository.
**Step 1: Add the Repository**
### 📦 Repository Installation (Recommended)
The easiest way to install and manage all modules:
```bash
.addrepo https://github.com/archquise/H.Modules/raw/main
```
**Step 2: Install Modules from the Repository**
After adding the repository, install any module:
```bash
.dlm <module_name>
```
**Example:** After adding the repository, to install example_module, use:
### 🎯 Direct Installation
Install a specific module directly:
```bash
.dlm example_module
.dlm https://raw.githubusercontent.com/archquise/H.Modules/main/<module_name>.py
```
---
## 📜 License
## 🛠️ Installation Guide
This project is licensed under a **Proprietary License**. By using this software, you agree to the terms and conditions outlined below.
### Step 1: Add Repository
> **You are granted permission to use the Software for personal and non-commercial purposes, subject to the following conditions:**
```bash
.addrepo https://github.com/archquise/H.Modules/raw/main
```
1. Modification or alteration of the Software is strictly prohibited without explicit written permission from the author.
2. Redistribution of the Software, in original or modified form, is strictly prohibited without explicit written permission from the author.
3. The Software is provided "as is", without any warranty, express or implied.
4. The copyright notice and this permission notice must be included in all copies or substantial portions of the Software.
5. By using the Software, you agree to be bound by the terms and conditions of this license.
### Step 2: Install Modules
**Contact:** For any inquiries or requests for permissions, please contact archquise@gmail.com.
```bash
# Install specific module
.dlm TelegraphComic
# Install from direct URL
.dlm https://raw.githubusercontent.com/archquise/H.Modules/main/TelegraphComic.py
```
### Step 4: Configure Modules
Most modules have configurable settings:
```bash
# View module configuration
.config TelegraphComic
# Update configuration
.config TelegraphComic upload_service catbox
```
## 🐛 Troubleshooting
### Common Issues
<details>
<summary>Show Full License Details</summary>
> <i>All files of this repository are under <b>Proprietary License.</b></i><br>
> <b>Permission is hereby granted to any person obtaining a copy of this software and associated documentation files (the "Software"), to use the Software for personal and non-commercial purposes, subject to the following conditions:</b>
<summary>❌ Module Installation Failed</summary>
1. The Software may not be modified, altered, or otherwise changed in any way without the explicit written permission of the author.
2. Redistribution of the Software, in original or modified form, is strictly prohibited without the explicit written permission of the author.
3. The Software is provided "as is", without warranty of any kind, express or implied.
4. The copyright notice and this permission notice must be included in all copies or substantial portions of the Software.
5. By using the Software, you agree to be bound by the terms and conditions of this license.
**Solution:**
1. Check repository URL is correct
2. Ensure you have internet connection
3. Try restarting Hikka/Heroku
4. Use direct installation method
```bash
.dlm https://raw.githubusercontent.com/archquise/H.Modules/main/<module_name>.py
```
</details>
<details>
<summary>⚠️ Module Not Working</summary>
**Solution:**
2. Check configuration: `.cfg <module_name>`
3. Check dependencies are installed
4. Update the module: `.dlm <module_name>`
</details>
<details>
<summary>🔧 Configuration Issues</summary>
**Solution:**
1. Reset to defaults: `.cfg <module_name> reset`
2. Check syntax: `.cfg <module_name>`
3. View help: `.help <module_name>`
For any inquiries or requests for permissions, please contact archquise@gmail.com.
</details>
---
<p align="center">
<img src="https://raw.githubusercontent.com/trinib/trinib/82213791fa9ff58d3ca768ddd6de2489ec23ffca/images/footer.svg" width="100%">
</p>
## 📜 License
<div align="center">
**🔒 Proprietary License**
This project is licensed under a proprietary license. By using this software, you agree to the following terms:
</div>
### 📋 License Terms
> **✅ What You CAN Do:**
> - Use the software for personal and non-commercial purposes
> - Install and use modules in Hikka/Heroku
> - Modify configuration settings
> - Report issues and suggest improvements
> **❌ What You CANNOT Do:**
> - Modify, alter, or change the software without explicit permission
> - Redistribute the software in original or modified form
> - Use for commercial purposes without permission
> - Remove copyright notices or attribution
### 📧 Contact
For inquiries or permission requests:
- **Email:** `archquise@gmail.com`
- **Telegram:** [@hikka_mods](https://t.me/hikka_mods)
---
<div align="center">
<picture>
<img src="https://raw.githubusercontent.com/trinib/trinib/82213791fa9ff58d3ca768ddd6de2489ec23ffca/images/footer.svg" alt="Footer" width="100%">
</picture>
<p>
<sub>Built with ❤️ for the Hikka/Heroku community</sub>
</p>
<p>
<a href="#top">⬆️ Back to Top</a>
</p>
</div>

View File

@@ -0,0 +1,536 @@
# Proprietary License Agreement
# Copyright (c) 2026-2029 CodWiz
# Permission is hereby granted to any person obtaining a copy of this software and associated documentation files (the "Software"), to use the Software for personal and non-commercial purposes, subject to the following conditions:
# 1. The Software may not be modified, altered, or otherwise changed in any way without the explicit written permission of the author.
# 2. Redistribution of the Software, in original or modified form, is strictly prohibited without the explicit written permission of the author.
# 3. The Software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and non-infringement. In no event shall the author or copyright holder be liable for any claim, damages, or other liability, whether in an action of contract, tort, or otherwise, arising from, out of, or in connection with the Software or the use or other dealings in the Software.
# 4. Any use of the Software must include the above copyright notice and this permission notice in all copies or substantial portions of the Software.
# 5. By using the Software, you agree to be bound by the terms and conditions of this license.
# For any inquiries or requests for permissions, please contact codwiz@yandex.ru.
# ---------------------------------------------------------------------------------
# Name: TelegraphComics
# Description: Create comics on Telegraph from ZIP/RAR archives
# Author: @hikka_mods
# ---------------------------------------------------------------------------------
# meta developer: @hikka_mods
# requires: aiohttp, zipfile, telegraph
# ---------------------------------------------------------------------------------
import asyncio
import logging
import os
import tempfile
from typing import List, Optional
import zipfile
import aiohttp
from telethon.types import MessageMediaDocument, Message
from telegraph import Telegraph
from .. import loader, utils
logger = logging.getLogger(__name__)
@loader.tds
class TelegraphComicMod(loader.Module):
"""Create comics on Telegraph from ZIP/CBZ/RAR archives"""
strings = {
"name": "TelegraphComic",
"invalid_args": "<emoji document_id=5388785832956016892>❌</emoji> Invalid arguments. Usage: .telegraphcomics <title> | <cover_url> (optional)",
"no_reply": "<emoji document_id=5388785832956016892>❌</emoji> Reply to a message with ZIP/CBZ/RAR file",
"unsupported_format": "<emoji document_id=5388785832956016892>❌</emoji> Unsupported file format. Only ZIP/CBZ/RAR files are supported",
"processing": "<emoji document_id=5256094480498436162>⏳</emoji> Processing archive...",
"uploading": "<emoji document_id=5854762571659218443>⏳</emoji> Uploading images...",
"creating_article": "<emoji document_id=5854762571659218443>⏳</emoji> Creating Telegraph article...",
"archive_extracted": "<emoji document_id=5854762571659218443>📦</emoji> Archive successfully extracted: <emoji document_id=5208422125924275090>✅</emoji>",
"upload_files": "<emoji document_id=5854762571659218443>📦</emoji> Upload image files:",
"creating_telegraph": "<emoji document_id=5854762571659218443>📝</emoji> Creating Telegraph article:",
"success": '<emoji document_id=5208422125924275090>✅</emoji> <b>Telegraph article created!</b>\n\n<emoji document_id=5256094480498436162>📦</emoji> Archive successfully extracted: <emoji document_id=5208422125924275090>✅</emoji>\n\n<emoji document_id=5256094480498436162>📦</emoji> Upload image files:\n{upload_status}\n\n<emoji document_id=5256230583717079814>📝</emoji> Creating Telegraph article:\n{article_status}\n\n<emoji document_id=5271604874419647061>🔗</emoji> <a href="{url}">{url}</a>',
"error": "<emoji document_id=5854929766146118183>❌</emoji> <b>Error:</b> {}",
"_cls_doc": "Create comics on Telegraph from ZIP/CBZ/RAR archives",
}
strings_ru = {
"_cls_doc": "Создание комиксов на Telegraph из ZIP/CBZ/RAR архивов",
"invalid_args": "<emoji document_id=5388785832956016892>❌</emoji> Неверные аргументы. Использование: .telegraphcomics <название> | <ссылкаа_обложку>(необязательно)",
"no_reply": "<emoji document_id=5388785832956016892>❌</emoji> Ответьте на сообщение с ZIP/CBZ/RAR файлом",
"unsupported_format": "<emoji document_id=5388785832956016892>❌</emoji> Неподдерживаемый формат. Только ZIP/CBZ/RAR файлы",
"processing": "<emoji document_id=5256094480498436162>⏳</emoji> Обработка архива...",
"uploading": "<emoji document_id=5256094480498436162>⏳</emoji> Загрузка изображений...",
"creating_article": "<emoji document_id=5854762571659218443>⏳</emoji> Создание Telegraph статьи...",
"archive_extracted": "<emoji document_id=5256094480498436162>📦</emoji> Архив успешно распакован: <emoji document_id=5208422125924275090>✅</emoji>",
"upload_files": "<emoji document_id=5256094480498436162>📦</emoji> Загрузка файлов изображений:",
"creating_telegraph": "<emoji document_id=5854762571659218443>📝</emoji> Создание Telegraph статьи:",
"success": '<emoji document_id=5208422125924275090>✅</emoji> <b>Telegraph статья создана!</b>\n\n<emoji document_id=5256094480498436162>📦</emoji> Архив успешно распакован: <emoji document_id=5208422125924275090>✅</emoji>\n\n<emoji document_id=5256094480498436162>📦</emoji> Загрузка файлов изображений:\n{upload_status}\n\n<emoji document_id=5256230583717079814>📝</emoji> Создание Telegraph статьи:\n{article_status}\n\n<emoji document_id=5271604874419647061>🔗</emoji> <a href="{url}">{url}</a>',
"error": "<emoji document_id=5388785832956016892>❌</emoji> <b>Ошибка:</b> {}",
"available_services": "Доступные сервисы: catbox, bashupload, kappa, x0, tmpfiles, pomf",
"current_service": "Текущий сервис: {}",
"invalid_service": "❌ Неизвестный сервис: {}\n\n{}",
}
def __init__(self):
self.config = loader.ModuleConfig(
loader.ConfigValue(
"upload_service",
"catbox",
"Upload service to use",
validator=loader.validators.Choice(
["catbox", "bashupload", "kappa", "x0", "tmpfiles", "pomf"]
),
),
loader.ConfigValue(
"short_name",
"HikkaMods",
"short name for the article",
validator=loader.validators.String(),
),
loader.ConfigValue(
"author_name",
"HikkaMods",
"nickname of the author of the article",
validator=loader.validators.String(),
),
loader.ConfigValue(
"author_url",
"https://t.me/hikka_mods",
"link to author",
validator=loader.validators.String(),
),
)
async def client_ready(self, client, db):
self.client = client
self.db = db
self.telegraph = Telegraph()
self.telegraph.create_account(
short_name=self.config["short_name"],
author_name=self.config["author_name"],
author_url=self.config["author_url"],
)
async def _upload_file_to_service(
self,
session: aiohttp.ClientSession,
url: str,
file_path: str,
field_name: str,
**extra_fields,
) -> Optional[str]:
"""Generic file upload method"""
try:
with open(file_path, "rb") as f:
data = aiohttp.FormData()
data.add_field(field_name, f, filename=os.path.basename(file_path))
for key, value in extra_fields.items():
data.add_field(key, value)
async with session.post(url, data=data) as response:
if response.status == 200:
result = await response.text()
return result.strip() if result else None
else:
logger.info(
f"Upload failed with status {response.status}: {await response.text()}"
)
except Exception as e:
logger.info(f"Error uploading to {url}: {e}")
return None
async def upload_to_catbox(self, file_path: str) -> Optional[str]:
"""Upload file to catbox.moe"""
async with aiohttp.ClientSession() as session:
result = await self._upload_file_to_service(
session,
"https://catbox.moe/user/api.php",
file_path,
"fileToUpload",
reqtype="fileupload",
)
return (
result
if result and result.startswith("https://files.catbox.moe/")
else None
)
async def upload_to_bashupload(self, file_path: str) -> Optional[str]:
"""Upload file to bashupload.com"""
async with aiohttp.ClientSession() as session:
try:
with open(file_path, "rb") as f:
data = aiohttp.FormData()
data.add_field("file", f, filename=os.path.basename(file_path))
async with session.post(
"https://bashupload.com", data=data
) as response:
if response.status == 200:
result = await response.text()
lines = result.strip().split("\n")
for line in lines:
if line.startswith("https://"):
return line
if "wget" in result:
urls = [
line
for line in result.split("\n")
if "wget" in line
]
if urls:
parts = urls[0].split()
for part in parts:
if part.startswith("https://"):
return part
except Exception as e:
logger.info(f"Error uploading to bashupload: {e}")
return None
async def upload_to_kappa(self, file_path: str) -> Optional[str]:
"""Upload file to kappa.lol"""
async with aiohttp.ClientSession() as session:
try:
with open(file_path, "rb") as f:
data = aiohttp.FormData()
data.add_field("file", f, filename=os.path.basename(file_path))
async with session.post(
"https://kappa.lol/api/upload", data=data
) as response:
if response.status == 200:
result = await response.json()
if result and "id" in result:
return f"https://kappa.lol/{result['id']}"
except Exception as e:
logger.info(f"Error uploading to kappa: {e}")
return None
async def upload_to_x0(self, file_path: str) -> Optional[str]:
"""Upload file to x0.at"""
async with aiohttp.ClientSession() as session:
try:
with open(file_path, "rb") as f:
data = aiohttp.FormData()
data.add_field("file", f, filename=os.path.basename(file_path))
async with session.post("https://x0.at", data=data) as response:
if response.status == 200:
result = await response.text()
return (
result.strip()
if result and "https://" in result
else None
)
except Exception as e:
logger.info(f"Error uploading to x0: {e}")
return None
async def upload_to_tmpfiles(self, file_path: str) -> Optional[str]:
"""Upload file to tmpfiles.org"""
async with aiohttp.ClientSession() as session:
try:
with open(file_path, "rb") as f:
data = aiohttp.FormData()
data.add_field("file", f, filename=os.path.basename(file_path))
async with session.post(
"https://tmpfiles.org/api/v1/upload", data=data
) as response:
if response.status == 200:
result = await response.json()
if result and "data" in result and "url" in result["data"]:
return result["data"]["url"]
except Exception as e:
logger.info(f"Error uploading to tmpfiles: {e}")
return None
async def upload_to_pomf(self, file_path: str) -> Optional[str]:
"""Upload file to pomf.lain.la"""
async with aiohttp.ClientSession() as session:
try:
with open(file_path, "rb") as f:
data = aiohttp.FormData()
data.add_field("files[]", f, filename=os.path.basename(file_path))
async with session.post(
"https://pomf.lain.la/upload.php", data=data
) as response:
if response.status == 200:
result = await response.json()
if result and "files" in result and result["files"]:
return result["files"][0].get("url")
except Exception as e:
logger.info(f"Error uploading to pomf: {e}")
return None
async def upload_file(self, file_path: str) -> Optional[str]:
"""Upload file to selected service"""
service_name = self.config["upload_service"]
service_map = {
"catbox": self.upload_to_catbox,
"bashupload": self.upload_to_bashupload,
"kappa": self.upload_to_kappa,
"x0": self.upload_to_x0,
"tmpfiles": self.upload_to_tmpfiles,
"pomf": self.upload_to_pomf,
}
service_func = service_map.get(service_name)
if not service_func:
return await self.upload_to_catbox(file_path)
try:
result = await service_func(file_path)
return result
except Exception as e:
logger.error(f"Upload to {service_name} failed: {e}")
return None
async def extract_zip_archive(self, zip_path: str, extract_dir: str) -> List[str]:
"""Extract ZIP archive and return sorted list of image files"""
image_extensions = {".png", ".jpg", ".jpeg", ".gif", ".bmp", ".webp", ".avif"}
image_files = []
try:
with zipfile.ZipFile(zip_path, "r") as zip_ref:
zip_ref.extractall(extract_dir)
for root, _, files in os.walk(extract_dir):
for file in files:
if os.path.splitext(file)[1].lower() in image_extensions:
image_files.append(os.path.join(root, file))
image_files.sort(key=lambda x: os.path.basename(x).lower())
except Exception as e:
logger.info(f"Error extracting ZIP archive: {e}")
return image_files
async def create_telegraph_article(
self, title: str, image_urls: List[str], cover_url: Optional[str] = None
) -> Optional[str]:
"""Create Telegraph article with images"""
try:
if cover_url:
content = f'<img src="{cover_url}"/><br>'
content += "<br>".join(f'<img src="{url}"/>' for url in image_urls)
else:
content = "<br>".join(f'<img src="{url}"/>' for url in image_urls)
response = await asyncio.to_thread(
lambda: self.telegraph.create_page(
title=title,
html_content=content,
author_name=self.config["author_name"],
author_url=self.config["author_url"],
)
)
return response["url"]
except Exception as e:
logger.info(f"Error creating Telegraph article: {e}")
return None
async def _process_cover_url(self, cover_url: str) -> Optional[str]:
"""Process cover URL - handle Telegram message links and direct URLs"""
if not cover_url:
return None
cover_url = cover_url.strip()
if "t.me/" in cover_url and "/" in cover_url.split("t.me/")[1]:
try:
parts = cover_url.split("/")
if len(parts) >= 4:
chat_username = parts[-3]
message_id = int(parts[-1])
message = await self.client.get_messages(
chat_username, ids=message_id
)
if message and message.media:
media_path = await message.download_media()
if media_path:
uploaded_url = await self.upload_file(media_path)
os.remove(media_path)
return uploaded_url
except Exception as e:
logger.info(f"Error processing Telegram cover link: {e}")
return cover_url
return cover_url
async def _process_comics_request(self, message, create_func) -> None:
"""Common logic for processing comics requests"""
args = utils.get_args_raw(message)
reply = await message.get_reply_message()
if not args or not reply:
await utils.answer(message, self.strings["invalid_args"])
return
if not isinstance(reply.media, MessageMediaDocument):
await utils.answer(message, self.strings["no_reply"])
return
if "|" in args:
title, cover_url = args.split("|", 1)
else:
title = args
cover_url = None
title = title.strip()
cover_url = (
await self._process_cover_url(cover_url.strip()) if cover_url else None
)
await utils.answer(message, self.strings["processing"])
file_path = await reply.download_media()
if not file_path:
await utils.answer(
message, self.strings["error"].format("Failed to download file")
)
return
try:
if not (file_path.lower().endswith((".zip", ".cbz"))):
await utils.answer(message, self.strings["unsupported_format"])
return
with tempfile.TemporaryDirectory() as temp_dir:
archive_path = file_path
if file_path.lower().endswith(".cbz"):
import shutil
zip_path = file_path[:-4] + ".zip"
shutil.copy2(file_path, zip_path)
archive_path = zip_path
image_files = await self.extract_zip_archive(archive_path, temp_dir)
if archive_path != file_path and os.path.exists(archive_path):
os.remove(archive_path)
if not image_files:
await utils.answer(
message,
self.strings["error"].format("No images found in archive"),
)
return
await utils.answer(message, self.strings["archive_extracted"])
await utils.answer(message, self.strings["uploading"])
upload_tasks = [self.upload_file(img_file) for img_file in image_files]
upload_results = await asyncio.gather(
*upload_tasks, return_exceptions=True
)
image_urls = []
failed_uploads = 0
upload_errors = []
upload_status_lines = []
for i, (img_file, result) in enumerate(
zip(image_files, upload_results)
):
filename = os.path.basename(img_file)
if isinstance(result, Exception):
error_str = str(result)
logger.info(f"Upload failed: {error_str}")
failed_uploads += 1
upload_errors.append(error_str)
upload_status_lines.append(
f"{filename} - <emoji document_id=5388785832956016892>❌</emoji>"
)
elif result and "https://" in result:
image_urls.append(result)
upload_status_lines.append(
f"{filename} - <emoji document_id=5208422125924275090>✅</emoji>"
)
else:
failed_uploads += 1
upload_errors.append("Invalid response from upload service")
upload_status_lines.append(
f"{filename} - <emoji document_id=5388785832956016892>❌</emoji>"
)
if not image_urls:
error_details = []
error_details.append(f"Failed uploads: {failed_uploads}")
if upload_errors:
unique_errors = list(set(upload_errors))[:3]
error_details.append("Errors: " + "; ".join(unique_errors))
error_msg = " | ".join(error_details)
await utils.answer(
message,
self.strings["error"].format(error_msg),
)
return
upload_status = (
self.strings["upload_files"] + "\n" + "\n".join(upload_status_lines)
)
await utils.answer(message, upload_status)
await utils.answer(message, self.strings["creating_article"])
article_url = await create_func(title, image_urls, cover_url)
if article_url:
article_status_lines = []
for i, (img_file, url) in enumerate(zip(image_files, image_urls)):
filename = os.path.basename(img_file)
article_status_lines.append(
f"{filename} - <emoji document_id=5208422125924275090>✅</emoji>"
)
upload_status = "\n".join(upload_status_lines)
article_status = "\n".join(article_status_lines)
await utils.answer(
message,
self.strings["success"].format(
upload_status=upload_status,
article_status=article_status,
url=article_url,
),
)
else:
await utils.answer(
message,
self.strings["error"].format("Failed to create article"),
)
except Exception as e:
await utils.answer(
message,
self.strings["error"].format(f"Processing error: {e}"),
)
finally:
if os.path.exists(file_path):
os.remove(file_path)
@loader.command(
ru_doc="Создать комикс на Telegraph из ZIP/CBZ/RAR архива\nАргументы: <название> | <ссылкаа_обложку>(необязательно)\nИспользование: .telegraphcomics <title> | <cover_url>(optional)",
en_doc="Create Telegraph comic from ZIP/CBZ/RAR archive\nArguments: <title> | <cover_url>(optional)\nUsage: .telegraphcomics <title> | <cover_url>(optional)",
)
async def telegraphcomicscmd(self, message):
await self._process_comics_request(message, self.create_telegraph_article)

View File

@@ -185,20 +185,25 @@ class TimedEmojiStatusMod(loader.Module):
return ""
if document_id:
return f"<emoji document_id={document_id}>📋</emoji>"
return f"[Custom Emoji ID: {document_id}]"
if emoji_str.isdigit():
return f"<emoji document_id={emoji_str}>📋</emoji>"
return f"[Custom Emoji ID: {emoji_str}]"
if "<emoji document_id=" in emoji_str:
return emoji_str
import re
match = re.search(r'document_id=(\d+)', emoji_str)
if match:
return f"[Custom Emoji ID: {match.group(1)}]"
return "[Custom Emoji]"
if len(emoji_str) == 1 or (
len(emoji_str) <= 4 and all(ord(c) >= 0x1F000 for c in emoji_str)
):
return emoji_str
return emoji_str
return emoji_str[:10] + "..." if len(emoji_str) > 10 else emoji_str
async def _set_emoji_status(
self, emoji_input: str, until: datetime | None = None, message: Message = None

View File

@@ -38,6 +38,7 @@ from .. import loader, utils
logger = logging.getLogger(__name__)
@loader.tds
class VirusTotalMod(loader.Module):
"""Professional file scanning with VirusTotal"""

View File

@@ -0,0 +1,223 @@
# Proprietary License Agreement
# Copyright (c) 2024-29 CodWiz
# Permission is hereby granted to any person obtaining a copy of this software and associated documentation files (the "Software"), to use the Software for personal and non-commercial purposes, subject to the following conditions:
# 1. The Software may not be modified, altered, or otherwise changed in any way without the explicit written permission of the author.
# 2. Redistribution of the Software, in original or modified form, is strictly prohibited without the explicit written permission of the author.
# 3. The Software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and non-infringement. In no event shall the author or copyright holder be liable for any claim, damages, or other liability, whether in an action of contract, tort, or otherwise, arising from, out of, or in connection with the Software or the use or other dealings in the Software.
# 4. Any use of the Software must include the above copyright notice and this permission notice in all copies or substantial portions of the Software.
# 5. By using the Software, you agree to be bound by the terms and conditions of this license.
# For any inquiries or requests for permissions, please contact codwiz@yandex.ru.
# ---------------------------------------------------------------------------------
# Name: CAliases
# Description: Module for custom aliases
# Author: @hikka_mods
# ---------------------------------------------------------------------------------
# meta developer: @hikka_mods
# scope: CAliases
# scope: CAliases 0.0.1
# ---------------------------------------------------------------------------------
import logging
from typing import Dict, Optional
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>",
}
def __init__(self):
self._aliases_cache: Optional[Dict[str, Dict[str, str]]] = None
self._prefix_cache: Optional[str] = None
def _get_aliases(self) -> Dict[str, Dict[str, str]]:
if self._aliases_cache is None:
self._aliases_cache = self.get("aliases", {})
return self._aliases_cache
def _save_aliases(self, aliases: Dict[str, Dict[str, str]]) -> None:
self.set("aliases", aliases)
self._aliases_cache = aliases
def _get_prefix(self) -> str:
if self._prefix_cache is None:
self._prefix_cache = self.get_prefix()
return self._prefix_cache
def _format_alias_list(self) -> str:
"""Format aliases list for display"""
aliases = self._get_aliases()
if not aliases:
return self.strings["no_aliases"]
lines = [self.strings["list"].format(len=len(aliases))]
for alias_name, alias_data in aliases.items():
cmd = alias_data["command"]
if alias_data.get("args"):
cmd += f" {alias_data['args']}"
lines.append(
f" <emoji document_id=5280726938279749656>▪️</emoji> <code>{alias_name}</code> "
f"<emoji document_id=5960671702059848143>👈</emoji> <code>{cmd}</code>"
)
return "\n".join(lines)
def _validate_command(self, cmd: str) -> bool:
"""Check if command exists"""
return cmd in self.allmodules.commands
def _parse_alias_args(self, message: types.Message) -> tuple:
"""Parse alias command arguments"""
raw_args = utils.get_args_raw(message)
if not raw_args:
return None, None, None
parts = raw_args.split(" ", 2)
if len(parts) < 2:
return None, None, None
alias_name = parts[0]
command = parts[1]
cmd_args = parts[2] if len(parts) > 2 else ""
return alias_name, command, cmd_args
@loader.command(
ru_doc="Получить список всех алиасов",
en_doc=" Get list of all aliases"
)
async def caliasescmd(self, message: types.Message):
"""Get all aliases"""
await utils.answer(message, self._format_alias_list())
@loader.command(
ru_doc="<имя> Удалить алиас",
en_doc="<name> Remove alias"
)
async def rmcaliascmd(self, message: types.Message):
"""Remove alias"""
args = utils.get_args(message)
if not args:
return await utils.answer(message, self.strings["no_args"])
alias_name = args[0]
aliases = self._get_aliases()
if alias_name not in aliases:
return await utils.answer(message, self.strings["a404"].format(alias_name))
del aliases[alias_name]
self._save_aliases(aliases)
await utils.answer(message, self.strings["deleted"].format(alias_name))
@loader.command(
ru_doc="<имя> <команда> [аргументы] Добавить новый алиас (может содержать ключевое слово {args})",
en_doc="<name> <command> [arguments] Add new alias (may contain {args} keyword)",
)
async def caliascmd(self, message: types.Message):
"""Add new alias (may contain {args} keyword)"""
alias_name, command, cmd_args = self._parse_alias_args(message)
if not alias_name or not command:
return await utils.answer(message, self.strings["no_args"])
if not self._validate_command(command):
return await utils.answer(message, self.strings["c404"].format(command))
aliases = self._get_aliases()
aliases[alias_name] = {"command": command, "args": cmd_args}
self._save_aliases(aliases)
prefix = self._get_prefix()
full_cmd = f"{command} {cmd_args}" if cmd_args else command
args_display = self.strings["argsopt"] if "{args}" in cmd_args else ""
await utils.answer(
message,
self.strings["added"].format(
alias=alias_name,
prefix=prefix,
cmd=full_cmd,
args=args_display,
),
)
@loader.tag(only_messages=True, no_media=True, no_inline=True, out=True)
async def watcher(self, message: types.Message):
"""Handle alias execution"""
if not message.raw_text:
return
aliases = self._get_aliases()
prefix = self._get_prefix()
text = message.raw_text
first_word = text.split()[0].lower()
if not first_word.startswith(prefix):
return
alias_name = first_word[len(prefix) :]
if alias_name not in aliases:
return
alias_data = aliases[alias_name]
command = alias_data["command"]
template_args = alias_data.get("args", "")
user_args = utils.get_args_raw(message)
if user_args and template_args:
final_command = f"{command} {template_args}".format(args=user_args)
else:
final_command = f"{command} {template_args}" if template_args else command
try:
await self.allmodules.commands[command](
await utils.answer(message, f"{prefix}{final_command}")
)
except Exception as e:
logger.error(f"Error executing alias '{alias_name}': {e}")

View File

@@ -1,7 +1,7 @@
# ---------------------------------------------------------------------------------
#░█▀▄░▄▀▀▄░█▀▄░█▀▀▄░█▀▀▄░█▀▀▀░▄▀▀▄░░░█▀▄▀█
#░█░░░█░░█░█░█░█▄▄▀░█▄▄█░█░▀▄░█░░█░░░█░▀░█
#░▀▀▀░░▀▀░░▀▀░░▀░▀▀░▀░░▀░▀▀▀▀░░▀▀░░░░▀░░▒▀
# ░█▀▄░▄▀▀▄░█▀▄░█▀▀▄░█▀▀▄░█▀▀▀░▄▀▀▄░░░█▀▄▀█
# ░█░░░█░░█░█░█░█▄▄▀░█▄▄█░█░▀▄░█░░█░░░█░▀░█
# ░▀▀▀░░▀▀░░▀▀░░▀░▀▀░▀░░▀░▀▀▀▀░░▀▀░░░░▀░░▒▀
# Name: DelMessTools
# Description: Module to manage and delete your messages in the current chat
# Author: @codrago_m
@@ -19,10 +19,11 @@
__version__ = (1, 1, 0)
from hikkatl.tl.types import Message, DocumentAttributeFilename
from telethon.tl.types import Message, DocumentAttributeFilename
from .. import loader, utils
class DelMessTools(loader.Module):
"""Module to manage and delete your messages in the current chat"""
@@ -38,7 +39,12 @@ class DelMessTools(loader.Module):
"enabled": "It's not operational now anyway.",
"disabled": "Operation status changed to disabled.",
"interrupted": "The deletion was interrupted because you changed your mind.",
"none": "You didn't even intend to delete anything here, but anyway it's disabled now."
"none": "You didn't even intend to delete anything here, but anyway it's disabled now.",
"no_args": "Please specify arguments for the command.",
"no_keyword": "Please specify a keyword to delete messages.",
"no_length": "Please specify a valid length.",
"invalid_time": "Invalid time format. Please use the format: YYYY-MM-DD HH:MM:SS",
"invalid_length": "Please specify a valid number for length.",
}
strings_ru = {
@@ -52,30 +58,58 @@ class DelMessTools(loader.Module):
"enabled": "Оно итак сейчас не работает.",
"disabled": "Режим работы изменен на выключено.",
"interrupted": "Удаление было прервано т.к вы передумали.",
"none": "Вы даже не пытались ничего здесь удалить, в любом случае сейчас оно выключено."
"none": "Вы даже не пытались ничего здесь удалить, в любом случае сейчас оно выключено.",
"no_args": "Пожалуйста, укажите аргументы для команды.",
"no_keyword": "Пожалуйста, укажите ключевое слово для удаления сообщений.",
"no_length": "Пожалуйста, укажите корректную длину.",
"invalid_time": "Неверный формат времени. Используйте формат: YYYY-MM-DD HH:MM:SS",
"invalid_length": "Пожалуйста, укажите корректное число для длины.",
}
def __init__(self):
self.client = None
self.db = None
self.tg_id = None
async def client_ready(self, client, db):
self.client = client
self.db = db
self.tg_id = (await client.get_me()).id
@loader.command(
ru_doc="[reply] [-img] [-voice] [-file] [-all] - удалить все ваши сообщения в текущем чате или только до сообщения, на которое ответили\n -all - удалять сообщения в каждой теме, если это форум, иначе флаг игнорируется",
en_doc="[reply] [-img] [-voice] [-file] [-all] - delete all your messages in current chat or only ones up to the message you replied to\n -all - to delete messages in each topic if this is a forum otherwise the flag'll just be ignored",
)
async def purge(self, message: Message):
if not self.client or not self.db or not self.tg_id:
return
async def purgecmd(self, message: Message):
""" [reply] [-img] [-voice] [-file] [-all] - delete all your messages in current chat or only ones up to the message you replied to
-all - to delete messages in each topic if this is a forum otherwise the flag'll just be ingored
"""
reply = await message.get_reply_message()
is_last = False
args, types_filter, is_each = self.get_types_filter(message)
is_forum = (await self.client.get_entity(message.chat.id)).forum
try:
entity = await self.client.get_entity(message.chat.id)
is_forum = getattr(entity, "forum", False)
except Exception:
is_forum = False
status = self.db.get(__name__, "status", {})
status[message.chat.id] = True
self.db.set(__name__, "status", status)
deleted_count = 0
async for i in self.client.iter_messages(message.peer_id):
status = self.db.get(__name__, "status", {})
if status.get(message.chat.id, None) is not True:
return await utils.answer(message, self.strings["interrupted"])
if is_forum and not is_each and utils.get_topic(message) != utils.get_topic(i):
continue
if is_forum and not is_each:
try:
if utils.get_topic(message) != utils.get_topic(i):
continue
except Exception:
pass
if i.from_id == self.tg_id and self.is_valid_type(i, types_filter):
if reply:
@@ -83,58 +117,86 @@ class DelMessTools(loader.Module):
break
if i.id == reply.id:
is_last = True
await message.client.delete_messages(message.peer_id, [i.id])
try:
await self.client.delete_messages(message.peer_id, [i.id])
deleted_count += 1
except Exception:
pass
if reply:
await utils.answer(message, self.strings["purge_reply_complete"])
else:
await utils.answer(message, self.strings["purge_complete"])
async def purgekeywordcmd(self, message: Message):
""" <keyword> [-img] [-voice] [-file] [-all] - delete all your messages containing the specified keyword in the current chat
-all - to delete messages in each topic if this is a forum otherwise the flag'll just be ingored
"""
@loader.command(
ru_doc="<ключевое слово> [-img] [-voice] [-file] [-all] - удалить все ваши сообщения с указанным ключевым словом в текущем чате\n -all - удалять сообщения в каждой теме, если это форум, иначе флаг игнорируется",
en_doc="<keyword> [-img] [-voice] [-file] [-all] - delete all your messages containing the specified keyword in the current chat\n -all - to delete messages in each topic if this is a forum otherwise the flag'll just be ignored",
)
async def purgekeyword(self, message: Message):
if not self.client or not self.db or not self.tg_id:
return
args = utils.get_args_raw(message)
if not args:
return await utils.answer(message, "Please specify anything because you didn't.")
return await utils.answer(message, self.strings["no_args"])
args, types_filter, is_each = self.get_types_filter(message)
if not args:
return await utils.answer(message, "Please specify a keyword to delete messages.")
return await utils.answer(message, self.strings["no_keyword"])
is_forum = (await self.client.get_entity(message.chat.id)).forum
try:
entity = await self.client.get_entity(message.chat.id)
is_forum = getattr(entity, "forum", False)
except Exception:
is_forum = False
status = self.db.get(__name__, "status", {})
status[message.chat.id] = True
self.db.set(__name__, "status", status)
deleted_count = 0
async for i in self.client.iter_messages(message.peer_id):
status = self.db.get(__name__, "status", {})
if status.get(message.chat.id, None) is not True:
return await utils.answer(message, self.strings["interrupted"])
if is_forum and not is_each and utils.get_topic(message) != utils.get_topic(i):
continue
if is_forum and not is_each:
try:
if utils.get_topic(message) != utils.get_topic(i):
continue
except Exception:
pass
if i.from_id == self.tg_id and args.lower() in (i.text or '').lower() and self.is_valid_type(i, types_filter):
await message.client.delete_messages(message.chat.id, [i.id])
if (
i.from_id == self.tg_id
and args.lower() in (i.text or "").lower()
and self.is_valid_type(i, types_filter)
):
try:
await self.client.delete_messages(message.chat.id, [i.id])
deleted_count += 1
except Exception:
pass
await utils.answer(message, self.strings["purge_keyword_complete"])
async def purgetimecmd(self, message: Message):
""" <start_time> <end_time> [-img] [-voice] [-file] [-all] - delete all your messages within the specified time range in the current chat
-all - to delete messages in each topic if this is a forum otherwise the flag'll just be ingored
Time format: YYYY-MM-DD HH:MM:SS
"""
@loader.command(
ru_doc="<начальное время> <конечное время> [-img] [-voice] [-file] [-all] - удалить все ваши сообщения в указанном временном диапазоне в текущем чате\n -all - удалять сообщения в каждой теме, если это форум, иначе флаг игнорируется\n Формат времени: YYYY-MM-DD HH:MM:SS",
en_doc="<start_time> <end_time> [-img] [-voice] [-file] [-all] - delete all your messages within the specified time range in the current chat\n -all - to delete messages in each topic if this is a forum otherwise the flag'll just be ignored\n Time format: YYYY-MM-DD HH:MM:SS",
)
async def purgetime(self, message: Message):
if not self.client or not self.db or not self.tg_id:
return
args = utils.get_args_raw(message)
if not args:
return await utils.answer(message, "Please specify anything because you didn't.")
return await utils.answer(message, self.strings["no_args"])
args, types_filter, is_each = self.get_types_filter(message)
args = args.split()
if not args or len(args) < 2:
return await utils.answer(message, "Please specify the start and end time in the format: YYYY-MM-DD HH:MM:SS")
return await utils.answer(message, self.strings["no_args"])
from datetime import datetime
@@ -142,66 +204,111 @@ class DelMessTools(loader.Module):
start_time = datetime.strptime(args[0], "%Y-%m-%d %H:%M:%S")
end_time = datetime.strptime(args[1], "%Y-%m-%d %H:%M:%S")
except ValueError:
return await utils.answer(message, "Invalid time format. Please use the format: YYYY-MM-DD HH:MM:SS")
return await utils.answer(message, self.strings["invalid_time"])
is_forum = (await self.client.get_entity(message.chat.id)).forum
try:
entity = await self.client.get_entity(message.chat.id)
is_forum = getattr(entity, "forum", False)
except Exception:
is_forum = False
status = self.db.get(__name__, "status", {})
status[message.chat.id] = True
self.db.set(__name__, "status", status)
deleted_count = 0
async for i in self.client.iter_messages(message.peer_id):
status = self.db.get(__name__, "status", {})
if status.get(message.chat.id, None) is not True:
return await utils.answer(message, self.strings["interrupted"])
if is_forum and not is_each and utils.get_topic(message) != utils.get_topic(i):
continue
if is_forum and not is_each:
try:
if utils.get_topic(message) != utils.get_topic(i):
continue
except Exception:
pass
if i.from_id == self.tg_id and start_time <= i.date <= end_time and self.is_valid_type(i, types_filter):
await message.client.delete_messages(message.peer_id, [i.id])
if (
i.from_id == self.tg_id
and start_time <= i.date <= end_time
and self.is_valid_type(i, types_filter)
):
try:
await self.client.delete_messages(message.peer_id, [i.id])
deleted_count += 1
except Exception:
pass
await utils.answer(message, self.strings["purge_time_complete"])
async def purgelengthcmd(self, message: Message):
""" <length> [-img] [-voice] [-file] [-all] - delete all your messages with the specified length in the current chat
-all - to delete messages in each topic if this is a forum otherwise the flag'll just be ingored
"""
@loader.command(
ru_doc="<длина> [-img] [-voice] [-file] [-all] - удалить все ваши сообщения указанной длины в текущем чате\n -all - удалять сообщения в каждой теме, если это форум, иначе флаг игнорируется",
en_doc="<length> [-img] [-voice] [-file] [-all] - delete all your messages with the specified length in the current chat\n -all - to delete messages in each topic if this is a forum otherwise the flag'll just be ignored",
)
async def purgelength(self, message: Message):
if not self.client or not self.db or not self.tg_id:
return
args = utils.get_args_raw(message)
if not args:
return await utils.answer(message, "Please specify anything because you didn't.")
return await utils.answer(message, self.strings["no_args"])
args, types_filter, is_each = self.get_types_filter(message)
if not args:
return await utils.answer(message, "Please specify a valid length.")
return await utils.answer(message, self.strings["no_length"])
length = int(args)
is_forum = (await self.client.get_entity(message.chat.id)).forum
try:
length = int(args)
except ValueError:
return await utils.answer(message, self.strings["invalid_length"])
try:
entity = await self.client.get_entity(message.chat.id)
is_forum = getattr(entity, "forum", False)
except Exception:
is_forum = False
status = self.db.get(__name__, "status", {})
status[message.chat.id] = True
self.db.set(__name__, "status", status)
deleted_count = 0
async for i in self.client.iter_messages(message.peer_id):
status = self.db.get(__name__, "status", {})
if status.get(message.chat.id, None) is not True:
return await utils.answer(message, self.strings["interrupted"])
if is_forum and not is_each and utils.get_topic(message) != utils.get_topic(i):
continue
if is_forum and not is_each:
try:
if utils.get_topic(message) != utils.get_topic(i):
continue
except Exception:
pass
if i.from_id == self.tg_id and len(i.text or '') == length and self.is_valid_type(i, types_filter):
await message.client.delete_messages(message.peer_id, [i.id])
if (
i.from_id == self.tg_id
and len(i.text or "") == length
and self.is_valid_type(i, types_filter)
):
try:
await self.client.delete_messages(message.peer_id, [i.id])
deleted_count += 1
except Exception:
pass
await utils.answer(message, self.strings["purge_length_complete"])
async def nopurgecmd(self, message: Message):
"""
Interrupt the deletion process
Use in the chat where you've previously started deletion
"""
@loader.command(
ru_doc="Прервать процесс удаления\nИспользуйте в чате, где вы ранее начали удаление",
en_doc="Interrupt the deletion process\nUse in the chat where you've previously started deletion",
)
async def nopurge(self, message: Message):
if not self.db:
return
chat_id = utils.get_chat_id(message)
status = self.db.get(__name__, "status", {})
_status = status.get(chat_id, None)
status[chat_id] = False
@@ -214,20 +321,26 @@ class DelMessTools(loader.Module):
else:
await utils.answer(message, self.strings["none"])
def get_types_filter(self, message: Message):
""" Get the types filter from the command arguments."""
args = utils.get_args_raw(message).split()
"""Get the types filter from the command arguments."""
args_raw = utils.get_args_raw(message)
if not args_raw:
return "", [], False
args = args_raw.split()
types_filter = []
valid_types = ["-img", "-voice", "-file", "-all"]
is_each = "-all" in args
_args = args_raw
args_ = ""
for i, arg in enumerate(args):
if arg in valid_types:
_args = " ".join(args[:i])
args_ = " ".join(args[i:])
break
if "-img" in args_:
types_filter.append("img")
if "-voice" in args_:
@@ -240,15 +353,17 @@ class DelMessTools(loader.Module):
return _args, types_filter, is_each
def is_valid_type(self, message: Message, types_filter):
""" Check if the message matches the specified types filter. """
"""Check if the message matches the specified types filter."""
if not types_filter:
return True # No filtering means all types are valid
if "img" in types_filter and message.photo:
if "img" in types_filter and hasattr(message, "photo") and message.photo:
return True
if "voice" in types_filter and message.voice:
return True
if "file" in types_filter and isinstance(message.document, DocumentAttributeFilename):
if "voice" in types_filter and hasattr(message, "voice") and message.voice:
return True
if "file" in types_filter and hasattr(message, "document") and message.document:
for attr in getattr(message.document, "attributes", []):
if isinstance(attr, DocumentAttributeFilename):
return True
return False

View File

@@ -0,0 +1,350 @@
# Proprietary License Agreement
# Copyright (c) 2024-29 CodWiz
# Permission is hereby granted to any person obtaining a copy of this software and associated documentation files (the "Software"), to use the Software for personal and non-commercial purposes, subject to the following conditions:
# 1. The Software may not be modified, altered, or otherwise changed in any way without the explicit written permission of the author.
# 2. Redistribution of the Software, in original or modified form, is strictly prohibited without the explicit written permission of the author.
# 3. The Software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and non-infringement. In no event shall the author or copyright holder be liable for any claim, damages, or other liability, whether in an action of contract, tort, or otherwise, arising from, out of, or in connection with the Software or the use or other dealings in the Software.
# 4. Any use of the Software must include the above copyright notice and this permission notice in all copies or substantial portions of the Software.
# 5. By using the Software, you agree to be bound by the terms and conditions of this license.
# For any inquiries or requests for permissions, please contact codwiz@yandex.ru.
# ---------------------------------------------------------------------------------
# Name: Privacy
# Description: Module for fast privacy settings management
# Author: @hikka_mods
# ---------------------------------------------------------------------------------
# meta developer: @hikka_mods
# scope: Privacy
# scope: Privacy 0.0.1
# ---------------------------------------------------------------------------------
import logging
import re
from typing import Dict, List, Optional
import telethon
from telethon import types
from .. import inline, loader, utils
logger = logging.getLogger(__name__)
@loader.tds
class PrivacyMod(loader.Module):
"""Module for fast privacy settings management"""
_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,
"bio": getattr(types, "InputPrivacyKeyAbout", None),
"invites": types.InputPrivacyKeyChatInvite,
}
_PRIVACY_RULES = {
types.PrivacyValueAllowAll: types.InputPrivacyValueAllowAll,
types.PrivacyValueAllowChatParticipants: types.InputPrivacyValueAllowChatParticipants,
types.PrivacyValueAllowContacts: types.InputPrivacyValueAllowContacts,
types.PrivacyValueAllowUsers: types.InputPrivacyValueAllowUsers,
types.PrivacyValueDisallowAll: types.InputPrivacyValueDisallowAll,
types.PrivacyValueDisallowChatParticipants: types.InputPrivacyValueDisallowChatParticipants,
types.PrivacyValueDisallowContacts: types.InputPrivacyValueDisallowContacts,
types.PrivacyValueDisallowUsers: types.InputPrivacyValueDisallowUsers,
}
strings = {
"name": "Privacy",
"privacy_types": (
"<emoji document_id=5974492756494519709>🔗</emoji> <b>Available privacy types:</b>\n"
),
"no_user": "<emoji document_id=5312383351217201533>⚠️</emoji> <b>User not specified</b>",
"u_silly": (
"<emoji document_id=5449682572223194186>🥺</emoji> <b>You can't set privacy exceptions for yourself</b>"
),
"choose_type": "🔑 <b>Select privacy type to manage</b>",
"not_supported_type": (
"<emoji document_id=5312383351217201533>⚠️</emoji> <b>Privacy type '{}' not supported</b>"
),
"allowed": (
"<emoji document_id=5298609004551887592>💕</emoji> <b>{user} added to allowed users for [{type}]</b>"
),
"disallowed": (
"<emoji document_id=5224379368242965520>💔</emoji> <b>{user} added to disallowed users for [{type}]</b>"
),
"privacy": {
"phone": "Phone Number",
"add_by_phone": "Find by Phone",
"p2p": "P2P Calls",
"online": "Last Seen",
"photos": "Profile Photos",
"forwards": "Message Forwards",
"calls": "Phone Calls",
"voices": "Voice Messages",
"bio": "Bio",
"invites": "Chat 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} добавлен в разрешённые для [{type}]</b>"
),
"disallowed": (
"<emoji document_id=5224379368242965520>💔</emoji> <b>{user} добавлен в запрещённые для [{type}]</b>"
),
"privacy": {
"phone": "Номер телефона",
"add_by_phone": "Поиск по номеру",
"p2p": "P2P звонки",
"online": "Последний вход",
"photos": "Фотографии профиля",
"forwards": "Пересылка сообщений",
"calls": "Звонки",
"voices": "Голосовые сообщения",
"bio": "О себе",
"invites": "Приглашения в чаты",
},
}
def __init__(self):
self._client: Optional[telethon.TelegramClient] = None
self._me: Optional[types.User] = None
async def client_ready(self, client: telethon.TelegramClient, db) -> None:
"""Initialize client and get current user"""
self._client = client
self._me = await client.get_me()
async def _get_user_id(self, message: types.Message) -> Optional[int]:
"""Extract user ID from reply or username"""
reply = await message.get_reply_message()
if reply:
return reply.sender_id
args = utils.get_args(message)
if not args:
return None
username = args[0]
match = re.search(r"(?:t\.me/|@|^(\w+)\.t\.me$)([a-zA-Z0-9_.]+)", username)
if not match:
return None
username = match.group(1) or match.group(2)
try:
entity = await self._client.get_entity(username)
return getattr(entity, "user_id", getattr(entity, "id", None))
except Exception:
return None
def _format_privacy_list(self) -> str:
"""Format privacy types list"""
lines = [self.strings["privacy_types"]]
for key, name in self.strings["privacy"].items():
if key in self._PRIVACY_TYPES:
lines.append(f" <code>{key}</code> — {name}")
return "\n".join(lines)
def _create_privacy_keyboard(
self, user: types.User, action: str
) -> List[List[Dict]]:
"""Create inline keyboard for privacy type selection"""
buttons = []
for key, name in self.strings["privacy"].items():
if key not in self._PRIVACY_TYPES:
continue
buttons.append(
[
{
"text": name,
"callback": self._privacy_callback_handler,
"args": (user, key, action),
}
]
)
return [buttons[i : i + 2] for i in range(0, len(buttons), 2)]
async def _privacy_callback_handler(self, call: inline.types.InlineCall) -> None:
"""Handle privacy type selection callback"""
user, privacy_key, action = call.data
if privacy_key not in self._PRIVACY_TYPES:
await call.answer(self.strings["not_supported_type"].format(privacy_key))
return
privacy_type = self._PRIVACY_TYPES[privacy_key]
await self._update_privacy_settings(user, privacy_type, action)
action_text = "allowed" if action == "allow" else "disallowed"
await call.edit(
self.strings[action_text].format(
user=telethon.utils.get_display_name(user),
type=self.strings["privacy"][privacy_key],
)
)
async def _update_privacy_settings(
self, user: types.User, privacy_key: types.TypeInputPrivacyKey, action: str
) -> None:
"""Update privacy settings for specified user"""
try:
current_rules = await self._client(
telethon.functions.account.GetPrivacyRequest(key=privacy_key)
)
except Exception as e:
logger.error(f"Error getting privacy rules: {e}")
return
new_rules = []
existing_user_ids = set()
for rule in current_rules.rules:
rule_type = type(rule)
if rule_type == types.PrivacyValueAllowUsers:
for user_id in rule.users:
existing_user_ids.add(user_id)
if user_id != user.id:
new_rules.append(rule)
elif rule_type == types.PrivacyValueDisallowUsers:
for user_id in rule.users:
existing_user_ids.add(user_id)
if user_id != user.id:
new_rules.append(rule)
if action == "allow" and user.id not in existing_user_ids:
new_rules.append(
types.InputPrivacyValueAllowUsers(
[types.InputUser(user.id, user.access_hash)]
)
)
elif action == "disallow" and user.id in existing_user_ids:
for rule in new_rules[:]:
if type(rule) in [
types.PrivacyValueAllowUsers,
types.PrivacyValueDisallowUsers,
]:
user_list = getattr(rule, "users", [])
if user.id in user_list:
user_list.remove(user.id)
if not user_list:
new_rules.remove(rule)
break
try:
await self._client(
telethon.functions.account.SetPrivacyRequest(
key=privacy_key, rules=new_rules
)
)
except Exception as e:
logger.error(f"Error updating privacy settings: {e}")
@loader.command(
ru_doc="Список типов настроек приватности",
en_doc="List of privacy types"
)
async def privacytypescmd(self, message: types.Message) -> None:
"""Show available privacy types"""
await utils.answer(message, self._format_privacy_list())
@loader.command(
ru_doc="<user> Добавить в разрешённые",
en_doc="<user> Add to allowed list",
)
async def allowusercmd(self, message: types.Message) -> None:
"""Add user to privacy exceptions"""
user_id = await self._get_user_id(message)
if not user_id:
return await utils.answer(message, self.strings["no_user"])
if user_id == self._me.id:
return await utils.answer(message, self.strings["u_silly"])
try:
user_entity = await self._client.get_entity(user_id)
except Exception:
return await utils.answer(message, self.strings["no_user"])
await self.inline.form(
message=message,
text=self.strings["choose_type"],
reply_markup=self._create_privacy_keyboard(user_entity, "allow"),
)
@loader.command(
ru_doc="<user> Добавить в запрещённые",
en_doc="<user> Add to forbidden list",
)
async def disallowuser(self, message: types.Message) -> None:
"""Add user to privacy restrictions"""
user_id = await self._get_user_id(message)
if not user_id:
return await utils.answer(message, self.strings["no_user"])
if user_id == self._me.id:
return await utils.answer(message, self.strings["u_silly"])
try:
user_entity = await self._client.get_entity(user_id)
except Exception:
return await utils.answer(message, self.strings["no_user"])
await self.inline.form(
message=message,
text=self.strings["choose_type"],
reply_markup=self._create_privacy_keyboard(user_entity, "disallow"),
)
async def _create_privacy_keyboard(
self, user: types.User, action: str
) -> List[List[Dict]]:
"""Create inline keyboard for privacy type selection"""
buttons = []
for key, name in self.strings["privacy"].items():
if key not in self._PRIVACY_TYPES:
continue
buttons.append(
[
{
"text": name,
"callback": self._privacy_callback_handler,
"args": (user, key, action),
}
]
)
return [buttons[i : i + 2] for i in range(0, len(buttons), 2)]

View File

@@ -1,30 +1,32 @@
__version__ = (1, 0, 0)
# █▄▀ ▄▀█ █▀▄▀█ █▀▀ █▄▀ █ █ █▀█ █▀█
# █ █ █▀█ █ ▀ █ ██▄ █ █ ▀▄▄▀ █▀▄ █▄█ ▄
# © Copyright 2025
# ✈ https://t.me/kamekuro
# Proprietary License Agreement
# 🔒 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
# Copyright (c) 2024-29 CodWiz
# You CANNOT edit, distribute or redistribute this file without direct permission from the author.
# Permission is hereby granted to any person obtaining a copy of this software and associated documentation files (the "Software"), to use the Software for personal and non-commercial purposes, subject to the following conditions:
# meta banner: https://raw.githubusercontent.com/kamekuro/hikka-mods/main/banners/sdsaver.png
# meta pic: https://raw.githubusercontent.com/kamekuro/hikka-mods/main/icons/sdsaver.png
# meta developer: @kamekuro_hmods
# scope: hikka_min 1.7.0
# 1. The Software may not be modified, altered, or otherwise changed in any way without the explicit written permission of the author.
# 2. Redistribution of the Software, in original or modified form, is strictly prohibited without the explicit written permission of the author.
# 3. The Software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and non-infringement. In no event shall the author or copyright holder be liable for any claim, damages, or other liability, whether in an action of contract, tort, or otherwise, arising from, out of, or in connection with the Software or the use or other dealings in the Software.
# 4. Any use of the Software must include the above copyright notice and this permission notice in all copies or substantial portions of the Software.
# 5. By using the Software, you agree to be bound by the terms and conditions of this license.
# For any inquiries or requests for permissions, please contact codwiz@yandex.ru.
# ---------------------------------------------------------------------------------
# Name: SDSaver
# Description: The module for automatically saving self-destructing mediat
# Author: @hikka_mods
# ---------------------------------------------------------------------------------
# meta developer: @hikka_mods
# scope: SDSaver
# scope: SDSaver 0.0.1
# ---------------------------------------------------------------------------------
import aiohttp
import asyncio
import io
import json
import logging
import random
import requests
import string
import aiogram
import telethon
@@ -43,17 +45,16 @@ class SDSaverMod(loader.Module):
"name": "SDSaver",
"sdmode_on": "<emoji document_id=5769230088960741619>🔥</emoji> <b>Automatic saving self-destructing media is enabled</b>",
"sdmode_off": "<emoji document_id=5769230088960741619>🔥</emoji> <b>Automatic saving self-destructing media is disabled</b>",
"sd": "🔥 <b><a href=\"{link}\">{name}</a> sent self-destructing media:</b>\n{caption}"
"sd": '🔥 <b><a href="{link}">{name}</a> sent self-destructing media:</b>\n{caption}',
}
strings_ru = {
"_cls_doc": "Модуль для автоматического сохранения самоуничтожающихся медиа",
"sdmode_on": "<emoji document_id=5769230088960741619>🔥</emoji> <b>Автоматическое сохранение самоуничтожающихся медиа включено</b>",
"sdmode_off": "<emoji document_id=5769230088960741619>🔥</emoji> <b>Автоматическое сохранение самоуничтожающихся медиа выключено</b>",
"sd": "🔥 <b><a href=\"{link}\">{name}</a> отправил(а) самоуничтожающееся медиа:</b>\n{caption}"
"sd": '🔥 <b><a href="{link}">{name}</a> отправил(а) самоуничтожающееся медиа:</b>\n{caption}',
}
async def client_ready(self, client, db):
self._client = client
self._db = db
@@ -68,28 +69,23 @@ class SDSaverMod(loader.Module):
)
self._channel = int(f"-100{channel.id}")
@loader.command(
ru_doc="👉 Включить/Выключить автоматическое сохранение самоуничтожающихся медиа"
ru_doc="Включить/Выключить автоматическое сохранение самоуничтожающихся медиа",
en_doc="Enable/Disable automatic saving self-destructing media",
)
async def sdmodecmd(self, message: telethon.types.Message):
"""👉 Enable/Disable automatic saving self-destructing media"""
need_mode = not self.get("save_sd", True)
self.set("save_sd", need_mode)
await utils.answer(
message, self.strings(f"sdmode_{'on' if need_mode else 'off'}")
)
@loader.watcher("in", only_messages=True)
async def watcher(self, message: telethon.types.Message):
if (
not self.get("save_sd", True)
) or (
not message.media
) or (
not getattr(message.media, "ttl_seconds", None)
(not self.get("save_sd", True))
or (not message.media)
or (not getattr(message.media, "ttl_seconds", None))
):
return
@@ -104,17 +100,17 @@ class SDSaverMod(loader.Module):
"caption": self.strings("sd").format(
link=utils.get_entity_url(sender),
name=utils.escape_html(telethon.utils.get_display_name(sender)),
caption=message.text if message.text else ''
)
caption=message.text if message.text else "",
),
}
if message.photo:
args['photo'] = aiogram.types.BufferedInputFile(media, "sd.png")
args["photo"] = aiogram.types.BufferedInputFile(media, "sd.png")
method = self.inline.bot.send_photo
if message.video or message.video_note:
args['video'] = aiogram.types.BufferedInputFile(media, "sd.mp4")
args["video"] = aiogram.types.BufferedInputFile(media, "sd.mp4")
method = self.inline.bot.send_video
if message.voice:
args['voice'] = aiogram.types.BufferedInputFile(media, "sd.ogg")
args["voice"] = aiogram.types.BufferedInputFile(media, "sd.ogg")
method = self.inline.bot.send_voice
await method(**args)
await method(**args)

View File

@@ -27,6 +27,7 @@
# ---------------------------------------------------------------------------------
from telethon.types import Message
from telethon import events
from .. import loader, utils
@@ -79,6 +80,7 @@ class SilentTRMod(loader.Module):
async def client_ready(self, client, db):
self._client = client
self._db = db
self._me = await client.get_me()
self._global_settings = self._db.get(
__name__, "global_settings", {"reactions": False, "tags": False}
@@ -87,27 +89,22 @@ class SilentTRMod(loader.Module):
self._global_ignore = self._db.get(__name__, "global_ignore", [])
self._chat_ignore = self._db.get(__name__, "chat_ignore", {})
client.add_event_handler(self._on_message_reaction_updated)
client.add_event_handler(self._on_new_message)
client.add_event_handler(
self._on_message_reaction_updated, events.MessageReactionsUpdated
)
client.add_event_handler(self._on_new_message, events.NewMessage)
async def on_unload(self):
self._client.remove_event_handler(self._on_message_reaction_updated)
self._client.remove_event_handler(self._on_new_message)
def _save_global_settings(self):
def _save_settings(self):
self._db.set(__name__, "global_settings", self._global_settings)
def _save_chat_settings(self):
self._db.set(__name__, "chat_settings", self._chat_settings)
def _save_global_ignore(self):
self._db.set(__name__, "global_ignore", self._global_ignore)
def _save_chat_ignore(self):
self._db.set(__name__, "chat_ignore", self._chat_ignore)
async def _on_message_reaction_updated(self, event):
"""Обработчик обновления реакций"""
try:
message = await self._client.get_messages(
event.chat_id, ids=event.message_id
@@ -115,226 +112,180 @@ class SilentTRMod(loader.Module):
except Exception:
return
if message.sender_id != (await self._client.get_me()).id:
if message.sender_id != self._me.id:
return
chat_id = str(event.chat_id)
user_id = event.user_id
if user_id in self._global_ignore:
return
if chat_id in self._chat_ignore and user_id in self._chat_ignore[chat_id]:
if user_id in self._global_ignore or (
chat_id in self._chat_ignore and user_id in self._chat_ignore[chat_id]
):
return
chat_settings = self._chat_settings.get(
chat_id, {"reactions": None, "tags": None}
)
if chat_settings["reactions"] is None:
if not self._global_settings["reactions"]:
return
else:
if not chat_settings["reactions"]:
return
reactions_enabled = (
chat_settings["reactions"]
if chat_settings["reactions"] is not None
else self._global_settings["reactions"]
)
await self._client.read_messages(event.chat_id, event.message_id)
if reactions_enabled:
await self._client.read_messages(event.chat_id, event.message_id)
async def _on_new_message(self, event):
"""Обработчик новых сообщений для упоминаний"""
if event.out:
return
me = await self._client.get_me()
mentioned = False
if event.mentioned:
mentioned = True
else:
if event.entities:
for entity in event.entities:
if entity.type == "mentionName" and entity.user_id == me.id:
mentioned = True
break
elif entity.type == "textMention" and entity.user_id == me.id:
mentioned = True
break
if not mentioned:
if event.out or not event.mentioned:
return
chat_id = str(event.chat_id)
user_id = event.sender_id
if user_id in self._global_ignore:
return
if chat_id in self._chat_ignore and user_id in self._chat_ignore[chat_id]:
if user_id in self._global_ignore or (
chat_id in self._chat_ignore and user_id in self._chat_ignore[chat_id]
):
return
chat_settings = self._chat_settings.get(
chat_id, {"reactions": None, "tags": None}
)
if chat_settings["tags"] is None:
if not self._global_settings["tags"]:
tags_enabled = (
chat_settings["tags"]
if chat_settings["tags"] is not None
else self._global_settings["tags"]
)
if tags_enabled:
await event.mark_read()
@loader.command(
ru_doc="[on/off] - тихие реакции во всех чатах",
en_doc="[on/off] - silent reactions in all chats",
)
async def _toggle_setting(
self, message: Message, setting_type: str, scope: str = "global"
):
args = utils.get_args_raw(message).lower()
chat_id = str(message.chat_id) if scope == "chat" else None
if args not in ["on", "off", ""]:
await utils.answer(
message,
self.strings["args_error"]
if scope == "global"
else self.strings["chat_args_error"],
)
return
if scope == "global":
if args == "on":
self._global_settings[setting_type] = True
elif args == "off":
self._global_settings[setting_type] = False
else:
status = "on" if self._global_settings[setting_type] else "off"
await utils.answer(message, f"Global silent {setting_type}: {status}")
return
else:
if not chat_settings["tags"]:
chat_settings = self._chat_settings.get(
chat_id, {"reactions": None, "tags": None}
)
if args == "on":
chat_settings[setting_type] = True
elif args == "off":
chat_settings[setting_type] = False
else:
status = chat_settings[setting_type]
if status is None:
status = f"global ({'on' if self._global_settings[setting_type] else 'off'})"
else:
status = "on" if status else "off"
await utils.answer(
message, f"Silent {setting_type} in this chat: {status}"
)
return
self._chat_settings[chat_id] = chat_settings
await event.mark_read()
self._save_settings()
status_key = "on" if args == "on" else "off"
if scope == "global":
key = f"global_{setting_type}_{status_key}"
else:
key = f"chat_{setting_type}_{status_key}"
await utils.answer(
message,
self.strings.get(
key,
f"{scope.title()} silent {setting_type} {'enabled' if args == 'on' else 'disabled'}",
),
)
@loader.command(
ru_doc="[on/off] - тихие реакции во всех чатах",
en_doc="[on/off] - silent reactions in all chats",
)
async def sreacts(self, message: Message):
"""Toggle global silent reactions"""
args = utils.get_args_raw(message).lower()
if args == "on":
self._global_settings["reactions"] = True
self._save_global_settings()
await utils.answer(message, self.strings["global_reactions_on"])
elif args == "off":
self._global_settings["reactions"] = False
self._save_global_settings()
await utils.answer(message, self.strings["global_reactions_off"])
elif args == "":
status = "on" if self._global_settings["reactions"] else "off"
await utils.answer(message, f"Global silent reactions: {status}")
else:
await utils.answer(message, self.strings["args_error"])
await self._toggle_setting(message, "reactions", "global")
@loader.command(
ru_doc="[on/off] - тихие упоминания во всех чатах",
en_doc="[on/off] - silent tags in all chats",
)
async def stags(self, message: Message):
"""Toggle global silent tags"""
args = utils.get_args_raw(message).lower()
if args == "on":
self._global_settings["tags"] = True
self._save_global_settings()
await utils.answer(message, self.strings["global_tags_on"])
elif args == "off":
self._global_settings["tags"] = False
self._save_global_settings()
await utils.answer(message, self.strings["global_tags_off"])
elif args == "":
status = "on" if self._global_settings["tags"] else "off"
await utils.answer(message, f"Global silent tags: {status}")
else:
await utils.answer(message, self.strings["args_error"])
await self._toggle_setting(message, "tags", "global")
@loader.command(
ru_doc="[on/off] - тихие реакции и упоминания во всех чатах",
en_doc="[on/off] - silent reactions and tags in all chats",
)
async def sall(self, message: Message):
"""Toggle global silent reactions and tags"""
args = utils.get_args_raw(message).lower()
if args == "on":
self._global_settings["reactions"] = True
self._global_settings["tags"] = True
self._save_global_settings()
await utils.answer(message, "✅ Global silent reactions and tags enabled")
elif args == "off":
self._global_settings["reactions"] = False
self._global_settings["tags"] = False
self._save_global_settings()
await utils.answer(message, "❌ Global silent reactions and tags disabled")
elif args == "":
status_r = "on" if self._global_settings["reactions"] else "off"
status_t = "on" if self._global_settings["tags"] else "off"
await utils.answer(
message, f"Global silent reactions: {status_r}, tags: {status_t}"
)
return
else:
await utils.answer(message, self.strings["args_error"])
return
self._save_settings()
await utils.answer(
message,
f"{'' if args == 'on' else ''} Global silent reactions and tags {'enabled' if args == 'on' else 'disabled'}",
)
@loader.command(
ru_doc="[on/off] - тихие реакции в этом чате",
en_doc="[on/off] - silent reactions in this chat",
)
async def hsreacts(self, message: Message):
"""Toggle silent reactions in this chat"""
args = utils.get_args_raw(message).lower()
chat_id = str(message.chat_id)
# Получаем настройки чата или создаем новые
chat_settings = self._chat_settings.get(
chat_id, {"reactions": None, "tags": None}
)
if args == "on":
chat_settings["reactions"] = True
self._chat_settings[chat_id] = chat_settings
self._save_chat_settings()
await utils.answer(message, self.strings["chat_reactions_on"])
elif args == "off":
chat_settings["reactions"] = False
self._chat_settings[chat_id] = chat_settings
self._save_chat_settings()
await utils.answer(message, self.strings["chat_reactions_off"])
elif args == "":
status = chat_settings["reactions"]
if status is None:
status = (
"global ("
+ ("on" if self._global_settings["reactions"] else "off")
+ ")"
)
else:
status = "on" if status else "off"
await utils.answer(message, f"Silent reactions in this chat: {status}")
else:
await utils.answer(message, self.strings["chat_args_error"])
await self._toggle_setting(message, "reactions", "chat")
@loader.command(
ru_doc="[on/off] - тихие упоминания в этом чате",
en_doc="[on/off] - silent tags in this chat",
)
async def hstags(self, message: Message):
"""Toggle silent tags in this chat"""
args = utils.get_args_raw(message).lower()
chat_id = str(message.chat_id)
chat_settings = self._chat_settings.get(
chat_id, {"reactions": None, "tags": None}
)
if args == "on":
chat_settings["tags"] = True
self._chat_settings[chat_id] = chat_settings
self._save_chat_settings()
await utils.answer(message, self.strings["chat_tags_on"])
elif args == "off":
chat_settings["tags"] = False
self._chat_settings[chat_id] = chat_settings
self._save_chat_settings()
await utils.answer(message, self.strings["chat_tags_off"])
elif args == "":
status = chat_settings["tags"]
if status is None:
status = (
"global ("
+ ("on" if self._global_settings["tags"] else "off")
+ ")"
)
else:
status = "on" if status else "off"
await utils.answer(message, f"Silent tags in this chat: {status}")
else:
await utils.answer(message, self.strings["chat_args_error"])
await self._toggle_setting(message, "tags", "chat")
@loader.command(
ru_doc="[on/off] - тихие реакции и упоминания в этом чате",
en_doc="[on/off] - silent reactions and tags in this chat",
)
async def hsall(self, message: Message):
"""Toggle silent reactions and tags in this chat"""
args = utils.get_args_raw(message).lower()
chat_id = str(message.chat_id)
chat_settings = self._chat_settings.get(
chat_id, {"reactions": None, "tags": None}
)
@@ -342,66 +293,58 @@ class SilentTRMod(loader.Module):
if args == "on":
chat_settings["reactions"] = True
chat_settings["tags"] = True
self._chat_settings[chat_id] = chat_settings
self._save_chat_settings()
await utils.answer(
message, "✅ Silent reactions and tags enabled in this chat"
)
elif args == "off":
chat_settings["reactions"] = False
chat_settings["tags"] = False
self._chat_settings[chat_id] = chat_settings
self._save_chat_settings()
await utils.answer(
message, "❌ Silent reactions and tags disabled in this chat"
)
elif args == "":
status_r = chat_settings["reactions"]
if status_r is None:
status_r = (
"global ("
+ ("on" if self._global_settings["reactions"] else "off")
+ ")"
)
else:
status_r = "on" if status_r else "off"
status_t = chat_settings["tags"]
if status_t is None:
status_t = (
"global ("
+ ("on" if self._global_settings["tags"] else "off")
+ ")"
)
else:
status_t = "on" if status_t else "off"
def format_status(status, setting_type):
if status is None:
return f"global ({'on' if self._global_settings[setting_type] else 'off'})"
return "on" if status else "off"
status_r = format_status(status_r, "reactions")
status_t = format_status(status_t, "tags")
await utils.answer(
message, f"Silent reactions: {status_r}, tags: {status_t} in this chat"
)
return
else:
await utils.answer(message, self.strings["chat_args_error"])
return
async def _get_user_id(self, message: Message):
"""Получить ID пользователя из аргументов или ответа"""
reply = await message.get_reply_message()
args = utils.get_args_raw(message)
if reply:
return reply.sender_id
elif args:
try:
user = await self._client.get_entity(args)
return user.id
except Exception:
return None
else:
return None
self._chat_settings[chat_id] = chat_settings
self._save_settings()
await utils.answer(
message,
f"{'' if args == 'on' else ''} Silent reactions and tags {'enabled' if args == 'on' else 'disabled'} in this chat",
)
@loader.command(
ru_doc="[ответ/username] - игнорировать пользователя глобально",
en_doc="[reply/username] - ignore user globally",
)
async def _get_user_id(self, message: Message):
reply = await message.get_reply_message()
args = utils.get_args_raw(message)
if reply:
return reply.sender_id
if args:
try:
user = await self._client.get_entity(args)
return user.id
except Exception:
return None
return None
@loader.command(
ru_doc="[ответ/username] - игнорировать пользователя в этом чате",
en_doc="[reply/username] - ignore user in this chat",
)
async def ignore(self, message: Message):
"""Toggle ignore user globally"""
user_id = await self._get_user_id(message)
if not user_id:
await utils.answer(message, self.strings["no_reply"])
@@ -414,21 +357,18 @@ class SilentTRMod(loader.Module):
self._global_ignore.append(user_id)
await utils.answer(message, self.strings["ignore_added"])
self._save_global_ignore()
self._save_settings()
@loader.command(
ru_doc="[ответ/username] - игнорировать пользователя в этом чате",
en_doc="[reply/username] - ignore user in this chat",
ru_doc="Показать статус Silent T&R", en_doc="Show Silent T&R status"
)
async def hignore(self, message: Message):
"""Toggle ignore user in this chat"""
user_id = await self._get_user_id(message)
if not user_id:
await utils.answer(message, self.strings["no_reply"])
return
chat_id = str(message.chat_id)
if chat_id not in self._chat_ignore:
self._chat_ignore[chat_id] = []
@@ -439,13 +379,12 @@ class SilentTRMod(loader.Module):
self._chat_ignore[chat_id].append(user_id)
await utils.answer(message, self.strings["hignore_added"])
self._save_chat_ignore()
self._save_settings()
@loader.command(
ru_doc="Показать статус Silent T&R", en_doc="Show Silent T&R status"
)
async def strstatus(self, message: Message):
"""Show status"""
global_reactions = "on" if self._global_settings["reactions"] else "off"
global_tags = "on" if self._global_settings["tags"] else "off"

View File

@@ -34,6 +34,7 @@ from .. import loader, utils
logger = logging.getLogger(__name__)
@loader.tds
class TimeZoneMod(loader.Module):
"""Prints current time in selected timezone (UTC+n and tzdata formats supported)"""
@@ -43,7 +44,7 @@ class TimeZoneMod(loader.Module):
"invalid_args": "<emoji document_id=5854929766146118183>❌</emoji> There is no arguments or they are invalid",
"_cls_doc": "Prints current time in selected timezone (UTC+n and tzdata formats supported)",
"time_utc": "<emoji document_id=5276412364458059956>🕓</emoji> Current time by UTC+{}: {}",
"time_tzdata": "<emoji document_id=5276412364458059956>🕓</emoji> Current time in {}: {}"
"time_tzdata": "<emoji document_id=5276412364458059956>🕓</emoji> Current time in {}: {}",
}
strings_ru = {
@@ -51,7 +52,7 @@ class TimeZoneMod(loader.Module):
"invalid_args": "<emoji document_id=5854929766146118183>❌</emoji> Нет аргументов или они неверны",
"tzdata_error": "<emoji document_id=5854929766146118183>❌</emoji> Произошла ошибка при получении времени по tzdata: {}\n\nУбедитесь, что часовой пояс указан верно",
"time_utc": "<emoji document_id=5276412364458059956>🕓</emoji> Текущее время по UTC+{}: {}",
"time_tzdata": "<emoji document_id=5276412364458059956>🕓</emoji> Текущее время в {}: {}"
"time_tzdata": "<emoji document_id=5276412364458059956>🕓</emoji> Текущее время в {}: {}",
}
@loader.command(
@@ -61,12 +62,14 @@ class TimeZoneMod(loader.Module):
async def utccmd(self, message):
args = utils.get_args(message)
if not args or not args[0].isdigit() or len(args) > 1:
await utils.answer(message, self.strings['invalid_args'])
return
await utils.answer(message, self.strings["invalid_args"])
return
offset = timedelta(hours=int(args[0]))
tz = timezone(offset)
time = datetime.now(tz)
await utils.answer(message, self.strings['time_utc'].format(args[0], time.strftime('%H:%M:%S')))
await utils.answer(
message, self.strings["time_utc"].format(args[0], time.strftime("%H:%M:%S"))
)
@loader.command(
ru_doc="Выводит время по часовому поясу tzdata | Использование: .tzdata Europe/Moscow",
@@ -75,12 +78,15 @@ class TimeZoneMod(loader.Module):
async def tzdatacmd(self, message):
args = utils.get_args(message)
if args[0].isdigit() or not args or len(args) > 1:
await utils.answer(message, self.strings['invalid_args'])
return
try:
await utils.answer(message, self.strings["invalid_args"])
return
try:
time = datetime.now(ZoneInfo(args[0]))
except Exception as e:
await utils.answer(message, self.strings['tzdata_error'].format(e))
logger.error(self.strings['tzdata_error'].format(e))
await utils.answer(message, self.strings["tzdata_error"].format(e))
logger.error(self.strings["tzdata_error"].format(e))
return
await utils.answer(message, self.strings['time_tzdata'].format(args[0], time.strftime('%H:%M:%S')))
await utils.answer(
message,
self.strings["time_tzdata"].format(args[0], time.strftime("%H:%M:%S")),
)

View File

@@ -42,6 +42,7 @@ from .. import loader, utils
logger = logging.getLogger(__name__)
@loader.tds
class YTDLMod(loader.Module):
"""Downloads and sends audio/video from YouTube"""
@@ -50,46 +51,47 @@ class YTDLMod(loader.Module):
"name": "YTDL",
"_cls_doc": "Downloads and sends audio/video from YouTube",
"invalid_args": "<emoji document_id=5854929766146118183>❌</emoji> There is no arguments or they are invalid",
"downloading_video": "<emoji document_id=5215484787325676090>🕐</emoji> Video is downloading...",
"downloaded_video": "<emoji document_id=5854762571659218443>✅</emoji> Video is downloaded!",
"downloading_audio": "<emoji document_id=5215484787325676090>🕐</emoji> Audio is downloading...",
"downloaded_audio": "<emoji document_id=5854762571659218443>✅</emoji> Audio is downloaded!",
"downloading": "<emoji document_id=5215484787325676090>🕐</emoji> Downloading...",
"done": "<emoji document_id=5854762571659218443>✅</emoji> Done!",
}
strings_ru = {
"_cls_doc": "Скачивает и отправляет аудио/видео с Ютуба",
"invalid_args": "<emoji document_id=5854929766146118183>❌</emoji> Нет аргументов или они неверны",
"downloading_video": "<emoji document_id=5215484787325676090>🕐</emoji> Видео скачивается...",
"downloaded_video": "<emoji document_id=5854762571659218443>✅</emoji> Видео загружено!",
"downloading_audio": "<emoji document_id=5215484787325676090>🕐</emoji> Аудио скачивается...",
"downloaded_audio": "<emoji document_id=5854762571659218443>✅</emoji> Аудио загружено!",
"downloading": "<emoji document_id=5215484787325676090>🕐</emoji> Скачиваю...",
"done": "<emoji document_id=5854762571659218443>✅</emoji> Готово!",
}
def _validate_url(self, url: str) -> bool:
"""Validate URL format"""
if not url:
return False
url_pattern = re.compile(
r'^(?:https?://)?(?:www\.|m\.)?(?:youtube\.com|youtu\.be|music\.youtube\.com)/(?:watch\?v=|playlist\?list=|channel/|@|live/|shorts/)?[\w-]+',
re.IGNORECASE
r"^(?:https?://)?(?:www\.|m\.)?(?:youtube\.com|youtu\.be|music\.youtube\.com)/(?:watch\?v=|playlist\?list=|channel/|@|live/|shorts/)?[\w-]+",
re.IGNORECASE,
)
return url_pattern.match(url) is not None
async def get_target(self):
system = platform.system()
machine = platform.machine().lower()
machine = platform.machine().lower()
if system == "Windows":
return "Windows"
if system == "Darwin":
return "aarch64-apple-darwin" if machine == "arm64" else "x86_64-apple-darwin"
return (
"aarch64-apple-darwin" if machine == "arm64" else "x86_64-apple-darwin"
)
if system == "Linux":
return "aarch64-unknown-linux-gnu" if machine in ("aarch64", "arm64") else "x86_64-unknown-linux-gnu"
return (
"aarch64-unknown-linux-gnu"
if machine in ("aarch64", "arm64")
else "x86_64-unknown-linux-gnu"
)
return "x86_64-unknown-linux-gnu"
@@ -106,138 +108,131 @@ class YTDLMod(loader.Module):
async def client_ready(self, client, db):
deno_path = Path("deno")
deno_which = shutil.which("deno")
# Trying to fix previous shitcode...
if self.get("deno_source") == "file":
self.set("deno_source", str(deno_path.resolve()))
if not deno_which and not deno_path.is_file():
logger.warning("Deno is not installed, attempting installation...")
target = await self.get_target()
if target == "Windows":
logger.critical("Windows platform is unsupported by this module. All future commands will fail. Please, unload the module.")
return
logger.critical(
"Windows platform is unsupported by this module. All future commands will fail. Please, unload the module."
)
return
async with aiohttp.ClientSession() as session:
download_link = f"https://github.com/denoland/deno/releases/latest/download/deno-{target}.zip"
async with session.get(download_link) as resp:
if resp.status == 200:
async with aiofiles.open("deno.zip", mode='wb') as f:
async for chunk in resp.content.iter_chunked(8192):
await f.write(chunk)
async with aiofiles.open("deno.zip", mode="wb") as f:
async for chunk in resp.content.iter_chunked(8192):
await f.write(chunk)
else:
logger.critical(f"Failed to download Deno: HTTP {resp.status}")
self.set("deno_source", "install_failed")
return
if Path("deno.zip").is_file():
with zipfile.ZipFile("deno.zip","r") as zip_ref:
with zipfile.ZipFile("deno.zip", "r") as zip_ref:
zip_ref.extractall()
os.remove("deno.zip")
os.chmod(deno_path, 0o755)
self.set("deno_source", "file")
self.set("deno_source", str(deno_path.resolve()))
elif deno_which:
self.set("deno_source", deno_which)
@loader.command(
en_doc="Download video",
ru_doc="Скачать видео"
)
@loader.command(en_doc="Download video", ru_doc="Скачать видео")
async def ytdlvcmd(self, message):
args = utils.get_args(message)
if not args or not self._validate_url(args[0]) or len(args) > 1:
await utils.answer(message, self.strings['invalid_args'])
await utils.answer(message, self.strings["invalid_args"])
return
source = self.get('deno_source')
deno_path = Path('deno').resolve() if source == 'file' else source if source != 'install_failed' else None
if not deno_path:
logger.critical("Deno wasn't installed in auto-mode. Please, install it manually or resolve the issue and reboot userbot.")
source = self.get("deno_source")
if source == "install_failed" or not Path(source).is_file():
logger.critical(
"Deno wasn't installed in auto-mode. Please, install it manually or resolve the issue and reboot userbot."
)
return
await utils.answer(message, self.strings['downloading_video'])
await utils.answer(message, self.strings["downloading"])
filename_prefix = f"video_{message.id}"
ydl_opts = {
'quiet': True,
'outtmpl': f'{filename_prefix}.%(ext)s',
'js_runtimes': {'deno': {'path': str(deno_path)}},
'extractor_args': {
'youtube': {
'player_client': ['mweb', 'android'],
"quiet": True,
"outtmpl": f"{filename_prefix}.%(ext)s",
"js_runtimes": {"deno": {"path": source}},
"postprocessors": [
{
"key": "FFmpegVideoConvertor",
"preferedformat": "mp4",
}
},
'format': 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best',
'postprocessors': [{
'key': 'FFmpegVideoConvertor',
'preferedformat': 'mp4',
}],
'postprocessor_args': {
'video_convertor': [
'-c:v', 'libx264',
'-pix_fmt', 'yuv420p',
'-preset', 'veryfast',
'-crf', '23',
'-c:a', 'aac'
],
"postprocessor_args": {
"video_convertor": [
"-c:v",
"libx264",
"-pix_fmt",
"yuv420p",
"-preset",
"veryfast",
"-crf",
"23",
"-c:a",
"aac",
],
'merger': [
'-movflags', 'faststart'
]
"merger": ["-movflags", "faststart"],
},
}
if self.get('youtube_cookie'):
ydl_opts['cookiefile'] = self.get('youtube_cookie')
if self.get("youtube_cookie"):
ydl_opts["cookiefile"] = self.get("youtube_cookie")
with YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(args[0], download=True)
filename = ydl.prepare_filename(info)
await self.client.send_file(message.chat_id, filename, caption=self.strings['downloaded_video'])
await message.delete()
filename = ydl.prepare_filename(info).split(".")[0] + ".mp4"
await utils.answer(message, self.strings['done'], file=filename, invert_media=True)
os.remove(filename)
@loader.command(
en_doc="Download audio",
ru_doc="Скачать аудио"
)
@loader.command(en_doc="Download audio", ru_doc="Скачать аудио")
async def ytdlacmd(self, message):
args = utils.get_args(message)
if not args or not self._validate_url(args[0]) or len(args) > 1:
await utils.answer(message, self.strings['invalid_args'])
await utils.answer(message, self.strings["invalid_args"])
return
source = self.get('deno_source')
deno_path = Path('deno').resolve() if source == 'file' else source if source != 'install_failed' else None
if not deno_path:
logger.critical("Deno wasn't installed in auto-mode. Please, install it manually or resolve the issue and reboot userbot.")
source = self.get("deno_source")
if source == "install_failed" or not Path(source).is_file():
logger.critical(
"Deno wasn't installed in auto-mode. Please, install it manually or resolve the issue and reboot userbot."
)
return
await utils.answer(message, self.strings['downloading_audio'])
await utils.answer(message, self.strings["downloading"])
filename_prefix = f"audio_{message.id}"
ydl_opts = {
'quiet': True,
'outtmpl': f'{filename_prefix}.%(ext)s',
'js_runtimes': {'deno': {'path': str(deno_path)}},
'postprocessors': [
{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '0',
},
{
'key': 'FFmpegMetadata',
'add_metadata': True,
},
{
'key': 'EmbedThumbnail',
},
],
'writethumbnail': True,
"quiet": True,
"outtmpl": f"{filename_prefix}.%(ext)s",
"js_runtimes": {"deno": {"path": source}},
"postprocessors": [
{
"key": "FFmpegExtractAudio",
"preferredcodec": "mp3",
"preferredquality": "0",
},
{
"key": "FFmpegMetadata",
"add_metadata": True,
},
{
"key": "EmbedThumbnail",
},
],
"writethumbnail": True,
}
if self.get('youtube_cookie'):
ydl_opts['cookiefile'] = self.get('youtube_cookie')
if self.get("youtube_cookie"):
ydl_opts["cookiefile"] = self.get("youtube_cookie")
with YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(args[0], download=True)
filename = ydl.prepare_filename(info).split(".")[0] + ".mp3"
await self.client.send_file(message.chat_id, filename, caption=self.strings['downloaded_audio'])
await message.delete()
await utils.answer(message, self.strings['done'], file=filename)
os.remove(filename)

74
backup.py Normal file
View File

@@ -0,0 +1,74 @@
import asyncio
import aiohttp
import argparse
import subprocess
import os
import glob
parser = argparse.ArgumentParser(description="Backup Script")
parser.add_argument(
"--token",
type=str,
required=True,
help="Token of Telegram bot",
)
parser.add_argument(
"--api_url",
type=str,
default="https://api.telegram.org",
help="API URL of Telegram API",
)
parser.add_argument(
"--chat_id",
type=str,
required=True,
help="Chat ID to send backup message to",
)
arguments = parser.parse_args()
async def send_file(session, file_path, caption=None):
url = f"{arguments.api_url}/bot{arguments.token}/sendDocument"
with open(file_path, 'rb') as f:
data = aiohttp.FormData()
data.add_field('chat_id', arguments.chat_id)
data.add_field('document', f, filename=os.path.basename(file_path))
if caption:
data.add_field('caption', caption)
data.add_field('parse_mode', 'Markdown')
async with session.post(url, data=data) as response:
return await response.json()
async def main():
# Get commit info
commit_message = subprocess.check_output(['git', 'log', '-1', '--pretty=%B']).decode().strip()
commit_date = subprocess.check_output(['git', 'log', '-1', '--pretty=%ci']).decode().strip()
commit_hash = subprocess.check_output(['git', 'rev-parse', '--short=6', 'HEAD']).decode().strip()
commit_url = f"https://github.com/MuRuLOSE/limoka/commit/{subprocess.check_output(['git', 'rev-parse', 'HEAD']).decode().strip()}"
message = f"Commit Date: {commit_date}, Commit Message: {commit_message}, Commit Hash: [`{commit_hash}`]({commit_url})"
# Create zip
subprocess.run(['git', 'archive', '--format=zip', '--output=repository-original.zip', 'HEAD'])
subprocess.run(['zip', '-9', 'repository.zip', 'repository-original.zip'])
os.remove('repository-original.zip')
# Split zip
subprocess.run(['split', '-b', '49M', 'repository.zip', 'repository-part-'])
# Send parts
async with aiohttp.ClientSession() as session:
parts = sorted(glob.glob('repository-part-*'))
first = True
for part in parts:
caption = message if first else None
result = await send_file(session, part, caption)
print(f"Sent {part}: {result}")
first = False
# Cleanup
os.remove('repository.zip')
for part in parts:
os.remove(part)
if __name__ == "__main__":
asyncio.run(main())

View File

@@ -1,126 +0,0 @@
import json
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.multiclass import OneVsRestClassifier
from sklearn.preprocessing import MultiLabelBinarizer
from tqdm import tqdm
import numpy as np
# Тренировочные данные (48 модулей)
training_data = {
"MuRuLOSE/HikkaModulesRepo/filters.py": ["Tools", "Chat"],
"MuRuLOSE/HikkaModulesRepo/autogiveawayjoin.py": ["Automation", "Social"],
"MuRuLOSE/HikkaModulesRepo/HTTPCat.py": ["Fun"],
"MuRuLOSE/HikkaModulesRepo/CustomPing.py": ["Tools", "Networking"],
"MuRuLOSE/HikkaModulesRepo/FuckTagOne.py": ["Moderation"],
"MuRuLOSE/HikkaModulesRepo/InlineButtons.py": ["Tools", "Chat"],
"MuRuLOSE/HikkaModulesRepo/YoutubeDL.py": ["Media"],
"MuRuLOSE/HikkaModulesRepo/youtubesearcher.py": ["Media", "Tools"],
"MuRuLOSE/HikkaModulesRepo/INumber.py": ["Fun", "Info"],
"MuRuLOSE/HikkaModulesRepo/RandomDog.py": ["Fun"],
"MuRuLOSE/HikkaModulesRepo/RemoveLinks.py": ["Moderation", "Chat"],
"MuRuLOSE/HikkaModulesRepo/SteamClient.py": ["Games", "Tools"],
"MuRuLOSE/HikkaModulesRepo/PinMoreChats.py": ["Chat", "Productivity"],
"MuRuLOSE/HikkaModulesRepo/MindGameCheat.py": ["Games", "Tools"],
"MuRuLOSE/HikkaModulesRepo/NasaImages.py": ["Media", "Info"],
"MuRuLOSE/HikkaModulesRepo/autoreader.py": ["Automation", "Chat"],
"MuRuLOSE/HikkaModulesRepo/K.py": ["Fun"],
"MuRuLOSE/HikkaModulesRepo/Genshin.py": ["Games"],
"MuRuLOSE/HikkaModulesRepo/compliments.py": ["Social", "Fun"],
"MuRuLOSE/HikkaModulesRepo/AutoLeave.py": ["Automation", "Chat"],
"MuRuLOSE/HikkaModulesRepo/ToTHosting.py": ["Tools", "Admin"],
"MuRuLOSE/HikkaModulesRepo/PasswordUtils.py": ["Security", "Tools"],
"MuRuLOSE/HikkaModulesRepo/FuckJoins.py": ["Security", "Chat"],
"MuRuLOSE/HikkaModulesRepo/SpyEVO.py": ["Tools", "Info"],
"MuRuLOSE/HikkaModulesRepo/FindID.py": ["Tools", "Admin"],
"MuRuLOSE/HikkaModulesRepo/ChannelCheck.py": ["Tools", "Social"],
"MuRuLOSE/HikkaModulesRepo/controlspam.py": ["Chat", "Tools"],
"MuRuLOSE/HikkaModulesRepo/VKMusic.py": ["Media"],
"MuRuLOSE/HikkaModulesRepo/morse.py": ["Tools", "Fun"],
"MuRuLOSE/HikkaModulesRepo/YamiManager.py": ["Chat", "Tools"],
"MuRuLOSE/HikkaModulesRepo/SearchersGenQuery.py": ["Tools", "Info"],
"MuRuLOSE/HikkaModulesRepo/Limoka.py": ["Utilities", "Tools"],
"MuRuLOSE/HikkaModulesRepo/CheckTime.py": ["Productivity", "Info"],
"MuRuLOSE/HikkaModulesRepo/ReplaceWords.py": ["Chat", "Customization"],
"MuRuLOSE/HikkaModulesRepo/TempJoinChannel.py": ["Chat", "Automation"],
"MuRuLOSE/HikkaModulesRepo/timer.py": ["Productivity", "Tools"],
"den4ikSuperOstryyPer4ik/astro-modules/astroafk.py": ["Automation", "Customization"],
"den4ikSuperOstryyPer4ik/astro-modules/akinator.py": ["Games"],
"den4ikSuperOstryyPer4ik/astro-modules/Emotions.py": ["Social", "Fun"],
"den4ikSuperOstryyPer4ik/astro-modules/RandomStatuses.py": ["Social", "Fun"],
"den4ikSuperOstryyPer4ik/astro-modules/RandomTrack.py": ["Media", "Fun"],
"den4ikSuperOstryyPer4ik/astro-modules/minesweeper.py": ["Games"],
"den4ikSuperOstryyPer4ik/astro-modules/inline_bot_manager.py": ["Tools", "Automation"],
"MuRuLOSE/HikkaModulesRepo/ReplaceWords.py": ["Customization", "Chat"],
"MuRuLOSE/HikkaModulesRepo/CheckTime.py": ["Productivity"],
"MuRuLOSE/HikkaModulesRepo/SearchersGenQuery.py": ["Utilities", "Info"]
}
all_categories = [
"Utilities", "Fun", "Admin", "Media", "Games", "Tools", "Security", "Social",
"Automation", "Info", "Chat", "Moderation", "Productivity", "Customization",
"Networking", "Education", "Finance", "Health", "Creative", "Other"
]
def get_module_text(module_path, module_data):
name = module_data.get("name", "").lower()
description = (module_data.get("description", "") or module_data.get("meta", {}).get("desc", "")).lower()
if not description or description == "desc":
description = ""
commands_text = " ".join([f"{cmd} {desc}".lower() for func in module_data.get("commands", []) for cmd, desc in func.items()])
new_commands_text = " ".join([f"{cmd} {data.get('doc', '')} {data.get('ru_doc', '') or ''}".lower()
for func in module_data.get("new_commands", []) for cmd, data in func.items()])
file_path = module_path.lower()
file_name = file_path.split("/")[-1]
return f"{file_name} {name} {description} {file_path} {commands_text} {new_commands_text}".strip()
with open("modules.json", "r", encoding="utf-8") as f:
modules = json.load(f)
# Подготовка тренировочных данных
train_texts = [get_module_text(path, modules[path]) for path in training_data.keys() if path in modules]
train_labels = [training_data[path] for path in training_data.keys() if path in modules]
# Векторизация текста
vectorizer = TfidfVectorizer(max_features=2000)
X_train = vectorizer.fit_transform(train_texts)
# Преобразование меток
mlb = MultiLabelBinarizer(classes=all_categories)
y_train = mlb.fit_transform(train_labels)
# Обучение модели с балансировкой классов
base_clf = LogisticRegression(class_weight="balanced", max_iter=1000)
clf = OneVsRestClassifier(base_clf)
clf.fit(X_train, y_train)
# Обработка всех модулей
print("Classifying all modules...")
texts = [get_module_text(path, data) for path, data in modules.items()]
X_all = vectorizer.transform(texts)
# Предсказание вероятностей
probs = clf.predict_proba(X_all)
# Присваивание категорий
threshold = 0.2 # Снижаем порог для большего разнообразия
for module_path, prob_vector in tqdm(zip(modules.keys(), probs), total=len(modules), desc="Assigning categories"):
module_data = modules[module_path]
sorted_indices = np.argsort(prob_vector)[::-1]
sorted_probs = prob_vector[sorted_indices]
sorted_labels = mlb.classes_[sorted_indices]
selected_categories = [label for label, prob in zip(sorted_labels, sorted_probs) if prob >= threshold][:2]
if not selected_categories:
selected_categories = ["Other"]
module_data["category"] = selected_categories
print(f"Module: {module_path} -> Categories: {selected_categories} (top probs: {[f'{p:.2f}' for p in sorted_probs[:3]]})")
# Сохранение результата
with open("modules.json", "w", encoding="utf-8") as f:
json.dump(modules, f, ensure_ascii=False, indent=2)
print("Done! Check modules_categorized.json.")

View File

@@ -3,58 +3,18 @@ import shutil
import subprocess
import re
import requests
import json
repos = [
"https://github.com/DziruModules/hikkamods",
"https://github.com/kamolgks/Hikkamods",
"https://github.com/thomasmod/hikkamods",
"https://github.com/SkillsAngels/Modules",
"https://github.com/Sad0ff/modules-ftg",
"https://github.com/Yahikoro/Modules-for-FTG",
"https://github.com/KeyZenD/modules",
"https://github.com/AlpacaGang/ftg-modules",
"https://github.com/trololo65/Modules",
"https://github.com/Ijidishurka/modules",
"https://github.com/Fl1yd/FTG-Modules",
"https://github.com/D4n13l3k00/FTG-Modules",
"https://github.com/iamnalinor/FTG-modules",
"https://github.com/SekaiYoneya/modules",
"https://github.com/GeekTG/FTG-Modules",
"https://github.com/Den4ikSuperOstryyPer4ik/Astro-modules",
"https://github.com/vsecoder/hikka_modules",
"https://github.com/sqlmerr/hikka_mods",
"https://github.com/N3rcy/modules",
"https://github.com/KorenbZla/HikkaModules",
"https://github.com/MuRuLOSE/HikkaModulesRepo",
"https://github.com/coddrago/modules",
"https://github.com/1jpshiro/hikka-modules",
"https://github.com/MoriSummerz/ftg-mods",
"https://github.com/anon97945/hikka-mods",
"https://github.com/dorotorothequickend/DorotoroModules",
"https://github.com/AmoreForever/amoremods",
"https://github.com/idiotcoders/idiotmodules",
"https://github.com/CakesTwix/Hikka-Modules",
"https://github.com/archquise/H.Modules",
"https://github.com/GD-alt/mm-hikka-mods",
"https://github.com/HitaloSama/FTG-modules-repo",
"https://github.com/SekaiYoneya/Friendly-telegram",
"https://github.com/blazedzn/ftg-modules",
"https://github.com/hikariatama/ftg",
"https://github.com/m4xx1m/FTG",
"https://github.com/skillzmeow/skillzmods_hikka",
"https://github.com/fajox1/famods",
"https://github.com/unneyon/hikka-mods",
"https://github.com/TheKsenon/MyHikkaModules",
"https://github.com/cryptexctl/modules-mirror",
"https://github.com/Ruslan-Isaev/modules",
"https://github.com/shadowhikka/sh.modules",
"https://github.com/fiksofficial/python-modules",
"https://github.com/mead0wsss/mead0wsMods",
"https://github.com/SenkoGuardian/SenModules",
"https://github.com/ZetGoHack/nullmod",
"https://github.com/yummy1gay/limoka"
]
def parse_repos(file_path: str) -> list:
"""Parse repository URLs from a given json file."""
repos = []
with open(file_path, "r", encoding="utf-8") as f:
data = json.load(f)
for repo in data.get("repositories", []):
repos.append(repo["url"])
return repos
repos = parse_repos("repositories.json")
def configure_git():
"""Configure Git to ignore file mode changes."""

1137
coddrago/modules/YaMusic.py Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -17,9 +17,9 @@ figlet
promoclaimer
passwordgen
send
lastfm
dbmod
chatmodule
stats
tagwatcher
hardspam
hardspam
YaMusic

View File

@@ -1,124 +0,0 @@
# ---------------------------------------------------------------------------------
#░█▀▄░▄▀▀▄░█▀▄░█▀▀▄░█▀▀▄░█▀▀▀░▄▀▀▄░░░█▀▄▀█
#░█░░░█░░█░█░█░█▄▄▀░█▄▄█░█░▀▄░█░░█░░░█░▀░█
#░▀▀▀░░▀▀░░▀▀░░▀░▀▀░▀░░▀░▀▀▀▀░░▀▀░░░░▀░░▒▀
# Name: LastFM
# Description: Module for music from different services
# Author: @codrago_m
# ---------------------------------------------------------------------------------
# 🔒 Licensed under the GNU AGPLv3
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
# ---------------------------------------------------------------------------------
# Author: @codrago
# Commands: nowplay
# scope: heroku_only
# meta developer: @codrago_m
# meta banner: https://raw.githubusercontent.com/coddrago/modules/refs/heads/main/banner.png
# meta pic: https://envs.sh/Hob.webp
# ---------------------------------------------------------------------------------
from .. import loader, utils
from herokutl import events
import requests
import asyncio
@loader.tds
class lastfmmod(loader.Module):
"""Module for music from different services"""
def __init__(self):
self.config = loader.ModuleConfig(
loader.ConfigValue(
"username_lastfm",
None,
lambda: self.strings["_doc_username_lastfm"],
),
loader.ConfigValue(
"text",
"<emoji document_id=6007938409857815902>🎧</emoji> <b>now playing...</b>\n"
"<emoji document_id=5915480455603295660>🎶</emoji><b> playlist: </b><code>{song_album}</code>\n"
"<emoji document_id=5891249688933305846>🎵</emoji> <b>track:</b> <code>{song_name}</code>\n"
"<emoji document_id=5897554554894946515>🎤</emoji> <b>artist:</b> <code>{song_artist}</code>",
lambda: self.strings["_doc_text"],
),
)
strings = {
"name": "LastFm",
"loading":"<emoji document_id=5873204392429096339>⌨️</emoji> Loading song...",
"bot_no_result": "<emoji document_id=5465665476971471368>❌</emoji> Nothing found.\nTitle: {song_name}\nAuthor: {song_artist}\nAlbum:{song_album}",
"_doc_text": "The text that will be written next to the file",
"_doc_username_lastfm": "Your username from last.fm",
"nick_error": "<emoji document_id=5465665476971471368>❌</emoji> Put your nickname from last.fm",
"tutorial": "Go to last.fm and register.\nBE SURE to remember the username and password, they will come in handy later.\nLet's look at the VK version\nAfter that, go to the @vkxci channel, download VK X and log in to your VK account, then go to settings and click «Integrations», select Last FM.\nEnter the username and password.\nThen you're almost done!\nWrite <code>{prefix}fcfg lastfm username_lastfm</code> {username}\nUse the <code>{prefix}nowplay</code> command and enjoy life!",
}
strings_ru = {
"name": "LastFm",
"loading": "<emoji document_id=5873204392429096339>⌨️</emoji> Загрузка трека...",
"bot_no_result": "<emoji document_id=5465665476971471368>❌</emoji> Ничего не найдено.\nНазвание: {song_name}\nИсполнитель: {song_artist}\nАльбом: {song_album}",
"_doc_text": "Текст, который будет написан рядом с файлом",
"_doc_username_lastfm": "Ваш username с last.fm",
"nick_error": "<emoji document_id=5465665476971471368>❌</emoji> Укажите ваш никнейм с last.fm",
"tutorial": "Зайдите на last.fm и зарегистрируйтесь.\nОБЯЗАТЕЛЬНО запомните логин и пароль, они пригодятся позже.\nРассмотрим вариант для VK\nПосле этого зайдите в канал @vkxci, скачайте VK X и авторизуйтесь в своём аккаунте VK, затем зайдите в настройки и нажмите «Интеграции», выберите Last FM.\nВведите логин и пароль.\nЗатем вы почти закончили!\nНапишите <code>{prefix}fcfg lastfm username_lastfm</code> {username}\nИспользуйте команду <code>{prefix}nowplay</code> и наслаждайтесь жизнью!",
}
@loader.command(alias="np")
async def nowplay(self, message):
"""| send playing track"""
lastfm_username = self.config["username_lastfm"]
API_KEY = "460cda35be2fbf4f28e8ea7a38580730" # Облегчение жизни школьникам
if not lastfm_username:
response_text = self.strings["nick_error"]
await self.invoke("config", "lastfm", message=message)
await utils.answer(message, response_text)
else:
try:
current_track_url = f'http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&nowplaying=true&user={lastfm_username}&api_key={API_KEY}&format=json'
response = requests.get(current_track_url)
data = response.json()
if 'recenttracks' in data and 'track' in data['recenttracks'] and data['recenttracks']['track']:
nowplaying_track = None
for track in data['recenttracks']['track']:
if '@attr' in track and 'nowplaying' in track['@attr']:
nowplaying_track = track
break
if nowplaying_track:
song_name = nowplaying_track.get('name', 'Unknown song')
song_artist = nowplaying_track.get('artist', {}).get('#text', 'Unknown Artist')
if nowplaying_track.get('album', {}).get('#text') == nowplaying_track.get('name'):
song_album = "single"
else:
song_album = nowplaying_track.get('album', {}).get('#text', 'Unknown Album')
response_text = f"/search {song_name} - {song_artist}"
try:
async with message.client.conversation("@LyaDownbot") as conv:
await conv.send_message(response_text)
while True:
response_bot = await conv.get_response()
if "Не удалось найти трек" in response_bot.text:
await utils.answer(message, self.strings["bot_no_result"])
return
if "Ищем треки..." in response_bot.text:
await utils.answer(message, self.strings["loading"])
if response_bot.media:
await message.client.send_file(message.chat_id, response_bot.media, caption = self.config["text"].format(song_artist=song_artist, song_album=song_album, song_name=song_name))
await message.delete()
return
except Exception as e:
await utils.answer(message, f"<pre><code class='language-python'>{e}</code></pre>")
except Exception as e:
await utils.answer(message, f"<pre><code class='language-python'>{e}</code></pre>")
@loader.command()
async def tutorl(self, message):
"""| tutorial"""
await utils.answer(message, self.strings['tutorial'].format(prefix = self.get_prefix(), username="{username}"))

View File

@@ -1,9 +1,13 @@
# meta developer: @codrago_m
# scope: heroku_min 2.0.0
import logging
from .. import utils, loader, main
from telethon.tl.functions.messages import MarkDialogUnreadRequest
from .. import loader, main, utils
logger = logging.getLogger("TagWatcher")
@@ -113,15 +117,8 @@ class TagWatcher(loader.Module):
validator=loader.validators.Boolean(),
),
)
async def client_ready(self):
await self.request_join("@xdesai_modules", self.strings["request_join_reason"])
self.xdlib = await self.import_lib(
"https://raw.githubusercontent.com/xdesai96/modules/refs/heads/main/libs/xdlib.py",
suspend_on_error=True,
)
self.asset_channel = self._db.get("legacy.forums", "channel_id", 0)
self.asset_channel = self._db.get("heroku.forums", "channel_id", 0)
self._notif_topic = await utils.asset_forum_topic(
self._client,
self._db,
@@ -131,6 +128,11 @@ class TagWatcher(loader.Module):
icon_emoji_id=5409025823388741707,
)
self.xdlib = await self.import_lib(
"https://raw.githubusercontent.com/coddrago/modules/refs/heads/main/libs/xdlib.py",
suspend_on_error=True,
)
async def render_text(self, m):
if self.config["custom_notif_text"]:
text = self.config["custom_notif_text"]
@@ -174,7 +176,7 @@ class TagWatcher(loader.Module):
user_id=id,
msg_content=msg_content,
reply_content=reply_content,
link=await m.link,
link=await m.link(),
)
@loader.command(
@@ -242,4 +244,4 @@ class TagWatcher(loader.Module):
message_thread_id=self._notif_topic.id,
)
except Exception as e:
logger.error(e)
logger.error(e)

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -11,6 +11,7 @@
# https://github.com/all-licenses/GNU-General-Public-License-v3.0
# meta developer: @pymodule
# meta fhsdesc: tool, tools, ai, assistant
from .. import loader, utils
import aiohttp

View File

@@ -11,6 +11,7 @@
# https://github.com/all-licenses/GNU-General-Public-License-v3.0
# meta developer: @pymodule
# meta fhsdesc: tool, tools, ai, username
# requires: aiohttp
import asyncio

View File

@@ -2,6 +2,7 @@
# https://github.com/all-licenses/GNU-General-Public-License-v3.0
# meta developer: @pymodule
# meta fhsdesc: tool, tools, user, profile
from hikkatl.types import Message
from telethon.tl.functions.account import UpdateProfileRequest

View File

@@ -11,6 +11,7 @@
# https://github.com/all-licenses/GNU-General-Public-License-v3.0
# meta developer: @pymodule
# meta fhsdesc: tool, tools, calculator, calc
from .. import loader, utils
import math

View File

@@ -1,7 +1,8 @@
# На модуль распространяется лицензия "GNU General Public License v3.0"
# На модуль распространяется лицензия "GNU General Public License v3.0
# https://github.com/all-licenses/GNU-General-Public-License-v3.0
# meta developer: @PyModule
# meta fhsdesc: tool, tools, channel, admintools, admin, admintool
from telethon.tl.types import Message
from .. import loader

View File

@@ -1,3 +1,4 @@
# meta fhsdesc: tool, tools, server, admin
from .. import loader, utils
import aiohttp
import asyncio

View File

@@ -11,6 +11,7 @@
# https://github.com/all-licenses/GNU-General-Public-License-v3.0
# meta developer: @pymodule
# meta fhsdesc: tool, tools, fun, packs
# requires: opencv-python pillow
import os

View File

@@ -11,6 +11,7 @@
# https://github.com/all-licenses/GNU-General-Public-License-v3.0
# meta developer: @pymodule
# meta fhsdesc: fun, cute, message, love
import random
import re

View File

@@ -11,6 +11,7 @@
# https://github.com/all-licenses/GNU-General-Public-License-v3.0
# meta developer: @pymodule
# meta fhsdesc: tool, tools, phone, info
# requires: aiohttp cachetools
import asyncio
@@ -105,7 +106,7 @@ class DeviceInfo(loader.Module):
self.config = loader.ModuleConfig(
loader.ConfigValue(
"api_base_url",
"https://mobilespecs.fiksofficial.fun",
"https://gmsarena.vercel.app/",
lambda: "API Url",
validator=loader.validators.String()
),

View File

@@ -3,6 +3,7 @@
# scope: hikka_only
# meta developer: @pymodule
# meta fhsdesc: tool, tools, scanner, domain
# requires: python-whois dnspython requests
import socket

View File

@@ -2,6 +2,7 @@
# https://github.com/all-licenses/GNU-General-Public-License-v3.0
# meta developer: @PyModule
# meta fhsdesc: tool, tools, user, id
from .. import loader, utils
@loader.tds

View File

@@ -11,183 +11,459 @@
# https://github.com/all-licenses/GNU-General-Public-License-v3.0
# meta developer: @pymodule
# meta fhsdesc: tool, tools, github, info, inline
from .. import loader, utils
from ..inline import InlineCall
import logging
import json
import re
import asyncio
import urllib.request
import json
from datetime import datetime, timedelta
@loader.tds
class GitHubInfoMod(loader.Module):
"""GitHub user info, recent activity and contribution graph"""
"""GitHub user information"""
strings = {
"name": "GitHubInfo",
"no_username": "❗ Provide a GitHub username.",
"user_not_found": "🚫 User not found: <b>{}</b>",
"profile": "Profile",
"api_error": "⚠ GitHub API error: <b>{msg}</b>",
"no_activity": "🕸 No recent activity from <b>{}</b>",
"no_contrib": "📭 No contribution data for <b>{}</b>",
"info_text": (
"👤 <b>{name}</b> | <a href=\"{url}\">{profile}</a>\n"
"🏢 {company} | 📍 {location}\n"
"📝 {bio}\n\n"
"📦 Repos: <b>{repos}</b> | "
"👥 Followers: <b>{followers}</b> | "
"no_contrib": "📭 No contribution data.",
"no_repos": "📭 No public repositories.",
"no_orgs": "📭 Not a member of any organizations.",
"no_title": "No title",
"no_desc": "No description",
"not_specified": "Not specified",
"more_commits": " ... and {} more\n",
"hireable_yes": "Yes",
"hireable_no": "No",
"menu_text": "Choose a section:",
"btn_activity": "🔥 Activity",
"btn_contrib": "📊 Contributions",
"btn_repos": "📦 Repositories",
"btn_orgs": "🏛 Organizations",
"btn_back": "← Back to profile",
"profile_header": "<b>Profile</b> <a href=\"{url}\">{username}</a>\n\n",
"profile_text": (
"👤 Name: <b>{name}</b>\n"
"🏷 Login: <code>{login}</code>\n"
"📝 Bio: {bio}\n"
"🏢 Company: {company}\n"
"📍 Location: {location}\n"
"📧 Email: {email}\n"
"🔗 Website: {blog}\n"
"🐦 Twitter: {twitter}\n"
"💼 Hireable: {hireable}\n"
"📊 Type: {type}\n"
"📦 Public repos: <b>{repos}</b>\n"
"⭐ Public gists: <b>{gists}</b>\n"
"👥 Followers: <b>{followers}</b>\n"
"👣 Following: <b>{following}</b>\n"
"🕒 Created: <code>{created}</code>"
"🕐 Created: <code>{created}</code>\n"
"🕐 Updated: <code>{updated}</code>"
),
"activity_header": "<b>Recent activity:</b>\n",
"activity_commit": "🔨 {count} commit(s) → <code>{branch}</code> in {repo}",
"activity_create": "✨ Created {ref_type} in {repo}",
"activity_pr": "🔄 {action} PR: {title}",
"activity_issue": "{action} issue: {title}",
"activity_star": "⭐ Starred {repo}",
"activity_fork": "⑂ Forked to {fork}",
"activity_other": "{event} in {repo}",
"contrib_header": "<b>Contribution graph</b> for <a href=\"https://github.com/{username}\">{username}</a>:\n",
"contrib_footer": "⬛ = 0, 🟩 = 1+ contributions",
"activity_header": "<b>Recent activity</b> <a href=\"https://github.com/{username}\">{username}</a>\n\n",
"push_header": "🔨 Pushed to <code>{branch}</code> → <a href=\"https://github.com/{repo}\">{repo}</a>\n",
"push_no_commits": "🔨 Pushed (no details) to <code>{branch}</code> → <a href=\"https://github.com/{repo}\">{repo}</a>\n",
"commit_line": "• <a href=\"{url}\"><code>{sha}</code></a>: {message}\n",
"create_branch": "✨ Created branch <code>{ref}</code> in <a href=\"https://github.com/{repo}\">{repo}</a>\n",
"create_tag": "✨ Created tag <code>{ref}</code> in <a href=\"https://github.com/{repo}/releases/tag/{ref}\">{repo}</a>\n",
"create_repo": "✨ Created repository <a href=\"https://github.com/{repo}\">{repo}</a>\n",
"pr_opened": "🔄 Opened PR <a href=\"{url}\">#{} {title}</a>\n",
"pr_closed": "🔄 Closed PR <a href=\"{url}\">#{} {title}</a>\n",
"pr_merged": "🔄 Merged PR <a href=\"{url}\">#{} {title}</a>\n",
"issue_opened": "❗ Opened issue <a href=\"{url}\">#{} {title}</a>\n",
"issue_closed": "❗ Closed issue <a href=\"{url}\">#{} {title}</a>\n",
"star": "⭐ Starred <a href=\"https://github.com/{repo}\">{repo}</a>\n",
"fork": "⑂ Forked <a href=\"https://github.com/{fork}\">{fork}</a>\n",
"other": "{event} in <a href=\"https://github.com/{repo}\">{repo}</a>\n",
"repos_header": "<b>Top repositories by stars</b> <a href=\"https://github.com/{username}\">{username}</a>\n\n",
"repo_line": "⭐ <b>{stars}</b> | <a href=\"{url}\">{name}</a> — {desc}\nLanguage: {lang} | Forks: {forks}\n\n",
"orgs_header": "<b>Organizations</b> <a href=\"https://github.com/{username}\">{username}</a>\n\n",
"org_line": "• <a href=\"{url}\">{login}</a> — {desc}\n",
"contrib_header": "<b>Contribution graph (last year)</b> <a href=\"https://github.com/{username}\">{username}</a>\n",
"contrib_footer": "\n⬛ = 0, 🟩 = 1+ contributions",
}
strings_ru = {
"no_username": "❗ Укажи имя пользователя GitHub.",
"_cls_doc": "Информация о GitHub-пользователе",
"no_username": "❗ Укажи GitHub username.",
"user_not_found": "🚫 Пользователь не найден: <b>{}</b>",
"profile": "Профиль",
"no_activity": "🕸 Нет активности у <b>{}</b>",
"no_contrib": "📭 Нет данных о вкладах <b>{}</b>",
"info_text": (
"👤 <b>{name}</b> | <a href=\"{url}\">{profile}</a>\n"
"🏢 {company} | 📍 {location}\n"
"📝 {bio}\n\n"
"📦 Репозитории: <b>{repos}</b> | "
"👥 Подписчики: <b>{followers}</b> | "
"api_error": "⚠ Ошибка GitHub API: <b>{msg}</b>",
"no_activity": "🕸 Нет недавней активности у <b>{}</b>",
"no_contrib": "📭 Нет данных о контрибуциях.",
"no_repos": "📭 Нет публичных репозиториев.",
"no_orgs": "📭 Не состоит в организациях.",
"no_title": "Без названия",
"no_desc": "Без описания",
"not_specified": "Не указано",
"more_commits": " ... и ещё {}\n",
"hireable_yes": "Да",
"hireable_no": "Нет",
"menu_text": "Выбери раздел:",
"btn_activity": "🔥 Активность",
"btn_contrib": "📊 Контрибы",
"btn_repos": "📦 Репозитории",
"btn_orgs": "🏛 Организации",
"btn_back": "← Назад к профилю",
"profile_header": "<b>Профиль</b> <a href=\"{url}\">{username}</a>\n\n",
"profile_text": (
"👤 Имя: <b>{name}</b>\n"
"🏷 Логин: <code>{login}</code>\n"
"📝 Био: {bio}\n"
"🏢 Компания: {company}\n"
"📍 Локация: {location}\n"
"📧 Email: {email}\n"
"🔗 Сайт: {blog}\n"
"🐦 Twitter: {twitter}\n"
"💼 Доступен для найма: {hireable}\n"
"📊 Тип аккаунта: {type}\n"
"📦 Публичные репозитории: <b>{repos}</b>\n"
"⭐ Публичные гисты: <b>{gists}</b>\n"
"👥 Подписчики: <b>{followers}</b>\n"
"👣 Подписки: <b>{following}</b>\n"
"🕒 Создан: <code>{created}</code>"
"🕐 Создан: <code>{created}</code>\n"
"🕐 Обновлён: <code>{updated}</code>"
),
"activity_header": "<b>Последняя активность:</b>\n",
"activity_commit": "🔨 {count} коммит(ов) → <code>{branch}</code> в {repo}",
"activity_create": "✨ Создан {ref_type} в {repo}",
"activity_pr": "🔄 {action} PR: {title}",
"activity_issue": "{action} issue: {title}",
"activity_star": "В избранное {repo}",
"activity_fork": "⑂ Форк в {fork}",
"activity_other": "{event} в {repo}",
"contrib_header": "<b>График активности</b> <a href=\"https://github.com/{username}\">{username}</a>:\n",
"contrib_footer": "⬛ = 0, 🟩 = 1+ контрибуций",
"activity_header": "<b>Последняя активность</b> <a href=\"https://github.com/{username}\">{username}</a>\n\n",
"push_header": "🔨 Запушил в <code>{branch}</code> → <a href=\"https://github.com/{repo}\">{repo}</a>\n",
"push_no_commits": "🔨 Запушил (без деталей) в <code>{branch}</code> → <a href=\"https://github.com/{repo}\">{repo}</a>\n",
"commit_line": "• <a href=\"{url}\"><code>{sha}</code></a>: {message}\n",
"create_branch": "✨ Создал ветку <code>{ref}</code> в <a href=\"https://github.com/{repo}\">{repo}</a>\n",
"create_tag": "✨ Создал тег <code>{ref}</code> в <a href=\"https://github.com/{repo}/releases/tag/{ref}\">{repo}</a>\n",
"create_repo": "✨ Создал репозиторий <a href=\"https://github.com/{repo}\">{repo}</a>\n",
"pr_opened": "🔄 Открыл PR <a href=\"{url}\">#{} {title}</a>\n",
"pr_closed": "🔄 Закрыл PR <a href=\"{url}\">#{} {title}</a>\n",
"pr_merged": "🔄 Замержил PR <a href=\"{url}\">#{} {title}</a>\n",
"issue_opened": "❗ Открыл issue <a href=\"{url}\">#{} {title}</a>\n",
"issue_closed": "❗ Закрыл issue <a href=\"{url}\">#{} {title}</a>\n",
"star": "⭐ Добавил в избранное <a href=\"https://github.com/{repo}\">{repo}</a>\n",
"fork": "⑂ Форкнул <a href=\"https://github.com/{fork}\">{fork}</a>\n",
"other": "{event} в <a href=\"https://github.com/{repo}\">{repo}</a>\n",
"repos_header": "<b>Топ репозитории по звёздам</b> <a href=\"https://github.com/{username}\">{username}</a>\n\n",
"repo_line": "⭐ <b>{stars}</b> | <a href=\"{url}\">{name}</a> — {desc}\nЯзык: {lang} | Форков: {forks}\n\n",
"orgs_header": "<b>Организации</b> <a href=\"https://github.com/{username}\">{username}</a>\n\n",
"org_line": "• <a href=\"{url}\">{login}</a> — {desc}\n",
"contrib_header": "<b>График контрибуций (последний год)</b> <a href=\"https://github.com/{username}\">{username}</a>\n",
"contrib_footer": "\n⬛ = 0, 🟩 = 1+ контрибуций",
}
def __init__(self):
self.logger = logging.getLogger(__name__)
def github_api(self, url):
async def github_fetch(self, url, github_api=True):
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36",
"Accept": "application/vnd.github+json" if github_api else "application/json",
"X-GitHub-Api-Version": "2022-11-28",
}
req = urllib.request.Request(url, headers=headers)
try:
with urllib.request.urlopen(url) as resp:
return json.loads(resp.read().decode())
with urllib.request.urlopen(req, timeout=15) as resp:
raw = resp.read().decode("utf-8")
return json.loads(raw) if raw else {}
except Exception as e:
self.logger.warning(f"[GitHub API] {e}")
return None
self.logger.error(f"[GitHub] {e}")
return {"message": str(e)}
def get_username(self, message):
args = message.text.split(maxsplit=1)
return args[1] if len(args) > 1 else None
@loader.command(doc="Show GitHub user info", ru_doc="Информация о пользователе GitHub")
async def gh(self, message):
"""Show GitHub user info"""
username = self.get_username(message)
@loader.command(ru_doc="{username без @} — Информация о GitHub пользователе")
async def github(self, message):
"""{username without @} — GitHub user information"""
username = utils.get_args_raw(message)
if not username:
return await message.edit(self.strings("no_username"))
await utils.answer(message, self.strings("no_username"))
return
data = self.github_api(f"https://api.github.com/users/{username}")
if not data:
return await message.edit(self.strings("user_not_found").format(username))
user_data = await self.github_fetch(f"https://api.github.com/users/{username}")
if "message" in user_data:
await utils.answer(message, self.strings("user_not_found").format(username))
return
await message.edit(self.strings("info_text").format(
name=data.get("name") or username,
url=data["html_url"],
profile=self.strings("profile"),
company=data.get("company", "N/A"),
location=data.get("location", "N/A"),
bio=data.get("bio", "No bio"),
repos=data.get("public_repos", 0),
followers=data.get("followers", 0),
following=data.get("following", 0),
created=data.get("created_at", "")[:10]
))
hireable = self.strings("hireable_yes") if user_data.get("hireable") else self.strings("hireable_no")
@loader.command(doc="Show recent GitHub activity", ru_doc="Последняя активность GitHub")
async def gha(self, message):
"""Show recent GitHub activity"""
username = self.get_username(message)
if not username:
return await message.edit(self.strings("no_username"))
profile_text = (
self.strings("profile_header").format(url=user_data["html_url"], username=username)
+ self.strings("profile_text").format(
name=user_data.get("name") or self.strings("not_specified"),
login=username,
bio=user_data.get("bio") or self.strings("no_desc"),
company=user_data.get("company") or self.strings("not_specified"),
location=user_data.get("location") or self.strings("not_specified"),
email=user_data.get("email") or self.strings("not_specified"),
blog=user_data.get("blog") or self.strings("not_specified"),
twitter=user_data.get("twitter_username") or self.strings("not_specified"),
hireable=hireable,
type=user_data.get("type", "User"),
repos=user_data.get("public_repos", 0),
gists=user_data.get("public_gists", 0),
followers=user_data.get("followers", 0),
following=user_data.get("following", 0),
created=user_data.get("created_at", "")[:10],
updated=user_data.get("updated_at", "")[:10],
)
+ "\n" + self.strings("menu_text")
)
events = self.github_api(f"https://api.github.com/users/{username}/events?per_page=5")
await self.inline.form(
message=message,
text=profile_text,
reply_markup=[
[{"text": self.strings("btn_activity"), "callback": self._activity, "args": (username,)}],
[{"text": self.strings("btn_contrib"), "callback": self._contrib, "args": (username,)}, {"text": self.strings("btn_repos"), "callback": self._repos, "args": (username,)}],
[{"text": self.strings("btn_orgs"), "callback": self._orgs, "args": (username,)}],
],
ttl=10 * 60,
)
async def _profile(self, call: InlineCall, username: str):
# Этот метод теперь используется только для возврата к профилю
data = await self.github_fetch(f"https://api.github.com/users/{username}")
if "message" in data:
await call.edit(self.strings("api_error").format(msg=data["message"]))
return
hireable = self.strings("hireable_yes") if data.get("hireable") else self.strings("hireable_no")
profile_text = (
self.strings("profile_header").format(url=data["html_url"], username=username)
+ self.strings("profile_text").format(
name=data.get("name") or self.strings("not_specified"),
login=username,
bio=data.get("bio") or self.strings("no_desc"),
company=data.get("company") or self.strings("not_specified"),
location=data.get("location") or self.strings("not_specified"),
email=data.get("email") or self.strings("not_specified"),
blog=data.get("blog") or self.strings("not_specified"),
twitter=data.get("twitter_username") or self.strings("not_specified"),
hireable=hireable,
type=data.get("type", "User"),
repos=data.get("public_repos", 0),
gists=data.get("public_gists", 0),
followers=data.get("followers", 0),
following=data.get("following", 0),
created=data.get("created_at", "")[:10],
updated=data.get("updated_at", "")[:10],
)
+ "\n" + self.strings("menu_text")
)
await call.edit(
text=profile_text,
reply_markup=[
[{"text": self.strings("btn_activity"), "callback": self._activity, "args": (username,)}],
[{"text": self.strings("btn_contrib"), "callback": self._contrib, "args": (username,)}, {"text": self.strings("btn_repos"), "callback": self._repos, "args": (username,)}],
[{"text": self.strings("btn_orgs"), "callback": self._orgs, "args": (username,)}],
]
)
async def _activity(self, call: InlineCall, username: str):
events = await self.github_fetch(f"https://api.github.com/users/{username}/events?per_page=40")
if "message" in events:
await call.edit(self.strings("api_error").format(msg=events["message"]), reply_markup=[[{"text": self.strings("btn_back"), "callback": self._profile, "args": (username,)}]])
return
if not events:
return await message.edit(self.strings("no_activity").format(username))
await call.edit(self.strings("no_activity").format(username=username), reply_markup=[[{"text": self.strings("btn_back"), "callback": self._profile, "args": (username,)}]])
return
lines = []
for event in events:
lines = [self.strings("activity_header").format(username=username)]
seen_repos = set()
for event in events[:25]:
etype = event["type"]
repo = event["repo"]["name"]
if repo in seen_repos and len(lines) > 20:
continue
payload = event.get("payload", {})
if etype == "PushEvent":
branch = re.sub(r"refs/heads/", "", payload.get("ref", "main"))
count = len(payload.get("commits", []))
lines.append(self.strings("activity_commit").format(count=count, branch=branch, repo=repo))
branch = payload.get("ref", "refs/heads/main").replace("refs/heads/", "")
commits = payload.get("commits", [])
if commits:
lines.append(self.strings("push_header").format(branch=branch, repo=repo))
for commit in commits[:5]:
sha = commit["sha"][:7]
message = commit["message"].split("\n")[0][:100]
if len(commit["message"].split("\n")[0]) > 100:
message += "..."
url = f"https://github.com/{repo}/commit/{commit['sha']}"
lines.append(self.strings("commit_line").format(url=url, sha=sha, message=message))
if len(commits) > 5:
lines.append(self.strings("more_commits").format(len(commits)-5))
else:
lines.append(self.strings("push_no_commits").format(branch=branch, repo=repo))
seen_repos.add(repo)
elif etype == "CreateEvent":
lines.append(self.strings("activity_create").format(ref_type=payload.get("ref_type"), repo=repo))
ref_type = payload.get("ref_type")
ref = payload.get("ref") or ""
if ref_type == "branch":
lines.append(self.strings("create_branch").format(ref=ref, repo=repo))
elif ref_type == "tag":
lines.append(self.strings("create_tag").format(ref=ref, repo=repo))
elif ref_type == "repository":
lines.append(self.strings("create_repo").format(repo=repo))
elif etype == "PullRequestEvent":
pr = payload.get("pull_request", {})
lines.append(self.strings("activity_pr").format(action=payload.get("action"), title=pr.get("title")))
number = pr.get("number", "?")
title = pr.get("title") or self.strings("no_title")
url = pr.get("html_url") or f"https://github.com/{repo}"
action = payload.get("action")
if action == "closed" and pr.get("merged"):
lines.append(self.strings("pr_merged").format(url=url, number=number, title=title))
elif action == "opened":
lines.append(self.strings("pr_opened").format(url=url, number=number, title=title))
elif action == "closed":
lines.append(self.strings("pr_closed").format(url=url, number=number, title=title))
elif etype == "IssuesEvent":
issue = payload.get("issue", {})
lines.append(self.strings("activity_issue").format(action=payload.get("action"), title=issue.get("title")))
number = issue.get("number", "?")
title = issue.get("title") or self.strings("no_title")
url = issue.get("html_url") or f"https://github.com/{repo}"
action = payload.get("action")
if action == "opened":
lines.append(self.strings("issue_opened").format(url=url, number=number, title=title))
elif action == "closed":
lines.append(self.strings("issue_closed").format(url=url, number=number, title=title))
elif etype == "WatchEvent":
lines.append(self.strings("activity_star").format(repo=repo))
lines.append(self.strings("star").format(repo=repo))
elif etype == "ForkEvent":
lines.append(self.strings("activity_fork").format(fork=payload.get("forkee", {}).get("full_name")))
fork = payload.get("forkee", {}).get("full_name", "unknown")
lines.append(self.strings("fork").format(fork=fork))
else:
lines.append(self.strings("activity_other").format(event=etype, repo=repo))
event_name = etype.replace("Event", "")
lines.append(self.strings("other").format(event=event_name, repo=repo))
await message.edit(self.strings("activity_header") + "\n".join(lines))
await call.edit(
text="".join(lines),
reply_markup=[[{"text": self.strings("btn_back"), "callback": self._profile, "args": (username,)}]]
)
@loader.command(doc="Show GitHub contribution graph", ru_doc="Показать график контрибов GitHub")
async def ghc(self, message):
"""Show GitHub contribution graph"""
username = self.get_username(message)
if not username:
return await message.edit(self.strings("no_username"))
async def _repos(self, call: InlineCall, username: str):
repos = await self.github_fetch(f"https://api.github.com/users/{username}/repos?sort=stars&per_page=10")
if "message" in repos:
await call.edit(self.strings("api_error").format(msg=repos["message"]), reply_markup=[[{"text": self.strings("btn_back"), "callback": self._profile, "args": (username,)}]])
return
if not repos:
await call.edit(self.strings("no_repos"), reply_markup=[[{"text": self.strings("btn_back"), "callback": self._profile, "args": (username,)}]])
return
data = self.github_api(f"https://github-contributions-api.deno.dev/{username}.json")
contribs = data.get("contributions") if data else None
lines = [self.strings("repos_header").format(username=username)]
for repo in repos[:10]:
lines.append(self.strings("repo_line").format(
stars=repo.get("stargazers_count", 0),
url=repo["html_url"],
name=repo["name"],
desc=repo.get("description") or self.strings("no_desc"),
lang=repo.get("language") or self.strings("not_specified"),
forks=repo.get("forks_count", 0),
))
if not isinstance(contribs, list):
return await message.edit(self.strings("no_contrib").format(username))
await call.edit(
text="".join(lines),
reply_markup=[[{"text": self.strings("btn_back"), "callback": self._profile, "args": (username,)}]]
)
async def _orgs(self, call: InlineCall, username: str):
orgs = await self.github_fetch(f"https://api.github.com/users/{username}/orgs")
if "message" in orgs:
await call.edit(self.strings("api_error").format(msg=orgs["message"]), reply_markup=[[{"text": self.strings("btn_back"), "callback": self._profile, "args": (username,)}]])
return
if not orgs:
await call.edit(self.strings("no_orgs"), reply_markup=[[{"text": self.strings("btn_back"), "callback": self._profile, "args": (username,)}]])
return
lines = [self.strings("orgs_header").format(username=username)]
for org in orgs:
lines.append(self.strings("org_line").format(
url=f"https://github.com/{org['login']}",
login=org["login"],
desc=org.get("description") or self.strings("no_desc"),
))
await call.edit(
text="".join(lines),
reply_markup=[[{"text": self.strings("btn_back"), "callback": self._profile, "args": (username,)}]]
)
async def _contrib(self, call: InlineCall, username: str):
data = await self.github_fetch(f"https://github-contributions-api.deno.dev/{username}.json", github_api=False)
if not data or not data.get("contributions"):
await call.edit(self.strings("no_contrib"), reply_markup=[[{"text": self.strings("btn_back"), "callback": self._profile, "args": (username,)}]])
return
raw_days = []
for week in data.get("contributions", []):
if isinstance(week, list):
raw_days.extend([day for day in week if isinstance(day, dict)])
today = datetime.utcnow().date()
start = today - timedelta(days=90)
matrix = [["" for _ in range(13)] for _ in range(7)]
weeks_count = 53
days_back = weeks_count * 7 + 7
start = today - timedelta(days=days_back)
for entry in contribs:
matrix = [["" for _ in range(weeks_count)] for _ in range(7)]
for entry in raw_days:
date_str = entry.get("date")
if not date_str:
continue
try:
date = datetime.strptime(entry["date"], "%Y-%m-%d").date()
if not (start <= date <= today):
date = datetime.strptime(date_str, "%Y-%m-%d").date()
if date < start or date > today:
continue
day = (date.weekday() + 1) % 7 # Sunday=0
week = (date - start).days // 7
if entry.get("contributionCount", 0) > 0:
matrix[day][week] = "🟩"
except:
count = entry.get("contributionCount") or entry.get("count", 0) or 0
if count > 0:
day_idx = (date.weekday() + 1) % 7
week_idx = (date - start).days // 7
if week_idx < weeks_count:
matrix[day_idx][week_idx] = "🟩"
except Exception:
continue
days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
graph = "\n".join(f"{days[i]} {''.join(matrix[i])}" for i in range(7))
days_labels = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
graph = "\n".join(f"{days_labels[i]} {''.join(matrix[i])}" for i in range(7))
await message.edit(
self.strings("contrib_header").format(username=username)
+ f"<pre>{graph}</pre>\n"
+ self.strings("contrib_footer")
await call.edit(
text=self.strings("contrib_header").format(username=username)
+ f"<pre>{graph}</pre>"
+ self.strings("contrib_footer"),
reply_markup=[[{"text": self.strings("btn_back"), "callback": self._profile, "args": (username,)}]]
)

View File

@@ -11,6 +11,7 @@
# https://github.com/all-licenses/GNU-General-Public-License-v3.0
# meta developer: @pymodule
# meta fhsdesc: tool, tools, auto, restart, heroku, hikka
from hikkatl.types import Message
from .. import loader, utils

View File

@@ -2,6 +2,7 @@
# https://github.com/all-licenses/GNU-General-Public-License-v3.0
# meta developer: @PyModule
# meta fhsdesc: fun, rp, rpgame
# requires: toml
import os
from hikka import loader, utils

View File

@@ -2,6 +2,7 @@
# https://github.com/all-licenses/GNU-General-Public-License-v3.0
# meta developer: @PyModule
# meta fhsdesc: tool, tools, lyrics, music
import requests
from bs4 import BeautifulSoup, Tag, NavigableString
import re

View File

@@ -11,6 +11,7 @@
# https://github.com/all-licenses/GNU-General-Public-License-v3.0
# meta developer: @pymodule
# meta fhsdesc: tool, tools, minecraft, game
import aiohttp
import base64

View File

@@ -11,6 +11,7 @@
# https://github.com/all-licenses/GNU-General-Public-License-v3.0
# meta developer: @pymodule
# meta fhsdesc: tool, tools, in heroku
# requires: asyncio
from .. import loader, utils

View File

@@ -11,6 +11,7 @@
# https://github.com/all-licenses/GNU-General-Public-License-v3.0
# meta developer: @pymodule
# meta fhsdesc: tool, tools, point, auto
from .. import loader, utils

View File

@@ -11,6 +11,7 @@
# https://github.com/all-licenses/GNU-General-Public-License-v3.0
# meta developer: @pymodule
# meta fhsdesc: tool, tools, qr
from .. import loader, utils
import requests

View File

@@ -3,6 +3,7 @@
# scope: hikka_only
# meta developer: @pymodule
# meta fhsdesc: tool, tools, random
from .. import loader, utils
import random

View File

@@ -11,6 +11,7 @@
# https://github.com/all-licenses/GNU-General-Public-License-v3.0
# meta developer: @pymodule
# meta fhsdesc: tool, tools, test, speedtest
# requires: speedtest-cli
import speedtest

View File

@@ -11,6 +11,7 @@
# https://github.com/all-licenses/GNU-General-Public-License-v3.0
# meta developer: @pymodule
# meta fhsdesc: tool, tools, info, sysinfo, system
# requires: psutil
from .. import loader, utils

View File

@@ -11,6 +11,7 @@
# https://github.com/all-licenses/GNU-General-Public-License-v3.0
# meta developer: @pymodule
# meta fhsdesc: tool, tools, admin, tag, alltag, tagall
from .. import loader, utils
from telethon.tl.types import ChannelParticipantsAdmins, UserStatusRecently, UserStatusOnline, Message

View File

@@ -5,6 +5,7 @@
# Name: UserParser
# Description: Данный модуль позволяет копировать ID, Username и Name участников чата при помощи команды .userpars
# meta developer: @PyModule
# meta fhsdesc: tool, tools, id, parser, userparser
from .. import loader, utils
import json

View File

@@ -12,6 +12,7 @@
# meta developer: @pymodule
# requires: aiohttp
# meta fhsdesc: tool, tools, wiki, wikipedia, info, wikiinfo
from .. import loader, utils
from ..inline.types import InlineQuery

View File

@@ -1,5 +1,5 @@
# -- version --
__version__ = (1, 2, 1)
__version__ = (1, 2, 2)
# -- version --
@@ -9,7 +9,7 @@ __version__ = (1, 2, 1)
# ██║╚██╔╝██║██╔══╝░░██╔══██║██║░░██║██║░░██║░░████╔═████║░░╚═══██╗░╚═══██╗
# ██║░╚═╝░██║███████╗██║░░██║██████╔╝╚█████╔╝░░╚██╔╝░╚██╔╝░██████╔╝██████╔╝
# ╚═╝░░░░░╚═╝╚══════╝╚═╝░░╚═╝╚═════╝░░╚════╝░░░░╚═╝░░░╚═╝░░╚═════╝░╚═════╝░
# © Copyright 2025
# © Copyright 2026
# ✈ https://t.me/mead0wssMods
@@ -33,14 +33,17 @@ class SenderGifts(loader.Module):
"checking_user": "<emoji document_id=5206634672204829887>🔍</emoji> Проверка пользователя...",
"checking_balance": "<emoji document_id=5206634672204829887>🔍</emoji> Проверка баланса...",
"user_not_found": "<emoji document_id=4958526153955476488>❌</emoji> Пользователь не найден",
"gift_menu": "<emoji document_id=5931696400982088015>🎁</emoji> Выберите категорию подарков.\n\n<emoji document_id=6032693626394382504>👤</emoji> Пользователь: {}\n<emoji document_id=5873153278023307367>📄</emoji> Текст: {}\n<emoji document_id=5951810621887484519>⭐</emoji> Баланс: {} звезд",
"category_menu": "<emoji document_id=5931696400982088015>🎁</emoji> Подарки за {}\n\n<emoji document_id=6032693626394382504>👤</emoji> Пользователь: {}\n<emoji document_id=5873153278023307367>📄</emoji> Текст: {}",
"gift_menu": "<tg-emoji emoji-id=5370781982886220096>🎁</tg-emoji> Выберите категорию подарков.\n\n<tg-emoji emoji-id=6048471184461271609>👤</tg-emoji> Пользователь: {}\n<tg-emoji emoji-id=6048762138430803961>📂</tg-emoji> Текст: {}\n<tg-emoji emoji-id=5321485469249198987>⭐</tg-emoji> Баланс: {} звезд",
"category_menu": "<tg-emoji emoji-id=5370781982886220096>🎁</tg-emoji> Подарки за {}\n\n<tg-emoji emoji-id=6048471184461271609>👤</tg-emoji> Пользователь: {}\n<tg-emoji emoji-id=6048762138430803961>📂</tg-emoji> Текст: {}",
"privacy_menu": "<tg-emoji emoji-id=5370781982886220096>🎁</tg-emoji> Выбран подарок: {}\n\nКак отправить подарок?",
"sending_gift": "<emoji document_id=5201691993775818138>🛫</emoji> Отправка подарка...",
"gift_sent": "<emoji document_id=5021905410089550576>✅</emoji> Подарок успешно отправлен!",
"not_enough_stars": "<emoji document_id=4958526153955476488>❌</emoji> Недостаточно звезд для отправки подарка {}!",
"min_stars_error": "<emoji document_id=4958526153955476488>❌</emoji> Недостаточно звезд для отправки минимального подарка!",
"no_available_gifts": "<emoji document_id=4958526153955476488>❌</emoji> Нет доступных подарков для вашего баланса",
"balance_error": "<emoji document_id=4958526153955476488>❌</emoji> Ошибка при проверке баланса",
"btn_public": "📢 Публично",
"btn_anon": "🕵️ Анонимно",
}
gift_categories = {
@@ -57,6 +60,7 @@ class SenderGifts(loader.Module):
{"id": 5170314324215857265, "emoji": "💐", "name": "Цветы"},
{"id": 5170564780938756245, "emoji": "🚀", "name": "Ракета"},
{"id": 5922558454332916696, "emoji": "🎄", "name": "Ёлка"},
{"id": 5956217000635139069, "emoji": "🧸", "name": "Новогодний мишка"}
],
100: [
{"id": 5168043875654172773, "emoji": "🏆", "name": "Кубок"},
@@ -135,9 +139,11 @@ class SenderGifts(loader.Module):
if row:
buttons.append(row)
helper_msg = await self.inline.form("🪐", balance_msg)
await utils.answer(
balance_msg,
helper_msg,
self.strings["gift_menu"].format(
f"@{user.username}" if user.username else user.first_name,
text if text else "-",
@@ -153,8 +159,8 @@ class SenderGifts(loader.Module):
for gift in gifts:
row.append({
"text": gift["emoji"],
"callback": self._send_gift,
"args": (user_id, gift["id"], text, gift["emoji"], msg_id, balance),
"callback": self._select_privacy,
"args": (user_id, gift["id"], text, gift["emoji"], msg_id, balance, price),
})
if len(row) == 3:
buttons.append(row)
@@ -183,6 +189,34 @@ class SenderGifts(loader.Module):
reply_markup=buttons
)
async def _select_privacy(self, call, user_id, gift_id, text, gift_emoji, msg_id, balance, price):
buttons = [
[
{
"text": self.strings["btn_public"],
"callback": self._send_gift,
"args": (user_id, gift_id, text, gift_emoji, msg_id, balance, False) # hide_name=False публично
},
{
"text": self.strings["btn_anon"],
"callback": self._send_gift,
"args": (user_id, gift_id, text, gift_emoji, msg_id, balance, True) # hide_name=True анонимно
}
],
[
{
"text": "⬅️ Назад",
"callback": self._show_category,
"args": (user_id, price, text, balance, msg_id)
}
]
]
await call.edit(
self.strings["privacy_menu"].format(gift_emoji),
reply_markup=buttons
)
async def _back_to_categories(self, call, user_id, text, balance, msg_id):
try:
user = await self.client.get_entity(user_id)
@@ -216,7 +250,7 @@ class SenderGifts(loader.Module):
reply_markup=buttons
)
async def _send_gift(self, call, user_id, gift_id, text, gift_emoji, msg_id, balance):
async def _send_gift(self, call, user_id, gift_id, text, gift_emoji, msg_id, balance, hide_name):
try:
await call.edit(
self.strings["sending_gift"],
@@ -227,11 +261,11 @@ class SenderGifts(loader.Module):
self.client.parse_mode,
)
text, entities = parse_mode.parse(text)
user = await self.client.get_input_entity(user_id)
inv = InputInvoiceStarGift(
user,
gift_id,
hide_name=hide_name,
message=TextWithEntities(text, entities) if text else TextWithEntities("", [])
)
form = await self.client(GetPaymentFormRequest(inv))

126513
modules.json

File diff suppressed because one or more lines are too long

497
parse.py
View File

@@ -1,171 +1,376 @@
import os
import ast
import json
import os
import logging
from typing import Dict, Any, Optional, List
from clone_repos import repos
from typing import Dict
logging.basicConfig(level=logging.WARNING, format="%(message)s")
logger = logging.getLogger(__name__)
# TODO: ADD VENV IGNORE
def safe_unparse(node: ast.AST) -> str:
try:
return ast.unparse(node)
except Exception:
if hasattr(node, "id"):
return str(node.id)
return str(node)
def load_blacklist(file_path):
with open(file_path, "r", encoding="utf-8") as f:
data = json.load(f)
repositories = data.get("repositories", [])
blacklisted_modules = {}
def get_module_info(module_path):
"""Парсит Python-модуль и извлекает информацию о нем."""
with open(module_path, "r", encoding="utf-8") as f:
module_content = f.read()
for i in repositories:
path = i.get("path", "")
blacklist = i.get("blacklist", [])
if path and blacklist:
blacklisted_modules[path] = blacklist
meta_info = {"pic": None, "banner": None}
for line in module_content.split("\n"):
if line.startswith("# meta"):
key, value = line.replace("# meta ", "").split(": ")
meta_info[key] = value
return blacklisted_modules
tree = ast.parse(module_content)
def is_loader_tds(deco: ast.AST) -> bool:
return (
isinstance(deco, ast.Attribute)
and isinstance(deco.value, ast.Name)
and deco.value.id == "loader"
and deco.attr in {"tds", "translatable_docstring"}
)
def get_decorator_names(decorator_list):
return [ast.unparse(decorator) for decorator in decorator_list]
def extract_string_value(node: ast.AST) -> Optional[str]:
try:
if isinstance(node, ast.Constant) and isinstance(node.value, str):
return node.value
def extract_loader_command_args(decorator):
"""Извлекает аргументы `ru_doc` и `en_doc` из `@loader.command`."""
if (
isinstance(decorator, ast.Call)
and hasattr(decorator.func, "attr")
and decorator.func.attr == "command"
):
ru_doc = None
en_doc = None
for keyword in decorator.keywords:
if keyword.arg == "ru_doc":
ru_doc = ast.literal_eval(keyword.value)
elif keyword.arg == "en_doc":
en_doc = ast.literal_eval(keyword.value)
return ru_doc, en_doc
return None, None
if isinstance(node, ast.Str):
return node.s
result = {}
for node in ast.walk(tree):
if isinstance(node, ast.ClassDef):
decorators = get_decorator_names(node.decorator_list)
is_tds_mod = [d for d in decorators if "loader.tds" in d]
if "Mod" not in node.name and not is_tds_mod:
if isinstance(node, ast.JoinedStr):
parts = []
for v in node.values:
if isinstance(v, ast.Constant) and isinstance(v.value, str):
parts.append(v.value)
elif isinstance(v, ast.FormattedValue):
parts.append("{" + safe_unparse(v.value) + "}")
return "".join(parts)
if isinstance(node, ast.Name):
return node.id
if isinstance(node, ast.Attribute):
return f"{safe_unparse(node.value)}.{node.attr}"
return None
except Exception:
return None
def extract_loader_command_args(decorator: ast.Call) -> Dict[str, Any]:
args = {"lang_docs": {}, "aliases": [], "usage": None}
try:
for kw in decorator.keywords:
arg_name = kw.arg
if not arg_name:
continue
if arg_name.endswith("_doc"):
lang = arg_name[:-4]
args["lang_docs"][lang] = extract_string_value(kw.value)
elif arg_name == "aliases":
try:
val = ast.literal_eval(kw.value)
if isinstance(val, (list, tuple)):
args["aliases"] = list(val)
except (ValueError, SyntaxError):
pass
elif arg_name == "usage":
args["usage"] = extract_string_value(kw.value)
except Exception:
pass
return args
class_docstring = ast.get_docstring(node)
class_info = {
"name": node.name,
"description": class_docstring,
"meta": meta_info,
"commands": [],
"new_commands": [],
}
def get_module_info(module_path: str) -> Optional[Dict[str, Any]]:
try:
with open(module_path, "r", encoding="utf-8") as f:
source = f.read()
except Exception as e:
logger.warning(f"Skipping {module_path}: read failed — {e}")
return None
for class_body_node in node.body:
if isinstance(class_body_node, (ast.FunctionDef, ast.AsyncFunctionDef)):
decorators = get_decorator_names(class_body_node.decorator_list)
is_loader_command = [d for d in decorators if "command" in d]
if not is_loader_command and "cmd" not in class_body_node.name:
continue
source = source.lstrip('\ufeff')
source = ''.join(c for c in source if ord(c) >= 32 or c in '\n\r\t') if source else source
method_docstring = ast.get_docstring(class_body_node)
command_name = class_body_node.name
ru_doc, en_doc = None, None
meta = {"pic": None, "banner": None, "developer": None}
for line in source.splitlines():
line = line.strip()
if line.startswith("# meta "):
try:
key, val = line[len("# meta "):].split(":", 1)
meta[key.strip()] = val.strip()
except ValueError:
pass
for decorator in class_body_node.decorator_list:
ru_doc_tmp, en_doc_tmp = extract_loader_command_args(decorator)
if ru_doc_tmp:
ru_doc = ru_doc_tmp
if en_doc_tmp:
en_doc = en_doc_tmp
try:
tree = ast.parse(source, filename=module_path)
except SyntaxError as e:
logger.warning(f"Skipping {module_path}: syntax error — {e}")
return {
"name": module_path.split(os.sep)[-1].replace(".py", ""),
"description": "",
"cls_doc": {},
"meta": meta,
"commands": [],
"new_commands": [],
"inline_handlers": [],
"strings": {},
"has_on_load": False,
"has_on_unload": False,
"class_cmd_names": {},
}
descriptions = []
if method_docstring:
descriptions.append(method_docstring)
if ru_doc:
descriptions.append(ru_doc)
if en_doc:
descriptions.append(en_doc)
module_data = None
class_info["commands"].append(
{command_name: ' '.join(descriptions)}
)
command_name = command_name.replace('cmd', '')
class_info["new_commands"].append(
{
command_name: {
"ru_doc": ru_doc,
"en_doc": en_doc,
"doc": method_docstring,
}
}
)
result = class_info
return result
def parse_developers(base_dir: str) -> Dict[str, list]:
developers = {
"repo": set(), # используем set внутри функции
"channel": set()
}
for repo_url in repos:
repo_path = repo_url.replace("https://github.com/", "")
try:
owner, repo_name = repo_path.split("/")
developers["repo"].add(owner)
except ValueError:
print(f"Incorrect URL of repository: {repo_url}")
for node in ast.walk(tree):
if not isinstance(node, ast.ClassDef):
continue
for root, _, files in os.walk(base_dir):
for file in files:
if file.endswith(".py"):
file_path = os.path.join(root, file)
try:
module_info = get_module_info(file_path)
if module_info and "meta" in module_info:
developer = module_info["meta"].get('developer')
if developer: # Проверяем, что developer не None
# Разделяем строки с запятыми, &, | и пробелами
for dev in developer.replace(',', ' ').replace('&', ' ').replace('|', ' ').split():
# Добавляем только элементы, начинающиеся с @
if dev.startswith('@'):
developers["channel"].add(dev.strip())
except Exception as e:
print(f"Ошибка при парсинге файла {file_path}: {e}")
is_module_class = (
"Mod" in node.name or
any(is_loader_tds(d) for d in node.decorator_list) or
any(isinstance(d, ast.Name) and d.id == "loader" for d in node.decorator_list)
)
# Преобразуем set в list перед возвратом
return {
"repo": list(developers["repo"]),
"channel": list(developers["channel"])
if not is_module_class:
continue
info = {
"name": node.name,
"description": ast.get_docstring(node) or "",
"cls_doc": {},
"meta": meta,
"commands": [],
"new_commands": [],
"inline_handlers": [],
"strings": {},
"has_on_load": False,
"has_on_load": False,
"has_on_unload": False,
"class_cmd_names": {},
}
for item in node.body:
if isinstance(item, ast.Assign):
for target in item.targets:
if isinstance(target, ast.Name) and (target.id == "strings" or target.id.startswith("strings_")):
try:
lit = ast.literal_eval(item.value)
if isinstance(lit, dict):
if target.id == "strings":
info["strings"].update(lit)
if "_cls_doc" in lit:
info["cls_doc"]["default"] = lit["_cls_doc"]
else:
lang = target.id.split("_", 1)[1] if "_" in target.id else None
if lang:
for k, v in lit.items():
if isinstance(k, str) and isinstance(v, str):
if k == "_cls_doc":
info["cls_doc"][lang] = v
elif k.startswith("_cmd_doc_"):
rest = k[len("_cmd_doc_"):]
info["strings"][f"_cmd_doc_{lang}_{rest}"] = v
info["strings"][f"_cmd_doc_{rest}_{lang}"] = v
elif k.startswith("_ihandle_doc_"):
rest = k[len("_ihandle_doc_"):]
info["strings"][f"_ihandle_doc_{lang}_{rest}"] = v
info["strings"][f"_ihandle_doc_{rest}_{lang}"] = v
elif k.startswith("_cls_cmd_"):
info["class_cmd_names"][lang] = v
else:
info["strings"][f"{k}_{lang}"] = v
except Exception:
pass
if "_cls_doc" in info["strings"]:
info["cls_doc"]["default"] = info["strings"]["_cls_doc"]
for func in node.body:
if not isinstance(func, (ast.FunctionDef, ast.AsyncFunctionDef)):
continue
name = func.name
if name == "on_load":
info["has_on_load"] = True
continue
if name == "on_unload":
info["has_on_unload"] = True
continue
is_decorated = any(
isinstance(d, ast.Call) and hasattr(d.func, 'attr') and
d.func.attr in ("command", "inline_handler", "unrestricted", "owner")
for d in func.decorator_list
)
if name.startswith("_") and not is_decorated:
continue
cmd = {
"name": name,
"doc": ast.get_docstring(func) or "",
"lang_docs": {},
"aliases": [],
"usage": None,
"inline": False,
"is_inline_handler": False,
"decorators": [],
"cmd_names": {},
}
for dec in func.decorator_list:
if isinstance(dec, ast.Call) and hasattr(dec.func, 'attr'):
attr = dec.func.attr
if attr == "command":
cmd.update(extract_loader_command_args(dec))
elif attr == "inline_handler":
cmd["inline"] = True
cmd["is_inline_handler"] = True
elif attr in ("unrestricted", "owner", "support"):
cmd["decorators"].append(attr)
for stmt in func.body:
if isinstance(stmt, ast.Assign):
for target in stmt.targets:
if isinstance(target, ast.Attribute):
attr = target.attr
val = extract_string_value(stmt.value)
if not val:
continue
if attr == "_cmd":
cmd["name"] = val
elif attr == "_doc":
cmd["doc"] = val
elif attr == "_cls_doc":
info["cls_doc"]["default"] = val
elif attr.startswith("_cls_doc_"):
lang = attr[len("_cls_doc_"):]
info["cls_doc"][lang] = val
elif attr.startswith("_cmd_"):
lang = attr[len("_cmd_"):]
cmd["cmd_names"][lang] = val
is_command_name = "cmd" in name and not name.startswith("__")
if not (is_decorated or is_command_name):
continue
clean_name = cmd["name"].replace("cmd", "").replace("_", "")
descs = []
legacy_key = f"_cmd_doc_{clean_name}"
legacy_doc = info["strings"].get(legacy_key)
base_doc = legacy_doc if legacy_doc else cmd["doc"]
if base_doc:
descs.append(base_doc)
for lang, text in cmd["lang_docs"].items():
if text:
descs.append(f"({lang.upper()}) {text}")
for k, v in info["strings"].items():
if k.startswith("_cmd_doc_") and clean_name in k and v:
if k.endswith(f"_{clean_name}"):
lang_part = k[len("_cmd_doc_"):-len(f"_{clean_name}")-1]
if lang_part:
descs.append(f"({lang_part.upper()}) {v}")
elif k.startswith(f"_cmd_doc_{clean_name}_"):
lang_part = k[len(f"_cmd_doc_{clean_name}_"):]
if lang_part:
descs.append(f"({lang_part.upper()}) {v}")
full_desc = " | ".join(filter(None, descs))
info["commands"].append({clean_name: full_desc})
desc_map = {"default": legacy_doc or cmd["doc"]}
desc_map.update(cmd["lang_docs"])
for k, v in info["strings"].items():
if k.startswith("_cmd_doc_") and clean_name in k and v:
if k.endswith(f"_{clean_name}"):
lang_part = k[len("_cmd_doc_"):-len(f"_{clean_name}")-1]
if lang_part:
desc_map[lang_part] = v
elif k.startswith(f"_cmd_doc_{clean_name}_"):
lang_part = k[len(f"_cmd_doc_{clean_name}_"):]
if lang_part:
desc_map[lang_part] = v
info["new_commands"].append({
"name": clean_name,
"original_name": cmd["name"],
"description": desc_map,
"cmd_names": cmd["cmd_names"],
"aliases": cmd["aliases"],
"usage": cmd["usage"],
"inline": cmd["inline"],
"is_inline_handler": cmd["is_inline_handler"],
"decorators": cmd["decorators"],
})
if cmd["is_inline_handler"]:
inline_desc_map = {"default": cmd["doc"]}
inline_desc_map.update(cmd["lang_docs"])
for k, v in info["strings"].items():
if k.startswith("_ihandle_doc_") and clean_name in k and v:
if k.endswith(f"_{clean_name}"):
lang_part = k[len("_ihandle_doc_"):-len(f"_{clean_name}")-1]
if lang_part:
inline_desc_map[lang_part] = v
elif k.startswith(f"_ihandle_doc_{clean_name}_"):
lang_part = k[len(f"_ihandle_doc_{clean_name}_"):]
if lang_part:
inline_desc_map[lang_part] = v
info["inline_handlers"].append({
"name": clean_name,
"description": inline_desc_map,
"decorators": cmd["decorators"],
})
module_data = info
break
return module_data
def main():
base_dir = os.getcwd()
modules = {}
blacklisted_modules = load_blacklist("repositories.json")
for root, dirs, files in os.walk(base_dir):
dirs[:] = [d for d in dirs if d not in ("venv", ".venv", "env", ".env", ".git")]
for file in files:
if file.endswith(".py") and not file.startswith("_") and file not in blacklisted_modules.get(os.path.relpath(root, base_dir), []):
path = os.path.join(root, file)
try:
data = get_module_info(path)
if data:
rel = os.path.relpath(path, base_dir).replace("\\", "/")
modules[rel] = data
except Exception as e:
logger.error(f"Error processing {path}: {e}")
output = {
"modules": modules,
"meta": {
"total_modules": len(modules),
"generated_at": __import__("datetime").datetime.now().isoformat(),
}
}
with open("modules.json", "w", encoding="utf-8") as f:
json.dump(output, f, ensure_ascii=False, indent=2)
modules_data = {}
base_dir = os.getcwd()
print(f"modules.json written ({len(modules)} modules)")
for root, _, files in os.walk(base_dir):
for file in files:
if file.endswith(".py"):
file_path = os.path.join(root, file)
try:
module_info = get_module_info(file_path)
if module_info:
relative_path = os.path.relpath(file_path, base_dir)
modules_data[relative_path] = module_info
except Exception as e:
print(f"Ошибка при парсинге файла {file_path}: {e}")
developers = parse_developers(base_dir)
with open("modules.json", "w", encoding="utf-8") as json_file:
json.dump(modules_data, json_file, ensure_ascii=False, indent=2)
print("Файл modules.json создан!")
with open("developers.json", "w", encoding="utf-8") as json_file:
json.dump(developers, json_file, ensure_ascii=False, indent=2)
print("Файл developers.json создан!")
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,214 @@
# =======================================
# _ __ __ __ _
# | |/ /___ | \/ | ___ __| |___
# | ' // _ \ | |\/| |/ _ \ / _` / __|
# | . \ __/ | | | | (_) | (_| \__ \
# |_|\_\___| |_| |_|\___/ \__,_|___/
# @ke_mods
# =======================================
#
# LICENSE: CC BY-ND 4.0 (Attribution-NoDerivatives 4.0 International)
# --------------------------------------
# https://creativecommons.org/licenses/by-nd/4.0/legalcode
# =======================================
# meta developer: @ke_mods
from .. import loader, utils
import requests
import io
import textwrap
from PIL import Image, ImageDraw, ImageEnhance, ImageFilter, ImageFont, ImageOps
class Banners:
def __init__(
self,
title: str,
artists: list,
track_cover: bytes,
font
):
self.title = title
self.artists = ", ".join(artists) if isinstance(artists, list) else artists
self.track_cover = track_cover
self.font_url = font
def _get_font(self, size, font_bytes):
return ImageFont.truetype(io.BytesIO(font_bytes), size)
def _prepare_cover(self, size, radius):
cover = Image.open(io.BytesIO(self.track_cover)).convert("RGBA")
cover = cover.resize((size, size), Image.Resampling.LANCZOS)
mask = Image.new("L", (size, size), 0)
draw = ImageDraw.Draw(mask)
draw.rounded_rectangle((0, 0, size, size), radius=radius, fill=255)
output = Image.new("RGBA", (size, size), (0, 0, 0, 0))
output.paste(cover, (0, 0), mask=mask)
return output
def _prepare_background(self, w, h):
bg = Image.open(io.BytesIO(self.track_cover)).convert("RGBA")
bg = bg.resize((w, h), Image.Resampling.BICUBIC)
bg = bg.filter(ImageFilter.GaussianBlur(radius=20))
bg = ImageEnhance.Brightness(bg).enhance(0.4)
return bg
def horizontal(self):
W, H = 1500, 600
padding = 60
cover_size = 480
font_bytes = requests.get(self.font_url).content
title_font = self._get_font(55, font_bytes)
artist_font = self._get_font(45, font_bytes)
lfm_font = self._get_font(35, font_bytes)
img = self._prepare_background(W, H)
draw = ImageDraw.Draw(img)
cover = self._prepare_cover(cover_size, 30)
img.paste(cover, (padding, (H - cover_size) // 2), cover)
text_x = padding + cover_size + 60
text_y_start = 100
text_width_limit = W - text_x - padding
display_title = self.title
while title_font.getlength(display_title) > text_width_limit and len(display_title) > 0:
display_title = display_title[:-1]
if len(display_title) < len(self.title): display_title += ""
display_artist = self.artists
while artist_font.getlength(display_artist) > text_width_limit and len(display_artist) > 0:
display_artist = display_artist[:-1]
if len(display_artist) < len(self.artists): display_artist += ""
draw.text((text_x, text_y_start), display_title, font=title_font, fill="white")
draw.text((text_x, text_y_start + 70), display_artist, font=artist_font, fill="#B3B3B3")
bar_y = 480
draw.text((text_x, bar_y), "last.fm", font=lfm_font, fill="white")
by = io.BytesIO()
img.save(by, format="PNG")
by.seek(0)
by.name = "banner.png"
return by
def vertical(self):
W, H = 1000, 1500
padding = 80
cover_size = 800
font_bytes = requests.get(self.font_url).content
title_font = self._get_font(60, font_bytes)
artist_font = self._get_font(45, font_bytes)
lfm_font = self._get_font(35, font_bytes)
img = self._prepare_background(W, H)
draw = ImageDraw.Draw(img)
cover = self._prepare_cover(cover_size, 40)
cover_x = (W - cover_size) // 2
cover_y = 120
img.paste(cover, (cover_x, cover_y), cover)
text_area_y = cover_y + cover_size + 120
text_width_limit = W - (padding * 2)
display_title = self.title
while title_font.getlength(display_title) > text_width_limit and len(display_title) > 0:
display_title = display_title[:-1]
if len(display_title) < len(self.title): display_title += ""
display_artist = self.artists
while artist_font.getlength(display_artist) > text_width_limit and len(display_artist) > 0:
display_artist = display_artist[:-1]
if len(display_artist) < len(self.artists): display_artist += ""
title_w = title_font.getlength(display_title)
draw.text(((W - title_w) / 2, text_area_y), display_title, font=title_font, fill="white")
artist_w = artist_font.getlength(display_artist)
draw.text(((W - artist_w) / 2, text_area_y + 75), display_artist, font=artist_font, fill="#B3B3B3")
bar_y = text_area_y + 260
lfm_w = lfm_font.getlength("last.fm")
draw.text(((W - lfm_w) / 2, bar_y), "last.fm", font=lfm_font, fill="white")
by = io.BytesIO()
img.save(by, format="PNG")
by.seek(0)
by.name = "banner.png"
return by
@loader.tds
class lastfmmod(loader.Module):
"""Module for music from different services"""
strings = {
"name": "LastFm",
"no_track": "<emoji document_id=5465665476971471368>❌</emoji> <b>No track is currently playing</b>",
"_doc_text": "The text that will be written next to the file",
"_doc_username": "Your username from last.fm",
"nick_error": "<emoji document_id=5465665476971471368>❌</emoji> <b>Put your nickname from last.fm</b>",
"uploading": "<emoji document_id=5841359499146825803>🕔</emoji> <i>Uploading banner...</i>",
}
strings_ru = {
"name": "LastFm",
"no_track": "<emoji document_id=5465665476971471368>❌</emoji> <b>Сейчас ничего не играет</b>",
"_doc_text": "Текст, который будет написан рядом с файлом",
"_doc_username": "Ваш username с last.fm",
"nick_error": "<emoji document_id=5465665476971471368>❌</emoji> <b>Укажите ваш никнейм с last.fm</b>",
"uploading": "<emoji document_id=5841359499146825803>🕔</emoji> <i>Загрузка баннера...</i>",
}
strings_jp = {
"name": "LastFm",
"no_track": "<emoji document_id=5465665476971471368>❌</emoji> <b>現在再生中のトラックはありません</b>",
"_doc_text": "ファイルの横に表示されるテキスト",
"_doc_username": "Last.fmのユーザー名",
"nick_error": "<emoji document_id=5465665476971471368>❌</emoji> <b>Last.fmのニックネームを入力してください</b>",
"uploading": "<emoji document_id=5841359499146825803>🕔</emoji> <i>バナーをアップロード中...</i>",
}
def __init__(self):
self.config = loader.ModuleConfig(
loader.ConfigValue("username", None, lambda: self.strings["_doc_username"]),
loader.ConfigValue("custom_text", "<emoji document_id=5413612466208799435>🤩</emoji> <b>{song_name}</b> — <b>{song_artist}</b>", lambda: self.strings["_doc_text"]),
loader.ConfigValue("font", "https://raw.githubusercontent.com/kamekuro/assets/master/fonts/Onest-Bold.ttf", "Custom font URL (ttf)"),
loader.ConfigValue("banner_version", "horizontal", lambda: "Banner version", validator=loader.validators.Choice(["horizontal", "vertical"])),
)
@loader.command(alias="np")
async def nowplay(self, message):
"""| send playing track info"""
user = self.config["username"]
if not user:
await self.invoke("config", "lastfm", message=message)
return await utils.answer(message, self.strings["nick_error"])
try:
url = f'http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&nowplaying=true&user={user}&api_key=460cda35be2fbf4f28e8ea7a38580730&format=json'
data = requests.get(url).json()
track = next((t for t in data.get('recenttracks', {}).get('track', []) if t.get('@attr', {}).get('nowplaying')), None)
if not track:
return await utils.answer(message, self.strings["no_track"])
name = track.get('name', 'Unknown')
artist = track.get('artist', {}).get('#text', 'Unknown')
caption = self.config["custom_text"].format(song_artist=artist, song_name=name)
imgs = track.get('image', [])
cov_url = next((i['#text'] for i in imgs if i['size'] == 'extralarge'), imgs[-1]['#text'] if imgs else None)
if not cov_url:
return await utils.answer(message, caption)
msg = await utils.answer(message, self.strings["uploading"])
cov_bytes = await utils.run_sync(requests.get, cov_url)
banners = Banners(name, artist, cov_bytes.content, self.config["font"])
file = await utils.run_sync(getattr(banners, self.config["banner_version"]))
await utils.answer(msg, caption, file=file)
except Exception as e:
await utils.answer(message, f"<pre><code class='language-python'>{e}</code></pre>")

View File

@@ -0,0 +1,48 @@
# =======================================
# _ __ __ __ _
# | |/ /___ | \/ | ___ __| |___
# | ' // _ \ | |\/| |/ _ \ / _` / __|
# | . \ __/ | | | | (_) | (_| \__ \
# |_|\_\___| |_| |_|\___/ \__,_|___/
# @ke_mods
# =======================================
#
# LICENSE: CC BY-ND 4.0 (Attribution-NoDerivatives 4.0 International)
# --------------------------------------
# https://creativecommons.org/licenses/by-nd/4.0/legalcode
# =======================================
# meta developer: @ke_mods
import subprocess
from .. import loader, utils
@loader.tds
class NeofetchMod(loader.Module):
strings = {
"name": "Neofetch",
"not_installed": "<b>Please, install</b> <i>Neofetch</i> <b>package</b>",
}
strings_ru = {
"not_installed": "<b>Пожалуйста, установите пакет</b> <i>Neofetch</i>",
}
strings_ua = {
"not_installed": "<b>Будь ласка, встановіть пакет<b> <i>Neofetch</i>",
}
@loader.command(
ru_doc="- запустить команду neofetch",
ua_doc="- запустити команду neofetch",
)
async def neofetchcmd(self, message):
"""- run neofetch command"""
try:
result = subprocess.run(["neofetch", "--stdout"], capture_output=True, text=True)
output = result.stdout
await utils.answer(message, f"<pre>{utils.escape_html(output)}</pre>")
except FileNotFoundError:
await utils.answer(message, self.strings("not_installed"))

View File

@@ -0,0 +1,211 @@
# =======================================
# _ __ __ __ _
# | |/ /___ | \/ | ___ __| |___
# | ' // _ \ | |\/| |/ _ \ / _` / __|
# | . \ __/ | | | | (_) | (_| \__ \
# |_|\_\___| |_| |_|\___/ \__,_|___/
# @ke_mods
# =======================================
#
# LICENSE: CC BY-ND 4.0 (Attribution-NoDerivatives 4.0 International)
# --------------------------------------
# https://creativecommons.org/licenses/by-nd/4.0/legalcode
# =======================================
# meta developer: @ke_mods
# requires: pillow
import io
import asyncio
from telethon import functions, types
from PIL import Image
from .. import loader, utils
@loader.tds
class PicToStoriesMod(loader.Module):
"""Grid for stories"""
strings = {
"name": "PicToStories",
"no_rep": (
"<emoji document_id=5879813604068298387>❗️</emoji> "
"<b>Reply to photo!</b>"
),
"work": (
"<emoji document_id=5841359499146825803>🕔</emoji> "
"<b>Processing...</b>"
),
"done": (
"<emoji document_id=5776375003280838798>✅</emoji> "
"<b>Done! Check your profile.</b>"
),
"err": (
"<emoji document_id=5778527486270770928>❌</emoji> "
"<b>Error:</b> {}"
),
}
strings_ru = {
"no_rep": (
"<emoji document_id=5879813604068298387>❗️</emoji> "
"<b>Реплай на фото!</b>"
),
"work": (
"<emoji document_id=5841359499146825803>🕔</emoji> "
"<b>Обрабатываю...</b>"
),
"done": (
"<emoji document_id=5776375003280838798>✅</emoji> "
"<b>Готово! Проверяй профиль.</b>"
),
"err": (
"<emoji document_id=5778527486270770928>❌</emoji> "
"<b>Ошибка:</b> {}"
),
}
def __init__(self):
self.config = loader.ModuleConfig(
loader.ConfigValue(
"period",
48,
lambda: "Visibility period in hours",
validator=loader.validators.Integer(),
),
loader.ConfigValue(
"blacklist",
[],
lambda: "Blacklisted user IDs",
validator=loader.validators.Series(loader.validators.Integer()),
),
loader.ConfigValue(
"cooldown",
0,
lambda: "Cooldown between stories in seconds",
validator=loader.validators.Integer(minimum=0),
),
)
@loader.command(ru_doc="<реплай на фото> [название альбома] - сделать сетку")
async def ptscmd(self, message):
"""<reply to photo> [album name] - make grid"""
args = utils.get_args_raw(message)
reply = await message.get_reply_message()
if not reply or not reply.media:
await utils.answer(message, self.strings("no_rep"))
return
try:
image_bytes = await reply.download_media(file=bytes)
img = Image.open(io.BytesIO(image_bytes))
except Exception as e:
await utils.answer(message, self.strings("err").format(e))
return
await utils.answer(message, self.strings("work"))
w, h = img.size
curr_ratio = w / h
variants = [
(5 / 4, 2),
(4 / 5, 3),
(3 / 5, 4),
(9 / 16, 5)
]
best_ratio, rows = min(variants, key=lambda x: abs(curr_ratio - x[0]))
new_h = int(w / best_ratio)
img = img.resize((w, new_h), Image.LANCZOS)
w, h = img.size
parts = []
pw, ph = w // 3, h // rows
for r in range(rows):
for c in range(3):
x, y = c * pw, r * ph
parts.append(img.crop((x, y, x + pw, y + ph)))
parts.reverse()
privacy = [types.InputPrivacyValueAllowAll()]
if self.config["blacklist"]:
entities = []
for uid in self.config["blacklist"]:
try:
entities.append(await self.client.get_input_entity(uid))
except Exception:
continue
if entities:
privacy.append(types.InputPrivacyValueDisallowUsers(users=entities))
story_ids = []
for i, p in enumerate(parts):
out = io.BytesIO()
p.save(out, "JPEG", quality=95)
out.seek(0)
uploaded_file = await self.client.upload_file(out, file_name="s.jpg")
res = await self.client(
functions.stories.SendStoryRequest(
peer=types.InputPeerSelf(),
media=types.InputMediaUploadedPhoto(uploaded_file),
privacy_rules=privacy,
period=self.config["period"] * 3600,
)
)
sid = next(
(
u.story_id if hasattr(u, "story_id") else u.id
for u in res.updates
if hasattr(u, "story_id") or hasattr(u, "id")
),
None,
)
if sid:
story_ids.append(sid)
if self.config["cooldown"] > 0 and i < len(parts) - 1:
await asyncio.sleep(self.config["cooldown"])
if not story_ids:
return
if args:
all_albums = await self.client(
functions.stories.GetAlbumsRequest(peer=types.InputPeerSelf(), hash=0)
)
target = next(
(a for a in all_albums.albums if getattr(a, 'title', '') == args),
None
)
if target:
await self.client(
functions.stories.UpdateAlbumRequest(
peer=types.InputPeerSelf(),
album_id=target.album_id,
add_stories=story_ids,
)
)
else:
await self.client(
functions.stories.CreateAlbumRequest(
peer=types.InputPeerSelf(),
stories=story_ids,
title=args,
)
)
else:
await self.client(
functions.stories.TogglePinnedRequest(
peer=types.InputPeerSelf(), id=story_ids, pinned=True
)
)
await utils.answer(message, self.strings("done"))

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,74 @@
# =======================================
# _ __ __ __ _
# | |/ /___ | \/ | ___ __| |___
# | ' // _ \ | |\/| |/ _ \ / _` / __|
# | . \ __/ | | | | (_) | (_| \__ \
# |_|\_\___| |_| |_|\___/ \__,_|___/
# @ke_mods
# =======================================
#
# LICENSE: CC BY-ND 4.0 (Attribution-NoDerivatives 4.0 International)
# --------------------------------------
# https://creativecommons.org/licenses/by-nd/4.0/legalcode
# =======================================
# meta developer: @ke_mods
from .. import loader, utils
from telethon.tl.types import ChatBannedRights
from telethon.tl.functions.channels import EditBannedRequest
from telethon.tl.types import ChannelParticipantsKicked
@loader.tds
class UnbanAllMod(loader.Module):
strings = {
"name": "UnbanAll",
"no_rights": "<b>❌ I don't have administrator rights to remove restrictions.</b>",
"success": "<b>✅ All banned chat members have been unbanned.</b>",
"unban_in_process": "<b>👀 Unbanning users...</b>",
"no_banned": "<b> There are no banned members in this chat.</b>",
"error_occured": "<b>💢 An error occurred while unbanning user <code>{}</code>:</b>\n<code>{}</code>",
}
strings_ru = {
"no_rights": "<b>❌ У меня нет прав администратора для снятия ограничений.</b>",
"success": "<b>✅ Все забаненные участники чата были разблокированы.</b>",
"unban_in_process": "<b>👀 Разбаниваю пользователей...</b>",
"no_banned": "<b> В этом чате нет забаненных участников.</b>",
"error_occured": "<b>💢 Произошла ошибка при разблокировке пользователя <code>{}</code>:</b>\n<code>{}</code>",
}
@loader.command(ru_doc="- Разбанить всех забаненных пользователей")
async def unbanallcmd(self, message):
"""- Unban all banned users"""
chat = await message.get_chat()
if not chat.admin_rights and not chat.creator:
await utils.answer(message, self.strings("no_rights"))
return
await utils.answer(message, self.strings("unban_in_process"))
no_banned = True
async for user in self.client.iter_participants(
message.chat_id, filter=ChannelParticipantsKicked
):
no_banned = False
try:
await self.client(EditBannedRequest(
message.chat_id,
user.id,
ChatBannedRights(until_date=0)
))
except Exception as e:
await utils.answer(message, self.strings("error_occured").format(user.id, e))
pass
if no_banned:
await utils.answer(message, self.strings("no_banned"))
return
await utils.answer(message, self.strings("success"))

View File

@@ -0,0 +1,7 @@
Neofetch
randomanimepic
SpotifyMod
UnbanAll
voicetotext
LastFm
PicToStories

View File

@@ -0,0 +1,65 @@
# =======================================
# _ __ __ __ _
# | |/ /___ | \/ | ___ __| |___
# | ' // _ \ | |\/| |/ _ \ / _` / __|
# | . \ __/ | | | | (_) | (_| \__ \
# |_|\_\___| |_| |_|\___/ \__,_|___/
# @ke_mods
# =======================================
#
# LICENSE: CC BY-ND 4.0 (Attribution-NoDerivatives 4.0 International)
# --------------------------------------
# https://creativecommons.org/licenses/by-nd/4.0/legalcode
# =======================================
# meta developer: @ke_mods
import requests
import asyncio
import logging
import traceback
from logging import basicConfig
from .. import loader, utils
basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
@loader.tds
class RandomAnimePicMod(loader.Module):
strings = {
"name": "RandomAnimePic",
"img": "<emoji document_id=4916036072560919511>✅</emoji> <b>Your anime pic</b>\n<emoji document_id=5877465816030515018>🔗</emoji> <b>URL:</b> {}",
"loading": "<emoji document_id=4911241630633165627>✨</emoji> <b>Loading image...</b>",
"error": "<emoji document_id=5116151848855667552>🚫</emoji> <b>An unexpected error occurred...</b>",
}
strings_ru = {
"img": "<emoji document_id=4916036072560919511>✅</emoji> <b>Ваша аниме-картинка</b>\n<emoji document_id=5877465816030515018>🔗</emoji> <b>Ссылка:</b> {}",
"loading": "<emoji document_id=4911241630633165627>✨</emoji> <b>Загрузка изображения...</b>",
"error": "<emoji document_id=5116151848855667552>🚫</emoji> <b>Произошла непредвиденная ошибка...</b>",
}
@loader.command(
ru_doc="- получить рандомную аниме-картинку 👀"
)
async def rapiccmd(self, message):
"""- fetch random anime-pic 👀"""
await utils.answer(message, self.strings("loading"))
try:
res = requests.get("https://api.nekosia.cat/api/v1/images/cute?count=1")
res.raise_for_status()
data = res.json()
image_url = data['image']['original']['url']
await asyncio.sleep(2)
await utils.answer(message, self.strings("img").format(image_url), file=image_url, reply_to=message.reply_to_msg_id)
except Exception:
logger.error("Error fetching random anime pic: %s", traceback.format_exc())
await utils.answer(message, self.strings("error"))
await asyncio.sleep(5)

View File

@@ -0,0 +1,77 @@
# =======================================
# _ __ __ __ _
# | |/ /___ | \/ | ___ __| |___
# | ' // _ \ | |\/| |/ _ \ / _` / __|
# | . \ __/ | | | | (_) | (_| \__ \
# |_|\_\___| |_| |_|\___/ \__,_|___/
# @ke_mods
# =======================================
#
# LICENSE: CC BY-ND 4.0 (Attribution-NoDerivatives 4.0 International)
# --------------------------------------
# https://creativecommons.org/licenses/by-nd/4.0/legalcode
# =======================================
# meta developer: @ke_mods
# scope: ffmpeg
# requires: pydub SpeechRecognition
from .. import loader, utils
import os
import speech_recognition as sr
from pydub import AudioSegment
@loader.tds
class VoiceToTextMod(loader.Module):
strings = {
"name": "VoiceToText",
"process_text": "<emoji document_id=4911241630633165627>✨</emoji> <b>Recognizing the message text...</b>",
"vtt_success": "<emoji document_id=5116110535565247270>🔥</emoji> <b>Recognized text:</b>\n<blockquote expandable>{}</blockquote>",
"vtt_failure": "<emoji document_id=5116151848855667552>🚫</emoji> <b>Failed to recognize the message.</b>",
"vtt_request_error": "<emoji document_id=5116151848855667552>🚫</emoji> <b>Error when contacting the recognition service:</b>\n<code>{}</code>",
"vtt_invalid": "<emoji document_id=5116151848855667552>🚫</emoji> <b>Please reply to a voice or video message with the command</b> <code>{}vtt</code>",
"vtt_successful": "<emoji document_id=4916036072560919511>✅</emoji> <b>Text recognized successfully</b>",
}
strings_ru = {
"process_text": "<emoji document_id=4911241630633165627>✨</emoji> <b>Распознаю текст сообщения...</b>",
"vtt_success": "<emoji document_id=5116110535565247270>🔥</emoji> <b>Распознанный текст:</b>\n<blockquote expandable>{}</blockquote>",
"vtt_failure": "<emoji document_id=5116151848855667552>🚫</emoji> <b>Не удалось распознать сообщение.</b>",
"vtt_request_error": "<emoji document_id=5116151848855667552>🚫</emoji> <b>Ошибка при обращении к сервису распознавания:</b>\n<code>{}</code>",
"vtt_invalid": "<emoji document_id=5116151848855667552>🚫</emoji> <b>Пожалуйста, ответьте на голосовое или видеосообщение командой</b> <code>{}vtt</code>",
"vtt_successful": "<emoji document_id=4916036072560919511>✅</emoji> <b>Текст успешно распознан</b>",
}
@loader.command(
ru_doc="- распознает текст из голосового или видеосообщения.",
)
async def vttcmd(self, message):
"""- recognizes text from voice or video messages."""
reply = await message.get_reply_message()
if not reply or not (reply.voice or reply.video_note):
await utils.answer(message, self.strings["vtt_invalid"].format(self.get_prefix()))
return
msg = await utils.answer(
message, self.strings["process_text"], reply_to=message.id
)
media_file = await reply.download_media()
wav_file = media_file.replace('.mp4', '.wav') if reply.video_note else media_file.replace('.oga', '.wav')
try:
AudioSegment.from_file(media_file).export(wav_file, format='wav')
recognizer = sr.Recognizer()
with sr.AudioFile(wav_file) as source:
audio_data = recognizer.record(source)
try:
text = recognizer.recognize_google(audio_data, language='ru-RU')
await utils.answer(msg, self.strings["vtt_success"].format(text))
except sr.UnknownValueError:
await utils.answer(msg, self.strings["vtt_failure"])
except sr.RequestError as e:
await utils.answer(msg, self.strings["vtt_request_error"].format(e))
finally:
os.remove(media_file)
os.remove(wav_file)

244
repositories.json Normal file
View File

@@ -0,0 +1,244 @@
{
"repositories": [
{
"url": "https://github.com/DziruModules/hikkamods",
"tags": [],
"blacklist": []
},
{
"url": "https://github.com/kamolgks/Hikkamods",
"tags": [],
"blacklist": []
},
{
"url": "https://github.com/thomasmod/hikkamods",
"tags": [],
"blacklist": []
},
{
"url": "https://github.com/SkillsAngels/Modules",
"tags": [],
"blacklist": []
},
{
"url": "https://github.com/Sad0ff/modules-ftg",
"tags": [],
"blacklist": []
},
{
"url": "https://github.com/Yahikoro/Modules-for-FTG",
"tags": [],
"blacklist": []
},
{
"url": "https://github.com/KeyZenD/modules",
"tags": [],
"blacklist": []
},
{
"url": "https://github.com/AlpacaGang/ftg-modules",
"tags": [],
"blacklist": []
},
{
"url": "https://github.com/trololo65/Modules",
"tags": [],
"blacklist": []
},
{
"url": "https://github.com/Ijidishurka/modules",
"tags": [],
"blacklist": []
},
{
"url": "https://github.com/Fl1yd/FTG-Modules",
"tags": [],
"blacklist": []
},
{
"url": "https://github.com/D4n13l3k00/FTG-Modules",
"tags": [],
"blacklist": []
},
{
"url": "https://github.com/iamnalinor/FTG-modules",
"tags": ["hikkatrusted", "nonactive"],
"blacklist": []
},
{
"url": "https://github.com/SekaiYoneya/modules",
"tags": [],
"blacklist": []
},
{
"url": "https://github.com/GeekTG/FTG-Modules",
"tags": [],
"blacklist": []
},
{
"url": "https://github.com/Den4ikSuperOstryyPer4ik/Astro-modules",
"tags": ["hikkatrusted", "herokutrusted"],
"blacklist": []
},
{
"url": "https://github.com/vsecoder/hikka_modules",
"tags": ["hikkatrusted", "herokutrusted"],
"blacklist": []
},
{
"url": "https://github.com/sqlmerr/hikka_mods",
"tags": ["hikkatrusted", "herokutrusted"],
"blacklist": []
},
{
"url": "https://github.com/N3rcy/modules",
"tags": ["hikkatrusted", "herokutrusted"],
"blacklist": []
},
{
"url": "https://github.com/KorenbZla/HikkaModules",
"tags": ["hikkatrusted", "herokutrusted"],
"blacklist": []
},
{
"url": "https://github.com/MuRuLOSE/HikkaModulesRepo",
"tags": [],
"blacklist": []
},
{
"url": "https://github.com/coddrago/modules",
"tags": ["herokutrusted", "hikkatrusted"],
"blacklist": []
},
{
"url": "https://github.com/1jpshiro/hikka-modules",
"tags": [],
"blacklist": []
},
{
"url": "https://github.com/MoriSummerz/ftg-mods",
"tags": ["hikkatrusted", "nonactive"],
"blacklist": []
},
{
"url": "https://github.com/anon97945/hikka-mods",
"tags": ["hikkatrusted", "nonactive"],
"blacklist": []
},
{
"url": "https://github.com/dorotorothequickend/DorotoroModules",
"tags": ["hikkatrusted", "nonlongermaintained"],
"blacklist": []
},
{
"url": "https://github.com/AmoreForever/amoremods",
"tags": [],
"blacklist": []
},
{
"url": "https://github.com/idiotcoders/idiotmodules",
"tags": ["hikkatrusted", "herokutrusted", "nonactive"],
"blacklist": []
},
{
"url": "https://github.com/CakesTwix/Hikka-Modules",
"tags": ["hikkatrusted", "nonactive"],
"blacklist": []
},
{
"url": "https://github.com/archquise/H.Modules",
"tags": ["hikkatrusted", "nonactive"],
"blacklist": []
},
{
"url": "https://github.com/GD-alt/mm-hikka-mods",
"tags": ["hikkatrusted", "herokutrusted", "nonactive"],
"blacklist": []
},
{
"url": "https://github.com/HitaloSama/FTG-modules-repo",
"tags": [],
"blacklist": []
},
{
"url": "https://github.com/SekaiYoneya/Friendly-telegram",
"tags": [],
"blacklist": []
},
{
"url": "https://github.com/blazedzn/ftg-modules",
"tags": [],
"blacklist": []
},
{
"url": "https://github.com/hikariatama/ftg",
"tags": ["hikkatrusted", "nonactive"],
"blacklist": []
},
{
"url": "https://github.com/m4xx1m/FTG",
"tags": [],
"blacklist": []
},
{
"url": "https://github.com/skillzmeow/skillzmods_hikka",
"tags": [],
"blacklist": []
},
{
"url": "https://github.com/fajox1/famods",
"tags": ["hikkatrusted", "herokutrusted"],
"blacklist": []
},
{
"url": "https://github.com/TheKsenon/MyHikkaModules",
"tags": ["hikkatrusted", "herokutrusted"],
"blacklist": []
},
{
"url": "https://github.com/cryptexctl/modules-mirror",
"tags": [],
"blacklist": []
},
{
"url": "https://github.com/Ruslan-Isaev/modules",
"tags": ["herokutrusted"],
"blacklist": []
},
{
"url": "https://github.com/shadowhikka/sh.modules",
"tags": [],
"blacklist": []
},
{
"url": "https://github.com/fiksofficial/python-modules",
"tags": ["herokutrusted"],
"blacklist": []
},
{
"url": "https://github.com/mead0wsss/mead0wsMods",
"tags": ["herokutrusted"],
"blacklist": []
},
{
"url": "https://github.com/SenkoGuardian/SenModules",
"tags": ["herokutrusted"],
"blacklist": []
},
{
"url": "https://github.com/ZetGoHack/nullmod",
"tags": ["herokutrusted"],
"blacklist": []
},
{
"url": "https://github.com/yummy1gay/limoka",
"tags": [],
"blacklist": []
},
{
"url": "https://github.com/radiocycle/Modules",
"tags": ["newbie"],
"blacklist": []
}
]
}

View File

@@ -1,20 +0,0 @@
{
"trusted": [
"iamnalinor/FTG-modules",
"vsecoder/hikka_modules",
"sqlmerr/hikka_mods",
"N3rcy/modules",
"KorenbZla/HikkaModules",
"coddrago/modules",
"MoriSummerz/ftg-mods",
"anon97945/hikka-mods",
"dorotorothequickend/DorotoroModules",
"idiotcoders/idiotmodules",
"C0dwiz/H.Modules",
"GD-alt/mm-hikka-mods",
"hikariatama/ftg",
"fajox1/famods",
"TheKsenon/MyHikkaModules",
"Den4ikSuperOstryyPer4ik/Astro-modules"
]
}

View File

@@ -1,402 +0,0 @@
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

@@ -1,28 +0,0 @@
# 🌘 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.

Before

Width:  |  Height:  |  Size: 552 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 593 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 592 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 674 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 579 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 612 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 584 KiB

View File

@@ -1,147 +0,0 @@
__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

@@ -1,141 +0,0 @@
__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

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

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 109 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

View File

@@ -1,63 +0,0 @@
en:
guide: "<emoji document_id=5956561916573782596>📜</emoji> <b><a href=\"https://yandex-music.rtfd.io/en/main/token.html\">Guide for obtaining access token for Yandex.Music</a></b>"
search: "<emoji document_id=5474304919651491706>🎧</emoji> <b>{performer} — {title}</b>\n<emoji document_id=5242574232688298747>🎵</emoji> <b><a href=\"https://music.yandex.ru/track/{track_id}\">Yandex.Music</a> | <a href=\"https://song.link/ya/{track_id}\">song.link</a></b>"
downloading_track: "\n\n<emoji document_id=5841359499146825803>🕔</emoji> <i>Downloading audio…</i>"
uploading_banner: "\n\n<emoji document_id=5841359499146825803>🕔</emoji> <i>Uploading banner…</i>"
lyrics: "<emoji document_id=5956561916573782596>📜</emoji> <b>Lyrics of the <a href=\"https://music.yandex.ru/track/{track_id}\">{track}</a> track:</b>\n<blockquote expandable>{text}</blockquote>\n\n<emoji document_id=5776287149724798198>©️</emoji> <b>Writers:</b> {writers}"
no_lyrics: "<emoji document_id=5872829476143894491>🚫</emoji> <b>Track <a href=\"https://music.yandex.ru/track/{track_id}\">{track}</a> has no lyrics!</b>"
errors:
no_query: "<emoji document_id=5872829476143894491>🚫</emoji> <b>Specify the search query first!</b>"
no_token_or_invalid: "<emoji document_id=5872829476143894491>🚫</emoji> <b>You specified an invalid access token or didn't specified it at all!</b>"
not_found: "<emoji document_id=5872829476143894491>🚫</emoji> <b>No results found.</b>"
no_playing: "<emoji document_id=5872829476143894491>🚫</emoji> <b>You don't listening to anything right now.</b>"
autobio:
enabled: "<emoji document_id=5242574232688298747>🎧</emoji> <b>Autobio was enabled.</b>"
disabled: "<emoji document_id=5242574232688298747>🎧</emoji> <b>Autobio was disabled.</b>"
likes:
liked: "<emoji document_id=5899833370052923106>❤️</emoji> <b>Track <a href=\"https://music.yandex.ru/track/{track_id}\">{track}</a> was liked.</b>"
unliked: "<emoji document_id=5992453811510186287>🖤</emoji> <b>Track <a href=\"https://music.yandex.ru/track/{track_id}\">{track}</a> was unliked.</b>"
disliked: "<emoji document_id=5952055319059239589>💔</emoji> <b>Track <a href=\"https://music.yandex.ru/track/{track_id}\">{track}</a> was disliked.</b>"
_entity_types:
VARIOUS: "Your queue"
RADIO: "«My Vibe»"
PLAYLIST: "Playlist «{}»"
ALBUM: "«{}»"
ARTIST: "Popular tracks by {}"
_cfg:
token: "The access token for Yandex.Music."
now_playing_text: "The caption for .ynow and .ynowt commands. May contain {performer}, {title}, {device}, {volume}, {playing_from}, {link}, {track_id}, {album_id} keywords."
autobio_text: "The text for automatically changing «Bio». May contains {performer} and {title}."
no_playing_bio_text: "The text for changing «Bio» when there is no playing tracks."
banner_version: "Banner version (old / new with lyrics / new without lyrics)."
ru:
guide: "<emoji document_id=5956561916573782596>📜</emoji> <b><a href=\"https://yandex-music.rtfd.io/en/main/token.html\">Гайд по получению токена Яндекс.Музыки</a></b>"
search: "<emoji document_id=5474304919651491706>🎧</emoji> <b>{performer} — {title}</b>\n<emoji document_id=5242574232688298747>🎵</emoji> <b><a href=\"https://music.yandex.ru/track/{track_id}\">Яндекс.Музыка</a> | <a href=\"https://song.link/ya/{track_id}\">song.link</a></b>"
downloading_track: "\n\n<emoji document_id=5841359499146825803>🕔</emoji> <i>Загрузка трека…</i>"
uploading_banner: "\n\n<emoji document_id=5841359499146825803>🕔</emoji> <i>Загрузка баннера…</i>"
lyrics: "<emoji document_id=5956561916573782596>📜</emoji> <b>Текст трека <a href=\"https://music.yandex.ru/track/{track_id}\">{track}</a>:</b>\n<blockquote expandable>{text}</blockquote>\n\n<emoji document_id=5776287149724798198>©️</emoji> <b>Авторы:</b> {writers}"
no_lyrics: "<emoji document_id=5872829476143894491>🚫</emoji> <b>У трека <a href=\"https://music.yandex.ru/track/{track_id}\">{track}</a> нет текста!</b>"
errors:
no_query: "<emoji document_id=5872829476143894491>🚫</emoji> <b>Укажите поисковый запрос!</b>"
no_token_or_invalid: "<emoji document_id=5872829476143894491>🚫</emoji> <b>Вы указали невалидный токен или не указали его вообще!</b>"
not_found: "<emoji document_id=5872829476143894491>🚫</emoji> <b>Результаты не найдены.</b>"
no_playing: "<emoji document_id=5872829476143894491>🚫</emoji> <b>Вы ничего не слушаете сейчас.</b>"
autobio:
enabled: "<emoji document_id=5242574232688298747>🎧</emoji> <b>Автобио теперь включено.</b>"
disabled: "<emoji document_id=5242574232688298747>🎧</emoji> <b>Автобио теперь выключено.</b>"
likes:
liked: "<emoji document_id=5899833370052923106>❤️</emoji> <b>Трек <a href=\"https://music.yandex.ru/track/{track_id}\">{track}</a> был лайкнут.</b>"
unliked: "<emoji document_id=5992453811510186287>🖤</emoji> <b>С трека <a href=\"https://music.yandex.ru/track/{track_id}\">{track}</a> был снят лайк.</b>"
disliked: "<emoji document_id=5952055319059239589>💔</emoji> <b>Трек <a href=\"https://music.yandex.ru/track/{track_id}\">{track}</a> был дизлайкнут.</b>"
_entity_types:
VARIOUS: "Ваша очередь"
RADIO: "«Моя волна»"
PLAYLIST: "Плейлист «{}»"
ALBUM: "«{}»"
ARTIST: "Популярные треки {}"
_cfg:
token: "Токен для Яндекс.Музыки."
now_playing_text: "Текст, использующийся в подписи к файлу в командах .ynow и .ynowt. Может содержать {performer}, {title}, {device}, {volume}, {playing_from}, {link}, {track_id} и {album_id}"
autobio_text: "Текст, использующийся при автоматическом изменении «О себе». Может содержать {performer} и {title}."
no_playing_bio_text: "Текст, использующийся при изменении «О себе», когда ничего не играет."
banner_version: "Версия баннера (старый / новый с текстом трека / новый без текста трека)."

View File

@@ -1,397 +0,0 @@
__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)]

View File

@@ -1,370 +0,0 @@
__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

@@ -1,183 +0,0 @@
__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

@@ -1,798 +0,0 @@
__version__ = (2, 0, 1)
# region KAMEKURO.
# █▄▀ ▄▀█ █▀▄▀█ █▀▀ █▄▀ █ █ █▀█ █▀█
# █ █ █▀█ █ ▀ █ ██▄ █ █ ▀▄▄▀ █▀▄ █▄█ ▄
# © 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.
# region YaMusic
# ▀▄▀ ▄▀█ █▀▄▀█ █ █ █▀▀ █ █▀▀
# █ █▀█ █ ▀ █ ▀▄▄▀ ▄▄█ █ █▄▄
# 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
# packurl: https://raw.githubusercontent.com/kamekuro/hikka-mods/main/langpacks/yamusic.yml
# scope: heroku_only
# scope: heroku_min 1.7.2
# requires: aiohttp asyncio requests pillow==12.0.0 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 textwrap
import typing
from PIL import Image, ImageDraw, ImageEnhance, ImageFilter, ImageFont
import telethon
import yandex_music
import yandex_music.exceptions
from .. import loader, utils
logger = logging.getLogger(__name__)
class Banners:
def __init__(
self,
title: str,
artists: list,
duration: int,
progress: int,
track_cover: bytes,
):
self.title = title
self.artists = artists
self.duration = duration
self.progress = progress
self.track_cover = track_cover
self.onest_b = "https://raw.githubusercontent.com/kamekuro/assets/master/fonts/Onest-Bold.ttf"
self.onest_r = "https://raw.githubusercontent.com/kamekuro/assets/master/fonts/Onest-Regular.ttf"
self.ysmusic_hb = "https://raw.githubusercontent.com/kamekuro/assets/master/fonts/YSMusic-HeadlineBold.ttf"
def measure(
self, text: str, font: ImageFont.FreeTypeFont, draw: ImageDraw.ImageDraw
):
bbox = draw.textbbox((0, 0), text, font=font)
return bbox[2] - bbox[0], bbox[3] - bbox[1]
def new(self):
W, H = 1920, 768
title_font = ImageFont.truetype(io.BytesIO(requests.get(self.onest_b).content), 80)
artist_font = ImageFont.truetype(io.BytesIO(requests.get(self.onest_b).content), 55)
time_font = ImageFont.truetype(io.BytesIO(requests.get(self.onest_b).content), 36)
track_cov = Image.open(io.BytesIO(self.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)
draw = ImageDraw.Draw(banner)
track_cov = track_cov.resize((H - 250, H - 250))
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)
space = (643, 75, 1870, 593)
title_lines = textwrap.wrap(self.title, width=23)
if len(title_lines) > 2:
title_lines = title_lines[:2]
title_lines[-1] = title_lines[-1][:-1] + ""
artist_lines = textwrap.wrap(", ".join(self.artists), width=23)
if len(artist_lines) > 1:
artist_lines = artist_lines[:1]
artist_lines[-1] = artist_lines[-1][:-1] + ""
lines = title_lines + artist_lines
lines_sizes = [
self.measure(
line, artist_font if (i == len(lines)-1) else title_font, draw
)
for i, line in enumerate(lines)
]
total_sizes = [sum(w for w, _ in lines_sizes), sum(h for _, h in lines_sizes)]
spacing = title_font.size + 10
y_start = space[1] + ((space[3]-space[1]-total_sizes[1]) / 2)
for i, line in enumerate(lines):
w, _ = lines_sizes[i]
draw.text(
(space[0] + (space[2]-space[0]-w) / 2, y_start),
line,
font=(artist_font if (i == (len(lines)-1)) else title_font),
fill="#FFFFFF",
)
y_start += spacing
draw.text(
(75, 650),
f"{(self.progress//1000//60):02}:{(self.progress//1000%60):02}",
font=time_font,
fill="#FFFFFF",
)
draw.text(
(1745, 650),
f"{(self.duration//1000//60):02}:{(self.duration//1000%60):02}",
font=time_font,
fill="#FFFFFF",
)
draw.rounded_rectangle([75, 700, 1845, 715], radius=15 // 2, fill="#A0A0A0")
draw.rounded_rectangle(
[75, 700, int(75 + (1770 * self.progress / self.duration)), 715],
radius=15 // 2,
fill="#FFFFFF",
)
by = io.BytesIO()
banner.save(by, format="PNG")
by.seek(0)
by.name = "banner.png"
return by
def old(self):
w, h = 1920, 768
title_font = ImageFont.truetype(io.BytesIO(requests.get(self.onest_b).content), 80)
art_font = ImageFont.truetype(io.BytesIO(requests.get(self.onest_r).content), 55)
time_font = ImageFont.truetype(io.BytesIO(requests.get(self.onest_b).content), 36)
track_cov = Image.open(io.BytesIO(self.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)
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)
title_lines = textwrap.wrap(self.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(self.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]
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
draw.rounded_rectangle(
[768, 650, 768 + 1072, 650 + 15], radius=15 // 2, fill="#A0A0A0"
)
draw.rounded_rectangle(
[768, 650, 768 + int(1072 * (self.progress / self.duration)), 650 + 15],
radius=15 // 2,
fill="#FFFFFF",
)
draw.text(
(768, 600),
f"{(self.progress//1000//60):02}:{(self.progress//1000%60):02}",
font=time_font,
fill="#FFFFFF",
)
draw.text(
(1745, 600),
f"{(self.duration//1000//60):02}:{(self.duration//1000%60):02}",
font=time_font,
fill="#FFFFFF",
)
by = io.BytesIO()
banner.save(by, format="PNG")
by.seek(0)
by.name = "banner.png"
return by
@loader.tds
class YaMusicMod(loader.Module):
"""The module for Yandex.Music streaming service"""
strings = {"name": "YaMusic", "iguide": "📜 <b><a href=\"https://yandex-music.rtfd.io/en/main/token.html\">Guide for obtaining access token for Yandex.Music</a></b>"}
strings_ru = {"_cls_doc": "Модуль для стримингового сервиса Яндекс.Музыка", "iguide": "📜 <b><a href=\"https://yandex-music.rtfd.io/en/main/token.html\">Гайд по получению токена Яндекс.Музыки</a></b>"}
def __init__(self):
self.config = loader.ModuleConfig(
loader.ConfigValue(
option="token",
default=None,
doc=lambda: self.strings["_cfg"]["token"],
validator=loader.validators.Hidden(),
),
loader.ConfigValue(
option="now_playing_text",
default=(
"<emoji document_id=5474304919651491706>🎧</emoji> <b>{performer}{title}</b>\n\n"
"<emoji document_id=6039404727542747508>⌨️</emoji> <b>Now is listening on <code>"
"{device}</code> (<emoji document_id=6039454987250044861>🔊</emoji> {volume}%)</b>\n"
"<emoji document_id=6039630677182254664>🗂</emoji> <b>Playing from:</b> {playing_from}"
"\n\n<emoji document_id=5242574232688298747>🎵</emoji> <b>{link} | "
'<a href="https://song.link/ya/{track_id}">song.link</a></b>'
),
doc=lambda: self.strings["_cfg"]["now_playing_text"],
validator=loader.validators.String(),
),
loader.ConfigValue(
option="autobio_text",
default="{performer}{title}",
doc=lambda: self.strings["_cfg"]["autobio_text"],
validator=loader.validators.String(),
),
loader.ConfigValue(
option="no_playing_bio_text",
default="I use Heroku with YaMusic mod btw",
doc=lambda: self.strings["_cfg"]["no_playing_bio_text"],
validator=loader.validators.String(),
),
loader.ConfigValue(
option="banner_version",
default="new",
doc=lambda: self.strings["_cfg"]["banner_version"],
validator=loader.validators.Choice(["old", "new"]),
),
)
async def client_ready(self, client, db):
self._client: telethon.TelegramClient = client
self._db = db
if not self.get("guide_sent", False):
await self.inline.bot.send_message(self._tg_id, self.strings("iguide"))
self.set("guide_sent", True)
me = await self._client.get_me()
self._premium = me.premium if hasattr(me, "premium") else False
if self.get("autobio", False):
self.autobio.start()
@loader.loop(1800, autostart=True)
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
now = await self.__get_now_playing()
if now and (not now["paused"]):
out = self.config["autobio_text"].format(
title=now["track"]["title"],
performer=", ".join(now["track"]["artist"]),
)
else:
out = self.config["no_playing_bio_text"]
try:
await self._client(
telethon.functions.account.UpdateProfileRequest(
about=out[: (140 if self._premium else 70)]
)
)
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"""
try:
ym_client = await yandex_music.ClientAsync(self.config["token"]).init()
except yandex_music.exceptions.UnauthorizedError:
return await utils.answer(
message, self.strings("errors")["no_token_or_invalid"]
)
bio = not self.get("autobio", False)
self.set("autobio", bio)
if bio:
await self.autobio.func(self)
self.autobio.start()
else:
self.autobio.stop()
try:
await self._client(
telethon.functions.account.UpdateProfileRequest(
about=self.config["no_playing_bio_text"][
: (140 if self._premium else 70)
]
)
)
except:
pass
bio = self.get("autobio", False)
await utils.answer(
message, self.strings("autobio")["enabled" if bio else "disabled"]
)
@loader.command(ru_doc="👉 Поиск треков в Яндекс.Музыке", alias="yq")
async def ysearchcmd(self, message: telethon.types.Message):
"""👉 Searching tracks in Yandex.Music"""
try:
ym_client = await yandex_music.ClientAsync(self.config["token"]).init()
except yandex_music.exceptions.UnauthorizedError:
return await utils.answer(
message, self.strings("errors")["no_token_or_invalid"]
)
query = utils.get_args_raw(message)
if not query:
return await utils.answer(message, self.strings("errors")["no_query"])
search = await ym_client.search(query, type_="track")
if (not search.tracks) or (len(search.tracks.results) == 0):
return await utils.answer(message, self.strings("errors")["not_found"])
track = search.tracks.results[0]
out = self.strings("search").format(
title=track.title,
performer=", ".join(track.artists_name()),
track_id=track.track_id,
)
await utils.answer(message, out + self.strings("downloading_track"))
audio = await self.__download_track(ym_client, search.tracks.results[0].id)
await utils.answer(
message=message,
response=out,
file=audio,
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]
),
)
]
),
)
@loader.command(
ru_doc="👉 Получить баннер трека, который играет сейчас", alias="yn"
)
async def ynowcmd(self, message: telethon.types.Message):
"""👉 Get the banner of the track playing right now"""
try:
ym_client = await yandex_music.ClientAsync(self.config["token"]).init()
except yandex_music.exceptions.UnauthorizedError:
return await utils.answer(
message, self.strings("errors")["no_token_or_invalid"]
)
await utils.answer(message, self.strings("uploading_banner"))
now = await self.__get_now_playing()
if not now:
return await utils.answer(message, self.strings("errors")["no_playing"])
track_object = (await ym_client.tracks(now["playable_id"]))[0]
playlist_name = ""
if now["entity_type"] == "PLAYLIST":
playlist = (await ym_client.playlists_list(now["entity_id"]))[0]
playlist_name = (
f'<b><a href ="https://music.yandex.ru/users/'
f"{playlist.owner.login}/playlists/{playlist.kind}"
f'">{playlist.title}</a></b>'
)
if now["entity_type"] == "ALBUM":
album = (await ym_client.albums(now["entity_id"]))[0]
playlist_name = (
f'<b><a href ="https://music.yandex.ru/album/'
f'{album.id}">{album.title}</a></b>'
)
if now["entity_type"] == "ARTIST":
artist = (await ym_client.artists(now["entity_id"]))[0]
playlist_name = (
f'<b><a href ="https://music.yandex.ru/artist/'
f'{artist.id}">{artist.name}</a></b>'
)
if now["entity_type"] not in self.strings("_entity_types").keys():
now["entity_type"] = "VARIOUS"
device, volume = "Unknown Device", ""
if now["device"]:
device = now["device"][0]["info"]["title"]
volume = round(now["device"][0]["volume"] * 100, 2)
out = self.config["now_playing_text"].format(
performer=", ".join(now["track"]["artist"]),
title=now["track"]["title"],
device=device,
volume=volume,
track_id=now["track"]["track_id"],
album_id=now["track"]["album_id"],
playing_from=self.strings("_entity_types")
.get(now["entity_type"])
.format(playlist_name),
link=f"<a href=\"https://music.yandex.ru/track/{now['playable_id']}\">Яндекс.Музыка</a>",
)
try:
await utils.answer(message, out + self.strings("uploading_banner"))
except:
pass
banners = Banners(
title=now["track"]["title"],
artists=now["track"]["artist"],
duration=now["duration_ms"],
progress=now["progress_ms"],
track_cover=requests.get(now["track"]["img"]).content,
)
file = getattr(banners, self.config["banner_version"], banners.new)()
await utils.answer(message=message, response=out, file=file)
@loader.command(ru_doc="👉 Получить трек, который играет сейчас", alias="ynt")
async def ynowtcmd(self, message: telethon.types.Message):
"""👉 Get the track playing right now"""
try:
ym_client = await yandex_music.ClientAsync(self.config["token"]).init()
except yandex_music.exceptions.UnauthorizedError:
return await utils.answer(
message, self.strings("errors")["no_token_or_invalid"]
)
await utils.answer(message, self.strings("downloading_track"))
now = await self.__get_now_playing()
if not now:
return await utils.answer(message, self.strings("errors")["no_playing"])
playlist_name = ""
if now["entity_type"] == "PLAYLIST":
playlist = (await ym_client.playlists_list(now["entity_id"]))[0]
playlist_name = (
f'<b><a href ="https://music.yandex.ru/users/'
f"{playlist.owner.login}/playlists/{playlist.kind}"
f'">{playlist.title}</a></b>'
)
if now["entity_type"] == "ALBUM":
album = (await ym_client.albums(now["entity_id"]))[0]
playlist_name = (
f'<b><a href ="https://music.yandex.ru/album/'
f'{album.id}">{album.title}</a></b>'
)
if now["entity_type"] == "ARTIST":
artist = (await ym_client.artists(now["entity_id"]))[0]
playlist_name = (
f'<b><a href ="https://music.yandex.ru/artist/'
f'{artist.id}">{artist.name}</a></b>'
)
if now["entity_type"] not in self.strings("_entity_types").keys():
now["entity_type"] = "VARIOUS"
device, volume = "Unknown Device", ""
if now["device"]:
device = now["device"][0]["info"]["title"]
volume = round(now["device"][0]["volume"] * 100, 2)
out = self.config["now_playing_text"].format(
performer=", ".join(now["track"]["artist"]),
title=now["track"]["title"],
device=device,
volume=volume,
track_id=now["track"]["track_id"],
album_id=now["track"]["album_id"],
playing_from=self.strings("_entity_types")
.get(now["entity_type"])
.format(playlist_name),
link=f"<a href=\"https://music.yandex.ru/track/{now['playable_id']}\">Яндекс.Музыка</a>",
)
try:
await utils.answer(message, out + self.strings("downloading_track"))
except:
pass
await utils.answer(
message=message,
response=out,
file=now["track"]["bytes_io"],
attributes=(
[
telethon.types.DocumentAttributeAudio(
duration=int(now["duration_ms"] / 1000),
title=now["track"]["title"],
performer=", ".join(now["track"]["artist"]),
)
]
),
)
@loader.command(ru_doc="👉 Лайкнуть играющий сейчас трек")
async def ylikecmd(self, message: telethon.types.Message):
"""👉 Like the track playing right now"""
try:
ym_client = await yandex_music.ClientAsync(self.config["token"]).init()
except yandex_music.exceptions.UnauthorizedError:
return await utils.answer(
message, self.strings("errors")["no_token_or_invalid"]
)
now = await self.__get_now_playing()
if not now:
return await utils.answer(message, self.strings("errors")["no_playing"])
await ym_client.users_likes_tracks_add(now["track"]["track_id"])
await utils.answer(
message,
self.strings("likes")["liked"].format(
track_id=now["track"]["track_id"],
track=f"{', '.join(now['track']['artist'])}{now['track']['title']}",
),
)
@loader.command(ru_doc="👉 Снять лайк с играющего сейчас трека")
async def yunlikecmd(self, message: telethon.types.Message):
"""👉 Unlike the track playing right now"""
try:
ym_client = await yandex_music.ClientAsync(self.config["token"]).init()
except yandex_music.exceptions.UnauthorizedError:
return await utils.answer(
message, self.strings("errors")["no_token_or_invalid"]
)
now = await self.__get_now_playing()
if not now:
return await utils.answer(message, self.strings("errors")["no_playing"])
await ym_client.users_likes_tracks_remove(now["track"]["track_id"])
await utils.answer(
message,
self.strings("likes")["unliked"].format(
track_id=now["track"]["track_id"],
track=f"{', '.join(now['track']['artist'])}{now['track']['title']}",
),
)
@loader.command(ru_doc="👉 Дизлайкнуть играющий сейчас трек")
async def ydislikecmd(self, message: telethon.types.Message):
"""👉 Dislike the track playing right now"""
try:
ym_client = await yandex_music.ClientAsync(self.config["token"]).init()
except yandex_music.exceptions.UnauthorizedError:
return await utils.answer(
message, self.strings("errors")["no_token_or_invalid"]
)
now = await self.__get_now_playing()
if not now:
return await utils.answer(message, self.strings("errors")["no_playing"])
await ym_client.users_dislikes_tracks_add(now["track"]["track_id"])
await utils.answer(
message,
self.strings("likes")["disliked"].format(
track_id=now["track"]["track_id"],
track=f"{', '.join(now['track']['artist'])}{now['track']['title']}",
),
)
@loader.command(ru_doc="👉 Получить текст играющего сейчас трека")
async def ylyricscmd(self, message: telethon.types.Message):
"""👉 Get the lyrics of the track playing right now"""
try:
ym_client = await yandex_music.ClientAsync(self.config["token"]).init()
except yandex_music.exceptions.UnauthorizedError:
return await utils.answer(
message, self.strings("errors")["no_token_or_invalid"]
)
now = await self.__get_now_playing()
if not now:
return await utils.answer(message, self.strings("errors")["no_playing"])
try:
lyrics = await ym_client.tracks_lyrics(now["track"]["track_id"])
await utils.answer(
message,
self.strings("lyrics").format(
track_id=now["track"]["track_id"],
track=f"{', '.join(now['track']['artist'])}{now['track']['title']}",
text=requests.get(lyrics.download_url).text,
writers=", ".join(lyrics.writers) if lyrics.writers else "Unknown",
),
)
except yandex_music.exceptions.NotFoundError:
await utils.answer(
message,
self.strings("no_lyrics").format(
track_id=now["track"]["track_id"],
track=f"{', '.join(now['track']['artist'])}{now['track']['title']}",
),
)
async def __download_track(
self,
client: yandex_music.ClientAsync,
track_id: typing.Union[int, str],
link_only: bool = False,
):
last_exception = None
for attempt in range(5):
try:
info = await client.tracks_download_info(
track_id, get_direct_links=True
)
if link_only:
return info[0].direct_link
by = io.BytesIO(await info[0].download_bytes_async())
by.name = "audio.mp3"
return by
except Exception as e:
if attempt != 4:
await asyncio.sleep(1)
continue
raise e
# Original code: https://raw.githubusercontent.com/MIPOHBOPOHIH/YMMBFA/main/main.py
async def __get_ynison(self):
async def create_ws(token, ws_proto):
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 {token}",
},
) as ws:
response = await ws.receive()
return json.loads(response.data)
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 create_ws(self.config["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 {self.config['token']}",
},
) as ws:
await ws.send_str(json.dumps(payload))
response = await ws.receive()
ynison: dict = json.loads(response.data)
return ynison
async def __get_now_playing(self):
if not self.config["token"]:
return {}
try:
ym_client = await yandex_music.ClientAsync(self.config["token"]).init()
except yandex_music.exceptions.UnauthorizedError:
return {}
ynison = await self.__get_ynison()
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"]
]
ym_client = await yandex_music.ClientAsync(self.config["token"]).init()
track_object = (await ym_client.tracks(raw_track["playable_id"]))[0]
return (
{
"paused": ynison["player_state"]["status"]["paused"],
"playable_id": raw_track["playable_id"],
"duration_ms": int(ynison["player_state"]["status"]["duration_ms"]),
"progress_ms": int(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": [
x
for x in ynison["devices"]
if x["info"]["device_id"]
== ynison.get("active_device_id_optional", "")
],
"track": {
"track_id": track_object.track_id,
"album_id": track_object.albums[0].id,
"title": track_object.title,
"artist": track_object.artists_name(),
"img": f"https://{track_object.cover_uri[:-2]}1000x1000",
"duration": track_object.duration_ms // 1000,
"minutes": round(track_object.duration_ms / 1000) // 60,
"seconds": round(track_object.duration_ms / 1000) % 60,
"bytes_io": (
await self.__download_track(ym_client, track_object.track_id)
),
},
}
if raw_track["playable_type"] != "LOCAL_TRACK"
else {}
)

195
update_diffs.py Normal file
View File

@@ -0,0 +1,195 @@
import asyncio
import aiohttp
import argparse
import subprocess
import os
import tempfile
from pathlib import Path
parser = argparse.ArgumentParser(description="Update Diffs Script")
parser.add_argument(
"--token",
type=str,
required=True,
help="Token of Telegram bot",
)
parser.add_argument(
"--api_url",
type=str,
default="https://api.telegram.org",
help="API URL of Telegram API",
)
parser.add_argument(
"--chat_id",
type=str,
required=True,
help="Chat ID to send updates to",
)
parser.add_argument(
"--base_commit",
type=str,
default="HEAD~1",
help="Base commit to compare against",
)
arguments = parser.parse_args()
async def send_message(session, text):
"""Send a text message to the channel"""
url = f"{arguments.api_url}/bot{arguments.token}/sendMessage"
data = {
'chat_id': arguments.chat_id,
'text': text,
'parse_mode': 'Markdown',
}
async with session.post(url, data=data) as response:
return await response.json()
async def send_document(session, file_path, caption=None):
"""Send a document to the channel"""
url = f"{arguments.api_url}/bot{arguments.token}/sendDocument"
with open(file_path, 'rb') as f:
data = aiohttp.FormData()
data.add_field('chat_id', arguments.chat_id)
data.add_field('document', f, filename=os.path.basename(file_path))
data.add_field('parse_mode', 'HTML')
if caption:
data.add_field('caption', caption)
data.add_field('parse_mode', 'Markdown')
async with session.post(url, data=data) as response:
return await response.json()
def get_changed_files(base_commit):
"""Get list of changed files between commits"""
try:
result = subprocess.check_output(
['git', 'diff', '--name-only', base_commit, 'HEAD'],
cwd=os.getcwd()
).decode().strip().split('\n')
return [f for f in result if f]
except subprocess.CalledProcessError:
return []
def get_file_diff(file_path, base_commit):
"""Get diff for a specific file"""
try:
diff = subprocess.check_output(
['git', 'diff', base_commit, 'HEAD', '--', file_path],
cwd=os.getcwd()
).decode()
return diff
except subprocess.CalledProcessError:
return ""
def is_module_file(file_path):
"""Check if file is a Python module in a modules directory"""
# Check if it's a .py file and in a modules-like directory
return file_path.endswith('.py') and any(
part in file_path.lower() for part in [
'modules', 'mods', 'ftg', 'hikka'
]
)
def extract_module_name(file_path):
"""Extract module name from file path"""
return Path(file_path).stem
async def main():
changed_files = get_changed_files(arguments.base_commit)
if not changed_files:
print("No changes detected")
return
# Filter for module files only
module_files = [f for f in changed_files if is_module_file(f)]
if not module_files:
print("No module changes detected")
return
async with aiohttp.ClientSession() as session:
for file_path in module_files:
try:
module_name = extract_module_name(file_path)
# Create message with raw GitHub URL
github_url = f"https://raw.githubusercontent.com/MuRuLOSE/limoka/refs/heads/main/{file_path}"
try:
new_hash = subprocess.check_output(
['git', 'rev-list', '-n', '1', 'HEAD', '--', file_path],
cwd=os.getcwd()
).decode().strip()
except Exception:
new_hash = 'HEAD'
try:
old_hash = subprocess.check_output(
['git', 'rev-list', '-n', '1', arguments.base_commit, '--', file_path],
cwd=os.getcwd()
).decode().strip()
except Exception:
old_hash = arguments.base_commit
diff_url = f"https://github.com/MuRuLOSE/limoka/compare/{old_hash}...{new_hash}.diff"
message = (
f"🪼 <b>Module <code>{module_name}</code> changes approved</b>\n\n"
f"<b><a href=\"{github_url}\">File URL</a></b> | "
f"<b><a href=\"{diff_url}\">Diff URL</a></b>"
)
# Get diff
diff = get_file_diff(file_path, arguments.base_commit)
if not diff:
print(f"Skipping {file_path} - no diff content")
continue
# Create temporary file with diff using only module name
diff_filename = f"{module_name}.diff"
with tempfile.NamedTemporaryFile(
mode='w',
suffix='',
prefix='',
delete=False,
encoding='utf-8',
dir=tempfile.gettempdir()
) as tmp_file:
tmp_file.write(diff)
tmp_file_path = tmp_file.name
try:
# Rename temp file to have proper name
final_path = os.path.join(tempfile.gettempdir(), diff_filename)
os.rename(tmp_file_path, final_path)
# Send diff as document with full message as caption
doc_result = await send_document(
session,
final_path,
caption=message
)
print(f"Sent diff for {module_name}: {doc_result}")
except Exception as e:
print(f"Error sending {module_name}: {e}")
finally:
# Cleanup temp files
if os.path.exists(tmp_file_path):
try:
os.remove(tmp_file_path)
except:
pass
final_path = os.path.join(tempfile.gettempdir(), diff_filename)
if os.path.exists(final_path):
try:
os.remove(final_path)
except:
pass
except Exception as e:
print(f"Error processing {file_path}: {e}")
if __name__ == "__main__":
asyncio.run(main())

View File

@@ -1,396 +1,409 @@
__version__ = (1, 1, 1, 1)
# This file is a part of Hikka Userbot!
# This product includes software developed by t.me/Fl1yd and t.me/spypm.
# Based on the "SQuotes" module.
# 🌐 https://github.com/hikariatama/Hikka
# You CAN edit this file without direct permission from the author.
# You can redistribute this file with any modifications.
# thx to t.me/LyoSU for github.com/LyoSU/quote-api
# meta developer: @yg_modules
# scope: hikka_only
# scope: hikka_min 1.6.3
# █▄█ █░█ █▀▄▀█ █▀▄▀█ █▄█   █▀▄▀█ █▀█ █▀▄ █▀
# ░█░ █▄█ █░▀░█ █░▀░█ ░█░   █░▀░█ █▄█ █▄▀ ▄█
import base64, io, requests, telethon
from time import gmtime
from typing import List, Optional, Tuple, Union
from PIL import Image, ImageDraw
from telethon.tl import types
from telethon.extensions import html
from telethon.tl.patched import Message
from .. import loader, utils
class Dick:
@staticmethod
def ents(es: types.TypeMessageEntity) -> List[dict]:
out: List[dict] = []
if not es: return out
for e in es:
try:
d = e.to_dict(); t = d.pop("_","").replace("MessageEntity","").lower()
if not t: continue
mt = {"bold": "bold","italic": "italic","underline": "underline","strikethrough": "strikethrough",
"code": "code","pre": "pre","texturl": "text_link","url": "url","email": "email",
"phone": "phone_number","mention": "mention",
"mentionname": "text_mention","hashtag": "hashtag","cashtag": "cashtag",
"botcommand": "bot_command","spoiler": "spoiler","customemoji": "custom_emoji"}.get(t,t)
it = {"type": mt,"offset": d.get("offset",0),"length": d.get("length",0)}
if t=="texturl": it["url"]=d.get("url","")
elif t=="mentionname": it["user"]={"id": d.get("user_id",0)}
elif t=="customemoji": it["custom_emoji_id"]=str(d.get("document_id",""))
elif t=="pre": it["language"]=d.get("language","")
out.append(it)
except Exception: continue
return out
@staticmethod
def dur(s: Union[int,float]) -> str:
t=gmtime(s); return (f"{t.tm_hour:02d}:" if t.tm_hour>0 else "")+f"{t.tm_min:02d}:{t.tm_sec:02d}"
@staticmethod
def desc(m: Message, rep: bool=False) -> str:
return (
"📷 Фото" if m.photo and rep else
(m.file.emoji+" Стикер") if m.sticker and rep else
"📹 Видеосообщение" if m.video_note and rep else
"📹 Видео" if m.video and rep else
"🖼 GIF" if m.gif else
"📊 Опрос" if m.poll else
"📍 Местоположение" if m.geo else
"👤 Контакт" if m.contact else
(f"🎵 Голосовое сообщение: {Dick.dur(m.voice.attributes[0].duration)}" if m.voice else
(f"🎧 Музыка: {Dick.dur(m.audio.attributes[0].duration)} | {m.audio.attributes[0].performer} - {m.audio.attributes[0].title}" if m.audio else
(f"💾 Файл: {m.file.name}" if isinstance(m.media, types.MessageMediaDocument) and not Dick.pick(m) else
(f"{m.media.emoticon} Кость: {m.media.value}" if isinstance(m.media, types.MessageMediaDice) else
(f"Сервисное сообщение: {m.action.to_dict().get('_')}" if isinstance(m, types.MessageService) else "")))))) #)))
@staticmethod
def split(name: Optional[str]) -> Tuple[str,str]:
if not name: return "",""
p=name.split(); return (p[0], " ".join(p[1:]) if len(p)>1 else "")
@staticmethod
def pick(m: Message):
if m and m.media:
return m.photo or m.sticker or m.video or m.video_note or m.gif or m.web_preview
return None
@staticmethod
def wf(b: Optional[bytes]) -> List[int]:
if not b: return []
n=(len(b)*8)//5
if not n: return []
out: List[int]=[]
last=n-1
for i in range(last):
j=i*5; bi,sh=j//8,j%8
v=int.from_bytes(b[bi:bi+2],"little") if bi+1<len(b) else b[bi]
out.append((v>>sh)&0b11111)
j=last*5; bi,sh=j//8,j%8
v=int.from_bytes(b[bi:bi+2],"little") if bi+1<len(b) else b[bi]
out.append((v>>sh)&0b11111)
return out
@staticmethod
async def img(b: bytes, circle: bool=False) -> Optional[str]:
try:
im=Image.open(io.BytesIO(b))
if im.mode!="RGBA": im=im.convert("RGBA")
if circle:
size=min(im.size)
mask=Image.new("L",(size,size),0); ImageDraw.Draw(mask).ellipse((0,0,size,size),fill=255)
sq=Image.new("RGBA",(size,size),(0,0,0,0))
off=((size-im.width)//2,(size-im.height)//2); sq.paste(im,off)
im=Image.composite(sq,Image.new("RGBA",(size,size),(0,0,0,0)),mask)
o=io.BytesIO(); im.save(o,format="PNG")
return f"data:image/png;base64,{base64.b64encode(o.getvalue()).decode()}"
except Exception:
return None
@staticmethod
async def stc(b: bytes) -> Optional[str]:
try:
im=Image.open(io.BytesIO(b))
if im.mode not in ("RGBA","LA"): im=im.convert("RGBA")
elif im.mode=="LA": im=im.convert("RGBA")
o=io.BytesIO(); im.save(o,format="PNG")
return f"data:image/png;base64,{base64.b64encode(o.getvalue()).decode()}"
except Exception:
return None
@staticmethod
async def proc(cli, obj, m: Message) -> Optional[dict]:
try:
if m.voice:
for a in m.voice.attributes or []:
if getattr(a,"voice",False) and hasattr(a,"waveform"):
return {"voice":{"waveform":Dick.wf(a.waveform)}}
b: bytes = await cli.download_media(obj, bytes, thumb=-1)
if not b: return None
if m.sticker:
u=await Dick.stc(b); return {"url": u} if u else None
u=await Dick.img(b, circle=bool(m.video_note))
return {"url": u} if u else None
except Exception:
return None
@staticmethod
async def ava(cli, uid: int) -> Optional[str]:
try:
b=await cli.download_profile_photo(uid, bytes)
if b: return f"data:image/jpeg;base64,{base64.b64encode(b).decode()}"
except Exception: pass
return None
@staticmethod
async def post(url: str, data: dict):
try:
return await utils.run_sync(requests.post, url, json=data, timeout=30)
except Exception:
return None
@loader.tds
class Quotes(loader.Module):
"""Модуль для создания цитат из сообщений"""
strings = {"name": "yg_quotes",
"no_reply": "<emoji document_id=6321272741005624970>🏳️‍🌈</emoji> Нет реплая на сообщение",
"processing": "<emoji document_id=6321272741005624970>🏳️‍🌈</emoji> Обработка…",
"api_processing": "<emoji document_id=6321272741005624970>🏳️‍🌈</emoji> Ожидание ответа API…",
"api_error": "<emoji document_id=6321272741005624970>🏳️‍🌈</emoji> Ошибка API: {}",
"loading_media": "<emoji document_id=6321272741005624970>🏳️‍🌈</emoji> Отправка…",
"no_args_or_reply": "<emoji document_id=6321272741005624970>🏳️‍🌈</emoji> Нет аргументов или реплая",
"args_error": "<emoji document_id=6321272741005624970>🏳️‍🌈</emoji> Ошибка разбора аргументов. Запрос: <code>{}</code>",
"too_many_messages": "<emoji document_id=6321272741005624970>🏳️‍🌈</emoji> Слишком много сообщений. Максимум: <code>{}</code>"}
def __init__(self):
self.config=loader.ModuleConfig(
loader.ConfigValue("type","quote",
lambda:"Тип цитаты",
validator=loader.validators.Choice(["quote", "stories"])),
loader.ConfigValue("bg_color","#162330",
lambda:"Цвет фона цитаты (например, #1a1a1a или red)"),
loader.ConfigValue("width",512,
lambda:"Ширина цитаты (px)",
validator=loader.validators.Integer(minimum=200,maximum=2000)),
loader.ConfigValue("height",768,
lambda:"Высота цитаты (px)",
validator=loader.validators.Integer(minimum=200,maximum=2000)),
loader.ConfigValue("scale",2,
lambda:"Масштаб рендера",
validator=loader.validators.Choice([1, 2, 3])),
loader.ConfigValue("emoji_brand","apple",
lambda:"Стиль эмодзи (apple, google, twitter и т.д.)"),
loader.ConfigValue("max_messages",15,
lambda:"Максимальное число сообщений в цитате",
validator=loader.validators.Integer(minimum=1,maximum=50)),
loader.ConfigValue("endpoint","https://kok.gay/gayotes/generate",
lambda:"URL API-эндпоинта (можешь поднять локально - github.com/yummy1gay/quote-api)",
validator=loader.validators.Link()))
async def client_ready(self, client, db):
self.client=client; self.db=db
async def qcmd(self, m: Message):
"""
Обычные цитаты:
• .q — процитировать одно сообщение из реплая
• .q 2 — процитировать 2 сообщения
• .q 3 #2d2d2d — 3 сообщения на тёмном фоне
• .q pink — фон по имени цвета
• .q !file — отправить как файл (PNG)
"""
try:
args=utils.get_args(m); rep=await m.get_reply_message()
if not rep: return await utils.answer(m,self.strings["no_reply"])
st=await utils.answer(m,self.strings["processing"])
doc="!file" in args
n=next((int(a) for a in args if a.isdigit() and int(a)>0),1)
bg=next((a for a in args if a!="!file" and not a.isdigit()), self.config["bg_color"])
if n>self.config["max_messages"]:
return await utils.answer(st,self.strings["too_many_messages"].format(self.config["max_messages"]))
js=await self.parse(m,n)
if not js: return await utils.answer(st,self.strings["api_error"].format("Не удалось собрать сообщения"))
pay={"backgroundColor":bg,"width":self.config["width"],"height":self.config["height"],
"scale":self.config["scale"],"emojiBrand":self.config["emoji_brand"],"messages":js,
"format": "webp" if not doc else "png", "type": self.config["type"]}
await utils.answer(st,self.strings["api_processing"])
r=await Dick.post(f"{self.config['endpoint']}.webp",pay)
if not r or r.status_code!=200:
try: err=r.json().get("error",f"HTTP {r.status_code}") if r else "Нетворк еррорь"
except Exception: err=f"HTTP {r.status_code}" if r else "Нетворк еррорь"
return await utils.answer(st,self.strings["api_error"].format(err))
buf=io.BytesIO(r.content); buf.name="YgQuote"+(".png" if doc else ".webp")
await utils.answer(st,buf,force_document=doc)
except Exception as e:
return await utils.answer(m,f"<emoji document_id=6321272741005624970>🏳️‍🌈</emoji> Ошибка: {e}")
async def fqcmd(self, m: Message):
"""
Фейковые цитаты:
• .fq <@ или ID> <текст> — цитата от пользователя
• .fq <reply> <текст> — цитата от автора реплая
• .fq <@/ID> <текст> -r <@/ID> <текст> — с ответом
• .fq user1 текст; user2 текст — несколько сообщений
"""
try:
raw=utils.get_args_html(m); rep=await m.get_reply_message()
if not (raw or rep): return await utils.answer(m,self.strings["no_args_or_reply"])
st= await utils.answer(m,self.strings["processing"])
try: js=await self.fake(raw,rep)
except (IndexError,ValueError): return await utils.answer(st,self.strings["args_error"].format(m.text))
if len(js)>self.config["max_messages"]:
return await utils.answer(st,self.strings["too_many_messages"].format(self.config["max_messages"]))
dickk={"backgroundColor":self.config["bg_color"],"width":self.config["width"],"height":self.config["height"],
"scale":self.config["scale"],"emojiBrand":self.config["emoji_brand"],"messages":js,
"format": "webp","type":self.config["type"]}
await utils.answer(st,self.strings["api_processing"])
r=await Dick.post(f"{self.config['endpoint']}.webp",dickk)
if not r or r.status_code!=200:
try: err=r.json().get("error",f"HTTP {r.status_code}") if r else "Нетворк еррорь"
except Exception: err=f"HTTP {r.status_code}" if r else "Нетворк еррорь"
return await utils.answer(st,self.strings["api_error"].format(err))
buf=io.BytesIO(r.content); buf.name="YgQuote.webp"
await utils.answer(st,buf)
except Exception as e:
return await utils.answer(m,f"<emoji document_id=6321272741005624970>🏳️‍🌈</emoji> Ошибка: {e}")
async def parse(self, trg: Message, n: int) -> Optional[List[dict]]:
try:
rep= await trg.get_reply_message()
lst: List[Message]=[mm async for mm in self.client.iter_messages(trg.chat_id,limit=n,reverse=True,add_offset=1,offset_id=rep.id if rep else None)]
except Exception:
return None
out: List[dict]=[]
for mm in lst:
try:
u=await self.who(mm)
if not u: continue
name=telethon.utils.get_display_name(u); f,l=Dick.split(name)
ava=await Dick.ava(self.client,getattr(u,"id",0)) if getattr(u,"id",None) else None
rb=None
try:
r=await mm.get_reply_message()
if r:
rname=telethon.utils.get_display_name(r.sender)
rtxt=Dick.desc(r,True)
if r.raw_text: rtxt=(rtxt+". "+r.raw_text) if rtxt else r.raw_text
rb={"name":rname,"text":rtxt or "","entities":Dick.ents(r.entities),
"chatId": r.sender.id if r.sender else mm.chat_id,"from":{"name":rname}}
except Exception: rb=None
med=None; obj=Dick.pick(mm)
if obj: med=await Dick.proc(self.client,obj,mm)
txt=mm.raw_text or ""; ad=Dick.desc(mm)
if ad: txt=f"{txt}\n\n{ad}" if txt else ad
item={"from":{"id":getattr(u,"id", 0),"first_name":getattr(u,"first_name","") or f,"last_name":getattr(u,"last_name","") or l,
"username":getattr(u,"username",None),"name":name,"photo":{"url":ava} if ava else {}},
"text":txt,"entities":Dick.ents(mm.entities),"avatar":True}
try:
if mm.voice:
a = next((a for a in mm.voice.attributes or []
if getattr(a, "voice", False) and hasattr(a, "waveform")), None)
if a: item["voice"] = {"waveform": Dick.wf(a.waveform)}
except Exception: pass
if med: item["voice" if "voice" in med else "media"] = med.get("voice", med)
es=getattr(u,"emoji_status",None)
if getattr(es,"document_id",None): item["from"]["emoji_status"]=str(es.document_id)
if rb: item["replyMessage"]=rb
out.append(item)
except Exception: continue
return out
async def who(self, m: Message):
try:
if m.fwd_from:
if m.fwd_from.from_id:
pid=m.fwd_from.from_id
uid=pid.channel_id if isinstance(pid, types.PeerChannel) else pid.user_id
try: return await self.client.get_entity(uid)
except Exception: return m.sender
if m.fwd_from.from_name:
return types.User(
id=hash(m.fwd_from.from_name)%2147483647, first_name=m.fwd_from.from_name,
username=None, phone=None, bot=False, verified=False, restricted=False,
scam=False, fake=False, premium=False)
return m.sender
except Exception:
return m.sender
async def fake(self, args: str, rep: Optional[Message]) -> List[dict]:
async def tok(ch: str):
p=ch.split()
if not p: return None,""
who=p[0]; tx=ch.split(maxsplit=1)[1] if len(p)>1 else ""
try:
u=await self.client.get_entity(int(who) if who.isdigit() else who)
return u,tx
except Exception:
return None,tx
if rep and not args:
u=rep.sender; name=telethon.utils.get_display_name(u); f,l=Dick.split(name)
ava=await Dick.ava(self.client,u.id) if getattr(u,"id",None) else None
msg={"from":{"id":u.id,"first_name":getattr(u,"first_name","") or f,"last_name":getattr(u,"last_name","") or l,
"username":getattr(u,"username",None),"name":name,"photo":{"url":ava} if ava else {}},
"text":"","entities":[], "avatar":True}
es=getattr(u,"emoji_status",None)
if getattr(es,"document_id", None): msg["from"]["emoji_status"]=str(es.document_id)
return [msg]
if rep and args:
u=rep.sender
return await self.fake(f"{getattr(u,'id','')} {args}", None)
out: List[dict]=[]
for part in args.split("; "):
try:
rb=None
if " -r " in part:
a,b=part.split(" -r ",1); u1,t1=await tok(a); u2,t2=await tok(b)
else:
u1,t1=await tok(part); u2,t2=None,None
if not u1: continue
txt1, ents1 = html.parse(t1) if t1 else ("", [])
name=telethon.utils.get_display_name(u1); f,l=Dick.split(name)
ava=await Dick.ava(self.client,u1.id)
if u2:
txt2, ents2 = html.parse(t2) if t2 else ("", [])
name2=telethon.utils.get_display_name(u2); ava2=await Dick.ava(self.client,u2.id)
rb={"name":name2,"text":txt2,"entities":Dick.ents(ents2),"chatId":u2.id,"from":{"name":name2,"photo":{"url":ava2} if ava2 else {}}}
msg={"from":{"id":u1.id,"first_name":getattr(u1,"first_name","") or f,"last_name":getattr(u1,"last_name","") or l,
"username":getattr(u1,"username",None),"name":name,"photo":{"url":ava} if ava else {}},
"text":txt1,"entities":Dick.ents(ents1), "avatar":True}
es=getattr(u1,"emoji_status",None)
if getattr(es,"document_id",None): msg["from"]["emoji_status"]=str(es.document_id)
if rb: msg["replyMessage"]=rb
out.append(msg)
except Exception: continue
__version__ = (1, 2, 0, 0)
# This file is a part of Hikka Userbot!
# This product includes software developed by t.me/Fl1yd and t.me/spypm.
# Based on the "SQuotes" module.
# 🌐 https://github.com/hikariatama/Hikka
# You CAN edit this file without direct permission from the author.
# You can redistribute this file with any modifications.
# thx to t.me/LyoSU for github.com/LyoSU/quote-api
# meta developer: @yg_modules
# scope: hikka_only
# scope: hikka_min 1.6.3
# Changelog v1.2:
# - Added: Proxy for users from RF
# - Fixed: Correct reply author resolving for forwarded messages
# █▄█ █░█ █▀▄▀█ █▀▄▀█ █▄█   █▀▄▀█ █▀█ █▀▄ █▀
# ░█░ █▄█ █░▀░█ █░▀░█ ░█░   █░▀░█ █▄█ █▄▀ ▄█
import base64, io, requests, telethon
from time import gmtime
from typing import List, Optional, Tuple, Union
from PIL import Image, ImageDraw
from telethon.tl import types
from telethon.extensions import html
from telethon.tl.patched import Message
from .. import loader, utils
class Dick:
@staticmethod
def ents(es: types.TypeMessageEntity) -> List[dict]:
out: List[dict] = []
if not es: return out
for e in es:
try:
d = e.to_dict(); t = d.pop("_","").replace("MessageEntity","").lower()
if not t: continue
mt = {"bold": "bold","italic": "italic","underline": "underline","strikethrough": "strikethrough",
"code": "code","pre": "pre","texturl": "text_link","url": "url","email": "email",
"phone": "phone_number","mention": "mention",
"mentionname": "text_mention","hashtag": "hashtag","cashtag": "cashtag",
"botcommand": "bot_command","spoiler": "spoiler","customemoji": "custom_emoji"}.get(t,t)
it = {"type": mt,"offset": d.get("offset",0),"length": d.get("length",0)}
if t=="texturl": it["url"]=d.get("url","")
elif t=="mentionname": it["user"]={"id": d.get("user_id",0)}
elif t=="customemoji": it["custom_emoji_id"]=str(d.get("document_id",""))
elif t=="pre": it["language"]=d.get("language","")
out.append(it)
except Exception: continue
return out
@staticmethod
def dur(s: Union[int,float]) -> str:
t=gmtime(s); return (f"{t.tm_hour:02d}:" if t.tm_hour>0 else "")+f"{t.tm_min:02d}:{t.tm_sec:02d}"
@staticmethod
def desc(m: Message, rep: bool=False) -> str:
return (
"📷 Фото" if m.photo and rep else
(m.file.emoji+" Стикер") if m.sticker and rep else
"📹 Видеосообщение" if m.video_note and rep else
"📹 Видео" if m.video and rep else
"🖼 GIF" if m.gif else
"📊 Опрос" if m.poll else
"📍 Местоположение" if m.geo else
"👤 Контакт" if m.contact else
(f"🎵 Голосовое сообщение: {Dick.dur(m.voice.attributes[0].duration)}" if m.voice else
(f"🎧 Музыка: {Dick.dur(m.audio.attributes[0].duration)} | {m.audio.attributes[0].performer} - {m.audio.attributes[0].title}" if m.audio else
(f"💾 Файл: {m.file.name}" if isinstance(m.media, types.MessageMediaDocument) and not Dick.pick(m) else
(f"{m.media.emoticon} Кость: {m.media.value}" if isinstance(m.media, types.MessageMediaDice) else
(f"Сервисное сообщение: {m.action.to_dict().get('_')}" if isinstance(m, types.MessageService) else "")))))) #)))
@staticmethod
def split(name: Optional[str]) -> Tuple[str,str]:
if not name: return "",""
p=name.split(); return (p[0], " ".join(p[1:]) if len(p)>1 else "")
@staticmethod
def pick(m: Message):
if m and m.media:
return m.photo or m.sticker or m.video or m.video_note or m.gif or m.web_preview
return None
@staticmethod
def wf(b: Optional[bytes]) -> List[int]:
if not b: return []
n=(len(b)*8)//5
if not n: return []
out: List[int]=[]
last=n-1
for i in range(last):
j=i*5; bi,sh=j//8,j%8
v=int.from_bytes(b[bi:bi+2],"little") if bi+1<len(b) else b[bi]
out.append((v>>sh)&0b11111)
j=last*5; bi,sh=j//8,j%8
v=int.from_bytes(b[bi:bi+2],"little") if bi+1<len(b) else b[bi]
out.append((v>>sh)&0b11111)
return out
@staticmethod
async def img(b: bytes, circle: bool=False) -> Optional[str]:
try:
im=Image.open(io.BytesIO(b))
if im.mode!="RGBA": im=im.convert("RGBA")
if circle:
size=min(im.size)
mask=Image.new("L",(size,size),0); ImageDraw.Draw(mask).ellipse((0,0,size,size),fill=255)
sq=Image.new("RGBA",(size,size),(0,0,0,0))
off=((size-im.width)//2,(size-im.height)//2); sq.paste(im,off)
im=Image.composite(sq,Image.new("RGBA",(size,size),(0,0,0,0)),mask)
o=io.BytesIO(); im.save(o,format="PNG")
return f"data:image/png;base64,{base64.b64encode(o.getvalue()).decode()}"
except Exception:
return None
@staticmethod
async def stc(b: bytes) -> Optional[str]:
try:
im=Image.open(io.BytesIO(b))
if im.mode not in ("RGBA","LA"): im=im.convert("RGBA")
elif im.mode=="LA": im=im.convert("RGBA")
o=io.BytesIO(); im.save(o,format="PNG")
return f"data:image/png;base64,{base64.b64encode(o.getvalue()).decode()}"
except Exception:
return None
@staticmethod
async def proc(cli, obj, m: Message) -> Optional[dict]:
try:
if m.voice:
for a in m.voice.attributes or []:
if getattr(a,"voice",False) and hasattr(a,"waveform"):
return {"voice":{"waveform":Dick.wf(a.waveform)}}
b: bytes = await cli.download_media(obj, bytes, thumb=-1)
if not b: return None
if m.sticker:
u=await Dick.stc(b); return {"url": u} if u else None
u=await Dick.img(b, circle=bool(m.video_note))
return {"url": u} if u else None
except Exception:
return None
@staticmethod
async def ava(cli, uid: int) -> Optional[str]:
try:
b=await cli.download_profile_photo(uid, bytes)
if b: return f"data:image/jpeg;base64,{base64.b64encode(b).decode()}"
except Exception: pass
return None
@staticmethod
async def post(url: str, data: dict):
try:
return await utils.run_sync(requests.post, url, json=data, timeout=30)
except Exception:
return None
@loader.tds
class Quotes(loader.Module):
"""Модуль для создания цитат из сообщений"""
strings = {"name": "yg_quotes",
"no_reply": "<emoji document_id=6321272741005624970>🏳️‍🌈</emoji> Нет реплая на сообщение",
"processing": "<emoji document_id=6321272741005624970>🏳️‍🌈</emoji> Обработка…",
"api_processing": "<emoji document_id=6321272741005624970>🏳️‍🌈</emoji> Ожидание ответа API…",
"api_error": "<emoji document_id=6321272741005624970>🏳️‍🌈</emoji> Ошибка API: {}",
"loading_media": "<emoji document_id=6321272741005624970>🏳️‍🌈</emoji> Отправка…",
"no_args_or_reply": "<emoji document_id=6321272741005624970>🏳️‍🌈</emoji> Нет аргументов или реплая",
"args_error": "<emoji document_id=6321272741005624970>🏳️‍🌈</emoji> Ошибка разбора аргументов. Запрос: <code>{}</code>",
"too_many_messages": "<emoji document_id=6321272741005624970>🏳️‍🌈</emoji> Слишком много сообщений. Максимум: <code>{}</code>"}
def __init__(self):
self.config=loader.ModuleConfig(
loader.ConfigValue("type","quote",
lambda:"Тип цитаты",
validator=loader.validators.Choice(["quote", "stories"])),
loader.ConfigValue("bg_color","#162330",
lambda:"Цвет фона цитаты (например, #1a1a1a или red)"),
loader.ConfigValue("width",512,
lambda:"Ширина цитаты (px)",
validator=loader.validators.Integer(minimum=200,maximum=2000)),
loader.ConfigValue("height",768,
lambda:"Высота цитаты (px)",
validator=loader.validators.Integer(minimum=200,maximum=2000)),
loader.ConfigValue("scale",2,
lambda:"Масштаб рендера",
validator=loader.validators.Choice([1, 2, 3])),
loader.ConfigValue("emoji_brand","apple",
lambda:"Стиль эмодзи (apple, google, twitter и т.д.)"),
loader.ConfigValue("max_messages",15,
lambda:"Максимальное число сообщений в цитате",
validator=loader.validators.Integer(minimum=1,maximum=50)),
loader.ConfigValue("endpoint","https://kok.gay/gayotes/generate",
lambda:"URL API-эндпоинта (можешь поднять локально - github.com/yummy1gay/quote-api)",
validator=loader.validators.Link()),
loader.ConfigValue("use_rf_proxy", False,
lambda:'Включает прокси для РФ, если основной эндпоинт возвращает ошибку "Нетворк еррорь", и при этом сервер с юзерботом находится в России или ты сам сидишь в России с ограниченным доступом к зарубежным ресурсам (Termux / UserLAnd)',
validator=loader.validators.Boolean()),
loader.ConfigValue("rf_endpoint", "https://ru.kok.gay/gayotes/generate",
lambda:"URL API-эндпоинта для РФ",
validator=loader.validators.Link()))
async def client_ready(self, client, db):
self.client=client; self.db=db
async def qcmd(self, m: Message):
"""
Обычные цитаты:
• .q — процитировать одно сообщение из реплая
• .q 2 — процитировать 2 сообщения
• .q 3 #2d2d2d — 3 сообщения на тёмном фоне
• .q pink — фон по имени цвета
• .q !file — отправить как файл (PNG)
"""
try:
args=utils.get_args(m); rep=await m.get_reply_message()
if not rep: return await utils.answer(m,self.strings["no_reply"])
st=await utils.answer(m,self.strings["processing"])
doc="!file" in args
n=next((int(a) for a in args if a.isdigit() and int(a)>0),1)
bg=next((a for a in args if a!="!file" and not a.isdigit()), self.config["bg_color"])
if n>self.config["max_messages"]:
return await utils.answer(st,self.strings["too_many_messages"].format(self.config["max_messages"]))
js=await self.parse(m,n)
if not js: return await utils.answer(st,self.strings["api_error"].format("Не удалось собрать сообщения"))
pay={"backgroundColor":bg,"width":self.config["width"],"height":self.config["height"],
"scale":self.config["scale"],"emojiBrand":self.config["emoji_brand"],"messages":js,
"format": "webp" if not doc else "png", "type": self.config["type"]}
await utils.answer(st,self.strings["api_processing"])
endpoint=self.config['rf_endpoint'] if self.config['use_rf_proxy'] else self.config['endpoint']
r=await Dick.post(f"{endpoint}.webp",pay)
if not r or r.status_code!=200:
try: err=r.json().get("error",f"HTTP {r.status_code}") if r else "Нетворк еррорь (попробуй включить <code>use_rf_proxy</code> в конфиге)"
except Exception: err=f"HTTP {r.status_code}" if r else "Нетворк еррорь (попробуй включить <code>use_rf_proxy</code> в конфиге)"
return await utils.answer(st,self.strings["api_error"].format(err))
buf=io.BytesIO(r.content); buf.name="YgQuote"+(".png" if doc else ".webp")
await utils.answer(st,buf,force_document=doc)
except Exception as e:
return await utils.answer(m,f"<emoji document_id=6321272741005624970>🏳️‍🌈</emoji> Ошибка: {e}")
async def fqcmd(self, m: Message):
"""
Фейковые цитаты:
• .fq <@ или ID> <текст> — цитата от пользователя
• .fq <reply> <текст> — цитата от автора реплая
• .fq <@/ID> <текст> -r <@/ID> <текст> — с ответом
• .fq user1 текст; user2 текст — несколько сообщений
"""
try:
raw=utils.get_args_html(m); rep=await m.get_reply_message()
if not (raw or rep): return await utils.answer(m,self.strings["no_args_or_reply"])
st= await utils.answer(m,self.strings["processing"])
try: js=await self.fake(raw,rep)
except (IndexError,ValueError): return await utils.answer(st,self.strings["args_error"].format(m.text))
if len(js)>self.config["max_messages"]:
return await utils.answer(st,self.strings["too_many_messages"].format(self.config["max_messages"]))
dickk={"backgroundColor":self.config["bg_color"],"width":self.config["width"],"height":self.config["height"],
"scale":self.config["scale"],"emojiBrand":self.config["emoji_brand"],"messages":js,
"format": "webp","type":self.config["type"]}
await utils.answer(st,self.strings["api_processing"])
endpoint=self.config['rf_endpoint'] if self.config['use_rf_proxy'] else self.config['endpoint']
r=await Dick.post(f"{endpoint}.webp",dickk)
if not r or r.status_code!=200:
try: err=r.json().get("error",f"HTTP {r.status_code}") if r else "Нетворк еррорь (попробуй включить <code>use_rf_proxy</code> в конфиге)"
except Exception: err=f"HTTP {r.status_code}" if r else "Нетворк еррорь (попробуй включить <code>use_rf_proxy</code> в конфиге)"
return await utils.answer(st,self.strings["api_error"].format(err))
buf=io.BytesIO(r.content); buf.name="YgQuote.webp"
await utils.answer(st,buf)
except Exception as e:
return await utils.answer(m,f"<emoji document_id=6321272741005624970>🏳️‍🌈</emoji> Ошибка: {e}")
async def parse(self, trg: Message, n: int) -> Optional[List[dict]]:
try:
rep= await trg.get_reply_message()
lst: List[Message]=[mm async for mm in self.client.iter_messages(trg.chat_id,limit=n,reverse=True,add_offset=1,offset_id=rep.id if rep else None)]
except Exception:
return None
out: List[dict]=[]
for mm in lst:
try:
u=await self.who(mm)
if not u: continue
name=telethon.utils.get_display_name(u); f,l=Dick.split(name)
ava=await Dick.ava(self.client,getattr(u,"id",0)) if getattr(u,"id",None) else None
rb=None
try:
r=await mm.get_reply_message()
if r:
ruser = await self.who(r)
rname=telethon.utils.get_display_name(ruser)
rtxt=Dick.desc(r,True)
if r.raw_text: rtxt=(rtxt+". "+r.raw_text) if rtxt else r.raw_text
rb={"name":rname,"text":rtxt or "","entities":Dick.ents(r.entities),
"chatId": r.sender.id if r.sender else mm.chat_id,"from":{"name":rname}}
except Exception: rb=None
med=None; obj=Dick.pick(mm)
if obj: med=await Dick.proc(self.client,obj,mm)
txt=mm.raw_text or ""; ad=Dick.desc(mm)
if ad: txt=f"{txt}\n\n{ad}" if txt else ad
item={"from":{"id":getattr(u,"id", 0),"first_name":getattr(u,"first_name","") or f,"last_name":getattr(u,"last_name","") or l,
"username":getattr(u,"username",None),"name":name,"photo":{"url":ava} if ava else {}},
"text":txt,"entities":Dick.ents(mm.entities),"avatar":True}
try:
if mm.voice:
a = next((a for a in mm.voice.attributes or []
if getattr(a, "voice", False) and hasattr(a, "waveform")), None)
if a: item["voice"] = {"waveform": Dick.wf(a.waveform)}
except Exception: pass
if med: item["voice" if "voice" in med else "media"] = med.get("voice", med)
es=getattr(u,"emoji_status",None)
if getattr(es,"document_id",None): item["from"]["emoji_status"]=str(es.document_id)
if rb: item["replyMessage"]=rb
out.append(item)
except Exception: continue
return out
async def who(self, m: Message):
try:
if m.fwd_from:
if m.fwd_from.from_id:
pid=m.fwd_from.from_id
uid=pid.channel_id if isinstance(pid, types.PeerChannel) else pid.user_id
try: return await self.client.get_entity(uid)
except Exception: return m.sender
if m.fwd_from.from_name:
return types.User(
id=hash(m.fwd_from.from_name)%2147483647, first_name=m.fwd_from.from_name,
username=None, phone=None, bot=False, verified=False, restricted=False,
scam=False, fake=False, premium=False)
return m.sender
except Exception:
return m.sender
async def fake(self, args: str, rep: Optional[Message]) -> List[dict]:
async def tok(ch: str):
p=ch.split()
if not p: return None,""
who=p[0]; tx=ch.split(maxsplit=1)[1] if len(p)>1 else ""
try:
u=await self.client.get_entity(int(who) if who.isdigit() else who)
return u,tx
except Exception:
return None,tx
if rep and not args:
u=rep.sender; name=telethon.utils.get_display_name(u); f,l=Dick.split(name)
ava=await Dick.ava(self.client,u.id) if getattr(u,"id",None) else None
msg={"from":{"id":u.id,"first_name":getattr(u,"first_name","") or f,"last_name":getattr(u,"last_name","") or l,
"username":getattr(u,"username",None),"name":name,"photo":{"url":ava} if ava else {}},
"text":"","entities":[], "avatar":True}
es=getattr(u,"emoji_status",None)
if getattr(es,"document_id", None): msg["from"]["emoji_status"]=str(es.document_id)
return [msg]
if rep and args:
u=rep.sender
return await self.fake(f"{getattr(u,'id','')} {args}", None)
out: List[dict]=[]
for part in args.split("; "):
try:
rb=None
if " -r " in part:
a,b=part.split(" -r ",1); u1,t1=await tok(a); u2,t2=await tok(b)
else:
u1,t1=await tok(part); u2,t2=None,None
if not u1: continue
txt1, ents1 = html.parse(t1) if t1 else ("", [])
name=telethon.utils.get_display_name(u1); f,l=Dick.split(name)
ava=await Dick.ava(self.client,u1.id)
if u2:
txt2, ents2 = html.parse(t2) if t2 else ("", [])
name2=telethon.utils.get_display_name(u2); ava2=await Dick.ava(self.client,u2.id)
rb={"name":name2,"text":txt2,"entities":Dick.ents(ents2),"chatId":u2.id,"from":{"name":name2,"photo":{"url":ava2} if ava2 else {}}}
msg={"from":{"id":u1.id,"first_name":getattr(u1,"first_name","") or f,"last_name":getattr(u1,"last_name","") or l,
"username":getattr(u1,"username",None),"name":name,"photo":{"url":ava} if ava else {}},
"text":txt1,"entities":Dick.ents(ents1), "avatar":True}
es=getattr(u1,"emoji_status",None)
if getattr(es,"document_id",None): msg["from"]["emoji_status"]=str(es.document_id)
if rb: msg["replyMessage"]=rb
out.append(msg)
except Exception: continue
return out