Commited backup

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

121
CakesTwix/Hikka-Modules/.gitignore vendored Normal file
View File

@@ -0,0 +1,121 @@
# For quick debug
test.py
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
.pytest_cache/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
.python-version
# celery beat schedule file
celerybeat-schedule
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# PyCharm
.idea/

View File

@@ -0,0 +1,65 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
Copyleft 2022 t.me/shadow_geektg
This program is free software; you can redistribute it and/or modify
"""
__version__ = (1, 0, 1)
# requires: requests
# meta pic: https://cdn-icons-png.flaticon.com/512/1005/1005340.png
# meta developer: @shadow_geektg, @cakestwix_mods
# scope: inline
# scope: hikka_only
import requests
import random
from .. import loader, utils
from telethon.tl.types import Message
async def photofox() -> str:
"""Fox photo handler"""
return (await utils.run_sync(requests.get, "https://randomfox.ca/floof")).json()["image"]
async def photodog() -> str:
"""Dog photo handler"""
return (await utils.run_sync(requests.get, "https://random.dog/woof.json")).json()["url"]
async def randomapi():
randomapis = random.choice(["https://randomfox.ca/floof", "https://random.dog/woof.json", "http://aws.random.cat/meow"])
if randomapis == "https://randomfox.ca/floof":
return (await utils.run_sync(requests.get, "https://randomfox.ca/floof")).json()["image"]
else:
return (await utils.run_sync(requests.get, "https://random.dog/woof.json")).json()["url"]
@loader.tds
class FoxGalerryMod(loader.Module):
"""🦊 Foxes, Dogs 🐶 and cats 🐱"""
strings = {"name": "FoxGallery"}
async def foxescmd(self, message: Message) -> None:
"""🦊 Sending photos with foxes"""
await self.inline.gallery(
message,
photofox,
)
async def dogscmd(self, message: Message) -> None:
"""🐶 Sending photos with dogs"""
await self.inline.gallery(
message,
photodog,
)
async def randomcdfcmd(self, message: Message) -> None:
"""Photos of dogs 🐶 and foxes 🦊"""
await self.inline.gallery(
message,
randomapi,
)

View File

@@ -0,0 +1,540 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
Copyleft 2022 t.me/CakesTwix
This program is free software; you can redistribute it and/or modify
"""
__version__ = (2, 1, 1) # BETA
# requires: httpx pydantic
# meta pic: https://www.seekpng.com/png/full/824-8246338_yandere-sticker-yandere-simulator-ayano-bloody.png
# meta developer: @cakestwix_mods
# scope: inline
# scope: hikka_only
# scope: hikka_min 1.1.2
from .. import loader, utils
import httpx
import asyncio
import logging
import ast
import telethon
from aiogram.types import InputFile
from aiogram.utils.markdown import hlink
from pydantic import BaseModel, Field
from typing import Optional
logger = logging.getLogger(__name__)
def rating_string(rating_list: list) -> str:
rating_str = ["s", "q", "e"]
if sum(rating_list) == 2:
return (
"-rating:"
+ rating_str[[i for i, val in enumerate(rating_list) if not val][0]]
)
elif sum(rating_list) == 1:
return f"rating:{rating_str[[i for i, val in enumerate(rating_list) if val][0]]}"
else:
return ""
# id: int | Айди
# tag: str = Field(alias='tag_string') | Теги
# rating: str | Рейтинг
# author: str | Автор
# file_size: int | Размер без сжатия
# sample_file_size: int | Размер со средним сжатием
# file_url: str | Без сжатия
# preview_file_url: str | Сильное сжатие
# sample_url: Optional[str] = None | Среднее сжатие
# source: Optional[str] = None | Откуда арт
class BooruModel(BaseModel):
id: int
tag: str = Field(alias='tag_string_general')
rating: str
author: Optional[str] = None
file_size: int
sample_file_size: int = Field(alias='file_size')
file_url: str
preview_file_url: str = Field(alias='large_file_url')
sample_url: Optional[str] = Field(alias='large_file_url')
source: Optional[str] = None
class MoebooruModel(BaseModel):
id: int
tag: str = Field(alias='tags')
rating: str
author: Optional[str] = None
file_size: int
sample_file_size: int
file_url: str
preview_file_url: str = Field(alias='preview_url')
sample_url: Optional[str] = None
source: Optional[str] = None
class Moebooru:
domain = 'yande.re'
get_url = f'https://{domain}'
post_url = '/post.json'
async def getLast(self, params):
async with httpx.AsyncClient() as client:
get = await client.get(self.get_url + self.post_url + params)
result = get.json()
return [MoebooruModel(**item) for item in result]
class Konachan_Net(Moebooru):
domain = 'konachan.net'
get_url = f'https://{domain}'
post_url = '/post.json'
class Lolibooru(Moebooru):
domain = 'lolibooru.moe'
get_url = f'https://{domain}'
post_url = '/post.json'
# Very buggy :(
class Booru:
domain = 'danbooru.donmai.us'
get_url = f'https://{domain}'
post_url = '/posts.json'
async def getLast(self, params):
async with httpx.AsyncClient() as client:
get = await client.get(self.get_url + self.post_url + params)
result = get.json()
list_art = []
for item in result:
try:
list_art.append(BooruModel(**item))
except Exception as err:
logger.debug(str(err)) # Fck Booru
return list_art
@loader.tds
class ImageBoardSenderMod(loader.Module):
"""Auto-posting art to your channels"""
strings = {
"cfg_channel": "Сhannel variable where the content will be posted",
"cfg_tags": "Filtering art by tags",
"name": "ImageBoardSender",
"no_chennel": "Channel does not exist",
"ok": "Everything is okay",
"no_ok": "Everything not okay (maybe not admin rights)",
"channel_status": "<b>Channel Status</b>:",
"channel_username": "<b>Channel username</b>:",
"channel_tags": "<b>Channel tags</b>:",
"channel_no_tags": "no tags",
"change_channel_username": "<b>Change the channel username</b>",
"changed_successfully": "Successfully changed",
"btn_menu_change_channel": "✍️ Change username channel",
"btn_menu_change_tags": "✍️ Change tags",
"btn_menu_change_input": "✍️ Enter new configuration value for this option",
"btn_menu_update": "Update",
"btn_menu_start": "Start",
"btn_menu_stop": "Stop",
"btn_menu_Safe": "Safe",
"btn_menu_Questionable": "Questionable",
"btn_menu_Explicit": "Explicit",
"btn_menu_autostart_on": "✅ Autostart",
"btn_menu_autostart_off": "❌ Autostart",
"source": "<b>List of available sources. \nThe source used:</b> <code>{}</code>",
}
strings_ru = {
"cfg_channel": "Переменная канала, где будет размещаться контент",
"cfg_tags": "Фильтрация артов по тегам",
"name": "ImageBoardSender",
"no_chennel": "Канал не существует",
"ok": "Все хорошо",
"no_ok": "Все не окей (возможно нет прав админа)",
"channel_status": "<b>Статус канала</b>:",
"channel_username": "<b>Имя канала</b>:",
"channel_tags": "<b>Теги канала</b>:",
"channel_no_tags": "нет тегов",
"change_channel_username": "<b>Изменить имя пользователя канала</b>",
"changed_successfully": "Успешно изменено",
"btn_menu_change_channel": "✍️ Изменить имя канал",
"btn_menu_change_tags": "✍️ Изменить теги",
"btn_menu_change_input": "✍️ Введите новое значение конфигурации для этой опции",
"btn_menu_update": "Обновить",
"btn_menu_start": "Start",
"btn_menu_stop": "Stop",
"btn_menu_Safe": "Безопасно",
"btn_menu_Questionable": "Под вопросом",
"btn_menu_Explicit": "Откровенное 18+",
"btn_menu_autostart_on": "✅ Автостарт",
"btn_menu_autostart_off": "❌ Автостарт",
"source": "<b>Список доступных источников. \nИспользуемый источник:</b> <code>{}</code>",
}
rating = {"e": "Explicit 🔴", "q": "Questionable 🟡", "s": "Safe 🟢"}
url = "https://yande.re/post.json"
def __init__(self):
self.config = loader.ModuleConfig(
"CONFIG_CHANNEL",
"@notset",
lambda: self.strings("cfg_channel"),
"CONFIG_TAGS",
"",
lambda: self.strings("cfg_tags"),
)
self.entity = None
self.last_id = 0
self.sources = {"Yandere": Moebooru(), "Konachan.net": Konachan_Net(), "LoliBooru": Lolibooru()}
self.source_btn = [{"text": item, "callback": self.callback__change_source, "args": (item,)} for item in self.sources]
# Check channel rights
async def check_entity(self) -> bool:
try:
if not self.entity:
self.entity = await self._client.get_entity(self.config["CONFIG_CHANNEL"])
if not isinstance(self.entity, telethon.types.Channel):
self.entity = None
return False
except ValueError:
self.entity = None
return False
if self.entity.admin_rights is None:
return False
elif self.entity.admin_rights.post_messages:
return True
async def menu_keyboard(self) -> list:
return [
[
{
"text": self.strings["btn_menu_change_channel"],
"input": self.strings["btn_menu_change_input"],
"handler": self.change_config,
"args": ("CONFIG_CHANNEL",),
},
{
"text": self.strings["btn_menu_change_tags"],
"input": self.strings["btn_menu_change_input"],
"handler": self.change_config,
"args": ("CONFIG_TAGS",),
},
],
[
{
"text": f"[ {self.strings['btn_menu_Safe']} ]"
if self._db.get(self.strings["name"], "rating")[0]
else self.strings["btn_menu_Safe"],
"callback": self.set_rating,
"args": ("s"),
},
{
"text": f"[ {self.strings['btn_menu_Questionable']} ]"
if self._db.get(self.strings["name"], "rating")[1]
else self.strings["btn_menu_Questionable"],
"callback": self.set_rating,
"args": ("q"),
},
{
"text": f"[ {self.strings['btn_menu_Explicit']} ]"
if self._db.get(self.strings["name"], "rating")[2]
else self.strings["btn_menu_Explicit"],
"callback": self.set_rating,
"args": ("e"),
},
]
if await self.check_entity()
else [],
[
{"text": self.strings["btn_menu_stop"], "callback": self.stop_posting}
if self.loop__send_arts.status
else {
"text": self.strings["btn_menu_start"],
"callback": self.start_posting,
},
{
"text": self.strings["btn_menu_autostart_on"]
if self._db.get(self.strings["name"], "autostart")
else self.strings["btn_menu_autostart_off"],
"callback": self.change_autostart,
},
]
if await self.check_entity()
else [],
[
{
"text": self.strings["btn_menu_update"],
"callback": self.update_channel_status,
}
],
]
# Just async init
async def _init(self) -> None:
await self.check_entity()
bot_info = await self.inline.bot.get_me()
if self.config["CONFIG_CHANNEL"] == "@notset":
return
self.entity = await self._client.get_entity(self.config["CONFIG_CHANNEL"])
try:
channel_bot = await self._client.edit_admin(self.config["CONFIG_CHANNEL"],
user=bot_info.username,
change_info=False,
post_messages=True,
edit_messages=True,
delete_messages=True,
ban_users=False,
invite_users=False,
pin_messages=True,
add_admins=False,)
logger.debug(f"[{self.strings['name']}] Bot added")
if self._db.get(self.strings["name"], "autostart"):
self.loop__send_arts.start()
except ValueError:
channel_bot = None
logger.warning(f"[{self.strings['name']}] Check channel username")
async def client_ready(self, client, db) -> None:
self._db = db
self._client = client
None if self._db.get(self.strings["name"], "source") else self._db.set(self.strings["name"], "source", "Yandere")
None if self._db.get(self.strings["name"], "rating") else self._db.set(self.strings["name"], "rating", [False, False, False])
None if self._db.get(self.strings["name"], "autostart") else self._db.set(self.strings["name"], "autostart", False)
await self._init()
async def on_unload(self) -> None:
try:
self.loop__send_arts.stop()
except Exception:
pass
# Caption
def string_builder(self, json):
# Thanks to Фрося <3
string = f"Tags : {'#' + str.join(' #', json.tag.split())}\n"
string += f'©️ : {json.author or "No author"}\n'
string += f'🔗 : {json.source or "No source"}\n'
string += f"Rating : {self.rating[json.rating]}\n\n"
string += ("🆔 : " + str(json.id))
return string
# Commands #
async def channelmenucmd(self, message):
"""🗒 Simple Menu and status"""
string = f"{self.strings['channel_status']} {self.strings['ok'] if await self.check_entity() else self.strings['no_ok']}\n"
string += f"{self.strings['channel_username']} {self.config['CONFIG_CHANNEL'] if self.config['CONFIG_CHANNEL'] != '@notset' else self.strings['change_channel_username']}\n"
string += f"{self.strings['channel_tags']} {self.config['CONFIG_TAGS'] if self.config['CONFIG_TAGS'] != '' else self.strings['channel_no_tags']}\n"
await self.inline.form(
text=string,
message=message,
reply_markup=await self.menu_keyboard(),
)
async def artsourcecmd(self, message):
"""🧑‍🎤 Change the source of art"""
await self.inline.form(
text=self.strings["source"].format(self._db.get(self.strings["name"], "source")),
message=message,
reply_markup=utils.chunks(self.source_btn, 2),
)
async def latestartcmd(self, message):
"""⌚️ Sending the last art for now"""
params = (
"?tags="
+ rating_string(self._db.get(self.strings["name"], "rating"))
+ " "
+ self.config["CONFIG_TAGS"]
)
art_data = await self.sources[self._db.get(self.strings["name"], "source")].getLast(params)
await self.inline.bot.send_photo(
self.config['CONFIG_CHANNEL'],
InputFile.from_url(art_data[0].sample_url),
self.string_builder(art_data[0]),
parse_mode="HTML",
reply_markup=self.inline._generate_markup(
[{"text": "Full", "url": art_data[0].file_url}]
),
)
await message.delete()
async def randomartcmd(self, message):
"""🎲 Sending a random art"""
params = (
"?tags=order:random "
+ rating_string(self._db.get(self.strings["name"], "rating"))
+ " "
+ self.config["CONFIG_TAGS"]
)
art_data = await self.sources[self._db.get(self.strings["name"], "source")].getLast(params)
await self.inline.bot.send_photo(
self.config['CONFIG_CHANNEL'],
InputFile.from_url(art_data[0].sample_url),
self.string_builder(art_data[0]),
parse_mode="HTML",
reply_markup=self.inline._generate_markup(
[{"text": "Full", "url": art_data[0].file_url}]
),
)
await message.delete()
# Inline callback handlers #
# From Hikka https://github.com/hikariatama/Hikka/blob/d3144fcebdbc8ecbec7f3d299cc927bb1fea00b6/hikka/modules/hikka_config.py#L51-L80
async def change_config(self, call, param, config_name) -> None:
for module in self.allmodules.modules:
if module.strings("name") == self.strings["name"]:
module.config[config_name] = param
if param:
try:
param = ast.literal_eval(param)
except (ValueError, SyntaxError):
pass
self._db.setdefault(module.__class__.__name__, {}).setdefault(
"__config__", {}
)[config_name] = param
else:
try:
del self._db.setdefault(
module.__class__.__name__, {}
).setdefault("__config__", {})[config_name]
except KeyError:
pass
self.allmodules.send_config_one(module, self._db, skip_hook=True)
self._db.save()
await call.edit(
text=self.strings["changed_successfully"],
reply_markup=[
{
"text": self.strings["btn_menu_update"],
"callback": self.update_channel_status,
}
],
)
async def update_channel_status(self, call) -> None:
string = f"{self.strings['channel_status']} {self.strings['ok'] if await self.check_entity() else self.strings['no_ok']}\n"
string += f"{self.strings['channel_username']} {self.config['CONFIG_CHANNEL'] if self.config['CONFIG_CHANNEL'] != '@notset' else self.strings['change_channel_username']}\n"
string += f"{self.strings['channel_tags']} {self.config['CONFIG_TAGS'] if self.config['CONFIG_TAGS'] != '' else self.strings['channel_no_tags']}\n"
await call.edit(
text=string,
reply_markup=await self.menu_keyboard(),
)
async def set_rating(self, call, rating) -> None:
list_rating = self._db.get(self.strings["name"], "rating")
if rating == "s":
list_rating[0] = not list_rating[0]
self._db.set(self.strings["name"], "rating", list_rating)
elif rating == "q":
list_rating[1] = not list_rating[1]
self._db.set(self.strings["name"], "rating", list_rating)
elif rating == "e":
list_rating[2] = not list_rating[2]
self._db.set(self.strings["name"], "rating", list_rating)
await self.update_channel_status(call)
async def start_posting(self, call) -> None:
if not self.loop__send_arts.status:
self.loop__send_arts.start()
await asyncio.sleep(0.5) # Otherwise the button does not update
await self.update_channel_status(call)
async def stop_posting(self, call) -> None:
if self.loop__send_arts.status:
self.loop__send_arts.stop()
await self.update_channel_status(call)
async def change_autostart(self, call) -> None:
self._db.set(
self.strings["name"],
"autostart",
not self._db.get(self.strings["name"], "autostart"),
)
await self.update_channel_status(call)
async def callback__change_source(self, call, source):
self._db.set(self.strings["name"], "source", source)
self.last_id = 0
await call.edit(text=self.strings["source"].format(self._db.get(self.strings["name"], "source")), reply_markup=utils.chunks(self.source_btn, 2))
# General loop #
@loader.loop(interval=60)
async def loop__send_arts(self):
"""Auto-Posting"""
params = (
"?tags="
+ rating_string(self._db.get(self.strings["name"], "rating"))
+ " "
+ self.config["CONFIG_TAGS"]
)
art_data = await self.sources[self._db.get(self.strings["name"], "source")].getLast(params)
if art_data == []:
logger.warning(f"[{self.strings['name']}] No arts, check tags")
return
if self.last_id == 0:
self.last_id = art_data[0].id
return
for item in reversed(art_data):
if item.id > self.last_id:
try:
# await self._client.send_file(
# self.entity,
# item["sample_url"],
# caption=self.string_builder(item),
# )
await self.inline.bot.send_photo(
self.config['CONFIG_CHANNEL'],
InputFile.from_url(item.sample_url),
self.string_builder(item),
parse_mode="HTML",
reply_markup=self.inline._generate_markup(
[{"text": "Full", "url": item.file_url}]
),
)
# break # DEBUG
except Exception as e:
logger.error(str(e))
await asyncio.sleep(1)
self.last_id = art_data[0].id
await asyncio.sleep(5 * 60)

View File

@@ -0,0 +1,104 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
Copyleft 2022 t.me/CakesTwix
This program is free software; you can redistribute it and/or modify
"""
__version__ = (1, 0, 0)
# requires: spotdl
# meta pic: https://cdn-icons-png.flaticon.com/512/2111/2111624.png
# meta developer: @cakestwix_mods
# scope: hikka_only
import os
import subprocess
import logging
import asyncio
import spotdl
from .. import loader, utils
logger = logging.getLogger(__name__)
@loader.tds
class InlineSpotifyDownloaderMod(loader.Module):
"""Module for downloading music from Spotify"""
strings = {
"name": "InlineSpotifyDownloader",
"cfg_spotdl_path": "Path to spotdl bin",
"no_args": "🎞 <b>You need to specify link</b>",
"no_track": "🎞 <b>You need to specify track link</b>",
"downloading": "🎞 <b>Downloading...</b>",
"no_spotdl": "🚫 <b>Spotdl not found... Check config or install spotdl (<code>.terminal pip install spotdl</code>)</b>",
"not_found": "🎧 <b>Music not found...</b>",
}
def __init__(self):
self.config = loader.ModuleConfig(
"CONFIG_SPOTDL_PATH",
"~/.local/bin/spotdl",
lambda: self.strings("cfg_spotdl_path"),
)
async def spotdlcmd(self, message):
"""Download music from Spotify (Only tracks)"""
if not (args := utils.get_args_raw(message)):
return await utils.answer(message, self.strings["no_args"])
if "https://open.spotify.com/track/" not in args:
return await utils.answer(message, self.strings["no_track"])
# Try write command
await utils.answer(message, self.strings["downloading"])
proc = await asyncio.create_subprocess_shell(
self.config["CONFIG_SPOTDL_PATH"] + " " + args,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
# Pass one line
_ = await proc.stdout.readline()
# Get console strings
line = (await proc.stdout.readline()).decode().rstrip()
await proc.wait()
# Check "not found" error
err = await proc.stderr.readline()
if ": not found" in err.decode():
return await utils.answer(message, self.strings["no_spotdl"])
# Try get youtube video id
if "https://www.youtube.com/watch?v=" in line and len(line.split("https://www.youtube.com/watch?v=")) == 2:
photo_id = line.split("https://www.youtube.com/watch?v=")[1]
elif "as it's already downloaded" in line:
photo_id = None
else:
return await utils.answer(message, self.strings["not_found"])
# Get track name and send message
track_name = line.split('"')[1]
await self.inline.form(
text=line,
photo=f"https://img.youtube.com/vi/{photo_id}/maxresdefault.jpg" if photo_id else None,
message=message,
reply_markup=[{"text": "Upload", "callback": self.inline__upload, "args": (track_name, message.chat.id)}]
)
async def inline__upload(self, call, track_name, chat_id):
with open(track_name + ".mp3","rb",) as input_file:
content = input_file.read()
input_file.seek(0)
await self._client.send_file(
chat_id,
track_name + ".mp3"
)
os.remove(track_name + ".mp3")
await call.delete()

View File

@@ -0,0 +1,443 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
Copyleft 2022 t.me/CakesTwix
This program is free software; you can redistribute it and/or modify
"""
__version__ = (1, 4, 5)
# requires: psutil py-cpuinfo
# meta pic: https://img.icons8.com/external-xnimrodx-lineal-color-xnimrodx/512/000000/external-pc-computer-xnimrodx-lineal-color-xnimrodx.png
# meta developer: @cakestwix_mods
# scope: inline
# scope: hikka_min 1.1.2
# For version info
import telethon
import aiogram
import git
import datetime
import logging
from typing import Union
import platform
import cpuinfo
import psutil
from aiogram.utils.markdown import quote_html
from os.path import exists
from .. import loader, utils
logger = logging.getLogger(__name__)
# https://www.adamsmith.haus/python/answers/how-to-remove-empty-lines-from-a-string-in-python
def remove_empty_lines(string_with_empty_lines):
lines = string_with_empty_lines.split("\n")
non_empty_lines = [line for line in lines if line.strip() != ""]
return "".join(line + "\n" for line in non_empty_lines)
backslash = "\n"
def get_os_release():
if not exists("/etc/os-release"):
return False
list_ = []
with open("/etc/os-release") as f:
list_.extend(item.split("=") for item in f.readlines())
return {item[0]: item[1].replace(backslash, "").replace('"', "") for item in list_}
# https://stackoverflow.com/questions/2756737/check-linux-distribution-name
def get_distro():
"""
Name of your Linux distro
"""
if not exists("/etc/issue"):
return False
with open("/etc/issue") as f:
return f.read().split()[0]
def progressbar(iteration: int, length: int) -> str:
percent = ("{0:." + str(1) + "f}").format(100 * (iteration / float(100)))
filledLength = int(length * iteration // 100)
return "" * filledLength + "" * (length - filledLength)
# From Hikka https://github.com/hikariatama/Hikka/blob/master/hikka/utils.py#L459-L461
def chunks(_list: Union[list, tuple, set], n: int, /) -> list:
"""Split provided `_list` into chunks of `n`"""
return [_list[i : i + n] for i in range(0, len(_list), n)]
def bytes2human(n):
# http://code.activestate.com/recipes/578019
# >>> bytes2human(10000)
# '9.8K'
# >>> bytes2human(100001221)
# '95.4M'
symbols = ("K", "M", "G", "T", "P", "E", "Z", "Y")
prefix = {s: 1 << (i + 1) * 10 for i, s in enumerate(symbols)}
for s in reversed(symbols):
if n >= prefix[s]:
value = float(n) / prefix[s]
return "%.1f%s" % (value, s)
return "%sB" % n
@loader.tds
class InlineSystemInfoMod(loader.Module):
"""🖥 Get detailed information about your server"""
strings = {
"name": "🖥 InlineSystemInfo",
}
AddressFamily = {
2: "IPv4",
10: "IPv6",
28: "IPv6",
17: "Link",
18: "Link",
}
def menu_keyboard(self) -> list:
keyboard = [
[
{
"text": "😼 General",
"callback": self.change_stuff,
"args": ("General",),
}
],
]
keyboard.extend(
iter(
chunks(
[
{
"text": "🧠 CPU",
"callback": self.change_stuff,
"args": ("CPU",),
},
{
"text": "🐧 Linux",
"callback": self.change_stuff,
"args": ("Linux",),
},
{
"text": "🗄 Memory",
"callback": self.change_stuff,
"args": ("Memory",),
},
{
"text": "🌐 Network Address",
"callback": self.change_stuff,
"args": ("Network Address",),
},
{
"text": "🌐 Network Stats",
"callback": self.change_stuff,
"args": ("Network Stats",),
},
{
"text": "💽 Disk",
"callback": self.change_stuff,
"args": ("Disk",),
},
{
"text": "🌡 Sensors",
"callback": self.change_stuff,
"args": ("Sensors",),
},
{
"text": "🐍 Python",
"callback": self.change_stuff,
"args": ("Python",),
}
],
3,
)
)
)
keyboard.append([{"text": "🚫 Close", "callback": self.inline__close}])
try:
return keyboard[3].remove([])
except ValueError:
return keyboard
def general_info(self):
string = "😼 <b>System Info</b>\n"
string += f" ├──<b>CPU Name</b>: <code>{self.cpu_info.get('brand_raw', 'Undetermined.')}</code> {self.cpu_count_logic}/{self.cpu_count} ({self.cpu_info['arch_string_raw']})\n"
string += f" ├──<b>RAM</b>: {progressbar(self.virtual_memory.percent, 10)} <code>({bytes2human(self.virtual_memory.used)}/{bytes2human(self.virtual_memory.total)})</code>\n"
string += f" └──<b>Swap</b>: {progressbar(self.swap_memory.percent, 10)} <code>({bytes2human(self.swap_memory.used)}/{bytes2human(self.swap_memory.total)})</code>\n\n"
string += "🐧 <b>Linux Info</b>\n"
string += f" ├──<b>Name</b>: <code>{get_distro()}</code>\n"
string += f" └──<b>Kernel</b>: <code>{platform.release()}</code>\n\n"
if hasattr(self, "disk_partitions"):
for disk_root in psutil.disk_partitions("/"):
if disk_root.mountpoint == '/':
disk_usage = psutil.disk_usage(disk_root.mountpoint)
string += "💽 <b>Disk Info</b> <code>(/)</code>\n"
string += f" └──<b>{disk_root.device}</b>\n"
string += f" ├── <b>Mount</b> {disk_root.mountpoint}\n"
string += f" ├── <b>FS</b> {disk_root.fstype}\n"
string += f" ├── <b>Disk Usage</b> {disk_usage.percent}% ({bytes2human(disk_usage.used)}/{bytes2human(disk_usage.total)})\n"
string += f" │ └──{progressbar(disk_usage.percent, 10)}\n"
string += f" └── <b>Options</b> {disk_root.opts}\n\n"
return string
def cpu_string(self):
string = "🧠 <b>CPU Info</b>\n"
string += f"⦁ <b>Name</b>: {self.cpu_info.get('brand_raw', 'Undetermined.')} ({self.cpu_info['arch_string_raw']})\n"
string += f"⦁ <b>Count</b>: {self.cpu_count_logic} ({self.cpu_count})\n"
string += (
f"⦁ <b>Freq</b>: {self.cpu_freq[0]} (max: {self.cpu_freq[2]} / min: {self.cpu_freq[1]})\n"
if hasattr(self, "cpu_freq") and self.cpu_freq
else ""
)
string += f"⦁ <b>Flags</b>: {' '.join(self.cpu_info.get('flags', 'No flags'))}\n"
string += (
f"⦁ <b>Load avg</b>: {self.loadavg[0]} {self.loadavg[1]} {self.loadavg[2]}\n"
if hasattr(self, "loadavg")
else ""
)
return string
def disks_string(self):
if not hasattr(self, "disk_partitions"):
return None
string = "💽 <b>Disk Info</b>\n"
for disk in self.disk_partitions:
disk_usage = psutil.disk_usage(disk.mountpoint)
string += f"<b>{disk.device}</b>\n"
string += f"├── <b>Mount</b> {disk.mountpoint}\n"
string += f"├── <b>FS</b> {disk.fstype}\n"
string += f"├── <b>Disk Usage</b> {disk_usage.percent}% ({bytes2human(disk_usage.used)}/{bytes2human(disk_usage.total)})\n"
string += f"│ └──{progressbar(disk_usage.percent, 10)}\n"
string += f"└── <b>Options</b> {disk.opts}\n\n"
return string
def network_addr_string(self):
if not hasattr(self, "net_if_addrs"):
return None
string = "🌐 <b>Network Info</b>\n"
string += "<b>Address</b>:\n"
for interf in self.net_if_addrs:
interface = self.net_if_addrs[interf]
string += f"<b>{interf}</b>\n"
for addr in interface:
attr = [
a
for a in dir(psutil.net_if_addrs()[interf][0])
if not a.startswith("__")
and not a.startswith("_")
and not callable(getattr(psutil.net_if_addrs()[interf][0], a))
]
string += f"{self.AddressFamily[getattr(addr, 'family')]}\n"
for item in attr[:-1]:
string += f"├── {item}: {getattr(addr, item)}\n"
string += f"└── {attr[-1]}: {getattr(addr, attr[-1])}\n"
string += "\n"
return string
def memory_string(self):
string = "🗄 <b>Memory Info</b>\n"
string += f"<b>RAM</b>: {progressbar(self.virtual_memory.percent, 10)} <code>({bytes2human(self.virtual_memory.used)}/{bytes2human(self.virtual_memory.total)})</code>\n"
string += f"<b>Swap</b>: {progressbar(self.swap_memory.percent, 10)} <code>({bytes2human(self.swap_memory.used)}/{bytes2human(self.swap_memory.total)})</code>\n"
return string
def sensors_string(self):
string = None
if hasattr(self, "sensors_temperatures"):
string = "🌡 <b>Sensors Info</b>\n" + "<b>Temperature</b>:\n"
for sensor_name in self.sensors_temperatures:
sensor = self.sensors_temperatures[sensor_name]
string += f"<b>{sensor_name}</b>\n"
for sensor_info in sensor:
attr = [
a
for a in dir(sensor_info)
if not a.startswith("__")
and not a.startswith("_")
and not callable(getattr(sensor_info, a))
]
for item in attr[:-1]:
string += f"├── {item}: {getattr(sensor_info, item)}\n"
string += f"└── {attr[-1]}: {getattr(sensor_info, attr[-1])}\n"
string += "\n"
if hasattr(self, "sensors_fans"):
string += "<b>Fans</b>:"
for sensor_name in self.sensors_fans:
sensor = self.sensors_fans[sensor_name]
string += f"<b>{sensor_name}</b>\n"
for sensor_info in sensor:
attr = [
a
for a in dir(sensor_info)
if not a.startswith("__")
and not a.startswith("_")
and not callable(getattr(sensor_info, a))
]
for item in attr[:-1]:
string += f"├── {item}: {getattr(sensor_info, item)}\n"
string += f"└── {attr[-1]}: {getattr(sensor_info, attr[-1])}\n"
return string
def network_stats_string(self):
if not hasattr(self, "net_if_stats"):
return None
string = "🌐 <b>Network Info</b>\n" + "<b>Stats</b>:\n"
for interf in self.net_if_stats:
interface = self.net_if_stats[interf]
string += f"<b>{interf}</b>\n"
string += f"└── {quote_html(interface)}\n\n"
return string
def linux_string(self):
os_release = get_os_release()
string = f"""🐧 <b>Linux Info</b>
Name: {get_distro()}
Kernel: {platform.release()}
Hostname: {platform.node()}
{f'glibc ver: {platform.glibc()[1]}' if hasattr(platform, 'glibc') else ''}
Boot time: {self.boot_time if hasattr(self, "boot_time") else "Termux moment"}
"""
if os_release:
string += f"""<b>\n /etc/os-releases Info:</b>
Pretty Name: {os_release["PRETTY_NAME"]}
Name: {os_release["NAME"]}
Version: {os_release.get("VERSION", "Not available")}
Documentation: {os_release.get("DOCUMENTATION_URL", "Not available")}
Support: {os_release.get("SUPPORT_URL", "Not available")}
Bug Report: {os_release["BUG_REPORT_URL"]}
"""
return remove_empty_lines(string)
def python_string(self):
string = "🐍 <b>Python Info</b>\n"
string += f" ├──<b>Version</b>: <code>{platform.python_version()}</code>\n"
string += f" ├──<b>Version (More details)</b>: <code>{cpuinfo.get_cpu_info()['python_version']}</code>\n"
string += f" └──<b>Python Packages version</b>\n"
string += f" ├──<b>Telethon</b>: <code>{telethon.__version__}</code>\n"
string += f" ├──<b>AIOgram</b>: <code>{aiogram.__version__}</code>\n"
string += f" ├──<b>Cpuinfo</b>: <code>{cpuinfo.get_cpu_info()['cpuinfo_version_string']}</code>\n"
string += f" ├──<b>psutil</b>: <code>{psutil.__version__}</code>\n"
string += f" └──<b>git</b>: <code>{git.__version__}</code>\n"
return string
def __init__(self):
# CPU stuff
self.cpu_count_logic = psutil.cpu_count()
self.cpu_count = psutil.cpu_count(logical=False)
try:
self.cpu_freq = psutil.cpu_freq()
except FileNotFoundError:
pass
self.cpu_info = cpuinfo.get_cpu_info()
# Network
try:
self.net_if_addrs = psutil.net_if_addrs()
self.net_if_stats = psutil.net_if_stats()
except PermissionError:
pass
def update_data(self):
# Memory
self.virtual_memory = psutil.virtual_memory()
self.swap_memory = psutil.swap_memory()
# Sensors
if hasattr(psutil, "sensors_temperatures"):
self.sensors_temperatures = psutil.sensors_temperatures()
if hasattr(psutil, "sensors_fans"):
self.sensors_fans = psutil.sensors_fans()
# self.sensors_battery = psutil.sensors_battery()
# CPU stuff
self.cpu_percent = psutil.cpu_percent(interval=None)
# Linux stuff
self.loadavg = psutil.getloadavg()
# Disks
try:
self.disk_partitions = psutil.disk_partitions()
except PermissionError:
pass
# Other
self.boot_time = datetime.datetime.fromtimestamp(psutil.boot_time()).strftime(
"%Y-%m-%d %H:%M:%S"
)
# Generate string
self.info_string = {
"General": self.general_info(),
"CPU": self.cpu_string(),
"Disk": self.disks_string(),
"Network Address": self.network_addr_string(),
"Network Stats": self.network_stats_string(),
"Memory": self.memory_string(),
"Sensors": self.sensors_string(),
"Linux": self.linux_string(),
"Python": self.python_string(),
}
async def client_ready(self, client, db) -> None:
if utils.get_platform_name() == '🕶 Termux':
raise loader.LoadError("No Termux support. Change your host")
async def systeminfocmd(self, message):
"""Get information about your server"""
await utils.run_sync(self.update_data)
await self.inline.form(
text=self.general_info(),
message=message,
reply_markup=self.menu_keyboard(),
)
# Inline callback
async def change_stuff(self, call, stuff):
if self.info_string[stuff] != None:
await call.edit(text=self.info_string[stuff], reply_markup=self.menu_keyboard())
else:
await call.answer("No data :(")
async def inline__close(self, call) -> None:
await call.delete()

View File

@@ -0,0 +1,337 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
Copyleft 2022 t.me/CakesTwix
This program is free software; you can redistribute it and/or modify
"""
__version__ = (1, 2, 0)
# requires: aiohttp timeago
# meta pic: https://b.thumbs.redditmedia.com/-cDkj6PuQHqdLEhPh1JYsYplTArOOUuBnKs5FC8sgKs.png
# meta developer: @cakestwix_mods
# scope: inline
import logging
import uuid
from datetime import datetime
from typing import Union
import aiohttp
import timeago
from .. import loader, utils # noqa
logger = logging.getLogger(__name__)
# From Hikka https://github.com/hikariatama/Hikka/blob/master/hikka/utils.py#L459-L461
def chunks(_list: Union[list, tuple, set], n: int, /) -> list:
"""Split provided `_list` into chunks of `n`"""
return [_list[i : i + n] for i in range(0, len(_list), n)]
@loader.tds
class InlineWynnCraftInfoMod(loader.Module):
"""A module for displaying player information on the WynnCraft rpg server"""
strings = {
"name": "InlineWynnCraft",
"error_message": "🚫 This entity does not exist or you entered it incorrectly",
"about_user": "<b>Available player information</b> <code>{}</code> {}\n",
"rank_user": "<b>Rank</b>: ",
"last_join_user": "\n<b>Last Seen</b>: ",
"first_join_user": "\n<b>First Join</b>: ",
"professions_user": "\n<b>Professions</b>: ",
"guild_user": "\n<b>Guild</b>: {} ({})",
"general_info_user": "\n\n👉 <b>General Information</b>",
"chestsFound": "\n 🔍 <b>Chests Found</b>: ",
"blocksWalked": "\n 🚶‍♀️ <b>Walked blocks</b>: ",
"mobsKilled": "\n 🐗 <b>Mobs Killed</b>: ",
"itemsIdentified": "\n 🧰 <b>Items analyzed</b>: ",
"logins": "\n 🎟 <b>Logins</b>: ",
"discoveries": "\n 🔎 <b>Discoveries</b>: ",
"dungeons": "\n 🪨 <b>Dungeons</b>: ",
"raids": "\n ⚔️ <b>Raids</b>: ",
"quests": "\n 📕 <b>Quests</b>: ",
"eventsWon": "\n 🎊 <b>Events Won</b>: ",
"pvp_user": "\n\n🗡 <b>PVP</b>: ",
"deaths": "\n ☠️ <b>Deaths</b>: ",
"kills": "\n ⚔️ <b>Kills</b>: ",
"completed": "\n✅ <b>Completed</b>",
"skills": "\n\n🔧 <b>Skills</b>",
"strength": "\n 💪 <b>Strength</b>: ",
"dexterity": "\n 💨 <b>Dexterity</b>: ",
"intelligence": "\n 🧐 <b>Intelligence</b>: ",
"defense": "\n 🧱 <b>Defence</b>: ",
"defence": "\n 🛡 <b>Defence</b>: ",
"agility": "\n 🤸‍♂️ <b>Agility</b>: ",
"professions": "\n\n👷‍♀️ <b>Professions</b>: ",
"alchemism": "\n 💧 <b>Alchemism</b>: ",
"armouring": "\n 🛡 <b>Armouring</b>: ",
"combat": "\n ⚔️ <b>Combat</b>: ",
"cooking": "\n 🍽 <b>Cooking</b>: ",
"farming": "\n 🌾️ <b>Farming</b>: ",
"fishing": "\n 🎣 <b>Fishing</b>: ",
"jeweling": "\n 💎 <b>Jeweling</b>: ",
"mining": "\n ⛏ <b>Mining</b>: ",
"scribing": "\n 🖋 <b>Scribing</b>: ",
"tailoring": "\n 🪡 <b>Tailoring</b>: ",
"weaponsmithing": "\n 🗡️ <b>Weaponsmithing</b>: ",
"woodcutting": "\n 🪓 <b>Woodcutting</b>: ",
"woodworking": "\n 🌳️ <b>Woodworking</b>: ",
"btn_back": "Back",
"btn_close": "Close",
"top_list": "<b>Top list:</b>",
}
strings_ru = {
"error_message": "🚫 Этот объект не существует или вы ввели его неправильно",
"about_user": "<b>Доступная информация об игроке</b> <code>{}</code> {}\n",
"rank_user": "<b>Ранг</b>: ",
"last_join_user": "\n<b>Последнее посещение</b>: ",
"first_join_user": "\n<b>Первое присоединение</b>: ",
"professions_user": "\n<b>Профессии</b>: ",
"guild_user": "\n<b>Гильдия</b>: {} ({})",
"general_info_user": "\n\n👉 <b>Главная Информация</b>",
"chestsFound": "\n 🔍 <b>Найдено сундуков</b>: ",
"blocksWalked": "\n 🚶‍♀️ <b>Пройдено блоков</b>: ",
"mobsKilled": "\n 🐗 <b>Мобов убито</b>: ",
"itemsIdentified": "\n 🧰 <b>Проанализировано предметов</b>: ",
"logins": "\n 🎟 <b>Заходил на сервер</b>: ",
"discoveries": "\n 🔎 <b>Открытий</b>: ",
"dungeons": "\n 🪨 <b>Подземелья</b>: ",
"raids": "\n ⚔️ <b>Рейды</b>: ",
"quests": "\n 📕 <b>Квесты</b>: ",
"eventsWon": "\n 🎊 <b>Выигранные события</b>: ",
"pvp_user": "\n\n🗡 <b>PVP</b>: ",
"deaths": "\n ☠️ <b>Смертей</b>: ",
"kills": "\n ⚔️ <b>Убийств</b>: ",
"completed": "\n✅ <b>Завершено</b>",
"skills": "\n\n🔧 <b>Навыки</b>",
"strength": "\n 💪 <b>Прочность</b>: ",
"dexterity": "\n 💨 <b>Ловкость</b>: ",
"intelligence": "\n 🧐 <b>Интеллект</b>: ",
"defense": "\n 🧱 <b>Оборона</b>: ",
"defence": "\n 🛡 <b>Защита</b>: ",
"agility": "\n 🤸‍♂️ <b>Ловкость</b>: ",
"professions": "\n\n👷‍♀️ <b>Профессии</b>: ",
"alchemism": "\n 💧 <b>Алхимизм</b>: ",
"armouring": "\n 🛡 <b>Бронирование</b>: ",
"combat": "\n ⚔️ <b>Бой</b>: ",
"cooking": "\n 🍽 <b>Готовка</b>: ",
"farming": "\n 🌾️ <b>Сельское хозяйство</b>: ",
"fishing": "\n 🎣 <b>Рыбалка</b>: ",
"jeweling": "\n 💎 <b>Ювелирное дело</b>: ",
"mining": "\n ⛏ <b>Добыча</b>: ",
"scribing": "\n 🖋 <b>Скрайбирование</b>: ",
"tailoring": "\n 🪡 <b>Портняжное дело</b>: ",
"weaponsmithing": "\n 🗡️ <b>Оружейное дело</b>: ",
"woodcutting": "\n 🪓 <b>Резьба по дереву</b>: ",
"woodworking": "\n 🌳️ <b>Деревообработка</b>: ",
"btn_back": "Назад",
"btn_close": "Закрыть",
"top_list": "<b>Топ:</b>",
}
base_url = "https://mc-heads.net/minecraft/profile/"
wynncraft_api = "https://api.wynncraft.com/v2/"
def general_info_builder(self, user) -> str:
text = self.strings["about_user"].format(
f'🟢 ({user["meta"]["location"]["server"]})'
if user["meta"]["location"]["online"]
else "🔴",
user["username"],
)
text += (
self.strings["rank_user"]
+ user["rank"]
+ (
f' ({user["meta"]["tag"]["value"]})'
if user["meta"]["tag"]["value"]
else ""
)
)
# Guild
text += (
self.strings["guild_user"].format(
user["guild"]["name"], user["guild"]["rank"]
)
if user["guild"]["name"]
else ""
)
text += self.strings["last_join_user"] + timeago.format(
datetime.strptime(user["meta"]["lastJoin"][:-5], "%Y-%m-%dT%H:%M:%S"),
datetime.now(),
)
text += self.strings["first_join_user"] + timeago.format(
datetime.strptime(user["meta"]["firstJoin"][:-5], "%Y-%m-%dT%H:%M:%S"),
datetime.now(),
)
# Global stuff
text += self.strings["general_info_user"]
for general_stuff in user["global"]:
if general_stuff in ["pvp", "totalLevel"]:
continue
text += (
self.strings[general_stuff]
+ f"<code>{user['global'][general_stuff]}</code>"
)
# PvP
text += self.strings["pvp_user"]
text += self.strings["kills"] + f"<code>{user['global']['pvp']['kills']}</code>"
text += (
self.strings["deaths"] + f"<code>{user['global']['pvp']['deaths']}</code>"
)
return text
def class_info_builder(self, class_) -> str:
text = self.strings["about_user"].format(
"".join([i for i in class_["name"].title() if not i.isdigit()]),
f"[{class_['level']}]",
)
# Completed stuff
text += self.strings["completed"]
for some_item in class_:
if some_item not in ["dungeons", "raids", "quests"]:
continue
text += (
self.strings[some_item]
+ f"<code>{class_[some_item]['completed']}</code>"
)
# Some stuff
text += self.strings["general_info_user"]
for some_item in class_:
if some_item in [
"itemsIdentified",
"mobsKilled",
"chestsFound",
"blocksWalked",
"logins",
"discoveries",
"eventsWon",
]:
text += self.strings[some_item] + f"<code>{class_[some_item]}</code>"
# PvP
text += self.strings["pvp_user"]
text += self.strings["kills"] + f"<code>{class_['pvp']['kills']}</code>"
text += self.strings["deaths"] + f"<code>{class_['pvp']['deaths']}</code>"
# Skills stuff
text += self.strings["skills"]
for skill in class_["skills"]:
text += self.strings[skill] + f"<code>{class_['skills'][skill]}</code>"
# Professions stuff
text += self.strings["professions"]
for skill in class_["professions"]:
text += self.strings[skill] + f"<code>{class_['professions'][skill]['level']} ({class_['professions'][skill]['xp']})</code>"
return text
def keyboard_class_builder(self, user):
return [
{
"text": f'[{class_["level"]}] {"".join([i for i in class_["name"].title() if not i.isdigit()])}',
"callback": self.inline__get_class,
"args": [class_, user],
}
for class_ in user["classes"]
]
async def wucheckcmd(self, message):
"""Check user by username"""
if not (args := utils.get_args_raw(message)):
return
async with aiohttp.ClientSession() as session:
async with session.get(f"{self.base_url}{args}") as get:
if get.status != 200:
return await utils.answer(message, self.strings["error_message"])
uuid_str = (await get.json())["id"]
# Get info about user
async with session.get(
self.wynncraft_api + "player/{}/stats".format(uuid.UUID(hex=uuid_str))
) as get:
logger.debug(str(await get.json()))
if (await get.json())["code"] != 200:
return await utils.answer(message, self.strings["error_message"])
user = (await get.json())["data"][0]
await self.inline.form(
text=self.general_info_builder(user),
message=message,
reply_markup=chunks(self.keyboard_class_builder(user), 3),
photo=f"https://wynndata.tk/gen/stats/{args}.png",
force_me=False, # optional: Allow other users to access form (all)
)
async def wplayertopcmd(self, message):
"""Top players"""
async with aiohttp.ClientSession() as session:
async with session.get(f"{self.wynncraft_api}leaderboards/player/overall/all") as get:
if get.status != 200:
return await utils.answer(message, self.strings["error_message"])
top_list = list(reversed(chunks((await get.json())["data"],10))) # oh no, cringe code
string = f"{self.strings['top_list']}\n\n"
for player in reversed(top_list[0]):
string += f"╭ <b>{player['name']} 🎮\n"
string += f"╰─ </b> LvL: <code>{player['level']}</code> / XP: <code>{player['xp']}</code> / Time: <code>{player['minPlayed']}</code>\n"
await self.inline.form(text=string, message=message, reply_markup=chunks([{"text": str(i + 1), "callback": self.inline__toplayer, "args": (top_list, i),} for i in range(10)], 5), force_me=False)
async def inline__toplayer(self, call, top_list: list, num: int):
string = f"{self.strings['top_list']}\n\n"
for player in reversed(top_list[num]):
string += f"╭ <b>{player['name']} 🎮\n"
string += f"╰─ </b> LvL: <code>{player['level']}</code> / XP: <code>{player['xp']}</code> / Time: <code>{player['minPlayed']}</code>\n"
await call.edit(text=string, reply_markup=chunks([{"text": str(i + 1), "callback": self.inline__toplayer, "args": (top_list, i),} for i in range(10)], 5), force_me=False)
async def inline__get_class(self, call, class_, player):
await call.edit(
text=self.class_info_builder(class_),
reply_markup=[
{
"text": self.strings["btn_back"],
"callback": self.inline__back,
"args": [player],
}
],
)
async def inline__back(self, call, player):
await call.edit(
text=self.general_info_builder(player),
reply_markup=chunks(self.keyboard_class_builder(player), 3),
)

View File

@@ -0,0 +1,211 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
Copyleft 2022 t.me/CakesTwix
This program is free software; you can redistribute it and/or modify
"""
__version__ = (1, 2, 3)
# meta pic: https://img.icons8.com/bubbles/512/000000/youtube-play.png
# meta developer: @cakestwix_mods
# requires: yt_dlp aiohttp
# scope: hikka_min 1.1.11
# scope: hikka_only
import asyncio
import logging
import aiohttp
import os
from yt_dlp.utils import DownloadError
import yt_dlp
from telethon.tl.types import Message
from telethon import functions, types
from .. import loader, utils
from ..inline.types import InlineCall
logger = logging.getLogger(__name__)
def bytes2human(num, suffix="B"):
if not num:
return 0
for unit in ["", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"]:
if abs(num) < 1024.0:
return f"{num:3.1f}{unit}{suffix}"
num /= 1024.0
return f"{num:.1f}Yi{suffix}"
def progressbar(iteration: int, length: int) -> str:
percent = ("{0:." + str(1) + "f}").format(100 * (iteration / float(100)))
filledLength = int(length * iteration // 100)
return "" * filledLength + "" * (length - filledLength)
@loader.tds
class YouTubeMod(loader.Module):
"""Download YouTube videos with video and audio quality selection"""
strings = {
"name": "InlineYouTube",
"args": "🎞 <b>You need to specify link</b>",
"downloading": "🎞 <b>Downloading...</b>",
"not_found": "🎞 <b>Video not found...</b>",
"no_qualt":"No quality",
"format": "<b>Format</b>:",
"ext": "<b>Ext</b>:",
"video_codec": "<b>Video codec</b>:",
"audio": "Audio",
"file_size": "<b>File size</b>:",
"uploading": "🎞 <b>Uploading File...</b>",
"getting_info": " <b>Getting information about the video...</b>",
}
strings_ru = {
"name": "InlineYouTube",
"args": "🎞 <b>Вам необходимо указать ссылку</b>",
"downloading": "🎞 <b>Скачиваю...</b>",
"not_found": "🎞 <b>Видео не найдено...</b>",
"no_qualt":"Нету такого качества",
"format": "<b>Формат</b>:",
"ext": "<b>Расширение</b>:",
"video_codec": "<b>Видео кодек</b>:",
"audio": "Аудио",
"file_size": "<b>Размер</b>:",
"uploading": "🎞 <b>Загружаю...</b>",
"getting_info": " <bПолучаю информацию про видео...</b>",
}
async def client_ready(self, client, db):
self._db = db
self._client = client
@loader.unrestricted
async def ytcmd(self, message: Message):
"""[quality(144p/720p/etc)] <link> - Download video from youtube"""
args = utils.get_args(message)
await utils.answer(message, self.strings("getting_info"))
if not args:
return await utils.answer(message, self.strings("args"))
with yt_dlp.YoutubeDL() as ydl:
try:
info_dict = ydl.extract_info(
args[1] if len(args) >= 2 else args[0], download=False
)
except DownloadError as e:
return await utils.answer(message, e.msg)
formats_list = [{"text": f"{item['format_note']} ({item['video_ext']})", "callback": self.format_change, "args": (item, info_dict, message.chat.id, item["format_id"],),} for item in info_dict["formats"] if item["ext"] in ["mp4", "webm"] and item["vcodec"] != "none" and (len(args) >= 2 and args[0] == item["format_note"] or len(args) < 2)]
caption = f"<b>{info_dict['title']}</b>\n\n"
# caption += info_dict["description"]
await self.inline.form(text=caption if formats_list else self.strings["no_qualt"], photo=f"https://img.youtube.com/vi/{info_dict['id']}/0.jpg", message=message, reply_markup=utils.chunks(formats_list, 2))
async def format_change(
self,
call: InlineCall,
quality: dict,
info_dict: dict,
chat_id: int,
format_id: int):
string = f"{self.strings['format']} {quality['format']}\n"
string += f"{self.strings['ext']} {quality['ext']}\n"
string += f"{self.strings['video_codec']} {quality['vcodec']}\n"
string += f"{self.strings['file_size']} {bytes2human(quality['filesize'])}\n"
audio_keyboard = [{"text": f"{self.strings['audio']} ({audio['format_note']})", "callback": self.download, "args": (info_dict["id"], quality["ext"], quality["format_id"], audio["format_id"], chat_id,),} for audio in info_dict["formats"] if audio["ext"] == "m4a"]
audio_keyboard.append(
{
"text": "Back",
"callback": self.back,
"args": (
info_dict,
chat_id,
),
},
)
await call.edit(
text=string,
reply_markup=audio_keyboard,
)
async def back(self, call: InlineCall, info_dict: dict, chat_id: int):
formats_list = [{"text": f"{item['format_note']} ({item['video_ext']})", "callback": self.format_change, "args": (item, info_dict, chat_id, item["format_id"]),} for item in info_dict["formats"] if item["ext"] in ["mp4", "webm"] and item["vcodec"] != "none"]
caption = f"<b>{info_dict['title']}</b>\n\n"
# caption += info_dict["description"]
await call.edit(text=caption, reply_markup=utils.chunks(formats_list, 2))
async def download(
self,
call: InlineCall,
video_id: str,
ext: str,
video_format: int,
audio_format: int,
chat_id: int,
):
meta = {}
def download():
nonlocal meta
with yt_dlp.YoutubeDL(
{
"format": "{}+{}".format(str(video_format), str(audio_format)),
"outtmpl": "%(resolution)s.%(id)s.%(ext)s",
}
) as yd:
meta = yd.extract_info(
"https://www.youtube.com/watch?v=" + video_id, download=False
)
yd.download("https://www.youtube.com/watch?v=" + video_id)
await call.edit(
text=f"{self.strings['downloading']}",
)
await utils.run_sync(download)
await call.edit(
text=f"{self.strings['uploading']}",
)
# Download thumb for video
async with aiohttp.ClientSession() as session:
async with session.get(f"https://img.youtube.com/vi/{meta['id']}/0.jpg") as resp:
with open(meta['id'] + ".jpg", 'wb') as fd:
async for chunk in resp.content.iter_chunked(512):
fd.write(chunk)
await self._client.send_file(
chat_id,
"{0}x{1}.{2}.{3}".format(
(meta["width"]),
(meta["height"]),
(meta["id"]),
(meta["ext"].replace("webm", "mkv")),
),
supports_streaming=True,
thumb=meta["id"] + ".jpg"
)
os.remove(
"{0}x{1}.{2}.{3}".format(
(meta["width"]),
(meta["height"]),
(meta["id"]),
(meta["ext"].replace("webm", "mkv")),
)
)
os.remove(meta["id"] + ".jpg")
await call.delete()

View File

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

View File

@@ -0,0 +1,5 @@
# Friendly Telegram / GeekTG Modules
Channel - https://t.me/cakestwix_mods
Author - @CakesTwix

View File

@@ -0,0 +1,71 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
Copyleft 2022 t.me/CakesTwix
This program is free software; you can redistribute it and/or modify
"""
__version__ = (1, 0, 0)
# requires: aiohttp
# meta pic: https://www.pngall.com/wp-content/uploads/12/Avatar-Transparent.png
# meta developer: @cakestwix_mods
import logging
from .. import loader, utils
import aiohttp
logger = logging.getLogger(__name__)
@loader.tds
class RandomPeopleMod(loader.Module):
"""Create your new identity"""
strings = {
"name": "RandomPeople",
"id":"Id",
"uuid":"UUID",
"firstname":"Firstname",
"lastname":"Lastname",
"username":"Username",
"password":"Password",
"email":"Email",
"ip":"IP",
"macAddress":"MAC-address",
"website":"Website",
"image":"Image",
}
strings_ru = {
"name": "RandomPeople",
"id":"Id",
"uuid":"UUID",
"firstname":"Имя",
"lastname":"Фамилия",
"username":"Юзернейм",
"password":"Пароль",
"email":"Почта",
"ip":"IP",
"macAddress":"MAC-адрес",
"website":"Сайт",
"image":"Фото",
}
async def prandomcmd(self, message):
"""Get random people"""
async with aiohttp.ClientSession() as session:
async with session.get("https://fakerapi.it/api/v1/users?_quantity=1") as get:
b = (await get.json())["data"][0]
await session.close()
string = "".join(f"<b>{self.strings[key]}</b>: <code>{val}</code>\n" for val, key in zip(b.values(), b.keys()))
await utils.answer(message, string)

View File

@@ -0,0 +1,119 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
Copyleft 2022 t.me/CakesTwix
This program is free software; you can redistribute it and/or modify
"""
__version__ = (1, 1, 1)
# requires: torch
# meta pic: https://cdn.pixabay.com/photo/2017/07/09/20/48/speaker-2488096_1280.png
# meta developer: @cakestwix_mods
# scope: hikka_only
import os
import re
import torch
import logging
from .. import loader, utils
import aiohttp
logger = logging.getLogger(__name__)
device = torch.device("cpu")
torch.set_num_threads(4)
@loader.tds
class SileroMod(loader.Module):
"""Silero Models: pre-trained speech-to-text, text-to-speech and text-enhancement models made embarrassingly simple"""
strings = {
"name": "Silero",
"cfg_as_audio_note": "Send audio as a voice message",
"cfg_rate": "Sound frequency",
"no_avx2": "Your server does not support AVX2 instructions.",
}
strings_ru = {
"name": "Silero",
"cfg_as_audio_note": "Отправлять аудио как голосовые сообщения",
"cfg_rate": "Частота звука",
"no_avx2": "Твой сервер не поддерживает AVX2 инструкции",
}
def __init__(self):
self.config = loader.ModuleConfig(
"CONFIG_AS_AUDIO_NOTE",
True,
lambda: self.strings("cfg_as_audio_note"),
"CONFIG_RATE",
48000,
lambda: self.strings("cfg_rate"),
)
async def client_ready(self, client, db) -> None:
with open("/proc/cpuinfo") as f:
if 'avx2' not in f.read():
raise loader.LoadError(self.strings["no_avx2"])
if not os.path.isfile(os.path.abspath(os.getcwd()) + "/assets/model.pt"):
torch.hub.download_url_to_file(
"https://models.silero.ai/models/tts/ru/ru_v3.pt", "assets/model.pt"
)
self.model = torch.package.PackageImporter("assets/model.pt").load_pickle(
"tts_models", "model"
)
self.model.to(device)
async def send_audio(self, text: str, speaker: str, message):
audio_paths = self.model.save_wav(
text=text, speaker=speaker, sample_rate=self.config["CONFIG_RATE"]
)
with open(audio_paths, "rb") as audio_file:
content = audio_file.read()
audio_file.seek(0)
await self._client.send_file(
message.chat.id,
audio_file,
voice_note=self.config["CONFIG_AS_AUDIO_NOTE"],
reply_to=await message.get_reply_message()
)
async def sxeniacmd(self, message):
"""From text to sound (xenia)"""
if args := utils.get_args_raw(message):
await message.delete()
await self.send_audio(args, "xenia", message)
async def saidarcmd(self, message):
"""From text to sound (aidar)"""
if args := utils.get_args_raw(message):
await message.delete()
await self.send_audio(args, "aidar", message)
async def sbayacmd(self, message):
"""From text to sound (baya)"""
if args := utils.get_args_raw(message):
await message.delete()
await self.send_audio(args, "baya", message)
async def skseniyacmd(self, message):
"""From text to sound (kseniya)"""
if args := utils.get_args_raw(message):
await message.delete()
await self.send_audio(args, "kseniya", message)
async def srandomcmd(self, message):
"""From text to sound (random)"""
if args := utils.get_args_raw(message):
await message.delete()
await self.send_audio(args, "random", message)

View File

@@ -0,0 +1,106 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
Copyleft 2022 t.me/CakesTwix
This program is free software; you can redistribute it and/or modify
"""
__version__ = (1, 0, 0)
# meta developer: @cakestwix_mods
# meta pic: https://img.icons8.com/officel/16/000000/broken-link.png
from .. import loader
import re
import logging
from telethon.tl.patched import Message
logger = logging.getLogger(__name__)
class NoLinksMod(loader.Module):
"""A simple link cleaner from your chats"""
strings = {"name": "SimpleNoLinks", "settings": "Setting for this chat", "add": "Add", "remove": "Remove"}
strings_ru = {"name": "SimpleNoLinks", "settings": "Настройка для данного чата", "add": "Добавить", "remove": "Убрать"}
async def linkcmd(self, message):
"""Configuration for chat"""
await self.inline.form(
message=message,
text=self.strings["settings"],
reply_markup=[
{
"text": self.strings["add"],
"callback": self.chat__callback,
"args": (
True,
message.chat.id,
),
}
]
if message.chat.id not in self.chats
else [
{
"text": self.strings["remove"],
"callback": self.chat__callback,
"args": (
False,
message.chat.id,
),
}
],
)
async def client_ready(self, client, db) -> None:
self._db = db
self._client = client
None if self._db.get(self.strings["name"], "chats") else self._db.set(
self.strings["name"], "chats", []
)
self.chats = self._db.get(self.strings["name"], "chats")
async def chat__callback(self, call, type_, id_):
if type_:
self.chats.append(id_)
else:
self.chats.remove(id_)
self._db.set(self.strings["name"], "chats", self.chats)
await call.edit(
text=self.strings["settings"],
reply_markup=[
{
"text": self.strings["add"],
"callback": self.chat__callback,
"args": (
True,
id_,
),
}
]
if id_ not in self.chats
else [
{
"text": self.strings["remove"],
"callback": self.chat__callback,
"args": (
False,
id_,
),
}
],
)
async def watcher(self, message):
if getattr(message, "sender_id", None) != self._client._tg_id and bool(
re.findall(
r"""(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))""",
message.text,
)
and message.chat.id in self.chats
):
await message.delete()

View File

@@ -0,0 +1,336 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
Copyleft 2022 t.me/CakesTwix
This program is free software; you can redistribute it and/or modify
"""
__version__ = (1, 0, 1)
# requires: aiohttp
# scope: inline
# scope: geektg_only
# scope: geektg_min 3.1.15
# meta pic: https://image.winudf.com/v2/image/cnUucmFkaWF0aW9ueC5hbmlsaWJyaWEuYXBwX2ljb25fMTUyODYyNzQ2NV8wMjY/icon.png?w=&fakeurl=1
# meta developer: @cakestwix_mods
from .. import loader, main
from ..inline import GeekInlineQuery, rand
from aiogram.types import InlineQueryResultPhoto, CallbackQuery
import aiohttp
import logging
from requests import post
import datetime
logger = logging.getLogger(__name__)
@loader.tds
class AniLibriaMod(loader.Module):
"""A non-profit project for the dubbing and adaptation of foreign TV series, cartoons and anime"""
strings = {
"name": "AniLibria",
"cfg_mail": "Your mail from anilibria.tv",
"cfg_pass": "Your password from anilibria.tv",
"announce": "<b>Анонс</b> :",
"status": "<b>Статус</b> :",
"type": "<b>Тип</b> :",
"genres": "<b>Жанры</b> :",
"favorite": "<b>Избранное &lt;3</b> :", # &lt; == <
"season": "<b>Сезон</b> :",
"inline": "Взаимодействие с аниме {}",
}
link = "https://anilibria.tv"
api = "https://api.anilibria.tv/v2/"
getFavorites_api = (
"https://api.anilibria.tv/v2/getFavorites?session={}&limit=999&filter=id"
)
weekdays = ["ПН", "ВТ", "СР", "ЧТ", "ПТ", "СБ", "ВС"]
def __init__(self):
self.config = loader.ModuleConfig(
"CONFIG_MAIL",
None,
lambda m: self.strings("cfg_mail", m),
"CONFIG_PASS",
None,
lambda m: self.strings("cfg_pass", m),
)
# Try login and get cookies for some methods
self.logined = False
if (
self.config["CONFIG_MAIL"] is not None
and self.config["CONFIG_PASS"] is not None
):
self.login = post(
f"{self.link}/public/login.php",
data={
"mail": self.config["CONFIG_MAIL"],
"passwd": self.config["CONFIG_PASS"],
},
)
if self.login.cookies.values() != []:
self.logined = True
self.cookies = self.login.cookies.values()[0]
async def client_ready(self, client, db) -> None:
self._client = client
@loader.unrestricted
@loader.ratelimit
async def arandomcmd(self, message) -> None:
"""Возвращает случайный тайтл из базы"""
async with aiohttp.ClientSession() as session:
async with session.get(f"{self.api}getRandomTitle") as get:
anime_title = await get.json()
await session.close()
text = f"{anime_title['names']['ru']} | {anime_title['names']['en']} \n"
text += f"{self.strings['status']} {anime_title['status']['string']}\n\n"
text += f"{self.strings['type']} {anime_title['type']['full_string']}\n"
text += f"{self.strings['season']} {anime_title['season']['string']} {anime_title['season']['year']}\n"
text += f"{self.strings['genres']} {' '.join(anime_title['genres'])}\n\n"
# text += f"<code>{anime_title['description']}</code>\n\n"
text += f"{self.strings['favorite']} {anime_title['in_favorites']}"
kb = [
[
{
"text": "Ссылка",
"url": f"https://anilibria.tv/release/{anime_title['code']}.html",
}
]
]
if self.logined:
async with aiohttp.ClientSession() as session:
async with session.get(
self.getFavorites_api.format(self.cookies)
) as get:
favorite_list = await get.json()
await session.close()
ids_favorite = [_id["id"] for _id in favorite_list]
if anime_title["id"] in ids_favorite:
kb.append(
[
{
"text": "Убрать из избранного",
"callback": self.inline__favorite,
"args": [anime_title["id"], "delFavorite"],
}
]
)
else:
kb.append(
[
{
"text": "Добавить в избранное",
"callback": self.inline__favorite,
"args": [anime_title["id"], "addFavorite"],
}
]
)
kb.extend(
[
{
"text": f"{torrent['quality']['string']}",
"url": f"https://anilibria.tv/{torrent['url']}",
}
]
for torrent in anime_title["torrents"]["list"]
)
kb.append([{"text": "🚫 Закрыть", "callback": self.inline__close}])
await message.client.send_file(
message.chat_id,
self.link + anime_title["posters"]["original"]["url"],
caption=text,
)
await self.inline.form(
self.strings["inline"].format(anime_title["names"]["ru"]),
message=message,
reply_markup=kb,
always_allow=self._client.dispatcher.security._owner,
)
async def aschedulecmd(self, message) -> None:
"""
Получить список последних обновлений тайтлов
"""
selected_weekday = datetime.datetime.weekday(datetime.datetime.now())
async with aiohttp.ClientSession() as session:
async with session.get(f"{self.api}getSchedule") as get:
schedule_list = await get.json()
await session.close()
kb = [[]]
for day in schedule_list:
kb[0].append(
{
"text": f"[{self.weekdays[day['day']]}]"
if day["day"] == selected_weekday
else self.weekdays[day["day"]], # With [] if current weekday
"callback": self.inline__update_schedule,
"args": [day["day"]], # Number of the day
}
)
if day["day"] == selected_weekday:
text = "".join(
f"<b>{new_anime['names']['ru']}</b>\n" for new_anime in day["list"]
)
await self.inline.form(
"Актуальное расписание Либрии\n" + text,
message=message,
reply_markup=kb,
always_allow=self._client.dispatcher.security._owner,
)
async def asearch_inline_handler(self, query: GeekInlineQuery) -> None:
"""
Возвращает список найденных по названию тайтлов
"""
text = query.args
if not text:
return
async with aiohttp.ClientSession() as session:
async with session.get(
self.api + f"searchTitles?search={text}&limit=10"
) as get:
search_list = await get.json()
await session.close()
inline_query = []
for anime in search_list:
text = f"{anime['names']['ru']} | {anime['names']['en']} \n"
text += f"{self.strings['status']} {anime['status']['string']}\n\n"
text += f"{self.strings['type']} {anime['type']['full_string']}\n"
text += f"{self.strings['season']} {anime['season']['string']} {anime['season']['year']}\n"
text += f"{self.strings['genres']} {' '.join(anime['genres'])}\n\n"
# text += f"<code>{anime['description']}</code>\n\n"
text += f"{self.strings['favorite']} {anime['in_favorites']}"
inline_query.append(
InlineQueryResultPhoto(
id=rand(20),
title=anime["names"]["ru"],
description=anime["type"]["full_string"],
caption=text,
thumb_url=f"{self.link}{anime['posters']['small']['url']}", # noqa
photo_url=f"{self.link}{anime['posters']['original']['url']}",
parse_mode="html",
)
)
await query.answer(
inline_query,
cache_time=0,
)
async def inline__close(self, call: CallbackQuery) -> None:
await call.delete()
async def inline__favorite(
self, call: CallbackQuery, _id: int, method: str
) -> None:
_id = str(_id)
async with aiohttp.ClientSession() as session:
# get anime by id for update buttons
async with session.get(f"{self.api}getTitle?id={_id}") as get:
anime_title = await get.json()
kb = [
[
{
"text": "Ссылка",
"url": f"https://anilibria.tv/release/{anime_title['code']}.html",
}
]
]
if method == "addFavorite":
async with session.put(
(self.api + f"{method}?session={self.cookies}&title_id={_id}")
) as get:
kb.append(
[
{
"text": "Убрать из избранного",
"callback": self.inline__favorite,
"args": [anime_title["id"], "delFavorite"],
}
]
)
else: # delFavorite
async with session.delete(
(self.api + f"{method}?session={self.cookies}&title_id={_id}")
) as get:
kb.append(
[
{
"text": "Добавить в избранное",
"callback": self.inline__favorite,
"args": [anime_title["id"], "addFavorite"],
}
]
)
kb.extend(
[
{
"text": f"{torrent['quality']['string']}",
"url": f"https://anilibria.tv/{torrent['url']}",
}
]
for torrent in anime_title["torrents"]["list"]
)
kb.append([{"text": "🚫 Закрыть", "callback": self.inline__close}])
await session.close()
await call.edit(
text="Взаимодействие с аниме " + anime_title["names"]["ru"],
reply_markup=kb,
)
async def inline__update_schedule(
self, call: CallbackQuery, day_inline: int
) -> None:
async with aiohttp.ClientSession() as session:
async with session.get(f"{self.api}getSchedule") as get:
schedule_list = await get.json()
await session.close()
kb = [[]]
for day in schedule_list:
kb[0].append(
{
"text": f"[{self.weekdays[day['day']]}]"
if day["day"] == day_inline
else self.weekdays[day["day"]], # With [] if current weekday
"callback": self.inline__update_schedule,
"args": [day["day"]], # Number of the day
}
)
if day["day"] == day_inline:
text = "".join(
f"<b>{new_anime['names']['ru']}</b>\n" for new_anime in day["list"]
)
await call.edit(
text="Актуальное расписание Либрии\n" + text,
reply_markup=kb,
)

View File

@@ -0,0 +1,81 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
Copyleft 2022 t.me/CakesTwix
This program is free software; you can redistribute it and/or modify
"""
__version__ = (1, 0, 1)
# meta pic: https://www.freeiconspng.com/uploads/facebook-circle-heart-love-png-4.png
# meta developer: @cakestwix_mods
import logging
import asyncio
from .. import loader, utils
logger = logging.getLogger(__name__)
@loader.tds
class CompliMod(loader.Module):
"""Send a compliment to a person"""
strings = {
"name": "Compliments",
"cfg_emoji":"Emoji at the end of the message",
"compliments_women":"умная хорошая милая добрая лучшая заботливая",
"compliments_man":"умный хороший милый добрый лучший заботливый",
}
strings_ru = {
"cfg_emoji":"Эмодзи в конце сообщения",
"compliments_women":"умная хорошая милая добрая лучшая заботливая",
"compliments_man":"умный хороший милый добрый лучший заботливый"
}
def __init__(self):
self.name = self.strings["name"]
self.config = loader.ModuleConfig(
"emoji",
"",
lambda: self.strings("cfg_emoji"),
)
self.gender = "women"
self.better = "Самая"
self.delay = 2
@loader.unrestricted
@loader.ratelimit
async def complicmd(self, message):
"""
Send a person compliments
.compli [delay] [man/women]
"""
if args := len(utils.get_args(message)) == 2 and utils.get_args(message):
try:
self.delay = int(args[0])
except:
pass
if "man" in args[1]:
self.gender = args[1]
self.better = "Самый"
elif args := utils.get_args(message):
try:
self.delay = int(args[0])
except:
if "man" in args[0]:
self.gender = args[0]
self.better = "Самый"
for compl in self.strings["compliments_" + self.gender].split():
message = await utils.answer(message, f"{self.better} {compl} {self.config['emoji']}")
await asyncio.sleep(self.delay)

View File

@@ -0,0 +1,266 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
Copyleft 2022 t.me/CakesTwix
This program is free software; you can redistribute it and/or modify
"""
__version__ = (1, 2, 0)
# requires: requests bs4 lxml
# meta pic: https://styles.redditmedia.com/t5_3htpk/styles/communityIcon_vlbulj1gn8l11.png
# meta developer: @cakestwix_mods
import logging
from requests import get
from .. import loader, utils
import asyncio
import aiohttp
from bs4 import BeautifulSoup
logger = logging.getLogger(__name__)
@loader.unrestricted
@loader.ratelimit
@loader.tds
class CustomRomsMod(loader.Module):
"""Miscellaneous stuff for custom ROMs"""
strings = {
"name": "ROMs",
"download": "⬇️ <b>Download</b> :",
"no_device": "🚫 <b>No device.<b>",
"no_codename": "🚫 <b>Pls codename((<b>",
"general_error": "🚫 <b>Oh no, cringe, error<b>",
}
strings_ru = {
"download": "⬇️ <b>Скачать</b> :",
"no_device": "🚫 <b>Нет устройства.<b>",
"no_codename": "🚫 <b>Пжл коднейм((<b>",
"general_error": "🚫 <b>❗️Ашибка❗️<b>",
}
twrp_api = "https://dl.twrp.me/"
# ROMs
@loader.unrestricted
@loader.ratelimit
async def sakuracmd(self, message):
"""Project Sakura"""
args = utils.get_args(message)
if args:
device = args[0].lower()
async with aiohttp.ClientSession() as session:
async with session.get(
"https://raw.githubusercontent.com/ProjectSakura/OTA/11/devices.json"
) as get:
data = await get.json()
await session.close()
for item in data:
if item["codename"] == device:
releases = f"Latest Project Sakura for {item['name']} ({item['codename']}) \n"
releases += f"👤 by {item['maintainer_name']} \n"
releases += f"{self.strings['download']} (https://projectsakura.xyz/download/#/{item['codename']}) \n"
await utils.answer(message, releases)
return
await utils.answer(message, f"{self.strings['no_device']}")
await asyncio.sleep(5)
await message.delete()
else:
await utils.answer(message, f"{self.strings['no_codename']}")
await asyncio.sleep(5)
await message.delete()
@loader.unrestricted
@loader.ratelimit
async def dotoscmd(self, message):
"""DotOS"""
args = utils.get_args(message)
if args:
device = args[0].lower()
async with aiohttp.ClientSession() as session:
async with session.get(
"https://api.droidontime.com/api/ota/{}".format(device)
) as get:
if get.ok:
data = await get.json()
else:
await utils.answer(message, f"{self.strings['no_device']}")
await asyncio.sleep(5)
await message.delete()
await session.close()
releases = f"<b>Latest DotOS for {data['brandName']} {data['deviceName']}</b> (<code>{data['codename']}</code>) \n"
releases += f"👤 : {data['maintainerInfo']['name']} \n"
releases += f"🆚 : {data['latestVersion']} \n"
releases += f"{self.strings['download']} "
releases += f"<a href={data['releases'][0]['url']}>{data['releases'][1]['type'].capitalize()}<a/>"
releases += f" / <a href={data['releases'][1]['url']}>{data['releases'][1]['type'].capitalize()}<a/>"
await utils.answer(message, releases)
else:
await utils.answer(message, f"{self.strings['no_codename']}")
await asyncio.sleep(5)
await message.delete()
@loader.unrestricted
@loader.ratelimit
async def aexcmd(self, message):
"""AOSP Extended"""
args = utils.get_args(message)
if args:
device_codename = args[0].lower()
async with aiohttp.ClientSession() as session:
async with session.get("https://api.aospextended.com/devices/") as get:
devices_json = await get.json()
for device in devices_json:
if device["codename"] == device_codename:
releases = f"Latest AOSP Extended for {device['brand']} {device['name']} ({device['codename']}) \n"
# releases += f"👤 by {device['maintainer_name']} \n"
releases += f"{self.strings['download']}"
for version in device["supported_versions"]:
async with session.get(
"https://api.aospextended.com/builds/{}/{}".format(
device_codename, version["version_code"]
)
) as get:
version_json = await get.json()
if "error" not in version_json:
releases += f" <a href={version_json[0]['download_link']}>{version['version_name']}</a> |"
await session.close()
await utils.answer(message, releases)
return
await utils.answer(message, f"{self.strings['no_device']}")
await asyncio.sleep(5)
await message.delete()
# Recovery
@loader.unrestricted
@loader.ratelimit
async def twrpcmd(self, message):
"""TWRP Devices"""
args = utils.get_args(message)
if args:
device = args[0].lower()
url = get(f"{self.twrp_api}{device}/")
if url.status_code == 404:
reply = f"`Couldn't find twrp downloads for {device}!`\n"
await utils.answer(message, reply)
await asyncio.sleep(5)
await message.delete()
return
page = BeautifulSoup(url.content, "lxml")
download = page.find("table").find_all("tr")
reply = f"『 Team Win Recovery Project for {device}: 』\n"
for item in download:
dl_link = f"{self.twrp_api}{item.find('a')['href']}"
dl_file = item.find("td").text
size = item.find("span", {"class": "filesize"}).text
reply += f"⦁ <a href={dl_link}>{dl_file}</a> - <tt>{size}</tt>\n"
await utils.answer(message, reply)
@loader.unrestricted
@loader.ratelimit
async def shrpcmd(self, message):
"""SHRP Devices"""
args = utils.get_args(message)
if args:
device = args[0].lower()
data = get(
"https://raw.githubusercontent.com/SHRP-Devices/device_data/master/deviceData.json"
).json()
for item in data[:-1]:
if item["codeName"] == device:
releases = f"『 SkyHawk Recovery Project for {item['model']} ({device}): 』\n"
releases += f"👤 <b>by<b> {item['maintainer']} \n"
releases += f" <b>Version<b> : {item['currentVersion']} \n"
releases += f"{self.strings['download']} : <a href={item['latestBuild']}>SourceForge</a> \n"
await utils.answer(message, releases)
return
await utils.answer(message, f"{self.strings['no_device']}")
await asyncio.sleep(5)
await message.delete()
@loader.unrestricted
@loader.ratelimit
async def pbrpcmd(self, message):
"""PBRP Devices"""
args = utils.get_args(message)
if args:
device = args[0].lower()
async with aiohttp.ClientSession() as session:
async with session.get(
f"https://pitchblackrecovery.com/{device}/"
) as get:
pbrp_page = await get.text()
await session.close()
page = BeautifulSoup(pbrp_page, "lxml")
status_error = page.find("h1", class_="error-code")
if status_error is not None:
return # No device
main_info = page.find_all(
"h3", class_="elementor-heading-title elementor-size-default"
)
download_info = page.find(
"section",
class_="has_eae_slider elementor-section elementor-inner-section elementor-element elementor-element-714ebe14 elementor-section-boxed elementor-section-height-default elementor-section-height-default",
)
version = main_info[0].text
date = main_info[2].text
status = main_info[4].text
maintainer = main_info[6].text
file_size = download_info.find_all(
"div", class_="elementor-text-editor elementor-clearfix"
)[1].text[10:]
md5 = download_info.find_all(
"div", class_="elementor-text-editor elementor-clearfix"
)[2].text[4:]
sourceforge = download_info.find_all(
"a", class_="elementor-button-link elementor-button elementor-size-md"
)[0]["href"]
github = download_info.find_all(
"a", class_="elementor-button-link elementor-button elementor-size-md"
)[1]["href"]
releases = f"『 Pitch Black Recovery Project for ({device}): 』\n"
releases += f"👤 <b>by</b> {maintainer} \n"
releases += f" <b>Status</b> : {status} \n"
releases += f" <b>Version</b> : {version} \n"
releases += f" <b>Date</b> : {date} \n"
releases += f" <b>MD5</b> : {md5} \n"
releases += f" <b>Size</b> : {file_size} \n"
releases += f"{self.strings['download']} : <a href={sourceforge}>SourceForge</a> | <a href={github}>GitHub</a>\n"
await utils.answer(message, releases)
# Other
@loader.unrestricted
@loader.ratelimit
async def magiskcmd(self, message):
"""Magisk by topjohnwu"""
magisk_repo = "https://raw.githubusercontent.com/topjohnwu/magisk-files/"
magisk_dict = {
"𝗦𝘁𝗮𝗯𝗹𝗲": magisk_repo + "master/stable.json",
"𝗕𝗲𝘁𝗮": magisk_repo + "master/beta.json",
"𝗖𝗮𝗻𝗮𝗿𝘆": magisk_repo + "master/canary.json",
}
releases = "<code><i>𝗟𝗮𝘁𝗲𝘀𝘁 𝗠𝗮𝗴𝗶𝘀𝗸 𝗥𝗲𝗹𝗲𝗮𝘀𝗲:</i></code>\n\n"
for name, release_url in magisk_dict.items():
data = get(release_url).json()
releases += f'{name}: <a href={data["magisk"]["link"]}>APK v{data["magisk"]["version"]}</a> | <a href={data["magisk"]["note"]}>Changelog</a>\n'
await utils.answer(message, releases)

View File

@@ -0,0 +1,591 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
Copyleft 2022 t.me/CakesTwix
This program is free software; you can redistribute it and/or modify
"""
__version__ = (1, 4, 1)
# requires: requests bs4 lxml
# scope: inline
# scope: geektg_only
# scope: geektg_min 3.1.15
# meta pic: https://styles.redditmedia.com/t5_3htpk/styles/communityIcon_vlbulj1gn8l11.png
# meta developer: @cakestwix_mods
import asyncio
import logging
import aiohttp
from aiogram.types import (
InlineKeyboardButton,
InlineKeyboardMarkup,
InlineQueryResultArticle,
InputTextMessageContent,
)
from aiogram.utils.markdown import hlink
from bs4 import BeautifulSoup
from requests import get
from .. import loader, utils
from ..inline import GeekInlineQuery, rand
logger = logging.getLogger(__name__)
@loader.unrestricted
@loader.ratelimit
@loader.tds
class CustomRomsMod(loader.Module):
"""Miscellaneous stuff for custom ROMs"""
strings = {
"name": "InlineROMs",
"download": "⬇️ <b>Download</b> :",
"no_device": "<b>No device.</b>",
"no_device_info": " Please check the correct codename or availability of the site",
"no_codename": "<b>Pls codename((</b>",
"write_codename": "Write the code name of your device",
"latest_releases": " Latest {} releases",
"latest_releases_no_format": " Latest ROM releases",
"latest_releases_device": " Latest {} {} releases for {}",
"gapps_version": "GApps version",
"vanilla_version": "Vanilla version",
"general_info": "General info about {} builds",
"general_info_description": " Maintainer, latest version, etc",
"not_updating": "❌ : There will be no updates at this time",
"updated": "✅ : Updated",
"magisk_latest": "𝗟𝗮𝘁𝗲𝘀𝘁 𝗠𝗮𝗴𝗶𝘀𝗸 𝗥𝗲𝗹𝗲𝗮𝘀𝗲𝘀:",
"app_by": "👤 by {}",
"Stable": "𝗦𝘁𝗮𝗯𝗹𝗲",
"Beta": "𝗕𝗲𝘁𝗮",
"Canary": "𝗖𝗮𝗻𝗮𝗿𝘆",
"md5": "<b>MD5: </b>",
"count": "<b>Downloads count: </b>",
"customAvbSupported": "<b>Custom Avb Supported:</b> ",
}
strings_ru = {
"download": "⬇️ <b>Скачать</b> :",
"no_device": "<b>Нет устройства.</b>",
"no_device_info": " Пожалуйста, проверьте правильное кодовое имя или доступность сайта",
"no_codename": "<b>Пжл коднейм((</b>",
"write_codename": "Напишите кодовое имя вашего устройства",
"latest_releases": " Последние {} релизы",
"latest_releases_no_format": " Последние релизы ПЗУ",
"latest_releases_device": " Последние релизы {} {} для {}",
"gapps_version": "GApps version",
"vanilla_version": "Ванила",
"general_info": "Общая информация о сборках {}",
"general_info_description": " Сопровождающий, последняя версия и т. д.",
"not_updating": "❌ : На данный момент обновлений не будет",
"updated": "✅ : Обновлено",
"magisk_latest": "<b>Последние релизы Magisk</b>:",
"app_by": "👤 от {}",
"Stable": "⦁ <b>Cтабильный</b>",
"Beta": "⦁ <b>Бета</b>",
"Canary": "⦁ <b>Канарейка</b>",
"md5": "<b>MD5: </b>",
"count": "<b>Количество загрузок: </b>",
"customAvbSupported": "<b>Поддерживается пользовательский Avb:</b> ",
}
magisk_dict = {
"topjohnwu": [
{
"Stable": "master/stable.json",
"Beta": "master/stable.json",
"Canary": "master/stable.json",
},
"https://raw.githubusercontent.com/topjohnwu/magisk-files/",
],
"vvb2060": [
{"Stable": "master/lite.json", "Canary": "alpha/alpha.json"},
"https://raw.githubusercontent.com/vvb2060/magisk_files/",
],
"TheHitMan7": [
{"Stable": "stable.json", "Beta": "beta.json", "Canary": "canary.json"},
"https://raw.githubusercontent.com/TheHitMan7/Magisk-Files/master/configs/",
],
}
twrp_api = "https://dl.twrp.me/"
no_codename = [
InlineQueryResultArticle(
id=rand(20),
title=strings["write_codename"],
description=strings["latest_releases_no_format"],
input_message_content=InputTextMessageContent(
strings["no_codename"], "HTML", disable_web_page_preview=True
),
thumb_url="https://img.icons8.com/android/128/26e07f/android.png",
thumb_width=128,
thumb_height=128,
)
]
# ROMs
@loader.unrestricted
@loader.ratelimit
async def sakuracmd(self, message):
"""Project Sakura"""
if args := utils.get_args(message):
device = args[0].lower()
data = get(
"https://raw.githubusercontent.com/ProjectSakura/OTA/11/devices.json"
).json()
for item in data:
if item["codename"] == device:
releases = f"Latest Project Sakura for {item['name']} ({item['codename']}) \n"
releases += f"👤 by {item['maintainer_name']} \n"
releases += f"{self.strings['download']} (https://projectsakura.xyz/download/#/{item['codename']}) \n"
await utils.answer(message, releases)
return
await utils.answer(message, f"{self.strings['no_device']}")
else:
await utils.answer(message, f"{self.strings['no_codename']}")
await asyncio.sleep(5)
await message.delete()
@loader.unrestricted
@loader.ratelimit
async def dotoscmd(self, message):
"""DotOS"""
if args := utils.get_args(message):
device = args[0].lower()
async with aiohttp.ClientSession() as session:
async with session.get(
f"https://api.droidontime.com/api/ota/{device}"
) as get:
if get.ok:
data = await get.json()
else:
await utils.answer(message, f"{self.strings['no_device']}")
await asyncio.sleep(5)
await message.delete()
await session.close()
releases = f"<b>Latest DotOS for {data['brandName']} {data['deviceName']}</b> (<code>{data['codename']}</code>) \n"
releases += f"👤 : {data['maintainerInfo']['name']} \n"
releases += f"🆚 : {data['latestVersion']} \n"
releases += f"{self.strings['download']} "
releases += f"<a href={data['releases'][0]['url']}>{data['releases'][1]['type'].capitalize()}<a/>"
releases += f" / <a href={data['releases'][1]['url']}>{data['releases'][1]['type'].capitalize()}<a/>"
await utils.answer(message, releases)
else:
await utils.answer(message, f"{self.strings['no_codename']}")
await asyncio.sleep(5)
await message.delete()
# Recovery
@loader.unrestricted
@loader.ratelimit
async def twrpcmd(self, message):
"""TWRP Devices"""
if args := utils.get_args(message):
device = args[0].lower()
url = get(f"{self.twrp_api}{device}/")
if url.status_code == 404:
reply = f"`Couldn't find twrp downloads for {device}!`\n"
await utils.answer(message, reply)
await asyncio.sleep(5)
await message.delete()
return
page = BeautifulSoup(url.content, "lxml")
download = page.find("table").find_all("tr")
reply = f"『 Team Win Recovery Project for {device}: 』\n"
for item in download:
dl_link = f"{self.twrp_api}{item.find('a')['href']}"
dl_file = item.find("td").text
size = item.find("span", {"class": "filesize"}).text
reply += f"⦁ <a href={dl_link}>{dl_file}</a> - <tt>{size}</tt>\n"
await utils.answer(message, reply)
@loader.unrestricted
@loader.ratelimit
async def shrpcmd(self, message):
"""SHRP Devices"""
if args := utils.get_args(message):
device = args[0].lower()
data = get(
"https://raw.githubusercontent.com/SHRP-Devices/device_data/master/deviceData.json"
).json()
for item in data[:-1]:
if item["codeName"] == device:
releases = f"『 SkyHawk Recovery Project for {item['model']} ({device}): 』\n"
releases += f"👤 <b>by<b> {item['maintainer']} \n"
releases += f" <b>Version<b> : {item['currentVersion']} \n"
releases += f"{self.strings['download']} : <a href={item['latestBuild']}>SourceForge</a> \n"
await utils.answer(message, releases)
return
await utils.answer(message, f"{self.strings['no_device']}")
await asyncio.sleep(5)
await message.delete()
@loader.unrestricted
@loader.ratelimit
async def pbrpcmd(self, message):
"""PBRP Devices"""
if args := utils.get_args(message):
device = args[0].lower()
async with aiohttp.ClientSession() as session:
async with session.get(
f"https://pitchblackrecovery.com/{device}/"
) as get:
pbrp_page = await get.text()
await session.close()
page = BeautifulSoup(pbrp_page, "lxml")
status_error = page.find("h1", class_="error-code")
if status_error is not None:
return # No device
main_info = page.find_all(
"h3", class_="elementor-heading-title elementor-size-default"
)
download_info = page.find(
"section",
class_="has_eae_slider elementor-section elementor-inner-section elementor-element elementor-element-714ebe14 elementor-section-boxed elementor-section-height-default elementor-section-height-default",
)
version = main_info[0].text
date = main_info[2].text
status = main_info[4].text
maintainer = main_info[6].text
file_size = download_info.find_all(
"div", class_="elementor-text-editor elementor-clearfix"
)[1].text[10:]
md5 = download_info.find_all(
"div", class_="elementor-text-editor elementor-clearfix"
)[2].text[4:]
sourceforge = download_info.find_all(
"a", class_="elementor-button-link elementor-button elementor-size-md"
)[0]["href"]
github = download_info.find_all(
"a", class_="elementor-button-link elementor-button elementor-size-md"
)[1]["href"]
releases = f"『 Pitch Black Recovery Project for ({device}): 』\n"
releases += f"👤 <b>by</b> {maintainer} \n"
releases += f" <b>Status</b> : {status} \n"
releases += f" <b>Version</b> : {version} \n"
releases += f" <b>Date</b> : {date} \n"
releases += f" <b>MD5</b> : {md5} \n"
releases += f" <b>Size</b> : {file_size} \n"
releases += f"{self.strings['download']} : <a href={sourceforge}>SourceForge</a> | <a href={github}>GitHub</a>\n"
await utils.answer(message, releases)
# Other
@loader.unrestricted
@loader.ratelimit
async def magiskcmd(self, message):
"""Magisk by topjohnwu"""
magisk_repo = "https://raw.githubusercontent.com/topjohnwu/magisk-files/"
magisk_dict = {
"𝗦𝘁𝗮𝗯𝗹𝗲": magisk_repo + "master/stable.json",
"𝗕𝗲𝘁𝗮": magisk_repo + "master/beta.json",
"𝗖𝗮𝗻𝗮𝗿𝘆": magisk_repo + "master/canary.json",
}
releases = f"<code><i>{self.strings['magisk_latest']}</i></code>\n\n"
for name, release_url in magisk_dict.items():
data = get(release_url).json()
releases += f'{name}: <a href={data["magisk"]["link"]}>APK v{data["magisk"]["version"]}</a> | <a href={data["magisk"]["note"]}>Changelog</a>\n'
await utils.answer(message, releases)
# Inline commands
async def opengapps_inline_handler(self, query: GeekInlineQuery) -> None:
"""
OpenGApps (Inline)
@allow: all
"""
text = query.args
async with aiohttp.ClientSession() as session:
async with session.get("https://api.opengapps.org/list") as get:
opengapps_list = await get.json()
await session.close()
arch_dict = {}
version_text = "<b>Avilable versions</b> :\n"
for arch in opengapps_list["archs"]:
apis_list = [str(apis) for apis in opengapps_list["archs"][arch]["apis"]]
arch_dict[arch] = apis_list
version_text += f"<b>{arch}</b> : {', '.join(apis_list)}\n"
if not text:
await query.answer(
[
InlineQueryResultArticle(
id=rand(20),
title="Select android version for your device",
description=" For example : 10.0. Click for more versions",
input_message_content=InputTextMessageContent(
version_text, "HTML", disable_web_page_preview=True
),
thumb_url="https://img.icons8.com/android/128/26e07f/android.png",
thumb_width=128,
thumb_height=128,
)
],
cache_time=0,
)
return
if len(text.split()) == 1:
archs_inline = []
archs_photo = {
"arm": "https://img.icons8.com/android/128/26e07f/32bit.png",
"arm64": "https://img.icons8.com/android/128/26e07f/64bit.png",
"x86": "https://img.icons8.com/android/128/26e07f/x86.png",
"x86_64": "https://img.icons8.com/android/128/26e07f/x64.png",
}
for arch in opengapps_list["archs"]: # arm arm64 x86 etc
if text in arch_dict[arch]:
markup = InlineKeyboardMarkup(row_width=3)
for variant in opengapps_list["archs"][arch]["apis"][text][
"variants"
]: # pico nano etc
markup.insert(
InlineKeyboardButton(variant["name"], url=variant["zip"])
)
archs_inline.append(
InlineQueryResultArticle(
id=rand(20),
title=arch,
description=" Select arch for your device",
input_message_content=InputTextMessageContent(
f"OpenGApps for Android {text} {arch}",
"HTML",
disable_web_page_preview=True,
),
thumb_url=archs_photo[arch],
thumb_width=128,
thumb_height=128,
reply_markup=markup,
)
)
markup = None
await query.answer(archs_inline, cache_time=0)
# https://img.icons8.com/fluency/48/26e07f/android-os.png
async def aex_inline_handler(self, query: GeekInlineQuery) -> None:
"""
AOSP Extended (Inline)
@allow: all
"""
device_codename = query.args
if not device_codename:
await query.answer(self.no_codename, cache_time=0)
return
async with aiohttp.ClientSession() as session:
async with session.get("https://api.aospextended.com/devices/") as get:
devices_json = await get.json()
for device in devices_json:
if device["codename"] == device_codename:
inline_query = []
for version in device["supported_versions"]:
releases = f"Latest AOSP Extended for {device['brand']} {device['name']} ({device['codename']}) \n"
async with session.get(
f"https://api.aospextended.com/builds/{device_codename}/{version['version_code']}"
) as get:
version_json = await get.json()
if "error" not in version_json:
releases += f"{self.strings['app_by'].format(version['maintainer_name'])} \n"
releases += f"💬 {hlink('Telegram Chat', version['tg_link'])} | {hlink('XDA', version['xda_thread'])} | {hlink('XDA Maintainer', version['maintainer_url'])} \n"
releases += f"{self.strings['download']} {hlink(version_json[0]['file_name'], version_json[0]['download_link'])} \n\n"
releases += (
f"{self.strings['md5']}{version_json[0]['md5']} \n"
)
releases += f"{self.strings['count']}{version_json[0]['downloads_count']} \n"
releases += f"{self.strings['customAvbSupported']} {'Yes' if version_json[0]['isCustomAvbSupported'] else 'No'}"
inline_query.append(
InlineQueryResultArticle(
id=rand(50),
title=version["version_name"],
description=self.strings["app_by"].format(
version["maintainer_name"]
),
input_message_content=InputTextMessageContent(
releases,
"HTML",
disable_web_page_preview=True,
),
)
)
await session.close()
await query.answer(inline_query, cache_time=0)
async def dotos_inline_handler(self, query: GeekInlineQuery) -> None:
"""
DotOS (Inline)
@allow: all
"""
text = query.args
if not text:
await query.answer(self.no_codename, cache_time=0)
return
if len(text.split()) == 1:
device = text
async with aiohttp.ClientSession() as session:
async with session.get(
f"https://api.droidontime.com/api/ota/{device}"
) as get:
if get.ok:
data = await get.json()
else:
await query.answer(
[
InlineQueryResultArticle(
id=rand(20),
title=self.strings["no_device"],
description=self.strings["no_device_info"],
input_message_content=InputTextMessageContent(
self.strings["no_device_info"],
"HTML",
disable_web_page_preview=True,
),
thumb_url="https://img.icons8.com/android/128/fa314a/cancel-2.png",
thumb_width=128,
thumb_height=128,
)
],
cache_time=0,
)
await session.close()
return
await session.close()
vanilla_markup = InlineKeyboardMarkup(row_width=3)
gapps_markup = InlineKeyboardMarkup(row_width=3)
for releases in data["releases"]:
if releases["type"] == "vanilla":
vanilla_markup.insert(
InlineKeyboardButton(releases["version"], url=releases["url"])
)
else:
gapps_markup.insert(
InlineKeyboardButton(releases["version"], url=releases["url"])
)
about_info = f"<b>DotOS for {data['brandName']} {data['deviceName']}</b> (<code>{data['codename']}</code>) \n"
about_info += f"👤 : {hlink(data['maintainerInfo']['name'], data['maintainerInfo']['profileURL'])} \n"
about_info += f"🆚 : {data['latestVersion']} \n"
about_info += (
self.strings["not_updating"]
if data["discontinued"]
else self.strings["updated"]
)
about_info += f"\n🔗 : {hlink('XDA',data['links']['xda'])} / {hlink('Telegram',data['links']['telegram'])} \n"
await query.answer( # About, Vanilla, Gapps
[
InlineQueryResultArticle(
id=rand(20),
title=self.strings["general_info"].format("DotOS"),
description=self.strings["general_info_description"],
input_message_content=InputTextMessageContent(
about_info,
"HTML",
disable_web_page_preview=True,
),
thumb_url="https://img.icons8.com/android/128/26e07f/info.png",
thumb_width=128,
thumb_height=128,
),
InlineQueryResultArticle(
id=rand(20),
title=self.strings["vanilla_version"],
description=self.strings["latest_releases"].format("DotOS"),
input_message_content=InputTextMessageContent(
self.strings["latest_releases_device"].format(
"DotOS", "Vanilla", device
),
"HTML",
disable_web_page_preview=True,
),
thumb_url="https://img.icons8.com/android/128/26e07f/forward.png",
thumb_width=128,
thumb_height=128,
reply_markup=vanilla_markup,
),
InlineQueryResultArticle(
id=rand(20),
title=self.strings["gapps_version"],
description=self.strings["latest_releases"].format("DotOS"),
input_message_content=InputTextMessageContent(
self.strings["latest_releases_device"].format(
"DotOS", "GApps", device
),
"HTML",
disable_web_page_preview=True,
),
thumb_url="https://img.icons8.com/android/128/26e07f/forward.png",
thumb_width=128,
thumb_height=128,
reply_markup=gapps_markup,
),
],
cache_time=0,
)
async def magisk_inline_handler(self, query: GeekInlineQuery) -> None:
"""
Magisk (Inline)
@allow: all
"""
inline_query = []
latest_releases = f"<code><i>{self.strings['magisk_latest']}</i></code>\n\n"
for magisk_author in self.magisk_dict: # topjohnwu vvb2060
text_type = ""
for magisk_type in self.magisk_dict[magisk_author][
0
]: # List(Stable, Beta, etc) by author
base_url = self.magisk_dict[magisk_author][1]
async with aiohttp.ClientSession() as session:
async with session.get(
base_url + self.magisk_dict[magisk_author][0][magisk_type]
) as get:
data = await get.json(content_type=None)
text_type += f'{self.strings[magisk_type]}: {hlink("APK v" + data["magisk"]["version"], data["magisk"]["link"])} | {hlink("Changelog", data["magisk"]["note"])} \n'
text_type += f'\n{self.strings["app_by"].format(magisk_author)}'
inline_query.append(
InlineQueryResultArticle(
id=rand(20),
title=self.strings["magisk_latest"],
description=self.strings["app_by"].format(magisk_author),
input_message_content=InputTextMessageContent(
latest_releases + text_type,
"HTML",
disable_web_page_preview=True,
),
thumb_url="https://upload.wikimedia.org/wikipedia/commons/b/b8/Magisk_Logo.png",
thumb_width=128,
thumb_height=128,
)
)
await query.answer(inline_query, cache_time=0)

View File

@@ -0,0 +1,138 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
Copyleft 2022 t.me/CakesTwix
This program is free software; you can redistribute it and/or modify
"""
__version__ = (1, 1, 0)
# meta pic: https://forum.f-droid.org/uploads/default/original/2X/c/cfb2c14973c28415b0e5b5f7adef9c8288cd8609.png
# meta developer: @cakestwix_mods
# scope: hikka_only
# requires: httpx bs4
import logging
import httpx
from aiogram.types import (
InlineKeyboardButton,
InlineKeyboardMarkup,
InlineQueryResultArticle,
InputTextMessageContent,
)
from aiogram.utils.markdown import hlink
from bs4 import BeautifulSoup
from .. import loader, utils
from ..inline.types import InlineQuery
logger = logging.getLogger(__name__)
async def fdroid_search(search_app = "") -> dict:
fdroid_main = "https://apt.izzysoft.de/fdroid/index.php?repo=main" # FDroid
async with httpx.AsyncClient() as client:
html = (await client.post(fdroid_main, data={"limit": 50, "searchterm": search_app, "doFilter": "Go%21"})).content
soup = BeautifulSoup(html, "html.parser")
apps = []
html_apps = soup.find_all("div", class_="approw")
for app in html_apps:
buff = {"Name": app.find("span", class_="boldname").get_text()}
buff["Desc"] = app.find_all("div", class_="appdetailcell")[-2].get_text()
buff["Icon"] = app.find("img")["src"] if app.find("img")["src"] != "/shared/images/spacer.gif" else "https://f-droid.org/repo/com.termux.tasker/en-US/icon.png"
buff["Minor-Details"] = app.find_all("span", class_="minor-details")
buff["Links"] = app.find_all("a", class_="paddedlink")[1:]
apps.append(buff)
return apps
def StringBuilder(app):
return f"<code>{app['Name']}</code> {app['Minor-Details'][0].get_text()} ({app['Minor-Details'][1].get_text()})\n\n{app['Desc']}"
class FDroidMod(loader.Module):
"""Search for android apps from FDroid"""
strings = {
"name": "FDroid",
"no_apps": "🚫 Unfortunately, I couldn't find any applications",
}
strings_ru = {
"name": "FDroid",
"no_apps": "🚫 К сожалению, не нашел приложений",
}
async def fdroidcmd(self, message):
"""Find the app in the FDroid catalog"""
args = utils.get_args_raw(message)
if apps := await fdroid_search(args):
markup = [[{"text": app.get_text(), "url": app["href"]} for app in apps[0]["Links"]]]
if len(apps) != 1:
markup.append([{"text":"➡️","callback": self.fdroid_pagination__callback, "args": (apps, 0, "+")}])
await self.inline.form(
text=StringBuilder(apps[0]),
message=message,
# photo=apps[0]["Icon"],
reply_markup=markup,
)
else:
await utils.answer(message, self.strings["no_apps"])
@loader.inline_everyone
async def fdroid_inline_handler(self, query: InlineQuery) -> None:
"""Find the app in the FDroid catalog (Inline)"""
query_args = query.args
if apps := await fdroid_search(query_args):
InlineQueryResult = []
for app in apps:
# Generate button
markup = InlineKeyboardMarkup()
for link in app["Links"]:
markup.insert(InlineKeyboardButton(link.get_text(), link["href"]))
# Add InlineQueryResultArticle
InlineQueryResult.append(
InlineQueryResultArticle(
id=utils.rand(64),
title=f'{app["Name"]} ({app["Minor-Details"][1].get_text()})',
description=app["Desc"],
input_message_content=InputTextMessageContent(
StringBuilder(app),
"HTML",
disable_web_page_preview=True,
),
reply_markup=markup,
# thumb_url=app["Icon"],
)
)
await query.answer(InlineQueryResult, cache_time=0)
else:
await query.e404()
# Just callbacks
async def fdroid_pagination__callback(self, call, apps, index, type_button):
markup = [[{"text": app.get_text(), "url": app["href"]} for app in apps[index]["Links"]],[]]
if type_button == "+":
index += 1
markup[1].append({"text":"⬅️","callback": self.fdroid_pagination__callback, "args": (apps, index, "-")})
if index != len(apps) - 1:
markup[1].append({"text":"➡️","callback": self.fdroid_pagination__callback, "args": (apps, index, "+")})
else:
index -= 1
if index != 0:
markup[1].append({"text":"⬅️","callback": self.fdroid_pagination__callback, "args": (apps, index, "-")})
markup[1].append({"text":"➡️","callback": self.fdroid_pagination__callback, "args": (apps, index, "+")})
await call.edit(text=StringBuilder(apps[index]), reply_markup=markup)

View File

@@ -0,0 +1,169 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
Copyleft 2022 t.me/CakesTwix
This program is free software; you can redistribute it and/or modify
"""
__version__ = (1, 0, 0)
# meta pic: https://allvpn.ru/assets/upload/t-200x200-7439447981535195421.png
# meta developer: @cakestwix_mods
# requires: httpx bs4
# scope: inline
import logging
import xml.etree.ElementTree as ET
from typing import Union
import httpx
from aiogram.types import (InlineKeyboardButton, InlineKeyboardMarkup,
InlineQueryResultArticle, InputTextMessageContent)
from bs4 import BeautifulSoup
from .. import loader, utils
from ..inline import GeekInlineQuery, rand
logger = logging.getLogger(__name__)
# From Hikka https://github.com/hikariatama/Hikka/blob/master/hikka/utils.py#L459-L461
def chunks(_list: Union[list, tuple, set], n: int, /) -> list:
"""Split provided `_list` into chunks of `n`"""
return [_list[i : i + n] for i in range(0, len(_list), n)]
async def search_book(query=None):
books_list = []
async with httpx.AsyncClient() as client:
if query:
xml_ = (await client.get(f"http://flibusta.is/opds/opensearch?searchTerm={query}&searchType=books&pageNumber=1"))
else:
xml_ = await client.get("http://flibusta.is/opds/opensearch?searchType=books&pageNumber=1")
myroot = ET.fromstring(xml_.text)
for book in myroot.findall('.//{http://www.w3.org/2005/Atom}entry'):
books_dict = {"Books": {}, "Name": book.find('./{http://www.w3.org/2005/Atom}title').text, "Author": ""}
for item in book.findall('./{http://www.w3.org/2005/Atom}author'):
books_dict["Author"] += item.find('./{http://www.w3.org/2005/Atom}name').text + " "
# Links and Formats
for item in book.findall('./{http://www.w3.org/2005/Atom}link'):
if "application/" in item.attrib["type"] and "related" not in item.attrib["rel"]:
books_dict["Books"][item.attrib["type"].split("/")[1].replace("+zip", "").replace("x-mobipocket-ebook", "mobi")] = item.attrib["href"]
# Read
if "title" in item.attrib:
books_dict["Read"] = [item.attrib["title"], item.attrib["href"]]
if books_dict["Books"] != {}:
books_list.append(books_dict)
return books_list
@loader.tds
class FlibustaMod(loader.Module):
"""Get books from flibusta"""
strings = {
"name": "Flibusta",
"no_args": "🎞 <b>You need to specify book name</b>",
"no_book": "🎞 <b>No books by your query :(</b>",
}
# Just commands
async def bookcmd(self, message):
"""🔎 Sending the form with the books. Send message with args if you want to find a book by title"""
# Get args from message
if args:= utils.get_args_raw(message):
books = await search_book(args)
else:
books = await search_book()
# No books ((
if books == []:
return await utils.answer(message, self.strings["no_book"])
string = f'📙 <b>{books[0]["Name"]}</b>'
string += f"\n<b>Author:</b> {books[0]['Author']}"
# epub pdf fb2 mobi / Read
reply_keyboard = [[{"text": file_, "url": f"http://flibusta.is{books[0]['Books'][file_]}"} for file_ in books[0]["Books"]], [{"text": "Read", "url": f"http://flibusta.is{books[0]['Read'][1]}"}]]
btn_buff = [{"text": str(i), "callback": self.change_book__callback, "args": (book, args or None)} for i, book in enumerate(books, start=1)]
reply_keyboard.extend(iter(chunks(btn_buff, 5)))
try:
reply_keyboard.remove([])
except ValueError:
pass
await self.inline.form(
text=string,
message=message,
reply_markup=reply_keyboard,
)
# Just callbacks
async def change_book__callback(self, call, book, search=None):
books = await search_book(search)
string = f'📙 <b>{book["Name"]}</b>'
string += f"\n<b>Author:</b> {book['Author']}"
# epub pdf fb2 mobi / Read
reply_keyboard = [[{"text": file_, "url": f"http://flibusta.is{book['Books'][file_]}"} for file_ in book["Books"]], [{"text": "Read", "url": f"http://flibusta.is{book['Read'][1]}"}]]
btn_buff = [{"text": str(i), "callback": self.change_book__callback, "args": (book, search or None)} for i, book in enumerate(books, start=1)]
reply_keyboard.extend(iter(chunks(btn_buff, 5)))
try:
reply_keyboard.remove([])
except ValueError:
pass
await call.edit(text=string, reply_markup=reply_keyboard)
# Just Inline
async def book_inline_handler(self, query: GeekInlineQuery) -> None:
"""
🔎 Sending the form with the books. Send message with args if you want to find a book by title (Inline)
"""
if text := query.args:
books = await search_book(text)
else:
books = await search_book()
# No books ((
if books == []:
return await query.e404()
InlineQueryResult = []
for book in books:
markup = InlineKeyboardMarkup(row_width=3)
for file_ in book["Books"]:
markup.insert(InlineKeyboardButton(file_, f"http://flibusta.is{book['Books'][file_]}"))
InlineQueryResult.append(
InlineQueryResultArticle(
id=utils.rand(50),
title=book["Name"],
description=book["Author"],
input_message_content=InputTextMessageContent(
f'📙 <b>{book["Name"]}</b>\n<b>Author:</b> {book["Author"]}',
"HTML",
disable_web_page_preview=True,
),
reply_markup=markup,
)
)
await query.answer(InlineQueryResult, cache_time=0)

View File

@@ -0,0 +1,23 @@
anilibria
compli
customroms_geek
customroms
FoxAndDogsGallery
ImageBoardSender
linux_packages
minecraft
qrcode
random_tools
tikcock
toloka_geek
translate
transmission
wynncraft_geek
yandere_geek
yandere
InlineSystemInfo
InlineYouTube
RandomPeople
InlineSpotifyDownloader
flibusta
SimpleNoLink

View File

@@ -0,0 +1,125 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
Copyleft 2022 t.me/CakesTwix
This program is free software; you can redistribute it and/or modify
"""
__version__ = (2, 0, 1)
# meta pic: https://seeklogo.com/images/H/hentai-haven-logo-B9D8C4B3B8-seeklogo.com.png
# meta developer: @cakestwix_mods
# requires: NHentai-API
import logging
from typing import Union
from NHentai import NHentaiAsync, CloudFlareSettings
from .. import loader, utils
from ..inline import GeekInlineQuery, rand
from aiogram.utils.markdown import hlink
import asyncio
logger = logging.getLogger(__name__)
# From Hikka https://github.com/hikariatama/Hikka/commit/03f7c71557acd6e14e816df4de932dd55668fd97#diff-b020ffc1f4d0e66f2cfd8724370d8ee28197d945f9d0f2cf7e4358717e71e27cR439-R441
def chunks(_list: Union[list, tuple, set], n: int, /) -> list:
"""Split provided `_list` into chunks of `n`"""
return [_list[i : i + n] for i in range(0, len(_list), n)]
def StringBuilder(Hentai):
tags = "".join(f"{hlink(tag.name, tag.url)} " for tag in Hentai.tags)
langs = "".join(f"{hlink(lang.name, lang.url)} " for lang in Hentai.languages)
text = f"{hlink(Hentai.title.english, Hentai.url)} [{Hentai.id}]\n\n"
text += f"{tags} \n\n"
text += f"Language: {langs} \n"
text += f"❤️ {Hentai.total_favorites} | 📄 {Hentai.total_pages}"
return text
@loader.tds
class NHentaiMod(loader.Module):
"""🍓 Hentai doujin module 18+"""
strings = {
"name": "NHentai",
"no_tags": "🎞 <b>No hentai by your query :(</b>",
"no_digit": "1⃣ <b>Please give me a number.</b>",
}
strings_ru = {
"name": "🍓 NHentai",
"no_tags": "🎞 <b>Не нашел хентая по твоему запросу :(</b>",
"no_digit": "1⃣ <b>Пожалуйста, дайте мне число.</b>",
}
def __init__(self):
self.config = loader.ModuleConfig(
"CONFIG_CSRFTOKEN",
"",
lambda: self.strings("cfg_csrftoken"),
"CONFIG_CF_CLEARANCE",
"",
lambda: self.strings("cfg_cf_clearance"),
)
async def client_ready(self, client, db) -> None:
self.nhentai_async = NHentaiAsync(request_settings=CloudFlareSettings(csrftoken=self.config["CONFIG_CSRFTOKEN"],
cf_clearance=self.config["CONFIG_CF_CLEARANCE"]))
async def nhrandomcmd(self, message):
"""🎲 Random hentai doujin"""
hentai = await self.nhentai_async.get_random()
await message.delete()
await message.client.send_file(message.chat_id, hentai.cover.src, caption=StringBuilder(hentai))
async def nhlastcmd(self, message):
"""⌚️ Latest hentai doujin"""
hentai = await self.nhentai_async.get_doujin((await self.nhentai_async.get_page(page=1)).doujins[0].id)
await message.delete()
await message.client.send_file(message.chat_id, hentai.cover.src, caption=StringBuilder(hentai))
async def nhidcmd(self, message):
"""1⃣ Hentai doujin by id"""
if args:= utils.get_args_raw(message):
if not args.isdigit():
return await message.answer(message, self.strings["no_digit"])
hentai = await self.nhentai_async.get_doujin(args)
await message.client.send_file(message.chat_id, hentai.cover.src, caption=StringBuilder(hentai))
async def nhsearchcmd(self, message):
"""🔎 Search hentai doujin"""
if args:= utils.get_args_raw(message):
hentai = await self.nhentai_async.search(args)
markup = [[{"text":"Link", "url":hentai.doujins[0].url}]]
if len(hentai.doujins) != 1:
markup.append([{"text":"➡️","callback": self.hentai_pagination__callback, "args": (hentai.doujins, 0, "+")}])
await self.inline.form(
text=StringBuilder(hentai.doujins[0]),
message=message,
photo=hentai.doujins[0].cover.src,
reply_markup=markup,
)
# Just callbacks
async def hentai_pagination__callback(self, call, list_doujins, index, type_button):
markup = [[{"text":"Link", "url": list_doujins[index].url}],[]]
if type_button == "+":
index += 1
markup[1].append({"text":"⬅️","callback": self.hentai_pagination__callback, "args": (list_doujins, index, "-")})
if index != len(list_doujins) - 1:
markup[1].append({"text":"➡️","callback": self.hentai_pagination__callback, "args": (list_doujins, index, "+")})
else:
index -= 1
if index != 0:
markup[1].append({"text":"⬅️","callback": self.hentai_pagination__callback, "args": (list_doujins, index, "-")})
markup[1].append({"text":"➡️","callback": self.hentai_pagination__callback, "args": (list_doujins, index, "+")})
await call.edit(text=StringBuilder(list_doujins[index]), reply_markup=markup, photo=list_doujins[index].cover.src)

View File

@@ -0,0 +1,108 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
# Copyleft 2022 t.me/CakesTwix
This program is free software; you can redistribute it and/or modify
"""
__version__ = (1, 0, 1)
# requires: requests hentai
# meta pic: https://seeklogo.com/images/H/hentai-haven-logo-B9D8C4B3B8-seeklogo.com.png
# meta developer: @cakestwix_mods
import asyncio
import logging
from hentai import Hentai, Utils
from requests.exceptions import HTTPError
from .. import loader, utils
logger = logging.getLogger(__name__)
# Utils
def StringBuilder(Hentai):
id_nh = Hentai.id
eng_name = Hentai.title()
link = Hentai.url
total_pages = Hentai.num_pages
total_favorites = Hentai.num_favorites
tags = "".join(f"{tag.name} " for tag in Hentai.tag)
text = f"<a href={link}>{eng_name}</a> [{id_nh}]\n\n"
text += f"{tags} \n"
text += f"❤️ {total_favorites} | 📄 {total_pages}"
return text
def ListHentaiBuilder(Hentais):
text = ""
for i, Hentai in enumerate(Hentais, start=1):
id_nh = Hentai.id
eng_name = Hentai.title()
link = Hentai.url
total_pages = Hentai.num_pages
total_favorites = Hentai.num_favorites
text += f"{i}: <a href={link}>{eng_name}</a> [{id_nh}] / "
text += f"❤️ {total_favorites} | 📄 {total_pages} \n"
return text
@loader.unrestricted
@loader.ratelimit
@loader.tds
class NHentaiMod(loader.Module):
"""Hentai module 18+ Legacy"""
strings = {
"name": "NHentai",
}
@loader.unrestricted
@loader.ratelimit
async def nhrandomcmd(self, message):
"""Random hentai manga"""
await message.delete()
hentai_info = Utils.get_random_hentai()
text = StringBuilder(hentai_info)
await message.client.send_file(message.chat_id, hentai_info.cover, caption=text)
@loader.unrestricted
@loader.ratelimit
async def nhtagcmd(self, message):
"""Search hentai manga by tag"""
if args := utils.get_args(message):
hentai_info = Utils.search_by_query(args)
text = ListHentaiBuilder(hentai_info)
await utils.answer(message, text)
else:
await utils.answer(message, "Pls tags")
await asyncio.sleep(5)
await message.delete()
@loader.unrestricted
@loader.ratelimit
async def nhidcmd(self, message):
"""Search hentai manga by id"""
args = utils.get_args(message)
if args[0].isdigit():
try:
hentai_info = Hentai(args[0])
text = StringBuilder(hentai_info)
await message.client.send_file(
message.chat_id, hentai_info.cover, caption=text
)
except HTTPError as e:
await utils.answer(message, str(e))
await asyncio.sleep(5)
await message.delete()
else:
await utils.answer(message, "Pls id")
await asyncio.sleep(5)
await message.delete()

View File

@@ -0,0 +1,292 @@
"""
█▄▀ █ █░█░█ █ █▄░█ █ █▀▀ █▀▀ █▀█
█░█ █ ▀▄▀▄▀ █ █░▀█ █ █▄▄ ██▄ █▀▄
Copyleft 2022 t.me/KiwiNicer
This program is free software; you can redistribute it and/or modify
"""
__version__ = (1, 1, 0)
# requires: aiohttp
# meta pic: https://img.icons8.com/clouds/512/000000/linux-client.png
# meta developer: @KiwiNicer
import aiohttp
import logging
import asyncio
from aiogram.types import CallbackQuery
from typing import Union
from .. import loader, utils
logger = logging.getLogger(__name__)
# From Hikka https://github.com/hikariatama/Hikka/blob/master/hikka/utils.py#L459-L461
def chunks(_list: Union[list, tuple, set], n: int, /) -> list:
"""Split provided `_list` into chunks of `n`"""
return [_list[i : i + n] for i in range(0, len(_list), n)]
@loader.tds
class LinuxPackagesMod(loader.Module):
"""Search package for Linux by name"""
strings = {
"name": "Packages",
"no_name": "Pls give me name",
"general_error": "<b>Unknown error</b> .-.",
"string_list": "<b>List of packages in the {}</b>\n\n",
"info_about": "<b>Info about</b> <code>{}</code>\n\n",
"ver": "<b>Version:</b> {}\n",
"description": "<b>Description:</b> {}\n",
"maintainer": "<b>Maintainer:</b> {}\n",
"no_packages": "<b>No packages</b>...",
}
strings_ru = {
"no_name": "Пожалуйста, дайте мне имя пакета",
"general_error": "<b>Неизвестная ошибка</b> .-.",
"string_list": "<b>Список пакетов в {}</b>\n\n",
"info_about": "<b>Информация о</b> <code>{}</code>\n\n",
"ver": "<b>Версия:</b> {}\n",
"description": "<b>Описание:</b> {}\n",
"maintainer": "<b>Сопровождающий:</b> {}\n",
"no_packages": "<b>Нет пакетов</b>...",
}
async def aurcmd(self, message):
"""Arch User Repository"""
args = utils.get_args_raw(message)
if not args:
await utils.answer(message, self.strings["no_name"])
return await asyncio.sleep(5)
async with aiohttp.ClientSession() as session:
async with session.get(
f"https://aur.archlinux.org/rpc/?v=5&type=search&arg={args}"
) as get:
if get.ok:
packages = await get.json()
if packages["resultcount"] == 0:
return await utils.answer(message, self.strings["no_packages"])
i = 1
reply_markup = []
string = self.strings["string_list"].format("AUR")
for package in packages["results"]:
string += f"{i}. {package['Name']}(v{package['Version']})\n"
reply_markup.append(
{
"text": str(i),
"callback": self.inline__get_package,
"args": [package["Name"], "AUR", args],
}
)
if i >= 10:
break
i = i + 1
await self.inline.form(
text=string,
message=message,
reply_markup=chunks(reply_markup, 5),
force_me=False, # optional: Allow other users to access form (all)
)
else:
await utils.answer(message, self.strings["general_error"])
return await asyncio.sleep(5)
async def inline__get_package(
self, call: CallbackQuery, Name: str, _type: str, search_arg: str
) -> None:
if _type == "AUR":
async with aiohttp.ClientSession() as session:
async with session.get(
f"https://aur.archlinux.org/rpc/?v=5&type=info&arg[]={Name}"
) as get:
if get.ok:
package = await get.json()
else:
await utils.answer(message, self.strings["general_error"])
return await asyncio.sleep(5)
string = self.strings["info_about"].format(Name)
string += self.strings["ver"].format(package["results"][0]["Version"])
string += self.strings["description"].format(
package["results"][0]["Description"]
)
string += self.strings["maintainer"].format(
package["results"][0]["Maintainer"]
)
btn = [
[
{
"text": "AUR",
"url": f"https://aur.archlinux.org/packages/{Name}",
},
{
"text": "Download snapshot",
"url": "https://aur.archlinux.org"
+ package["results"][0]["URLPath"],
},
],
[
{
"text": "Back",
"callback": self.inline__back,
"args": [search_arg, "AUR"],
}
],
]
elif _type == "pacman":
async with aiohttp.ClientSession() as session:
async with session.get(
f"https://www.archlinux.org/packages/search/json/?q={Name}"
) as get:
if get.ok:
package = await get.json()
else:
await utils.answer(message, self.strings["general_error"])
return await asyncio.sleep(5)
string = self.strings["info_about"].format(Name)
string += self.strings["ver"].format(package["results"][0]["pkgver"])
string += self.strings["description"].format(
package["results"][0]["pkgdesc"]
)
string += self.strings["maintainer"].format(
package["results"][0]["maintainers"][0]
)
btn = [
[
{
"text": "Pacman",
"url": f"https://archlinux.org/packages/{package['results'][0]['repo']}/{package['results'][0]['arch']}/{package['results'][0]['pkgname']}",
},
],
[
{
"text": "Back",
"callback": self.inline__back,
"args": [search_arg, "pacman"],
}
],
]
await call.edit(
text=string,
reply_markup=btn, # optional: Change buttons in message. If not specified, buttons will be removed
force_me=False, # optional: Change button privacy mode
)
async def inline__back(self, call: CallbackQuery, Name: str, _type: str) -> None:
if _type == "AUR":
async with aiohttp.ClientSession() as session:
async with session.get(
f"https://aur.archlinux.org/rpc/?v=5&type=search&arg={Name}"
) as get:
if get.ok:
packages = await get.json()
i = 1
reply_markup = []
string = self.strings["string_list"].format("AUR")
for package in packages["results"]:
string += f"{i}. {package['Name']}(v{package['Version']})\n"
reply_markup.append(
{
"text": str(i),
"callback": self.inline__get_package,
"args": [package["Name"], "AUR", Name],
}
)
if i >= 10:
break
i = i + 1
await call.edit(
text=string,
reply_markup=chunks(reply_markup, 5),
force_me=False, # optional: Allow other users to access form (all)
)
else:
await utils.answer(message, self.strings["general_error"])
return await asyncio.sleep(5)
elif _type == "pacman":
async with aiohttp.ClientSession() as session:
async with session.get(
f"https://www.archlinux.org/packages/search/json/?q={Name}"
) as get:
if get.ok:
packages = await get.json()
if len(packages["results"]) == 0:
return await utils.answer(message, self.strings["no_packages"])
i = 1
reply_markup = []
string = self.strings["string_list"].format("pacman")
for package in packages["results"]:
string += f"{i}. {package['pkgname']}(v{package['pkgver']})\n"
reply_markup.append(
{
"text": str(i),
"callback": self.inline__get_package,
"args": [package["pkgname"], "pacman", Name],
}
)
if i >= 10:
break
i = i + 1
await call.edit(
text=string,
reply_markup=chunks(reply_markup, 5),
force_me=False, # optional: Allow other users to access form (all)
)
async def pacmancmd(self, message):
"""Pacman"""
if not (args := utils.get_args_raw(message)):
return
async with aiohttp.ClientSession() as session:
async with session.get(
f"https://www.archlinux.org/packages/search/json/?q={args}"
) as get:
if get.ok:
packages = await get.json()
if len(packages["results"]) == 0:
return await utils.answer(message, self.strings["no_packages"])
i = 1
reply_markup = []
string = self.strings["string_list"].format("pacman")
for package in packages["results"]:
string += f"{i}. {package['pkgname']}(v{package['pkgver']})\n"
reply_markup.append(
{
"text": str(i),
"callback": self.inline__get_package,
"args": [package["pkgname"], "pacman", args],
}
)
if i >= 10:
break
i = i + 1
await self.inline.form(
text=string,
message=message,
reply_markup=chunks(reply_markup, 5),
force_me=False, # optional: Allow other users to access form (all)
)

View File

@@ -0,0 +1,97 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
Copyleft 2022 t.me/CakesTwix
This program is free software; you can redistribute it and/or modify
"""
__version__ = (1, 1, 0)
# requires: aiohttp
# meta pic: https://icons.iconarchive.com/icons/blackvariant/button-ui-requests-2/1024/Minecraft-2-icon.png
# meta developer: @cakestwix_mods
import logging
import aiohttp
from .. import loader, utils
logger = logging.getLogger(__name__)
@loader.tds
class InlineMinecraftInfoMod(loader.Module):
"""Information about players and server status"""
strings = {
"name": "MinecraftInfo",
"error_message": "🚫 This entity does not exist or you entered it incorrectly",
"about_user": "<b>Available player information</b> <code>{}</code>:'\n",
"about_server": "<b>Available server information</b> <code>{}</code>:'\n",
"username": "<b>Username:</b> <code>{}</code>\n",
"id": "<b>Id:</b> <code>{}</code>\n",
"description": "<b>Description</b>: {}\n",
"latency": "<b>Latency</b>: {}\n",
"players": "<b>Players</b>: {} in {}\n",
"versions": "<b>Versions</b>: {}\n",
}
strings_ru = {
"error_message": "🚫 Этот объект не существует или вы ввели его неправильно",
"about_user": "<b>Доступная информация об игроке</b> <code>{}</code>:'\n",
"about_server": "<b>Доступная информация о сервере</b> <code>{}</code>:'\n",
"username": "<b>Имя игрока:</b> <code>{}</code>\n",
"id": "<b>Id:</b> <code>{}</code>\n",
"description": "<b>Описание</b>: {}\n",
"latency": "<b>Задержка</b>: {}\n",
"players": "<b>Игроки</b>: {} in {}\n",
"versions": "<b>Версии</b>: {}\n",
}
base_url = "https://api.minetools.eu"
async def mucheckcmd(self, message):
"""Check user by username"""
if args := utils.get_args_raw(message):
async with aiohttp.ClientSession() as session:
async with session.get(f"{self.base_url}/uuid/{args}") as get:
data = await get.json()
if data["status"] == "ERR":
return await utils.answer(
message, self.strings["error_message"]
)
async with session.get(f"{self.base_url}/profile/{data['id']}") as get:
user = await get.json()
text = self.strings["about_user"].format(user["decoded"]["profileName"])
text += self.strings["id"].format(user["decoded"]["profileId"])
text += self.strings["username"].format(user["decoded"]["profileName"])
for texture in user["decoded"]["textures"]:
text += f"<b>{texture}</b>: <a href={user['decoded']['textures'][texture]['url']}>URL</a>\n"
await utils.answer(message, text)
async def mpingcmd(self, message):
"""Ping minecraft server"""
if args := utils.get_args_raw(message):
async with aiohttp.ClientSession() as session:
async with session.get(f"{self.base_url}/ping/{args}") as get:
data = await get.json()
if "error" in data:
return await utils.answer(
message, self.strings["error_message"]
)
text = self.strings["about_user"].format(args)
text += self.strings["description"].format(data["description"])
text += self.strings["latency"].format(data["latency"])
text += self.strings["players"].format(
data["players"]["online"], data["players"]["max"]
)
text += self.strings["versions"].format(data["version"]["name"])
await utils.answer(message, text)

View File

@@ -0,0 +1,61 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
Copyleft 2022 t.me/CakesTwix
This program is free software; you can redistribute it and/or modify
"""
__version__ = (1, 0, 0)
# requires: qrcode
# meta pic: https://cdn1.iconfinder.com/data/icons/social-messaging-ui-color-shapes/128/qr-code-circle-blue-512.png
# meta developer: @cakestwix_mods
import asyncio
import io
import logging
import qrcode
from .. import loader, utils
logger = logging.getLogger(__name__)
@loader.unrestricted
@loader.ratelimit
@loader.tds
class QrCodeMod(loader.Module):
"""Module for creating Qr codes"""
strings = {
"name": "QrCode",
}
@loader.unrestricted
@loader.ratelimit
async def qrcmd(self, message):
"""Create QrCode"""
reply = await message.get_reply_message()
if len(message.text) > 3:
text = message.text[4:] # .qr_
elif reply and reply.text != "":
text = reply.text
else:
text = None
if text != None:
img = qrcode.make(text)
with io.BytesIO() as output:
img.save(output)
contents = output.getvalue()
await message.delete()
await message.client.send_file(message.chat_id, contents, caption=text)
else:
await utils.answer(message, "Pls text")
await asyncio.sleep(5)
await message.delete()

View File

@@ -0,0 +1,116 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
Copyleft 2022 t.me/CakesTwix
This program is free software; you can redistribute it and/or modify
"""
__version__ = (1, 1, 0)
# meta pic: https://i0.wp.com/alliancestake.org/wp-content/uploads/2017/09/icon-circle-tools-blue-1.png?fit=300%2C300&ssl=1
# meta developer: @cakestwix_mods
import logging
import aiohttp
import asyncio
from .. import loader, utils
logger = logging.getLogger(__name__)
@loader.unrestricted
@loader.ratelimit
@loader.tds
class RToolsMod(loader.Module):
"""Random tools"""
strings = {
"name": "Tools",
"no_found": "No found",
"no_args": "Not found args, pls check help",
"general_error": "Oh no, cringe, error",
}
strings_ru = {
"no_found": "Не найдено",
"no_args": "Аргументы не найдены, пожалуйста, проверьте справку",
"general_error": "❗️Ашибка❗️ ",
}
@loader.unrestricted
@loader.ratelimit
async def mac2vendorcmd(self, message):
"""Get vendor name by mac"""
if args := utils.get_args(message):
mac = args[0].lower()
async with aiohttp.ClientSession() as session:
async with session.get(f"http://api.macvendors.com/{mac}") as get:
if get.ok:
await utils.answer(message, await get.text())
else:
await utils.answer(message, self.strings["no_found"])
await asyncio.sleep(5)
await message.delete()
else:
await utils.answer(message, self.strings["no_args"])
await asyncio.sleep(5)
await message.delete()
@loader.unrestricted
@loader.ratelimit
async def oneptcmd(self, message):
"""A simple URL shortener (1pt.co)"""
if args := utils.get_args(message):
mac = args[0].lower()
async with aiohttp.ClientSession() as session:
async with session.get(f"https://api.1pt.co/addURL?long={mac}") as get:
if get.ok:
answer_json = await get.json()
await utils.answer(message, "1pt.co/" + answer_json["short"])
else:
await utils.answer(message, self.strings["general_error"])
await asyncio.sleep(5)
await message.delete()
else:
await utils.answer(message, self.strings["no_args"])
await asyncio.sleep(5)
await message.delete()
@loader.unrestricted
@loader.ratelimit
async def npcmd(self, message):
"""Нова Пошта"""
if args := utils.get_args(message):
document_number = args[0].lower()
data = {
"apiKey": "abe3a74549c55e4b703ed042c5169406",
"modelName": "TrackingDocument",
"calledMethod": "getStatusDocuments",
"methodProperties": {
"Documents": [{"DocumentNumber": document_number, "Phone": ""}]
},
}
async with aiohttp.ClientSession() as session:
async with session.get(
"https://api.novaposhta.ua/v2.0/json/", json=data
) as get:
answer = await get.json()
await session.close()
item = answer["data"][0]
caption = f"Экспресс-накладная: {item['Number']}"
caption += f"\nСтатус: {item['Status']}"
if "DateCreated" in item:
caption += f"\nБыло создано: {item['DateCreated']}"
caption += f"\nОжид. дата доставки: {item['ScheduledDeliveryDate']}"
caption += f"\n{item['CitySender']} -> {item['CityRecipient']}"
if item.get("DocumentCost") is not None:
caption += f"\nЦена доставки: {item['DocumentCost']} грн."
await utils.answer(message, caption)

View File

@@ -0,0 +1,110 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
Copyleft 2022 t.me/CakesTwix
This program is free software; you can redistribute it and/or modify
"""
__version__ = (1, 1, 0)
# meta pic: https://img.icons8.com/external-flaticons-lineal-color-flat-icons/512/000000/external-anime-addiction-flaticons-lineal-color-flat-icons.png
# meta developer: @cakestwix_mods
# requires: saucenao_api
# scope: inline
# scope: hikka_only
# scope: hikka_min 1.2.7
import logging
import os
from .. import loader, utils
from saucenao_api import AIOSauceNao
from saucenao_api.errors import ShortLimitReachedError, LongLimitReachedError
from saucenao_api.containers import BasicSauce
logger = logging.getLogger(__name__)
def string_builder(sauce_item):
string = "Unsupported type, sorry("
if isinstance(sauce_item, BasicSauce):
string = f"<b>Similarity</b>: <code>{sauce_item.similarity}</code>\n\n"
string += f"<b>Title</b>: <code>{sauce_item.title}</code>\n"
string += f"<b>Author</b>: <code>{sauce_item.author}</code>\n"
string += f"<b>Urls</b>: {' '.join(sauce_item.urls)}\n"
return string
@loader.tds
class SauceNaoMod(loader.Module):
"""🔎 SauceNao - image source locator"""
strings = {
"name": "SauceNao",
"cfg_api_key": "https://saucenao.com/user.php?page=search-api",
"no_args_reply": "🚫 Not found args or reply, pls check help",
"wrong_url": "🚫 <b>Wrong Url</b>",
}
def __init__(self):
self.config = loader.ModuleConfig(
"CONFIG_API_KEY",
None,
lambda: self.strings("cfg_api_key"),
)
async def client_ready(self, client, db) -> None:
self._db = db
self._client = client
# Just commands
async def saucecmd(self, message):
"""🔗 Search for the source by link/photo"""
if not self.config["CONFIG_API_KEY"]:
return await utils.answer(message, "🚫 <b>No API Key</b>")
results = None
# If message has reply
if reply := await message.get_reply_message():
if reply.photo:
async with AIOSauceNao(self.config["CONFIG_API_KEY"]) as aio:
try:
file_ = await self._client.download_media(reply.photo)
with open(file_, 'rb') as img:
results = await aio.from_file(img)
os.remove(file_)
except ShortLimitReachedError:
return await utils.answer(message, "🚫 <b>ShortLimitReachedError</b>")
except LongLimitReachedError:
return await utils.answer(message, "🚫 <b>LongLimitReachedError</b>")
# If message not have reply, then get args from message
if url := utils.get_args_raw(message):
if utils.check_url(utils.get_args_raw(message)):
async with AIOSauceNao(self.config["CONFIG_API_KEY"]) as aio:
try:
results = await aio.from_url(url)
except ShortLimitReachedError:
return await utils.answer(message, "🚫 <b>ShortLimitReachedError</b>")
except LongLimitReachedError:
return await utils.answer(message, "🚫 <b>LongLimitReachedError</b>")
else:
await utils.answer(message, self.strings["wrong_url"])
if not results:
return await utils.answer(message, self.strings["no_args_reply"])
await self.inline.gallery(
message,
[url_photo.thumbnail for url_photo in results],
[
f"<b>Request limits (per 30 seconds limit)</b>: <code>{results.short_remaining}</code>\n<b>Request limits (per day limit)</b>: <code>{results.long_remaining}</code>\n"
+ string_builder(item)
for item in results
],
)

View File

@@ -0,0 +1,73 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
Copyleft 2022 t.me/CakesTwix
This program is free software; you can redistribute it and/or modify
"""
__version__ = (2, 0, 1)
# meta pic: http://assets.stickpng.com/images/5cb78671a7c7755bf004c14b.png
# meta developer: @cakestwix_mods
# scope: hikka_only
# requires: httpx
import logging
import re
import httpx
from aiogram.utils.markdown import hlink
from telethon.errors.rpcerrorlist import BotResponseTimeoutError
from .. import loader, utils
logger = logging.getLogger(__name__)
@loader.tds
class TikTokMod(loader.Module):
"""Yet Another TikTok Downloader"""
strings = {
"name": "YATikTok-DL",
"no_args": "🚫 Not found args, pls check help",
"no_item": "Couldn't find it("
}
strings_ru = {
"name": "YATikTok-DL",
"no_args": "🚫 Аргументы не найдены, пожалуйста, проверьте справку",
"no_item": "Не нашел(("
}
async def client_ready(self, client, db) -> None:
self._db = db
self._client = client
async def ttdlcmd(self, message):
"""Download video/music from tiktok"""
args = utils.get_args_raw(message)
if not args:
return await utils.answer(message, self.strings["no_args"])
elif "www.tiktok.com" in args or "vm.tiktok.com" in args:
async with httpx.AsyncClient() as client:
if tik_info := re.findall(r'\/.*\/([\d]*)?', (await client.head(args)).headers["Location"] if "vm.tiktok.com" in args else args):
tik_get = (await client.get("http://api.tiktokv.com/aweme/v1/multi/aweme/detail/?aweme_ids=[" + tik_info[0])).json()
logger.debug(tik_get)
await self.inline.form(
message=message,
text=hlink(tik_get["aweme_details"][0]["share_info"]["share_title"], tik_get["aweme_details"][0]["share_info"]["share_url"]),
reply_markup=[[{"text":"Without watermark", "callback": self.download__callback, "args": (tik_get["aweme_details"][0]["video"]["play_addr"]["url_list"][0], message.to_id)}, {"text":"With watermark", "callback": self.download__callback, "args": (tik_get["aweme_details"][0]["video"]["download_addr"]["url_list"][0], message.to_id)}], [{"text":"Audio", "callback": self.download__callback, "args": (tik_get["aweme_details"][0]["music"]["play_url"]["url_list"][0], message.to_id)}]],
photo=tik_get["aweme_details"][0]["video"]["origin_cover"]["url_list"][0]
)
else:
await utils.answer(message, "")
async def download__callback(self, call, url, id_):
await self._client.send_file(id_, url)
await call.delete()

View File

@@ -0,0 +1,145 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
Copyleft 2022 t.me/CakesTwix
This program is free software; you can redistribute it and/or modify
"""
__version__ = (1, 0, 1)
# scope: inline
# scope: geektg_only
# scope: geektg_min 3.1.15
# meta pic: https://img.icons8.com/external-others-iconmarket/512/000000/external-national-flags-others-iconmarket-5.png
# meta developer: @cakestwix_mods
import asyncio
import aiohttp
import logging
from aiogram.utils.markdown import hlink
from aiogram.types import (
InlineQueryResultArticle,
InputTextMessageContent,
)
from ..inline import GeekInlineQuery, rand
from .. import loader, utils
logger = logging.getLogger(__name__)
@loader.unrestricted
@loader.ratelimit
@loader.tds
class HurtomMod(loader.Module):
"""Український торрент трекер"""
strings = {
"name": "InlineHurtom",
"no_args": "🚫 <b>Будь ласка, введіть ключові слова, за якими я знайду Вам тему</b>",
"no_args_inline": "Будь ласка, введіть ключові слова, за якими я знайду Вам тему",
"no_args_inline_description": " Наприклад : Кот",
"no_torrent": "🚫 Не було знайдено жодного торрента",
"forum_name": "<b>Назва Розділу</b> : ",
"comments": "<b>Коментарі</b> : ",
"size": "<b>Розмір</b> : ",
"size_inline": "Розмір: ",
"seeders": "<b>Роздають</b> : ",
"leechers": "<b>Завантажують</b> : ",
}
def stringBuilder(self, json):
text = "<b>{}</b>\n".format(hlink(json["title"], json["link"]))
text += (
self.strings["forum_name"]
+ json["forum_name"]
+ " | "
+ json["forum_parent"]
+ "\n"
)
text += self.strings["comments"] + json["comments"] + "\n"
text += self.strings["size"] + json["size"] + "\n"
text += self.strings["seeders"] + json["seeders"] + "\n"
text += self.strings["leechers"] + json["leechers"] + "\n"
return text
@loader.unrestricted
@loader.ratelimit
async def hsearchcmd(self, message):
"""Пошук по трекеру toloka.to (повертає перший елемент)"""
args = utils.get_args_raw(message)
if not args:
await utils.answer(message, self.strings["no_args"])
await asyncio.sleep(5)
await message.delete()
return
async with aiohttp.ClientSession() as session:
async with session.get(f"https://toloka.to/api.php?search={args}") as get:
if not get.ok:
return
data = await get.json()
if data == []:
await utils.answer(message, self.strings["no_torrent"])
return
await session.close()
await utils.answer(message, self.stringBuilder(data[0]))
# Inline
async def hsearch_inline_handler(self, query: GeekInlineQuery) -> None:
"""
Пошук по трекеру toloka.to (Inline)
@allow: all
"""
text = query.args
if not text:
await query.answer(
[
InlineQueryResultArticle(
id=1,
title=self.strings["no_args_inline"],
description=self.strings["no_args_inline_description"],
input_message_content=InputTextMessageContent(
self.strings["no_args"],
"HTML",
disable_web_page_preview=True,
),
thumb_url="https://img.icons8.com/android/128/26e07f/ball-point-pen.png",
thumb_width=128,
thumb_height=128,
)
],
cache_time=0,
)
return
async with aiohttp.ClientSession() as session:
async with session.get(f"https://toloka.to/api.php?search={text}") as get:
if not get.ok:
return
data = await get.json()
if data == []:
return
await session.close()
inline_query = [
InlineQueryResultArticle(
id=rand(50),
title=torrent["title"],
description=self.strings["size_inline"] + torrent["size"],
input_message_content=InputTextMessageContent(
self.stringBuilder(torrent), "HTML", disable_web_page_preview=True
),
)
for torrent in data
]
await query.answer(inline_query, cache_time=0)

View File

@@ -0,0 +1,137 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
Copyleft 2022 t.me/CakesTwix
This program is free software; you can redistribute it and/or modify
"""
__version__ = (2, 0, 0)
# meta pic: https://img.icons8.com/color/512/40C057/translate-text.png
# meta developer: @cakestwix_mods
# requires: translators
import logging
import aiohttp, asyncio
from .. import loader, utils
import translators as trl
logger = logging.getLogger(__name__)
@loader.unrestricted
@loader.ratelimit
@loader.tds
class TranslatorMod(loader.Module):
"""
🔡 Module for text translation
➡️ .tr en ru | Hello World
➡️ .tr ru | Hello World
➡️ .tr ru + reply to message
"""
strings = {
"name": "🔡 Translator",
"cfg_lingva_url": "Alternative front-end for Google Translate",
"error": "Error!\n .gtr [en] ru | text or check help",
}
strings_ru = {
"cfg_lingva_url": "Альтернативный интерфейс для Google Translate",
"error": "Ошибка!\n .gtr [en] ru | текст или проверьте хелп",
}
def __init__(self):
self.config = loader.ModuleConfig(
"lingva_url",
"https://lingva.ml/api/v1/{source}/{target}/{query}",
lambda m: self.strings("cfg_lingva_url", m),
)
self.name = self.strings["name"]
async def tr(self, message, translator):
if args:= utils.get_args_raw(message):
lang_args = args.split("|")[0].split() # Lang
if reply := await message.get_reply_message():
if reply.message == '':
return await utils.answer(message, self.strings["error"])
if len(lang_args) == 2:
translated_text = translator(reply.message, from_language=lang_args[0], to_language=lang_args[1])
return await utils.answer(message, translated_text)
elif len(lang_args) == 1:
translated_text = translator(reply.message, to_language=lang_args[0])
return await utils.answer(message, translated_text)
else:
await utils.answer(message, self.strings["error"])
await asyncio.sleep(5)
await message.delete()
return
text_args = args.split("|")[1] # Text
if len(lang_args) == 2 and text_args:
translated_text = translator(text_args, from_language=lang_args[0], to_language=lang_args[1])
elif len(lang_args) == 1 and text_args:
translated_text = translator(text_args, to_language=lang_args[0])
else:
await utils.answer(message, self.strings["error"])
await asyncio.sleep(5)
await message.delete()
return
await utils.answer(message, translated_text)
else:
await utils.answer(message, self.strings["error"])
await asyncio.sleep(5)
await message.delete()
async def atrcmd(self, message):
"""
Based on Argos (LibreTranslate)
"""
await self.tr(message, trl.argos)
async def itrcmd(self, message):
"""
Based on Iciba
"""
await self.tr(message, trl.iciba)
async def gtrcmd(self, message):
"""
Based on Google Translate
"""
await self.tr(message, trl.google)
async def ltrcmd(self, message):
"""
Based on lingva.ml (Google Translate)
"""
if args:= utils.get_args_raw(message):
lang_args = args.split("|")[0].split() # Lang
text_args = args.split("|")[1] # Text
if len(lang_args) == 2 and text_args:
url = self.config["lingva_url"].format(
source=lang_args[0], target=lang_args[1], query=text_args
)
elif len(lang_args) == 1 and text_args:
url = self.config["lingva_url"].format(
source="auto", target=lang_args[0], query=text_args
)
else:
await utils.answer(message, self.strings["error"])
await asyncio.sleep(5)
await message.delete()
return
async with aiohttp.ClientSession() as session:
async with session.get(url) as get:
translated_text = await get.json()
await session.close()
await utils.answer(message, translated_text["translation"])
else:
await utils.answer(message, self.strings["error"])
await asyncio.sleep(5)
await message.delete()

View File

@@ -0,0 +1,512 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
Copyleft 2022 t.me/CakesTwix
This program is free software; you can redistribute it and/or modify
"""
__version__ = (1, 0, 1)
# requires: transmission-rpc
# scope: inline
# scope: geektg_only
# scope: geektg_min 3.1.15
# meta pic: https://img.icons8.com/ios-filled/512/40C057/torrent.png
# meta developer: @cakestwix_mods
import logging
from .. import loader, utils
import asyncio
from telethon.tl.functions.channels import CreateChannelRequest
from ..inline import GeekInlineQuery, rand
from aiogram.types import (
InlineQueryResultArticle,
InputTextMessageContent,
InlineKeyboardMarkup,
InlineKeyboardButton,
CallbackQuery,
)
from aiogram.utils.exceptions import MessageNotModified
from transmission_rpc import Client
from transmission_rpc.utils import format_size
from transmission_rpc.error import TransmissionConnectError
logger = logging.getLogger(__name__)
@loader.unrestricted
@loader.ratelimit
@loader.tds
class TransmissionMod(loader.Module):
"""Simple torrent client for Transmission"""
strings = {
"name": "Transmission",
"cfg_username": "Username",
"cfg_password": "Password",
"cfg_port": "Post (9091)",
"cfg_host": "Host (localhost)",
"cfg_protocol": "Protocol (http)",
"cfg_rpc": "RPC url (/transmission/)",
"not_ready": "Pls check config",
"torrent_name": "<b>Name:</b> ",
"torrent_status": "<b>Status:</b> ",
"torrent_hash": "<b>Hash:</b> ",
"torrent_dir": "<b>Directory:</b> ",
"torrent_size": "<b>Size:</b> ",
"kb_update": "🔄 Update",
"kb_close": "🚫 Close",
"torrent_eta": "ETA: ",
"torrent_error": "<b>Torrent not found in result</b>",
"kb_start": "▶️",
"kb_stop": "",
"kb_delete": "❌ Delete torrent ❌",
"kb_delete_data": "❌ Delete torrent with data ❌",
"answer_start": "Torrent starting",
"answer_stop": "Torrent stopped",
"answer_delete": "Torrent removed",
"inline_title": "Torrent Manager",
"inline_desc": " Click to view the parameters",
"inline_answer": " No changes",
}
strings_ru = {
"cfg_username": "Юзернейм",
"cfg_password": "Пароль",
"cfg_port": "Сообщение (9091)",
"cfg_host": "Хост (localhost)",
"cfg_protocol": "Протокол (http)",
"cfg_rpc": "URL-адрес RPC (/transmission/)",
"not_ready": "Пожалуйста, проверьте конфиг",
"torrent_name": "<b>Имя:</b> ",
"torrent_status": "<b>Статус:</b> ",
"torrent_hash": "<b>Хэш:</b> ",
"torrent_dir": "<b>Директория:</b> ",
"torrent_size": "<b>Размер:</b> ",
"kb_update": "🔄 Обновить",
"kb_close": "🚫 Закрыть",
"torrent_eta": "ETA: ",
"torrent_error": "<b>Torrent not found in result</b>",
"kb_delete": "❌ Удалить торрент ❌",
"kb_delete_data": "❌ Удалить торрент с данными ❌",
"answer_start": "Запуск торрента",
"answer_stop": "Торрент остановлен",
"answer_delete": "Торрент удален",
"inline_title": "Торрент-менеджер",
"inline_desc": " Нажмите, чтобы просмотреть параметры",
"inline_answer": " Без изменений",
}
def stringTorrent(self, torrent):
torrent_text = f"{self.strings['torrent_name']}{torrent.name} \n"
torrent_text += f"{self.strings['torrent_status']}{torrent.status} \n"
torrent_text += f"{self.strings['torrent_eta']}{torrent.format_eta()} \n"
torrent_text += f"{self.strings['torrent_hash']}{torrent.hashString} \n"
torrent_text += f"{self.strings['torrent_size']}{format_size(torrent.total_size)[0]} {format_size(torrent.total_size)[1]} \n"
torrent_text += f"{self.strings['torrent_dir']}{torrent.download_dir} \n"
return torrent_text
def __init__(self):
self.config = loader.ModuleConfig(
"username",
None,
lambda m: self.strings("cfg_username", m),
"password",
None,
lambda m: self.strings("cfg_password", m),
"port",
9091,
lambda m: self.strings("cfg_port", m),
"host",
"127.0.0.1",
lambda m: self.strings("cfg_host", m),
"protocol",
"http",
lambda m: self.strings("cfg_protocol", m),
"rpc",
"/transmission/",
lambda m: self.strings("cfg_rpc", m),
)
self.name = self.strings["name"]
# Check Transmission Server
self.is_ready = False
try:
self.TransmissionClientUserBot = Client(
host=self.config["host"],
port=self.config["port"],
username=self.config["username"],
password=self.config["password"],
path=self.config["rpc"],
protocol=self.config["protocol"],
)
self.is_ready = True
except TransmissionConnectError:
pass
async def client_ready(self, client, db):
self._client = client
self._me = await client.get_me(True)
@loader.unrestricted
@loader.ratelimit
async def tinfocmd(self, message):
"""Useful information about transmission server"""
if self.is_ready:
session_stats = self.TransmissionClientUserBot.session_stats()
timeout = self.TransmissionClientUserBot.timeout
rpc_version = self.TransmissionClientUserBot.rpc_version
is_port_open = self.TransmissionClientUserBot.port_test()
port = session_stats.peer_port
download_dir = session_stats.download_dir
free_space = self.TransmissionClientUserBot.free_space(download_dir)
string = "Info about your Transmission Server\n\n"
string += f"RPC version : {rpc_version}\n"
string += f"Current timeout for HTTP queries : {timeout}\n"
string += f"Port is open : {is_port_open}\n"
string += f"Port : {port}\n"
string += f"Download path : {download_dir}\n"
string += f"Free space : {format_size(free_space)[0]} {format_size(free_space)[1]}\n"
await utils.answer(message, string)
else:
await utils.answer(message, self.strings["not_ready"])
await asyncio.sleep(5)
await message.delete()
@loader.unrestricted
@loader.ratelimit
async def tdownloadcmd(self, message):
"""Download Torrent file"""
reply, args = await message.get_reply_message(), utils.get_args_raw(message)
if reply and reply.media.document.mime_type == "application/x-bittorrent":
path = await self._client.download_media(reply.media, "scam.torrent")
torrent = self.TransmissionClientUserBot.add_torrent(
"file://scam.torrent", download_dir=args or None
)
kb = [
[
{
"text": self.strings["kb_update"],
"callback": self.inline_update_torrent,
"args": [torrent.id],
}
],
[
{
"text": self.strings["kb_start"],
"callback": self.inline__start,
"args": [torrent.id],
},
{
"text": self.strings["kb_stop"],
"callback": self.inline__stop,
"args": [torrent.id],
},
],
[
{
"text": self.strings["kb_delete_data"],
"callback": self.inline__delete,
"args": [torrent.id, True],
},
{
"text": self.strings["kb_delete"],
"callback": self.inline__delete,
"args": [torrent.id, False],
},
],
[{"text": self.strings["kb_close"], "callback": self.inline__close}],
]
await self.inline.form(
self.stringTorrent(
self.TransmissionClientUserBot.get_torrent(torrent.id)
),
message=message,
reply_markup=kb,
always_allow=self._client.dispatcher.security._owner,
)
async def transmission_inline_handler(self, query: GeekInlineQuery) -> None:
"""
General info (Inline)
"""
args = query.args
param = {"list": "List of 10 torrents", "search": "Search torrents by name"}
param_text = "<b>Available parameters: </b>\n"
for item in param:
param_text += f"{item} - {param[item]}\n"
if not args:
await query.answer(
[
InlineQueryResultArticle(
id=1,
title=self.strings["inline_title"],
description=self.strings["inline_desc"],
input_message_content=InputTextMessageContent(
param_text, "HTML", disable_web_page_preview=True
),
thumb_url="https://img.icons8.com/ios-filled/128/26e07f/torrent.png",
thumb_width=128,
thumb_height=128,
)
],
cache_time=0,
)
return
if "list" in args:
kb_torrent_list = []
for torrent in self.TransmissionClientUserBot.get_torrents():
torrent_markup = InlineKeyboardMarkup(row_width=3)
torrent_markup.insert(
InlineKeyboardButton(
self.strings["kb_update"],
callback_data="cake_update" + str(torrent.id),
),
)
torrent_markup.add(
InlineKeyboardButton(
self.strings["kb_start"],
callback_data="cake_start" + str(torrent.id),
),
InlineKeyboardButton(
self.strings["kb_stop"],
callback_data="cake_stop" + str(torrent.id),
),
)
torrent_markup.add(
InlineKeyboardButton(
self.strings["kb_delete_data"],
callback_data="cake_delete" + str(torrent.id),
),
InlineKeyboardButton(
self.strings["kb_delete"],
callback_data="cake_remove" + str(torrent.id),
),
)
kb_torrent_list.append(
InlineQueryResultArticle(
id=rand(10),
title=torrent.name,
description=self.strings["inline_desc"],
input_message_content=InputTextMessageContent(
self.stringTorrent(
self.TransmissionClientUserBot.get_torrent(torrent.id)
),
"HTML",
disable_web_page_preview=True,
),
reply_markup=torrent_markup,
)
)
if len(kb_torrent_list) == 10:
break
await query.answer(kb_torrent_list[:10], cache_time=0)
return
if "search" in args:
search_arg = " ".join(args.split()[1:]) # transmission search BlaBlaBla
kb_torrent_list = []
for torrent in self.TransmissionClientUserBot.get_torrents():
if search_arg in torrent.name:
torrent_markup = InlineKeyboardMarkup(row_width=3)
torrent_markup.insert(
InlineKeyboardButton(
self.strings["kb_update"],
callback_data="cake_update" + str(torrent.id),
),
)
torrent_markup.add(
InlineKeyboardButton(
self.strings["kb_start"],
callback_data="cake_start" + str(torrent.id),
),
InlineKeyboardButton(
self.strings["kb_stop"],
callback_data="cake_stop" + str(torrent.id),
),
)
torrent_markup.add(
InlineKeyboardButton(
self.strings["kb_delete_data"],
callback_data="cake_delete" + str(torrent.id),
),
InlineKeyboardButton(
self.strings["kb_delete"],
callback_data="cake_remove" + str(torrent.id),
),
)
kb_torrent_list.append(
InlineQueryResultArticle(
id=rand(20),
title=torrent.name,
description=self.strings["inline_desc"],
input_message_content=InputTextMessageContent(
self.stringTorrent(
self.TransmissionClientUserBot.get_torrent(
torrent.id
)
),
"HTML",
disable_web_page_preview=True,
),
reply_markup=torrent_markup,
)
)
return await query.answer(kb_torrent_list[:10], cache_time=0)
# Inline button handler
async def inline__close(self, call) -> None:
await call.delete()
async def inline_update_torrent(self, call, torrent_id) -> None:
kb = [
[
{
"text": self.strings["kb_update"],
"callback": self.inline_update_torrent,
"args": [torrent_id],
}
],
[
{
"text": self.strings["kb_start"],
"callback": self.inline__start,
"args": [torrent_id],
},
{
"text": self.strings["kb_stop"],
"callback": self.inline__stop,
"args": [torrent_id],
},
],
[
{
"text": self.strings["kb_delete_data"],
"callback": self.inline__delete,
"args": [torrent_id, True],
},
{
"text": self.strings["kb_delete"],
"callback": self.inline__delete,
"args": [torrent_id, False],
},
],
[{"text": self.strings["kb_close"], "callback": self.inline__close}],
]
try:
await call.edit(
self.stringTorrent(
self.TransmissionClientUserBot.get_torrent(torrent_id)
),
reply_markup=kb,
)
except KeyError:
await call.edit(self.strings["torrent_error"])
async def inline__start(self, call, torrent_id) -> None:
self.TransmissionClientUserBot.get_torrent(torrent_id).start()
await call.answer(self.strings["answer_start"])
async def inline__stop(self, call, torrent_id) -> None:
self.TransmissionClientUserBot.get_torrent(torrent_id).stop()
await call.answer(self.strings["answer_stop"])
async def inline__delete(self, call, torrent_id, delete_data) -> None:
self.TransmissionClientUserBot.remove_torrent(torrent_id, delete_data)
await call.answer(self.strings["answer_delete"])
# Callback buttons (for Inline search)
async def button_callback_handler(self, call: CallbackQuery) -> None:
"""
Process button presses
"""
# await call.answer(call.data, show_alert=True) # Debug
# Update
if call.data[:11] == "cake_update":
torrent_markup = InlineKeyboardMarkup(row_width=3)
torrent_markup.insert(
InlineKeyboardButton(
self.strings["kb_update"],
callback_data="cake_update" + str(call.data[11:]),
),
)
torrent_markup.add(
InlineKeyboardButton(
self.strings["kb_start"],
callback_data="cake_start" + str(call.data[10:]),
),
InlineKeyboardButton(
self.strings["kb_stop"],
callback_data="cake_stop" + str(call.data[9:]),
),
)
torrent_markup.add(
InlineKeyboardButton(
self.strings["kb_delete_data"],
callback_data="cake_detete" + str(call.data[11:]),
),
InlineKeyboardButton(
self.strings["kb_delete"],
callback_data="cake_remove" + str(call.data[11:]),
),
)
try:
torrent = self.TransmissionClientUserBot.get_torrent(
int(call.data[11:])
)
await self.inline.bot.edit_message_text(
self.stringTorrent(torrent),
reply_markup=torrent_markup,
inline_message_id=call.inline_message_id,
parse_mode="HTML",
)
except KeyError:
await self.inline.bot.edit_message_text(
self.strings["torrent_error"],
inline_message_id=call.inline_message_id,
parse_mode="HTML",
)
except MessageNotModified:
await call.answer(self.strings["inline_answer"])
# Start
if call.data[:10] == "cake_start":
self.TransmissionClientUserBot.get_torrent(int(call.data[11:])).start()
return await call.answer(self.strings["answer_start"])
# Stop
if call.data[:9] == "cake_stop":
self.TransmissionClientUserBot.get_torrent(int(call.data[11:])).stop()
return await call.answer(self.strings["answer_stop"])
# Delete torrent with data
if call.data[:11] == "cake_delete":
self.TransmissionClientUserBot.remove_torrent(int(call.data[11:]), True)
return await call.answer(self.strings["answer_delete"])
# Just delete torrent
if call.data[:11] == "cake_remove":
self.TransmissionClientUserBot.remove_torrent(int(call.data[11:]), False)
return await call.answer(self.strings["answer_delete"])

View File

@@ -0,0 +1,144 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
Copyleft 2022 t.me/CakesTwix
This program is free software; you can redistribute it and/or modify
"""
__version__ = (1, 0, 0)
# requires: aiohttp
# meta pic: https://www.seekpng.com/png/full/824-8246338_yandere-sticker-yandere-simulator-ayano-bloody.png
# meta developer: @cakestwix_mods
import logging
import aiohttp, asyncio
from .. import loader, utils
logger = logging.getLogger(__name__)
@loader.unrestricted
@loader.ratelimit
@loader.tds
class MoebooruMod(loader.Module):
"""Module for obtaining art from the ImageBoard yande.re"""
strings = {
"name": "Yandere",
"url": "https://yande.re/post.json",
"vote_url": "https://yande.re/post/vote.json?login={login}&password_hash={password_hash}",
"vote_ok": "OK!",
"vote_login": "Login or password incorrect.",
"vote_error": "ERROR, .logs 40 or .logs error",
"cfg_yandere_login": "Login from yande.re",
"cfg_yandere_password_hash": "SHA1 hashed password",
}
strings_ru = {
"vote_login": "Неверный логин или пароль.",
"vote_error": "ОШИБКА, .logs 40 или .logs error",
"cfg_yandere_login": "Войти через yande.re",
"cfg_yandere_password_hash": "Хэшированный пароль SHA1",
}
def __init__(self):
self.config = loader.ModuleConfig(
"yandere_login",
"None",
lambda m: self.strings("cfg_yandere_login", m),
"yandere_password_hash",
"None",
lambda m: self.strings("cfg_yandere_password_hash", m),
)
self.name = self.strings["name"]
def string_builder(self, json):
string = f"Tags : {json['tags']}\n"
string += f"©️ : {json['author'] or 'No author'}\n"
string += f"🔗 : {json['source'] or 'No source'}\n\n"
string += (
f"🆔 : <a href=https://yande.re/post/show/{json['id']}>{json['id']}</a>"
)
return string
@loader.unrestricted
@loader.ratelimit
async def ylastcmd(self, message):
"""The last posted art"""
args = utils.get_args(message)
await message.delete()
params = f"?login={self.config['yandere_login']}&password_hash={self.config['yandere_password_hash']}&tags="
async with aiohttp.ClientSession() as session:
async with session.get(self.strings["url"] + params) as get:
art_data = await get.json()
await session.close()
await message.client.send_file(
message.chat_id,
art_data[0]["sample_url"],
caption=self.string_builder(art_data[0]),
)
@loader.unrestricted
@loader.ratelimit
async def yrandomcmd(self, message):
"""Random posted art"""
args = utils.get_args(message)
await message.delete()
params = f"?login={self.config['yandere_login']}&password_hash={self.config['yandere_password_hash']}&tags=order:random"
async with aiohttp.ClientSession() as session:
async with session.get(self.strings["url"] + params) as get:
art_data = await get.json()
await session.close()
await message.client.send_file(
message.chat_id,
art_data[0]["sample_url"],
caption=self.string_builder(art_data[0]),
)
@loader.unrestricted
@loader.ratelimit
async def yvotecmd(self, message):
"""
Vote for art
Bad = -1, None = 0, Good = 1, Great = 2, Favorite = 3
"""
reply = await message.get_reply_message()
args = utils.get_args(message)
if reply and args:
yandere_id = reply.raw_text.split("🆔")[1][2:]
params = {"id": yandere_id, "score": args[0]}
async with aiohttp.ClientSession() as session:
async with session.post(
self.strings["vote_url"].format(
login=self.config["yandere_login"],
password_hash=self.config["yandere_password_hash"],
),
data=params,
) as post:
result_code = post.status
await session.close()
if result_code == 200:
await utils.answer(message, self.strings("vote_ok"))
elif result_code == 403:
await utils.answer(message, self.strings("vote_login"))
else:
await utils.answer(message, self.strings("vote_error"))
await asyncio.sleep(5)
await message.delete()
return
await utils.answer(message, "Pls code! Check help Yandere")
await asyncio.sleep(5)
await message.delete()

View File

@@ -0,0 +1,311 @@
"""
█▀▀ ▄▀█ █▄▀ █▀▀ █▀ ▀█▀ █░█░█ █ ▀▄▀
█▄▄ █▀█ █░█ ██▄ ▄█ ░█░ ▀▄▀▄▀ █ █░█
Copyleft 2022 t.me/CakesTwix
This program is free software; you can redistribute it and/or modify
"""
__version__ = (1, 2, 1)
# requires: aiohttp
# scope: inline
# scope: geektg_only
# scope: geektg_min 3.1.15
# meta pic: https://www.seekpng.com/png/full/824-8246338_yandere-sticker-yandere-simulator-ayano-bloody.png
# meta developer: @cakestwix_mods
import logging
import aiohttp
import asyncio
from .. import loader, main, utils
from ..inline import GeekInlineQuery, rand
from aiogram.types import InlineQueryResultPhoto
from aiogram.utils.markdown import quote_html
logger = logging.getLogger(__name__)
@loader.unrestricted
@loader.ratelimit
@loader.tds
class InlineMoebooruMod(loader.Module):
"""Module for obtaining art from the ImageBoard yande.re"""
strings = {
"name": "InlineYandere",
"url": "https://yande.re/post.json",
"vote_url": "https://yande.re/post/vote.json?login={login}&password_hash={password_hash}",
"vote_text": "Vote for this art. The buttons are only available to me",
"vote_ok": "OK!",
"vote_login": "Login or password incorrect.",
"vote_error": "ERROR, .logs 40 or .logs error",
"cfg_yandere_login": "Login from yande.re",
"cfg_yandere_password_hash": "SHA1 hashed password",
}
strings_ru = {
"vote_text": "Голосуйте за этот арт. Кнопки доступны только мне",
"vote_login": "Неверный логин или пароль.",
"vote_error": "ОШИБКА, .logs 40 или .logs error",
"cfg_yandere_login": "Войти через yande.re",
"cfg_yandere_password_hash": "Хэшированный пароль SHA1",
}
def __init__(self):
self.config = loader.ModuleConfig(
"yandere_login",
"None",
lambda m: self.strings("cfg_yandere_login", m),
"yandere_password_hash",
"None",
lambda m: self.strings("cfg_yandere_password_hash", m),
)
self.name = self.strings["name"]
async def client_ready(self, client, db) -> None:
self.db = db
self.client = client
def string_builder(self, json):
string = f"Tags : {quote_html(json['tags'])}\n"
string += (
f"©️ : {quote_html(json['author']) if json['author'] else 'No author'}\n"
)
string += (
f"🔗 : {quote_html(json['source']) if json['source'] else 'No source'}\n\n"
)
string += f"🆔 : https://yande.re/post/show/{json['id']}"
return string
@loader.unrestricted
@loader.ratelimit
async def ylastcmd(self, message):
"""The last posted art"""
await message.delete()
async with aiohttp.ClientSession() as session:
async with session.get(self.strings["url"]) as get:
art_data = await get.json()
await session.close()
await message.client.send_file(
message.chat_id,
art_data[0]["sample_url"],
caption=self.string_builder(art_data[0]),
)
@loader.unrestricted
@loader.ratelimit
async def yrandomcmd(self, message):
"""The random posted art"""
await message.delete()
params = "?tags=order:random"
async with aiohttp.ClientSession() as session:
async with session.get(self.strings["url"] + params) as get:
art_data = await get.json()
await session.close()
await message.client.send_file(
message.chat_id,
art_data[0]["sample_url"],
caption=self.string_builder(art_data[0]),
)
@loader.unrestricted
@loader.ratelimit
async def yvotecmd(self, message) -> None:
"""
Vote for art
Bad = -1, None = 0, Good = 1, Great = 2, Favorite = 3
"""
reply = await message.get_reply_message()
args = utils.get_args(message)
if reply and args:
yandere_id = reply.raw_text.split("🆔")[1].split("/")[5]
params = {"id": yandere_id, "score": args[0]}
async with aiohttp.ClientSession() as session:
async with session.post(
self.strings["vote_url"].format(
login=self.config["yandere_login"],
password_hash=self.config["yandere_password_hash"],
),
data=params,
) as post:
result_code = post.status
await session.close()
if result_code == 200:
await utils.answer(message, self.strings("vote_ok"))
elif result_code == 403:
await utils.answer(message, self.strings("vote_login"))
else:
await utils.answer(message, self.strings("vote_error"))
await asyncio.sleep(5)
await message.delete()
return
elif reply:
yandere_id = reply.raw_text.split("🆔")[1][2:]
kb = [
[
{
"text": "Bad",
"callback": self.inline__vote,
"args": [-1, yandere_id],
}
],
[
{
"text": "Good",
"callback": self.inline__vote,
"args": [1, yandere_id],
}
],
[
{
"text": "Great",
"callback": self.inline__vote,
"args": [2, yandere_id],
}
],
[
{
"text": "Favorite",
"callback": self.inline__vote,
"args": [3, yandere_id],
}
],
]
await self.inline.form(
self.strings["vote_text"],
message=message,
reply_markup=kb,
always_allow=self.client.dispatcher.security._owner,
)
return
await utils.answer(message, "Pls code! Check help Yandere")
await asyncio.sleep(5)
await message.delete()
# Inline commands
async def ylast_inline_handler(self, query: GeekInlineQuery) -> None:
"""
The last posted art (Inline)
@allow: all
"""
async with aiohttp.ClientSession() as session:
async with session.get(self.strings["url"]) as get:
arts = await get.json()
await session.close()
inline_query = [
InlineQueryResultPhoto(
id=rand(20),
title="Title",
description="Description",
caption=self.string_builder(art),
thumb_url=art["preview_url"],
photo_url=art["sample_url"],
parse_mode="html",
)
for art in arts
]
await query.answer(
inline_query,
cache_time=0,
)
async def yrandom_inline_handler(self, query: GeekInlineQuery) -> None:
"""
The random posted art (Inline)
@allow: all
"""
params = "?tags=order:random"
async with aiohttp.ClientSession() as session:
async with session.get(self.strings["url"] + params) as get:
arts = await get.json()
await session.close()
inline_query = [
InlineQueryResultPhoto(
id=rand(20),
title="Title",
description="Description",
caption=self.string_builder(art),
thumb_url=art["preview_url"],
photo_url=art["sample_url"],
parse_mode="html",
)
for art in arts
]
await query.answer(
inline_query,
cache_time=0,
)
async def ysearch_inline_handler(self, query: GeekInlineQuery) -> None:
"""
Search art by tags. (https://yande.re/help)
@allow: all
"""
text = query.args
if not text:
return
params = "?tags=order:random " + text
async with aiohttp.ClientSession() as session:
async with session.get(self.strings["url"] + params) as get:
arts = await get.json()
await session.close()
inline_query = [
InlineQueryResultPhoto(
id=rand(20),
title="Title",
description="Description",
caption=self.string_builder(art),
thumb_url=art["preview_url"],
photo_url=art["sample_url"],
parse_mode="html",
)
for art in arts
]
await query.answer(
inline_query,
cache_time=0,
)
# Inline button handler
async def inline__close(self, call: "aiogram.types.CallbackQuery") -> None:
await call.delete()
async def inline__vote(self, call, score, _id) -> None:
params = {"id": _id, "score": score}
async with aiohttp.ClientSession() as session:
async with session.post(
self.strings["vote_url"].format(
login=self.config["yandere_login"],
password_hash=self.config["yandere_password_hash"],
),
data=params,
) as post:
result_code = post.status
await session.close()
kb = [[{"text": "🚫 Close", "callback": self.inline__close}]]
if result_code == 200:
await call.edit(self.strings("vote_ok"), reply_markup=kb)
elif result_code == 403:
await call.edit(self.strings("vote_login"), reply_markup=kb)
else:
await call.edit(self.strings("vote_error"), reply_markup=kb)