Merge pull request #2 from MuRuLOSE:update-submodules_35e8befc453031d1d68aa11d84f353566ee7b2bb

Update of repositories 2025-07-11 08:28:43
This commit is contained in:
Macsim
2025-07-11 13:02:37 +03:00
committed by GitHub
321 changed files with 38145 additions and 33524 deletions

0
AlpacaGang/ftg-modules/DND.py Normal file → Executable file
View File

0
AlpacaGang/ftg-modules/Tag.py Normal file → Executable file
View File

0
AlpacaGang/ftg-modules/spam.py Normal file → Executable file
View File

View File

@@ -1,69 +1,69 @@
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
# 🔒 Licensed under the GNU GPLv3
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
# 👤 https://t.me/hikamoru
# meta developer: @hikamorumods
# meta banner: https://raw.githubusercontent.com/AmoreForever/assets/master/Hacker.jpg
__version__ = (1, 0, 0)
from .. import loader, utils
import requests
from PIL import Image,ImageFont,ImageDraw
import io
from textwrap import wrap
@loader.tds
class HackerMod(loader.Module):
"""Create hacker message stickers"""
strings = {
'name': 'Hacker',
'what': 'Reply to text or write text <emoji document_id="5467928559664242360">❗️</emoji>',
'processing': 'Processing <emoji document_id="6334710044407368265">🚀</emoji>'
}
@loader.owner
async def hackercmd(self, message):
"""Reply to text or write text"""
ufr = requests.get("https://0x0.st/opzq.ttf")
f = ufr.content
reply = await message.get_reply_message()
args = utils.get_args_raw(message)
if not args:
if not reply:
await message.edit(self.strings('what', message))
return
else:
txt = reply.raw_text
else:
txt = utils.get_args_raw(message)
await message.edit(self.strings("processing"))
pic = requests.get("https://0x0.st/opzN.jpg")
pic.raw.decode_content = True
img = Image.open(io.BytesIO(pic.content)).convert("RGB")
W, H = img.size
txt = txt.replace("\n", "𓃐")
text = "\n".join(wrap(txt, 19))
t = text + "\n"
t = t.replace("𓃐","\n")
draw = ImageDraw.Draw(img)
font = ImageFont.truetype(io.BytesIO(f), 32, encoding='UTF-8')
w, h = draw.multiline_textsize(t, font=font)
imtext = Image.new("RGBA", (w+10, h+10), (255, 250, 250, 1))
draw = ImageDraw.Draw(imtext)
draw.multiline_text((10, 10),t,(255, 255, 255),font=font, align='left')
imtext.thumbnail((339, 181))
w, h = 339, 181
img.paste(imtext, (10,10), imtext)
out = io.BytesIO()
out.name = "amore.webp"
img.save(out)
out.seek(0)
await message.client.send_file(message.to_id, out, reply_to=reply)
await message.delete()
# █ █ █ █▄▀ ▄▀█ █▀▄▀█ █▀█ █▀█ █ █
# █▀█ █ █ █ █▀█ █ ▀ █ █▄█ █▀▄ █▄█
# 🔒 Licensed under the GNU GPLv3
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
# 👤 https://t.me/hikamoru
# meta developer: @hikamorumods
# meta banner: https://raw.githubusercontent.com/AmoreForever/assets/master/Hacker.jpg
__version__ = (1, 0, 0)
from .. import loader, utils
import requests
from PIL import Image,ImageFont,ImageDraw
import io
from textwrap import wrap
@loader.tds
class HackerMod(loader.Module):
"""Create hacker message stickers"""
strings = {
'name': 'Hacker',
'what': 'Reply to text or write text <emoji document_id="5467928559664242360">❗️</emoji>',
'processing': 'Processing <emoji document_id="6334710044407368265">🚀</emoji>'
}
@loader.owner
async def hackercmd(self, message):
"""Reply to text or write text"""
ufr = requests.get("https://0x0.st/opzq.ttf")
f = ufr.content
reply = await message.get_reply_message()
args = utils.get_args_raw(message)
if not args:
if not reply:
await message.edit(self.strings('what', message))
return
else:
txt = reply.raw_text
else:
txt = utils.get_args_raw(message)
await message.edit(self.strings("processing"))
pic = requests.get("https://0x0.st/opzN.jpg")
pic.raw.decode_content = True
img = Image.open(io.BytesIO(pic.content)).convert("RGB")
W, H = img.size
txt = txt.replace("\n", "𓃐")
text = "\n".join(wrap(txt, 19))
t = text + "\n"
t = t.replace("𓃐","\n")
draw = ImageDraw.Draw(img)
font = ImageFont.truetype(io.BytesIO(f), 32, encoding='UTF-8')
w, h = draw.multiline_textsize(t, font=font)
imtext = Image.new("RGBA", (w+10, h+10), (255, 250, 250, 1))
draw = ImageDraw.Draw(imtext)
draw.multiline_text((10, 10),t,(255, 255, 255),font=font, align='left')
imtext.thumbnail((339, 181))
w, h = 339, 181
img.paste(imtext, (10,10), imtext)
out = io.BytesIO()
out.name = "amore.webp"
img.save(out)
out.seek(0)
await message.client.send_file(message.to_id, out, reply_to=reply)
await message.delete()

View File

@@ -1,176 +1,176 @@
# Proprietary License Agreement
# Copyright (c) 2024-29 CodWiz
# Permission is hereby granted to any person obtaining a copy of this software and associated documentation files (the "Software"), to use the Software for personal and non-commercial purposes, subject to the following conditions:
# 1. The Software may not be modified, altered, or otherwise changed in any way without the explicit written permission of the author.
# 2. Redistribution of the Software, in original or modified form, is strictly prohibited without the explicit written permission of the author.
# 3. The Software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and non-infringement. In no event shall the author or copyright holder be liable for any claim, damages, or other liability, whether in an action of contract, tort, or otherwise, arising from, out of, or in connection with the Software or the use or other dealings in the Software.
# 4. Any use of the Software must include the above copyright notice and this permission notice in all copies or substantial portions of the Software.
# 5. By using the Software, you agree to be bound by the terms and conditions of this license.
# For any inquiries or requests for permissions, please contact codwiz@yandex.ru.
# ---------------------------------------------------------------------------------
# Name: FakeWallet
# Description: Fun joke - fake crypto wallet. You can change cryptocurrency values using .cfg FakeWallet.
# Author: @hikka_mods
# ---------------------------------------------------------------------------------
# -----------------------------------------------------------------------------------
# meta developer: @hikka_mods
# scope: hikka_only
# scope: hikka_min 1.4.2
# -----------------------------------------------------------------------------------
from .. import loader, utils
@loader.tds
class FakeWallet(loader.Module):
"""Fun joke - fake crypto wallet. You can change cryptocurrency values using .cfg FakeWallet."""
def __init__(self):
self.config = loader.ModuleConfig(
loader.ConfigValue(
"Toncoin",
0,
lambda: self.strings("ton"),
validator=loader.validators.Integer(),
),
loader.ConfigValue(
"Tether",
0,
lambda: self.strings("tether"),
validator=loader.validators.Integer(),
),
loader.ConfigValue(
"Bitcoin",
0,
lambda: self.strings("btc"),
validator=loader.validators.Integer(),
),
loader.ConfigValue(
"Etherium",
0,
lambda: self.strings("ether"),
validator=loader.validators.Integer(),
),
loader.ConfigValue(
"Binance",
0,
lambda: self.strings("binc"),
validator=loader.validators.Integer(),
),
loader.ConfigValue(
"Tron",
0,
lambda: self.strings("tron"),
validator=loader.validators.Integer(),
),
loader.ConfigValue(
"USDT",
0,
lambda: self.strings("usdt"),
validator=loader.validators.Integer(),
),
loader.ConfigValue(
"Gram",
0,
lambda: self.strings("gram"),
validator=loader.validators.Integer(),
),
loader.ConfigValue(
"Litecoin",
0,
lambda: self.strings("lite"),
validator=loader.validators.Integer(),
),
)
strings = {
"name": "FakeWallet",
"crypto": "Enter a value for your cryptovalute",
"wallet": "<emoji document_id=5438626338560810621>👛</emoji> <b>Wallet</b>\n\n"
"<emoji document_id=5215276644620586569>☺️</emoji> <a href='https://ton.org'>Toncoin</a>: {} TON\n\n"
"<emoji document_id=5215699136258524363>☺️</emoji> <a href='https://tether.to'>Tether</a>: {} USDT\n\n"
"<emoji document_id=5215590800003451651>☺️</emoji> <a href='https://bitcoin.org'>Bitcoin</a>: {} BTC\n\n"
"<emoji document_id=5217867240044512715>☺️</emoji> <a href='https://etherium.org'>Etherium</a>: {} ETH\n\n"
"<emoji document_id=5215595550237279768>☺️</emoji> <a href='https://binance.org'>Binance coin</a>: {} BNB\n\n"
"<emoji document_id=5215437796088499410>☺️</emoji> <a href='https://tron.network'>TRON</a>: {} TRX\n\n"
"<emoji document_id=5215440441788351459>☺️</emoji> <a href='https://www.centre.io/usdc'>USD Coin</a>: {} USDC\n\n"
"<emoji document_id=5215267041073711005>☺️</emoji> <a href='https://gramcoin.org'>Gram</a>: {} GRAM\n\n"
"<emoji document_id=5217877586620729050>☺️</emoji> <a href='https://litecoin.org'>Litecoin</a>: {} LTC",
"ton": "Enter a value for Toncoin",
"teth": "Enter a value for Tethcoin",
"btc": "Enter a value for Bitcoin",
"ether": "Enter a value for Etherium",
"binc": "Enter a value for Binance coin",
"tron": "Enter a value for Tron",
"usdt": "Enter a value for USDT coin",
"gram": "Enter a value for Gramcoin",
"lite": "Enter a value for Litecoin",
"info": "<b><emoji document_id=5305467350064047192>🫥</emoji><i>Attention!</b>\n\n"
"<i><emoji document_id=5915991028430542030>☝️</emoji>This module is strictly prohibited from being used for the purposes of <b>scam, fraud and advertising</b>.\n\n"
"<emoji document_id=5787190061644647815>🗣</emoji>The module is provided solely for entertainment purposes, and any violation of the <b>Rules for using the module</b>, if detected, will be subject <b>to appropriate punishment</i>",
}
strings_ru = {
"wallet": "<emoji document_id=5438626338560810621>👛</emoji> <b>Кошелёк</b>\n\n"
"<emoji document_id=5215276644620586569>☺️</emoji> <a href='https://ton.org'>Toncoin</a>: {} TON\n\n"
"<emoji document_id=5215699136258524363>☺️</emoji> <a href='https://tether.to'>Tether</a>: {} USDT\n\n"
"<emoji document_id=5215590800003451651>☺️</emoji> <a href='https://bitcoin.org'>Bitcoin</a>: {} BTC\n\n"
"<emoji document_id=5217867240044512715>☺️</emoji> <a href='https://etherium.org'>Etherium</a>: {} ETH\n\n"
"<emoji document_id=5215595550237279768>☺️</emoji> <a href='https://binance.org'>Binance coin</a>: {} BNB\n\n"
"<emoji document_id=5215437796088499410>☺️</emoji> <a href='https://tron.network'>TRON</a>: {} TRX\n\n"
"<emoji document_id=5215440441788351459>☺️</emoji> <a href='https://www.centre.io/usdc'>USD Coin</a>: {} USDC\n\n"
"<emoji document_id=5215267041073711005>☺️</emoji> <a href='https://gramcoin.org'>Gram</a>: {} GRAM\n\n"
"<emoji document_id=5217877586620729050>☺️</emoji> <a href='https://litecoin.org'>Litecoin</a>: {} LTC",
"ton": "Введите количество валюты для Toncoin",
"teth": "Введите количество валюты для Tethcoin",
"btc": "Введите количество валюты для Bitcoin",
"ether": "Введите количество валюты для Etherium",
"binc": "Введите количество валюты для Binance coin",
"tron": "Введите количество валюты для Tron",
"usdt": "Введите количество валюты для USDT coin",
"gram": "Введите количество валюты для Gramcoin",
"lite": "Введите количество валюты для Litecoin",
"info": "<b><emoji document_id=5305467350064047192>🫥</emoji><i> Внимание!</b>\n\n"
"<i><emoji document_id=5915991028430542030>☝️</emoji> Использование этого модуля в целях <b>скама, обмана и рекламы</b> строго запрещено.\n\n"
"<emoji document_id=5787190061644647815>🗣</emoji> Модуль предоставлен исключительно в развлекательных целях, и любое нарушение <b>Правил использования модуля</b>, если его обнаружат, будет подлежать соответствующему наказанию.</i>",
}
@loader.command(
ru_doc="Чтобы заполучить поддельный кошелек",
en_doc="To get a fake wallet",
)
@loader.command()
async def fwalletcmd(self, message):
ton = self.config["Toncoin"]
teth = self.config["Tether"]
btc = self.config["Bitcoin"]
ether = self.config["Etherium"]
binc = self.config["Binance"]
tron = self.config["Tron"]
usdt = self.config["USDT"]
gram = self.config["Gram"]
lite = self.config["Litecoin"]
await utils.answer(
message,
self.strings("wallet").format(
ton, teth, btc, ether, binc, tron, usdt, gram, lite
),
)
@loader.command(
ru_doc="Информация о FakeModule",
en_doc="Info about FakeModule",
)
@loader.command()
async def fwinfocmd(self, message):
await utils.answer(message, self.strings("info"))
# Proprietary License Agreement
# Copyright (c) 2024-29 CodWiz
# Permission is hereby granted to any person obtaining a copy of this software and associated documentation files (the "Software"), to use the Software for personal and non-commercial purposes, subject to the following conditions:
# 1. The Software may not be modified, altered, or otherwise changed in any way without the explicit written permission of the author.
# 2. Redistribution of the Software, in original or modified form, is strictly prohibited without the explicit written permission of the author.
# 3. The Software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and non-infringement. In no event shall the author or copyright holder be liable for any claim, damages, or other liability, whether in an action of contract, tort, or otherwise, arising from, out of, or in connection with the Software or the use or other dealings in the Software.
# 4. Any use of the Software must include the above copyright notice and this permission notice in all copies or substantial portions of the Software.
# 5. By using the Software, you agree to be bound by the terms and conditions of this license.
# For any inquiries or requests for permissions, please contact codwiz@yandex.ru.
# ---------------------------------------------------------------------------------
# Name: FakeWallet
# Description: Fun joke - fake crypto wallet. You can change cryptocurrency values using .cfg FakeWallet.
# Author: @hikka_mods
# ---------------------------------------------------------------------------------
# -----------------------------------------------------------------------------------
# meta developer: @hikka_mods
# scope: hikka_only
# scope: hikka_min 1.4.2
# -----------------------------------------------------------------------------------
from .. import loader, utils
@loader.tds
class FakeWallet(loader.Module):
"""Fun joke - fake crypto wallet. You can change cryptocurrency values using .cfg FakeWallet."""
def __init__(self):
self.config = loader.ModuleConfig(
loader.ConfigValue(
"Toncoin",
0,
lambda: self.strings("ton"),
validator=loader.validators.Integer(),
),
loader.ConfigValue(
"Tether",
0,
lambda: self.strings("tether"),
validator=loader.validators.Integer(),
),
loader.ConfigValue(
"Bitcoin",
0,
lambda: self.strings("btc"),
validator=loader.validators.Integer(),
),
loader.ConfigValue(
"Etherium",
0,
lambda: self.strings("ether"),
validator=loader.validators.Integer(),
),
loader.ConfigValue(
"Binance",
0,
lambda: self.strings("binc"),
validator=loader.validators.Integer(),
),
loader.ConfigValue(
"Tron",
0,
lambda: self.strings("tron"),
validator=loader.validators.Integer(),
),
loader.ConfigValue(
"USDT",
0,
lambda: self.strings("usdt"),
validator=loader.validators.Integer(),
),
loader.ConfigValue(
"Gram",
0,
lambda: self.strings("gram"),
validator=loader.validators.Integer(),
),
loader.ConfigValue(
"Litecoin",
0,
lambda: self.strings("lite"),
validator=loader.validators.Integer(),
),
)
strings = {
"name": "FakeWallet",
"crypto": "Enter a value for your cryptovalute",
"wallet": "<emoji document_id=5438626338560810621>👛</emoji> <b>Wallet</b>\n\n"
"<emoji document_id=5215276644620586569>☺️</emoji> <a href='https://ton.org'>Toncoin</a>: {} TON\n\n"
"<emoji document_id=5215699136258524363>☺️</emoji> <a href='https://tether.to'>Tether</a>: {} USDT\n\n"
"<emoji document_id=5215590800003451651>☺️</emoji> <a href='https://bitcoin.org'>Bitcoin</a>: {} BTC\n\n"
"<emoji document_id=5217867240044512715>☺️</emoji> <a href='https://etherium.org'>Etherium</a>: {} ETH\n\n"
"<emoji document_id=5215595550237279768>☺️</emoji> <a href='https://binance.org'>Binance coin</a>: {} BNB\n\n"
"<emoji document_id=5215437796088499410>☺️</emoji> <a href='https://tron.network'>TRON</a>: {} TRX\n\n"
"<emoji document_id=5215440441788351459>☺️</emoji> <a href='https://www.centre.io/usdc'>USD Coin</a>: {} USDC\n\n"
"<emoji document_id=5215267041073711005>☺️</emoji> <a href='https://gramcoin.org'>Gram</a>: {} GRAM\n\n"
"<emoji document_id=5217877586620729050>☺️</emoji> <a href='https://litecoin.org'>Litecoin</a>: {} LTC",
"ton": "Enter a value for Toncoin",
"teth": "Enter a value for Tethcoin",
"btc": "Enter a value for Bitcoin",
"ether": "Enter a value for Etherium",
"binc": "Enter a value for Binance coin",
"tron": "Enter a value for Tron",
"usdt": "Enter a value for USDT coin",
"gram": "Enter a value for Gramcoin",
"lite": "Enter a value for Litecoin",
"info": "<b><emoji document_id=5305467350064047192>🫥</emoji><i>Attention!</b>\n\n"
"<i><emoji document_id=5915991028430542030>☝️</emoji>This module is strictly prohibited from being used for the purposes of <b>scam, fraud and advertising</b>.\n\n"
"<emoji document_id=5787190061644647815>🗣</emoji>The module is provided solely for entertainment purposes, and any violation of the <b>Rules for using the module</b>, if detected, will be subject <b>to appropriate punishment</i>",
}
strings_ru = {
"wallet": "<emoji document_id=5438626338560810621>👛</emoji> <b>Кошелёк</b>\n\n"
"<emoji document_id=5215276644620586569>☺️</emoji> <a href='https://ton.org'>Toncoin</a>: {} TON\n\n"
"<emoji document_id=5215699136258524363>☺️</emoji> <a href='https://tether.to'>Tether</a>: {} USDT\n\n"
"<emoji document_id=5215590800003451651>☺️</emoji> <a href='https://bitcoin.org'>Bitcoin</a>: {} BTC\n\n"
"<emoji document_id=5217867240044512715>☺️</emoji> <a href='https://etherium.org'>Etherium</a>: {} ETH\n\n"
"<emoji document_id=5215595550237279768>☺️</emoji> <a href='https://binance.org'>Binance coin</a>: {} BNB\n\n"
"<emoji document_id=5215437796088499410>☺️</emoji> <a href='https://tron.network'>TRON</a>: {} TRX\n\n"
"<emoji document_id=5215440441788351459>☺️</emoji> <a href='https://www.centre.io/usdc'>USD Coin</a>: {} USDC\n\n"
"<emoji document_id=5215267041073711005>☺️</emoji> <a href='https://gramcoin.org'>Gram</a>: {} GRAM\n\n"
"<emoji document_id=5217877586620729050>☺️</emoji> <a href='https://litecoin.org'>Litecoin</a>: {} LTC",
"ton": "Введите количество валюты для Toncoin",
"teth": "Введите количество валюты для Tethcoin",
"btc": "Введите количество валюты для Bitcoin",
"ether": "Введите количество валюты для Etherium",
"binc": "Введите количество валюты для Binance coin",
"tron": "Введите количество валюты для Tron",
"usdt": "Введите количество валюты для USDT coin",
"gram": "Введите количество валюты для Gramcoin",
"lite": "Введите количество валюты для Litecoin",
"info": "<b><emoji document_id=5305467350064047192>🫥</emoji><i> Внимание!</b>\n\n"
"<i><emoji document_id=5915991028430542030>☝️</emoji> Использование этого модуля в целях <b>скама, обмана и рекламы</b> строго запрещено.\n\n"
"<emoji document_id=5787190061644647815>🗣</emoji> Модуль предоставлен исключительно в развлекательных целях, и любое нарушение <b>Правил использования модуля</b>, если его обнаружат, будет подлежать соответствующему наказанию.</i>",
}
@loader.command(
ru_doc="Чтобы заполучить поддельный кошелек",
en_doc="To get a fake wallet",
)
@loader.command()
async def fwalletcmd(self, message):
ton = self.config["Toncoin"]
teth = self.config["Tether"]
btc = self.config["Bitcoin"]
ether = self.config["Etherium"]
binc = self.config["Binance"]
tron = self.config["Tron"]
usdt = self.config["USDT"]
gram = self.config["Gram"]
lite = self.config["Litecoin"]
await utils.answer(
message,
self.strings("wallet").format(
ton, teth, btc, ether, binc, tron, usdt, gram, lite
),
)
@loader.command(
ru_doc="Информация о FakeModule",
en_doc="Info about FakeModule",
)
@loader.command()
async def fwinfocmd(self, message):
await utils.answer(message, self.strings("info"))

View File

@@ -1,213 +1,213 @@
# Proprietary License Agreement
# Copyright (c) 2024-29 CodWiz
# Permission is hereby granted to any person obtaining a copy of this software and associated documentation files (the "Software"), to use the Software for personal and non-commercial purposes, subject to the following conditions:
# 1. The Software may not be modified, altered, or otherwise changed in any way without the explicit written permission of the author.
# 2. Redistribution of the Software, in original or modified form, is strictly prohibited without the explicit written permission of the author.
# 3. The Software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and non-infringement. In no event shall the author or copyright holder be liable for any claim, damages, or other liability, whether in an action of contract, tort, or otherwise, arising from, out of, or in connection with the Software or the use or other dealings in the Software.
# 4. Any use of the Software must include the above copyright notice and this permission notice in all copies or substantial portions of the Software.
# 5. By using the Software, you agree to be bound by the terms and conditions of this license.
# For any inquiries or requests for permissions, please contact codwiz@yandex.ru.
# ---------------------------------------------------------------------------------
# Name: InlineHelper
# Description: Basic management of the UB in case only the inline works
# Author: @hikka_mods
# ---------------------------------------------------------------------------------
# meta developer: @hikka_mods
# scope: InlineHelper
# scope: InlineHelper 0.0.1
# ---------------------------------------------------------------------------------
import sys
import os
import asyncio
import logging
from ..inline.types import InlineQuery
from .. import loader, utils, main
@loader.tds
class InlineHelperMod(loader.Module):
"""Basic management of the UB in case only the inline works"""
strings = {
"name": "InlineHelper",
"call_restart": "Restarting...",
"call_update": "Updating...",
"res_prefix": "Successfully reset prefix to default",
"restart_inline_handler_title": "Restart Userbot",
"restart_inline_handler_description": "Restart your userbot via inline",
"restart_inline_handler_message": "Press the button below to restart your userbot",
"restart_inline_handler_reply_text": "Restart",
"update_inline_handler_title": "Update Userbot",
"update_inline_handler_description": "Update your userbot via inline",
"update_inline_handler_message": "Press the button below to update your userbot",
"update_inline_handler_reply_text": "Update",
"terminal_inline_handler_title": "Command Executed!",
"terminal_inline_handler_description": "Command executed successfully",
"terminal_inline_handler_message": "Command {text} executed successfully in terminal",
"modules_inline_handler_title": "Modules",
"modules_inline_handler_description": "List all installed modules",
"modules_inline_handler_result": "☘️ Installed modules:\n",
"resetprefix_inline_handler_title": "Reset Prefix",
"resetprefix_inline_handler_description": "Reset your prefix back to default",
"resetprefix_inline_handler_message": "Are you sure you want to reset your prefix to default dot?",
"resetprefix_inline_handler_reply_text_yes": "Yes",
"resetprefix_inline_handler_reply_text_no": "No",
}
strings_ru = {
"call_restart": "Перезагружаю...",
"call_update": "Обновляю...",
"res_prefix": "Префикс успешно сброшен по умолчанию",
"restart_inline_handler_title": "Перезагрузить юзербота",
"restart_inline_handler_description": "Перезагрузить юзербота через инлайн",
"restart_inline_handler_message": "<b>Нажмите на кнопку ниже для рестарта юзербота</b>",
"restart_inline_handler_reply_text": "Перезапуск",
"update_inline_handler_title": "Обновить юзербота",
"update_inline_handler_description": "Обновить юзербота через инлайн",
"update_inline_handler_message": "<b>Нажмите на кнопку ниже для обновления юзербота</b>",
"update_inline_handler_reply_text": "Обновить",
"terminal_inline_handler_title": "Команда выполнена!",
"terminal_inline_handler_description": "Команда завершена.",
"terminal_inline_handler_message": "Команда <code>{text}</code> была успешно выполнена в терминале",
"modules_inline_handler_title": "Модули",
"modules_inline_handler_description": "Вывести список установленных моудей",
"modules_inline_handler_result": "☘️ Все установленные модули:\n",
"resetprefix_inline_handler_title": "Сбросить префикс",
"resetprefix_inline_handler_description": "Сбросить префикс по умолчанию",
"resetprefix_inline_handler_message": "Вы действительно хотите сбросить ваш префикс и установить стандартную точку?",
"resetprefix_inline_handler_reply_text_yes": "Да",
"resetprefix_inline_handler_reply_text_no": "Нет",
}
async def client_ready(self, client, db):
self.client = client
self.db = db
async def restart(self, call):
"""Restart callback"""
logging.error("InlineHelper: restarting userbot...")
await call.edit(self.strings("call_restart"))
await sys.exit(0)
async def update(self, call):
"""Update callback"""
logging.error("InlineHelper: updating userbot...")
os.system(f"cd {utils.get_base_dir()} && cd .. && git reset --hard HEAD")
os.system("git pull")
await call.edit(self.strings("call_update"))
await sys.exit(0)
async def reset_prefix(self, call):
"""Reset prefix"""
self.db.set(main.__name__, "command_prefix", ".")
await call.edit(self.strings("res_prefix"))
@loader.inline_handler(
ru_doc="Перезагрузить юзербота",
en_doc="Reboot the userbot",
)
async def restart_inline_handler(self, _: InlineQuery):
return {
"title": self.strings("restart_inline_handler_title"),
"description": self.strings("restart_inline_handler_description"),
"message": self.strings("restart_inline_handler_message"),
"reply_markup": [
{
"text": self.strings("restart_inline_handler_reply_text"),
"callback": self.restart,
}
],
}
@loader.inline_handler(
ru_doc="Обновить юзербота",
en_doc="Update the userbot",
)
async def update_inline_handler(self, _: InlineQuery):
return {
"title": self.strings("update_inline_handler_title"),
"description": self.strings("update_inline_handler_description"),
"message": self.strings("update_inline_handler_message"),
"reply_markup": [
{
"text": self.strings("update_inline_handler_reply_text"),
"callback": self.update,
}
],
}
@loader.inline_handler(
ru_doc="Выполнить команду в терминале (лучше сразу подготовить команду и просто вставить)",
en_doc="Execute the command in the terminal (it is better to prepare the command immediately and just paste it)",
)
async def terminal_inline_handler(self, _: InlineQuery):
text = _.args
await asyncio.create_subprocess_shell(
f"{text}",
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
cwd=utils.get_base_dir(),
)
return {
"title": self.strings("terminal_inline_handler_title"),
"description": self.strings("terminal_inline_handler_description"),
"message": self.strings("terminal_inline_handler_message").format(
text=text
),
}
@loader.inline_handler(
ru_doc="Вывести список установленных модулей через инлайн",
en_doc="Display a list of installed modules via the inline",
)
async def modules_inline_handler(self, _: InlineQuery):
result = self.strings("modules_inline_handler_result")
for mod in self.allmodules.modules:
try:
name = mod.strings["name"]
except KeyError:
name = mod.__clas__.__name__
result += f"{name}\n"
return {
"title": self.strings("modules_inline_handler_title"),
"description": self.strings("modules_inline_handler_description"),
"message": result,
}
@loader.inline_handler(
ru_doc="Сбросить префикс (осторожнее, сбрасывает ваш префикс на . )",
en_doc="Reset the prefix (be careful, resets your prefix to . )",
)
async def resetprefix_inline_handler(self, _: InlineQuery):
return {
"title": self.strings("resetprefix_inline_handler_title"),
"description": self.strings("resetprefix_inline_handler_description"),
"message": self.strings("resetprefix_inline_handler_message"),
"reply_markup": [
{
"text": self.strings("resetprefix_inline_handler_reply_text_yes"),
"callback": self.reset_prefix,
},
{
"text": self.strings("resetprefix_inline_handler_reply_text_no"),
"action": "close",
},
],
}
# Proprietary License Agreement
# Copyright (c) 2024-29 CodWiz
# Permission is hereby granted to any person obtaining a copy of this software and associated documentation files (the "Software"), to use the Software for personal and non-commercial purposes, subject to the following conditions:
# 1. The Software may not be modified, altered, or otherwise changed in any way without the explicit written permission of the author.
# 2. Redistribution of the Software, in original or modified form, is strictly prohibited without the explicit written permission of the author.
# 3. The Software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and non-infringement. In no event shall the author or copyright holder be liable for any claim, damages, or other liability, whether in an action of contract, tort, or otherwise, arising from, out of, or in connection with the Software or the use or other dealings in the Software.
# 4. Any use of the Software must include the above copyright notice and this permission notice in all copies or substantial portions of the Software.
# 5. By using the Software, you agree to be bound by the terms and conditions of this license.
# For any inquiries or requests for permissions, please contact codwiz@yandex.ru.
# ---------------------------------------------------------------------------------
# Name: InlineHelper
# Description: Basic management of the UB in case only the inline works
# Author: @hikka_mods
# ---------------------------------------------------------------------------------
# meta developer: @hikka_mods
# scope: InlineHelper
# scope: InlineHelper 0.0.1
# ---------------------------------------------------------------------------------
import sys
import os
import asyncio
import logging
from ..inline.types import InlineQuery
from .. import loader, utils, main
@loader.tds
class InlineHelperMod(loader.Module):
"""Basic management of the UB in case only the inline works"""
strings = {
"name": "InlineHelper",
"call_restart": "Restarting...",
"call_update": "Updating...",
"res_prefix": "Successfully reset prefix to default",
"restart_inline_handler_title": "Restart Userbot",
"restart_inline_handler_description": "Restart your userbot via inline",
"restart_inline_handler_message": "Press the button below to restart your userbot",
"restart_inline_handler_reply_text": "Restart",
"update_inline_handler_title": "Update Userbot",
"update_inline_handler_description": "Update your userbot via inline",
"update_inline_handler_message": "Press the button below to update your userbot",
"update_inline_handler_reply_text": "Update",
"terminal_inline_handler_title": "Command Executed!",
"terminal_inline_handler_description": "Command executed successfully",
"terminal_inline_handler_message": "Command {text} executed successfully in terminal",
"modules_inline_handler_title": "Modules",
"modules_inline_handler_description": "List all installed modules",
"modules_inline_handler_result": "☘️ Installed modules:\n",
"resetprefix_inline_handler_title": "Reset Prefix",
"resetprefix_inline_handler_description": "Reset your prefix back to default",
"resetprefix_inline_handler_message": "Are you sure you want to reset your prefix to default dot?",
"resetprefix_inline_handler_reply_text_yes": "Yes",
"resetprefix_inline_handler_reply_text_no": "No",
}
strings_ru = {
"call_restart": "Перезагружаю...",
"call_update": "Обновляю...",
"res_prefix": "Префикс успешно сброшен по умолчанию",
"restart_inline_handler_title": "Перезагрузить юзербота",
"restart_inline_handler_description": "Перезагрузить юзербота через инлайн",
"restart_inline_handler_message": "<b>Нажмите на кнопку ниже для рестарта юзербота</b>",
"restart_inline_handler_reply_text": "Перезапуск",
"update_inline_handler_title": "Обновить юзербота",
"update_inline_handler_description": "Обновить юзербота через инлайн",
"update_inline_handler_message": "<b>Нажмите на кнопку ниже для обновления юзербота</b>",
"update_inline_handler_reply_text": "Обновить",
"terminal_inline_handler_title": "Команда выполнена!",
"terminal_inline_handler_description": "Команда завершена.",
"terminal_inline_handler_message": "Команда <code>{text}</code> была успешно выполнена в терминале",
"modules_inline_handler_title": "Модули",
"modules_inline_handler_description": "Вывести список установленных моудей",
"modules_inline_handler_result": "☘️ Все установленные модули:\n",
"resetprefix_inline_handler_title": "Сбросить префикс",
"resetprefix_inline_handler_description": "Сбросить префикс по умолчанию",
"resetprefix_inline_handler_message": "Вы действительно хотите сбросить ваш префикс и установить стандартную точку?",
"resetprefix_inline_handler_reply_text_yes": "Да",
"resetprefix_inline_handler_reply_text_no": "Нет",
}
async def client_ready(self, client, db):
self.client = client
self.db = db
async def restart(self, call):
"""Restart callback"""
logging.error("InlineHelper: restarting userbot...")
await call.edit(self.strings("call_restart"))
await sys.exit(0)
async def update(self, call):
"""Update callback"""
logging.error("InlineHelper: updating userbot...")
os.system(f"cd {utils.get_base_dir()} && cd .. && git reset --hard HEAD")
os.system("git pull")
await call.edit(self.strings("call_update"))
await sys.exit(0)
async def reset_prefix(self, call):
"""Reset prefix"""
self.db.set(main.__name__, "command_prefix", ".")
await call.edit(self.strings("res_prefix"))
@loader.inline_handler(
ru_doc="Перезагрузить юзербота",
en_doc="Reboot the userbot",
)
async def restart_inline_handler(self, _: InlineQuery):
return {
"title": self.strings("restart_inline_handler_title"),
"description": self.strings("restart_inline_handler_description"),
"message": self.strings("restart_inline_handler_message"),
"reply_markup": [
{
"text": self.strings("restart_inline_handler_reply_text"),
"callback": self.restart,
}
],
}
@loader.inline_handler(
ru_doc="Обновить юзербота",
en_doc="Update the userbot",
)
async def update_inline_handler(self, _: InlineQuery):
return {
"title": self.strings("update_inline_handler_title"),
"description": self.strings("update_inline_handler_description"),
"message": self.strings("update_inline_handler_message"),
"reply_markup": [
{
"text": self.strings("update_inline_handler_reply_text"),
"callback": self.update,
}
],
}
@loader.inline_handler(
ru_doc="Выполнить команду в терминале (лучше сразу подготовить команду и просто вставить)",
en_doc="Execute the command in the terminal (it is better to prepare the command immediately and just paste it)",
)
async def terminal_inline_handler(self, _: InlineQuery):
text = _.args
await asyncio.create_subprocess_shell(
f"{text}",
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
cwd=utils.get_base_dir(),
)
return {
"title": self.strings("terminal_inline_handler_title"),
"description": self.strings("terminal_inline_handler_description"),
"message": self.strings("terminal_inline_handler_message").format(
text=text
),
}
@loader.inline_handler(
ru_doc="Вывести список установленных модулей через инлайн",
en_doc="Display a list of installed modules via the inline",
)
async def modules_inline_handler(self, _: InlineQuery):
result = self.strings("modules_inline_handler_result")
for mod in self.allmodules.modules:
try:
name = mod.strings["name"]
except KeyError:
name = mod.__clas__.__name__
result += f"{name}\n"
return {
"title": self.strings("modules_inline_handler_title"),
"description": self.strings("modules_inline_handler_description"),
"message": result,
}
@loader.inline_handler(
ru_doc="Сбросить префикс (осторожнее, сбрасывает ваш префикс на . )",
en_doc="Reset the prefix (be careful, resets your prefix to . )",
)
async def resetprefix_inline_handler(self, _: InlineQuery):
return {
"title": self.strings("resetprefix_inline_handler_title"),
"description": self.strings("resetprefix_inline_handler_description"),
"message": self.strings("resetprefix_inline_handler_message"),
"reply_markup": [
{
"text": self.strings("resetprefix_inline_handler_reply_text_yes"),
"callback": self.reset_prefix,
},
{
"text": self.strings("resetprefix_inline_handler_reply_text_no"),
"action": "close",
},
],
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,103 +1,103 @@
# Proprietary License Agreement
# Copyright (c) 2024-29 CodWiz
# Permission is hereby granted to any person obtaining a copy of this software and associated documentation files (the "Software"), to use the Software for personal and non-commercial purposes, subject to the following conditions:
# 1. The Software may not be modified, altered, or otherwise changed in any way without the explicit written permission of the author.
# 2. Redistribution of the Software, in original or modified form, is strictly prohibited without the explicit written permission of the author.
# 3. The Software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and non-infringement. In no event shall the author or copyright holder be liable for any claim, damages, or other liability, whether in an action of contract, tort, or otherwise, arising from, out of, or in connection with the Software or the use or other dealings in the Software.
# 4. Any use of the Software must include the above copyright notice and this permission notice in all copies or substantial portions of the Software.
# 5. By using the Software, you agree to be bound by the terms and conditions of this license.
# For any inquiries or requests for permissions, please contact codwiz@yandex.ru.
# ---------------------------------------------------------------------------------
# Name: SafetyMod
# Description: generate random password
# Author: @hikka_mods
# ---------------------------------------------------------------------------------
# meta developer: @hikka_mods
# scope: Api SafetyMod
# scope: Api SafetyMod 0.0.1
# ---------------------------------------------------------------------------------
import random
import string
from .. import loader, utils
def generate_password(
length: int, letters: bool = True, numbers: bool = True, symbols: bool = True
) -> str:
"""Generates a random password with customizable options.
Args:
length: The desired length of the password.
letters: Include lowercase and uppercase letters (default: True).
numbers: Include digits (default: True).
symbols: Include common symbols (default: True).
Returns:
A randomly generated password string.
Raises:
ValueError: If all character sets are disabled (letters, numbers, symbols).
"""
character_sets = []
if letters:
character_sets.append(string.ascii_letters)
if numbers:
character_sets.append(string.digits)
if symbols:
character_sets.append(string.punctuation)
if not character_sets:
raise ValueError("At least one of letters, numbers, or symbols must be True")
combined_characters = "".join(character_sets)
password = "".join(random.choice(combined_characters) for _ in range(length))
return password
@loader.tds
class SafetyMod(loader.Module):
"""generate random password"""
strings = {
"name": "Safety",
"pass": "<emoji document_id=5472287483318245416>*⃣</emoji> <b>Here is your secure password:</b> <code>{}</code>",
}
strings_ru = {
"pass": "<emoji document_id=5472287483318245416>*⃣</emoji> <b>Вот ваш безопасный пароль:</b> <code>{}</code>"
}
@loader.command(
ru_doc="Случайный пароль\n-n - цифры\n-s - символы \n -l - буквы",
en_doc="Random password\n-n - numbers\n-s - symbols \n -l - letters",
)
async def password(self, message):
"""random password\n-n - numbers\n-s - symbols \n -l - letters"""
text = message.text.split()
length = 10
letters = True
numbers = False
symbols = False
for i in text:
if i.startswith("password"):
length = int(i.split("password")[1])
elif i == "-n":
numbers = True
elif i == "-s":
symbols = True
elif i == "-l":
letters = True
password = generate_password(
length=length, letters=letters, numbers=numbers, symbols=symbols
)
await utils.answer(message, self.strings("pass").format(password))
# Proprietary License Agreement
# Copyright (c) 2024-29 CodWiz
# Permission is hereby granted to any person obtaining a copy of this software and associated documentation files (the "Software"), to use the Software for personal and non-commercial purposes, subject to the following conditions:
# 1. The Software may not be modified, altered, or otherwise changed in any way without the explicit written permission of the author.
# 2. Redistribution of the Software, in original or modified form, is strictly prohibited without the explicit written permission of the author.
# 3. The Software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and non-infringement. In no event shall the author or copyright holder be liable for any claim, damages, or other liability, whether in an action of contract, tort, or otherwise, arising from, out of, or in connection with the Software or the use or other dealings in the Software.
# 4. Any use of the Software must include the above copyright notice and this permission notice in all copies or substantial portions of the Software.
# 5. By using the Software, you agree to be bound by the terms and conditions of this license.
# For any inquiries or requests for permissions, please contact codwiz@yandex.ru.
# ---------------------------------------------------------------------------------
# Name: SafetyMod
# Description: generate random password
# Author: @hikka_mods
# ---------------------------------------------------------------------------------
# meta developer: @hikka_mods
# scope: Api SafetyMod
# scope: Api SafetyMod 0.0.1
# ---------------------------------------------------------------------------------
import random
import string
from .. import loader, utils
def generate_password(
length: int, letters: bool = True, numbers: bool = True, symbols: bool = True
) -> str:
"""Generates a random password with customizable options.
Args:
length: The desired length of the password.
letters: Include lowercase and uppercase letters (default: True).
numbers: Include digits (default: True).
symbols: Include common symbols (default: True).
Returns:
A randomly generated password string.
Raises:
ValueError: If all character sets are disabled (letters, numbers, symbols).
"""
character_sets = []
if letters:
character_sets.append(string.ascii_letters)
if numbers:
character_sets.append(string.digits)
if symbols:
character_sets.append(string.punctuation)
if not character_sets:
raise ValueError("At least one of letters, numbers, or symbols must be True")
combined_characters = "".join(character_sets)
password = "".join(random.choice(combined_characters) for _ in range(length))
return password
@loader.tds
class SafetyMod(loader.Module):
"""generate random password"""
strings = {
"name": "Safety",
"pass": "<emoji document_id=5472287483318245416>*⃣</emoji> <b>Here is your secure password:</b> <code>{}</code>",
}
strings_ru = {
"pass": "<emoji document_id=5472287483318245416>*⃣</emoji> <b>Вот ваш безопасный пароль:</b> <code>{}</code>"
}
@loader.command(
ru_doc="Случайный пароль\n-n - цифры\n-s - символы \n -l - буквы",
en_doc="Random password\n-n - numbers\n-s - symbols \n -l - letters",
)
async def password(self, message):
"""random password\n-n - numbers\n-s - symbols \n -l - letters"""
text = message.text.split()
length = 10
letters = True
numbers = False
symbols = False
for i in text:
if i.startswith("password"):
length = int(i.split("password")[1])
elif i == "-n":
numbers = True
elif i == "-s":
symbols = True
elif i == "-l":
letters = True
password = generate_password(
length=length, letters=letters, numbers=numbers, symbols=symbols
)
await utils.answer(message, self.strings("pass").format(password))

File diff suppressed because it is too large Load Diff

0
CakesTwix/Hikka-Modules/linux_packages.py Normal file → Executable file
View File

View File

@@ -1,223 +1,223 @@
# .------.------.------.------.------.------.------.------.------.------.
# |D.--. |4.--. |N.--. |1.--. |3.--. |L.--. |3.--. |K.--. |0.--. |0.--. |
# | :/\: | :/\: | :(): | :/\: | :(): | :/\: | :(): | :/\: | :/\: | :/\: |
# | (__) | :\/: | ()() | (__) | ()() | (__) | ()() | :\/: | :\/: | :\/: |
# | '--'D| '--'4| '--'N| '--'1| '--'3| '--'L| '--'3| '--'K| '--'0| '--'0|
# `------`------`------`------`------`------`------`------`------`------'
#
# Copyright 2023 t.me/D4n13l3k00
# Licensed under the Creative Commons CC BY-NC-ND 4.0
#
# Full license text can be found at:
# https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode
#
# Human-friendly one:
# https://creativecommons.org/licenses/by-nc-nd/4.0
import contextlib
import os
import re
from typing import *
import pytgcalls
import youtube_dl
from pytgcalls import PyTgCalls, StreamType
from pytgcalls.types.input_stream import AudioPiped, AudioVideoPiped
from pytgcalls.types.input_stream.quality import HighQualityAudio, HighQualityVideo
from telethon import types
from .. import loader, utils # type: ignore
# meta developer: @D4n13l3k00
# requires: py-tgcalls youtube-dl
@loader.tds
class ChatVoiceMod(loader.Module):
"""Module for working with voicechat"""
strings = {
"name": "ChatVoiceMod",
"downloading": "<b>[ChatVoiceMod]</b> Downloading...",
"playing": "<b>[ChatVoiceMod]</b> Playing...",
"notjoined": "<b>[ChatVoiceMod]</b> You are not joined",
"stop": "<b>[ChatVoiceMod]</b> Playing stopped!",
"leave": "<b>[ChatVoiceMod]</b> Leaved!",
"pause": "<b>[ChatVoiceMod]</b> Paused!",
"resume": "<b>[ChatVoiceMod]</b> Resumed!",
"mute": "<b>[ChatVoiceMod]</b> Muted!",
"unmute": "<b>[ChatVoiceMod]</b> Unmuted!",
"error": "<b>[ChatVoiceMod]</b> Error: <code>{}</code>",
"noargs": "<b>[ChatVoiceMod]</b> No args",
"noreply": "<b>[ChatVoiceMod]</b> No reply",
"nofile": "<b>[ChatVoiceMod]</b> No file",
"nofiles": "<b>[ChatVoiceMod]</b> No files",
"deleted": "<b>[ChatVoiceMod]</b> <code>{}</code> successfully deleted",
"downloaded": "<b>[ChatVoiceMod]</b> Downloaded to <code>dl/{0}</code>. For playing use:\n<code>.cplaya dl/{0}</code>\n<code>.cplayv dl/{0}</code>",
}
async def client_ready(self, client, _):
self.client = client
self.call = PyTgCalls(client)
@self.call.on_stream_end()
async def _(_, update):
with contextlib.suppress(Exception):
await self.call.leave_group_call(update.chat_id)
await self.call.start()
async def parse_args(self, args):
if not args or not re.match(
r"http(?:s?):\/\/(?:www\.)?youtu(?:be\.com\/watch\?v=|\.be\/)([\w\-\_]*)(&(amp;)?[\w\?=]*)?",
args,
):
return args
with youtube_dl.YoutubeDL({"format": "best"}) as ydl:
info = ydl.extract_info(args, download=False)
return info["formats"][0]["url"]
async def cdlcmd(self, m: types.Message):
"<reply_to_media> <name: optional> - Download media to server in `dl` folder"
args = utils.get_args_raw(m)
reply = await m.get_reply_message()
if not reply:
return await utils.answer(m, self.strings("noreply"))
name = args or reply.file.name
try:
m = await utils.answer(m, self.strings("downloading"))
await reply.download_media(f"dl/{name}")
await utils.answer(m, self.strings("downloaded").format(name))
except Exception as e:
await utils.answer(m, self.strings("error").format(str(e)))
async def clscmd(self, m: types.Message):
"List all files in `dl` folder"
if not os.path.isdir("dl") or not os.listdir("dl"):
return await utils.answer(m, self.strings("nofiles"))
files = [f"<code>dl/{f}</code>" for f in os.listdir("dl")]
await utils.answer(m, "\n".join(files))
# command for deleting file from dl folder
async def cdelcmd(self, m: types.Message):
"<name> - Delete file from `dl` folder"
args = utils.get_args_raw(m)
if not args:
return await utils.answer(m, self.strings("noargs"))
if not args.startswith("dl/"):
args = f"dl/{args}"
if not os.path.isfile(f"{args}"):
return await utils.answer(m, self.strings("nofile"))
try:
os.remove(f"{args}")
await utils.answer(m, self.strings("deleted").format(args))
except Exception as e:
await utils.answer(m, self.strings("error").format(str(e)))
async def cplayvcmd(self, m: types.Message):
"<link/path/reply_to_video> - Play video in voice chat"
try:
reply = await m.get_reply_message()
path = await self.parse_args(utils.get_args_raw(m))
chat = m.chat.id
if not path:
if not reply:
return await utils.answer(m, self.strings("noargs"))
m = await utils.answer(m, self.strings("downloading"))
path = await reply.download_media()
with contextlib.suppress(pytgcalls.exceptions.GroupCallNotFound):
self.call.get_active_call(chat)
await self.call.leave_group_call(chat)
await self.call.join_group_call(
chat,
AudioVideoPiped(
path,
HighQualityAudio(),
HighQualityVideo(),
),
stream_type=StreamType().pulse_stream,
)
await utils.answer(m, self.strings("playing"))
except Exception as e:
await utils.answer(m, self.strings("error").format(str(e)))
async def cplayacmd(self, m: types.Message):
"<link/path/reply_to_audio> - Play audio in voice chat"
try:
reply = await m.get_reply_message()
path = await self.parse_args(utils.get_args_raw(m))
chat = m.chat.id
if not path:
if not reply:
return await utils.answer(m, self.strings("noargs"))
m = await utils.answer(m, self.strings("downloading"))
path = await reply.download_media()
with contextlib.suppress(pytgcalls.exceptions.GroupCallNotFound):
self.call.get_active_call(chat)
await self.call.leave_group_call(chat)
await self.call.join_group_call(
chat,
AudioPiped(
path,
HighQualityAudio(),
),
stream_type=StreamType().pulse_stream,
)
await utils.answer(m, self.strings("playing"))
except Exception as e:
await utils.answer(m, self.strings("error").format(str(e)))
async def cleavecmd(self, m: types.Message):
"Leave"
try:
self.call.get_active_call(m.chat.id)
await self.call.leave_group_call(m.chat.id)
await utils.answer(m, self.strings("leave"))
except pytgcalls.exceptions.GroupCallNotFound:
await utils.answer(m, self.strings("notjoined"))
except Exception as e:
await utils.answer(m, self.strings("error").format(str(e)))
async def cmutecmd(self, m: types.Message):
"Mute"
try:
self.call.get_active_call(m.chat.id)
await self.call.mute_stream(m.chat.id)
await utils.answer(m, self.strings("mute"))
except pytgcalls.exceptions.GroupCallNotFound:
await utils.answer(m, self.strings("notjoined"))
except Exception as e:
await utils.answer(m, self.strings("error").format(str(e)))
async def cunmutecmd(self, m: types.Message):
"Unmute"
try:
self.call.get_active_call(m.chat.id)
await self.call.unmute_stream(m.chat.id)
await utils.answer(m, self.strings("unmute"))
except pytgcalls.exceptions.GroupCallNotFound:
await utils.answer(m, self.strings("notjoined"))
except Exception as e:
await utils.answer(m, self.strings("error").format(str(e)))
async def cpausecmd(self, m: types.Message):
"Pause"
try:
self.call.get_active_call(m.chat.id)
await self.call.pause_stream(m.chat.id)
await utils.answer(m, self.strings("pause"))
except pytgcalls.exceptions.GroupCallNotFound:
await utils.answer(m, self.strings("notjoined"))
except Exception as e:
await utils.answer(m, self.strings("error").format(str(e)))
async def cresumecmd(self, m: types.Message):
"Resume"
try:
self.call.get_active_call(m.chat.id)
await self.call.resume_stream(m.chat.id)
await utils.answer(m, self.strings("resume"))
except pytgcalls.exceptions.GroupCallNotFound:
await utils.answer(m, self.strings("notjoined"))
except Exception as e:
await utils.answer(m, self.strings("error").format(str(e)))
# .------.------.------.------.------.------.------.------.------.------.
# |D.--. |4.--. |N.--. |1.--. |3.--. |L.--. |3.--. |K.--. |0.--. |0.--. |
# | :/\: | :/\: | :(): | :/\: | :(): | :/\: | :(): | :/\: | :/\: | :/\: |
# | (__) | :\/: | ()() | (__) | ()() | (__) | ()() | :\/: | :\/: | :\/: |
# | '--'D| '--'4| '--'N| '--'1| '--'3| '--'L| '--'3| '--'K| '--'0| '--'0|
# `------`------`------`------`------`------`------`------`------`------'
#
# Copyright 2023 t.me/D4n13l3k00
# Licensed under the Creative Commons CC BY-NC-ND 4.0
#
# Full license text can be found at:
# https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode
#
# Human-friendly one:
# https://creativecommons.org/licenses/by-nc-nd/4.0
import contextlib
import os
import re
from typing import *
import pytgcalls
import youtube_dl
from pytgcalls import PyTgCalls, StreamType
from pytgcalls.types.input_stream import AudioPiped, AudioVideoPiped
from pytgcalls.types.input_stream.quality import HighQualityAudio, HighQualityVideo
from telethon import types
from .. import loader, utils # type: ignore
# meta developer: @D4n13l3k00
# requires: py-tgcalls youtube-dl
@loader.tds
class ChatVoiceMod(loader.Module):
"""Module for working with voicechat"""
strings = {
"name": "ChatVoiceMod",
"downloading": "<b>[ChatVoiceMod]</b> Downloading...",
"playing": "<b>[ChatVoiceMod]</b> Playing...",
"notjoined": "<b>[ChatVoiceMod]</b> You are not joined",
"stop": "<b>[ChatVoiceMod]</b> Playing stopped!",
"leave": "<b>[ChatVoiceMod]</b> Leaved!",
"pause": "<b>[ChatVoiceMod]</b> Paused!",
"resume": "<b>[ChatVoiceMod]</b> Resumed!",
"mute": "<b>[ChatVoiceMod]</b> Muted!",
"unmute": "<b>[ChatVoiceMod]</b> Unmuted!",
"error": "<b>[ChatVoiceMod]</b> Error: <code>{}</code>",
"noargs": "<b>[ChatVoiceMod]</b> No args",
"noreply": "<b>[ChatVoiceMod]</b> No reply",
"nofile": "<b>[ChatVoiceMod]</b> No file",
"nofiles": "<b>[ChatVoiceMod]</b> No files",
"deleted": "<b>[ChatVoiceMod]</b> <code>{}</code> successfully deleted",
"downloaded": "<b>[ChatVoiceMod]</b> Downloaded to <code>dl/{0}</code>. For playing use:\n<code>.cplaya dl/{0}</code>\n<code>.cplayv dl/{0}</code>",
}
async def client_ready(self, client, _):
self.client = client
self.call = PyTgCalls(client)
@self.call.on_stream_end()
async def _(_, update):
with contextlib.suppress(Exception):
await self.call.leave_group_call(update.chat_id)
await self.call.start()
async def parse_args(self, args):
if not args or not re.match(
r"http(?:s?):\/\/(?:www\.)?youtu(?:be\.com\/watch\?v=|\.be\/)([\w\-\_]*)(&(amp;)?[\w\?=]*)?",
args,
):
return args
with youtube_dl.YoutubeDL({"format": "best"}) as ydl:
info = ydl.extract_info(args, download=False)
return info["formats"][0]["url"]
async def cdlcmd(self, m: types.Message):
"<reply_to_media> <name: optional> - Download media to server in `dl` folder"
args = utils.get_args_raw(m)
reply = await m.get_reply_message()
if not reply:
return await utils.answer(m, self.strings("noreply"))
name = args or reply.file.name
try:
m = await utils.answer(m, self.strings("downloading"))
await reply.download_media(f"dl/{name}")
await utils.answer(m, self.strings("downloaded").format(name))
except Exception as e:
await utils.answer(m, self.strings("error").format(str(e)))
async def clscmd(self, m: types.Message):
"List all files in `dl` folder"
if not os.path.isdir("dl") or not os.listdir("dl"):
return await utils.answer(m, self.strings("nofiles"))
files = [f"<code>dl/{f}</code>" for f in os.listdir("dl")]
await utils.answer(m, "\n".join(files))
# command for deleting file from dl folder
async def cdelcmd(self, m: types.Message):
"<name> - Delete file from `dl` folder"
args = utils.get_args_raw(m)
if not args:
return await utils.answer(m, self.strings("noargs"))
if not args.startswith("dl/"):
args = f"dl/{args}"
if not os.path.isfile(f"{args}"):
return await utils.answer(m, self.strings("nofile"))
try:
os.remove(f"{args}")
await utils.answer(m, self.strings("deleted").format(args))
except Exception as e:
await utils.answer(m, self.strings("error").format(str(e)))
async def cplayvcmd(self, m: types.Message):
"<link/path/reply_to_video> - Play video in voice chat"
try:
reply = await m.get_reply_message()
path = await self.parse_args(utils.get_args_raw(m))
chat = m.chat.id
if not path:
if not reply:
return await utils.answer(m, self.strings("noargs"))
m = await utils.answer(m, self.strings("downloading"))
path = await reply.download_media()
with contextlib.suppress(pytgcalls.exceptions.GroupCallNotFound):
self.call.get_active_call(chat)
await self.call.leave_group_call(chat)
await self.call.join_group_call(
chat,
AudioVideoPiped(
path,
HighQualityAudio(),
HighQualityVideo(),
),
stream_type=StreamType().pulse_stream,
)
await utils.answer(m, self.strings("playing"))
except Exception as e:
await utils.answer(m, self.strings("error").format(str(e)))
async def cplayacmd(self, m: types.Message):
"<link/path/reply_to_audio> - Play audio in voice chat"
try:
reply = await m.get_reply_message()
path = await self.parse_args(utils.get_args_raw(m))
chat = m.chat.id
if not path:
if not reply:
return await utils.answer(m, self.strings("noargs"))
m = await utils.answer(m, self.strings("downloading"))
path = await reply.download_media()
with contextlib.suppress(pytgcalls.exceptions.GroupCallNotFound):
self.call.get_active_call(chat)
await self.call.leave_group_call(chat)
await self.call.join_group_call(
chat,
AudioPiped(
path,
HighQualityAudio(),
),
stream_type=StreamType().pulse_stream,
)
await utils.answer(m, self.strings("playing"))
except Exception as e:
await utils.answer(m, self.strings("error").format(str(e)))
async def cleavecmd(self, m: types.Message):
"Leave"
try:
self.call.get_active_call(m.chat.id)
await self.call.leave_group_call(m.chat.id)
await utils.answer(m, self.strings("leave"))
except pytgcalls.exceptions.GroupCallNotFound:
await utils.answer(m, self.strings("notjoined"))
except Exception as e:
await utils.answer(m, self.strings("error").format(str(e)))
async def cmutecmd(self, m: types.Message):
"Mute"
try:
self.call.get_active_call(m.chat.id)
await self.call.mute_stream(m.chat.id)
await utils.answer(m, self.strings("mute"))
except pytgcalls.exceptions.GroupCallNotFound:
await utils.answer(m, self.strings("notjoined"))
except Exception as e:
await utils.answer(m, self.strings("error").format(str(e)))
async def cunmutecmd(self, m: types.Message):
"Unmute"
try:
self.call.get_active_call(m.chat.id)
await self.call.unmute_stream(m.chat.id)
await utils.answer(m, self.strings("unmute"))
except pytgcalls.exceptions.GroupCallNotFound:
await utils.answer(m, self.strings("notjoined"))
except Exception as e:
await utils.answer(m, self.strings("error").format(str(e)))
async def cpausecmd(self, m: types.Message):
"Pause"
try:
self.call.get_active_call(m.chat.id)
await self.call.pause_stream(m.chat.id)
await utils.answer(m, self.strings("pause"))
except pytgcalls.exceptions.GroupCallNotFound:
await utils.answer(m, self.strings("notjoined"))
except Exception as e:
await utils.answer(m, self.strings("error").format(str(e)))
async def cresumecmd(self, m: types.Message):
"Resume"
try:
self.call.get_active_call(m.chat.id)
await self.call.resume_stream(m.chat.id)
await utils.answer(m, self.strings("resume"))
except pytgcalls.exceptions.GroupCallNotFound:
await utils.answer(m, self.strings("notjoined"))
except Exception as e:
await utils.answer(m, self.strings("error").format(str(e)))

View File

@@ -1,120 +1,120 @@
# .------.------.------.------.------.------.------.------.------.------.
# |D.--. |4.--. |N.--. |1.--. |3.--. |L.--. |3.--. |K.--. |0.--. |0.--. |
# | :/\: | :/\: | :(): | :/\: | :(): | :/\: | :(): | :/\: | :/\: | :/\: |
# | (__) | :\/: | ()() | (__) | ()() | (__) | ()() | :\/: | :\/: | :\/: |
# | '--'D| '--'4| '--'N| '--'1| '--'3| '--'L| '--'3| '--'K| '--'0| '--'0|
# `------`------`------`------`------`------`------`------`------`------'
#
# Copyright 2023 t.me/D4n13l3k00
# Licensed under the Creative Commons CC BY-NC-ND 4.0
#
# Full license text can be found at:
# https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode
#
# Human-friendly one:
# https://creativecommons.org/licenses/by-nc-nd/4.0
# meta developer: @D4n13l3k00
import contextlib
from random import choice
from telethon import functions
from .. import loader # type: ignore
@loader.tds
class ReactionsMod(loader.Module):
"Telegram reactions"
strings = {"name": __doc__}
async def client_ready(self, client, _):
self.client = client
def reaction(func):
async def wrapper(self, *args):
"<reply>"
message = args[0]
emoji = await func(self)
if reply := await message.get_reply_message():
with contextlib.suppress(Exception):
await self.client(
functions.messages.SendReactionRequest(
reply.peer_id, reply.id, reaction=emoji
)
)
if message.out:
await message.delete()
return wrapper
@reaction
async def randrcmd(self):
return choice("👍👎❤️🔥🎉🤩😱😁😢💩🤮🥰🤯🤔🤬👏")
@reaction
async def lovecmd(self):
return ""
@reaction
async def sadcmd(self):
return "😢"
@reaction
async def nastycmd(self):
return "🤮"
@reaction
async def cutecmd(self):
return "🥰"
@reaction
async def clapcmd(self):
return "👏"
@reaction
async def fuckcmd(self):
return "🤬"
@reaction
async def wtfcmd(self):
return "🤯"
@reaction
async def hmmcmd(self):
return "🤔"
@reaction
async def hooraycmd(self):
return "🎉"
@reaction
async def likecmd(self):
return "👍"
@reaction
async def dislikecmd(self):
return "👎"
@reaction
async def firecmd(self):
return "🔥"
@reaction
async def omgcmd(self):
return "😱"
@reaction
async def wowcmd(self):
return "🤩"
@reaction
async def hehecmd(self):
return "😁"
@reaction
async def shitcmd(self):
return "💩"
# .------.------.------.------.------.------.------.------.------.------.
# |D.--. |4.--. |N.--. |1.--. |3.--. |L.--. |3.--. |K.--. |0.--. |0.--. |
# | :/\: | :/\: | :(): | :/\: | :(): | :/\: | :(): | :/\: | :/\: | :/\: |
# | (__) | :\/: | ()() | (__) | ()() | (__) | ()() | :\/: | :\/: | :\/: |
# | '--'D| '--'4| '--'N| '--'1| '--'3| '--'L| '--'3| '--'K| '--'0| '--'0|
# `------`------`------`------`------`------`------`------`------`------'
#
# Copyright 2023 t.me/D4n13l3k00
# Licensed under the Creative Commons CC BY-NC-ND 4.0
#
# Full license text can be found at:
# https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode
#
# Human-friendly one:
# https://creativecommons.org/licenses/by-nc-nd/4.0
# meta developer: @D4n13l3k00
import contextlib
from random import choice
from telethon import functions
from .. import loader # type: ignore
@loader.tds
class ReactionsMod(loader.Module):
"Telegram reactions"
strings = {"name": __doc__}
async def client_ready(self, client, _):
self.client = client
def reaction(func):
async def wrapper(self, *args):
"<reply>"
message = args[0]
emoji = await func(self)
if reply := await message.get_reply_message():
with contextlib.suppress(Exception):
await self.client(
functions.messages.SendReactionRequest(
reply.peer_id, reply.id, reaction=emoji
)
)
if message.out:
await message.delete()
return wrapper
@reaction
async def randrcmd(self):
return choice("👍👎❤️🔥🎉🤩😱😁😢💩🤮🥰🤯🤔🤬👏")
@reaction
async def lovecmd(self):
return ""
@reaction
async def sadcmd(self):
return "😢"
@reaction
async def nastycmd(self):
return "🤮"
@reaction
async def cutecmd(self):
return "🥰"
@reaction
async def clapcmd(self):
return "👏"
@reaction
async def fuckcmd(self):
return "🤬"
@reaction
async def wtfcmd(self):
return "🤯"
@reaction
async def hmmcmd(self):
return "🤔"
@reaction
async def hooraycmd(self):
return "🎉"
@reaction
async def likecmd(self):
return "👍"
@reaction
async def dislikecmd(self):
return "👎"
@reaction
async def firecmd(self):
return "🔥"
@reaction
async def omgcmd(self):
return "😱"
@reaction
async def wowcmd(self):
return "🤩"
@reaction
async def hehecmd(self):
return "😁"
@reaction
async def shitcmd(self):
return "💩"

View File

@@ -1,65 +1,65 @@
# .------.------.------.------.------.------.------.------.------.------.
# |D.--. |4.--. |N.--. |1.--. |3.--. |L.--. |3.--. |K.--. |0.--. |0.--. |
# | :/\: | :/\: | :(): | :/\: | :(): | :/\: | :(): | :/\: | :/\: | :/\: |
# | (__) | :\/: | ()() | (__) | ()() | (__) | ()() | :\/: | :\/: | :\/: |
# | '--'D| '--'4| '--'N| '--'1| '--'3| '--'L| '--'3| '--'K| '--'0| '--'0|
# `------`------`------`------`------`------`------`------`------`------'
#
# Copyright 2023 t.me/D4n13l3k00
# Licensed under the Creative Commons CC BY-NC-ND 4.0
#
# Full license text can be found at:
# https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode
#
# Human-friendly one:
# https://creativecommons.org/licenses/by-nc-nd/4.0
# meta developer: @D4n13l3k00
import io
from telethon import types
from .. import loader, utils # type: ignore
@loader.tds
class SaverMod(loader.Module):
strings = {"name": "Saver"}
async def client_ready(self, client, db):
self.db = db
@loader.owner
async def бляcmd(self, m: types.Message):
".бля <reply> - скачать самоуничтожающееся фото"
reply = await m.get_reply_message()
if not reply or not reply.media or not reply.media.ttl_seconds:
return await m.edit("бля")
await m.delete()
new = io.BytesIO(await reply.download_media(bytes))
new.name = reply.file.name
await m.client.send_file("me", new)
@loader.owner
async def swбляcmd(self, m: types.Message):
"Переключить режим автозагрузки фото в лс"
new_val = not self.db.get("Saver", "state", False)
self.db.set("Saver", "state", new_val)
await utils.answer(m, f"<b>[Saver]</b> <pre>{new_val}</pre>")
async def watcher(self, m: types.Message):
if (
m
and m.media
and m.media.ttl_seconds
and self.db.get("Saver", "state", False)
):
new = io.BytesIO(await m.download_media(bytes))
new.name = m.file.name
await m.client.send_file(
"me",
new,
caption=f"<b>[Saver] Фото от</b> {f'@{m.sender.username}' if m.sender.username else m.sender.first_name} | <pre>{m.sender.id}</pre>\n"
f"Время жизни: <code>{m.media.ttl_seconds}sec</code>",
)
# .------.------.------.------.------.------.------.------.------.------.
# |D.--. |4.--. |N.--. |1.--. |3.--. |L.--. |3.--. |K.--. |0.--. |0.--. |
# | :/\: | :/\: | :(): | :/\: | :(): | :/\: | :(): | :/\: | :/\: | :/\: |
# | (__) | :\/: | ()() | (__) | ()() | (__) | ()() | :\/: | :\/: | :\/: |
# | '--'D| '--'4| '--'N| '--'1| '--'3| '--'L| '--'3| '--'K| '--'0| '--'0|
# `------`------`------`------`------`------`------`------`------`------'
#
# Copyright 2023 t.me/D4n13l3k00
# Licensed under the Creative Commons CC BY-NC-ND 4.0
#
# Full license text can be found at:
# https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode
#
# Human-friendly one:
# https://creativecommons.org/licenses/by-nc-nd/4.0
# meta developer: @D4n13l3k00
import io
from telethon import types
from .. import loader, utils # type: ignore
@loader.tds
class SaverMod(loader.Module):
strings = {"name": "Saver"}
async def client_ready(self, client, db):
self.db = db
@loader.owner
async def бляcmd(self, m: types.Message):
".бля <reply> - скачать самоуничтожающееся фото"
reply = await m.get_reply_message()
if not reply or not reply.media or not reply.media.ttl_seconds:
return await m.edit("бля")
await m.delete()
new = io.BytesIO(await reply.download_media(bytes))
new.name = reply.file.name
await m.client.send_file("me", new)
@loader.owner
async def swбляcmd(self, m: types.Message):
"Переключить режим автозагрузки фото в лс"
new_val = not self.db.get("Saver", "state", False)
self.db.set("Saver", "state", new_val)
await utils.answer(m, f"<b>[Saver]</b> <pre>{new_val}</pre>")
async def watcher(self, m: types.Message):
if (
m
and m.media
and m.media.ttl_seconds
and self.db.get("Saver", "state", False)
):
new = io.BytesIO(await m.download_media(bytes))
new.name = m.file.name
await m.client.send_file(
"me",
new,
caption=f"<b>[Saver] Фото от</b> {f'@{m.sender.username}' if m.sender.username else m.sender.first_name} | <pre>{m.sender.id}</pre>\n"
f"Время жизни: <code>{m.media.ttl_seconds}sec</code>",
)

View File

@@ -1,36 +1,36 @@
**Describe the bug**
A clear and concise description of what the bug is.
---
**To Reproduce**
Steps to reproduce the behavior:
1. Run '...'
2. Do '....'
3. See error
---
**Expected behavior**
A clear and concise description of what you expected to happen.
---
**Screenshots**
If applicable, add screenshots to help explain your problem.
---
**Please complete the following information:**
- OS: [e.g. Ubuntu Server 20.04 LTS or Android 12 Termux]
- Userbot: [e.g. GeekTG Userbot `git rev-parse HEAD`]
---
**Additional context**
Add any other context about the problem here.
**Describe the bug**
A clear and concise description of what the bug is.
---
**To Reproduce**
Steps to reproduce the behavior:
1. Run '...'
2. Do '....'
3. See error
---
**Expected behavior**
A clear and concise description of what you expected to happen.
---
**Screenshots**
If applicable, add screenshots to help explain your problem.
---
**Please complete the following information:**
- OS: [e.g. Ubuntu Server 20.04 LTS or Android 12 Termux]
- Userbot: [e.g. GeekTG Userbot `git rev-parse HEAD`]
---
**Additional context**
Add any other context about the problem here.

0
D4n13l3k00/FTG-Modules/format.sh Normal file → Executable file
View File

View File

@@ -1,198 +1,198 @@
__version__ = (2, 0, 0)
#
# @@@@@@ @@@@@@ @@@@@@@ @@@@@@@ @@@@@@ @@@@@@@@@@ @@@@@@ @@@@@@@ @@@ @@@ @@@ @@@@@@@@ @@@@@@
# @@@@@@@@ @@@@@@@ @@@@@@@ @@@@@@@@ @@@@@@@@ @@@@@@@@@@@ @@@@@@@@ @@@@@@@@ @@@ @@@ @@@ @@@@@@@@ @@@@@@@
# @@! @@@ !@@ @@! @@! @@@ @@! @@@ @@! @@! @@! @@! @@@ @@! @@@ @@! @@@ @@! @@! !@@
# !@! @!@ !@! !@! !@! @!@ !@! @!@ !@! !@! !@! !@! @!@ !@! @!@ !@! @!@ !@! !@! !@!
# @!@!@!@! !!@@!! @!! @!@!!@! @!@ !@! @!! !!@ @!@ @!@ !@! @!@ !@! @!@ !@! @!! @!!!:! !!@@!!
# !!!@!!!! !!@!!! !!! !!@!@! !@! !!! !@! ! !@! !@! !!! !@! !!! !@! !!! !!! !!!!!: !!@!!!
# !!: !!! !:! !!: !!: :!! !!: !!! !!: !!: !!: !!! !!: !!! !!: !!! !!: !!: !:!
# :!: !:! !:! :!: :!: !:! :!: !:! :!: :!: :!: !:! :!: !:! :!: !:! :!: :!: !:!
# :: ::: :::: :: :: :: ::: ::::: :: ::: :: ::::: :: :::: :: ::::: :: :: :::: :: :::: :::: ::
# : : : :: : : : : : : : : : : : : : : :: : : : : : : :: : : : :: :: :: : :
#
# © Copyright 2024
#
# https://t.me/Den4ikSuperOstryyPer4ik
# and
# https://t.me/ToXicUse
#
# 🔒 Licensed under the GNU AGPLv3
# https://www.gnu.org/licenses/agpl-3.0.html
#
# meta developer: @AstroModules
# meta banner: https://raw.githubusercontent.com/Den4ikSuperOstryyPer4ik/Astro-modules/main/Banners/PasswordGenerator.jpg
import logging
import random
from telethon.tl.types import Message
from .. import loader, utils
from ..inline.types import InlineCall
logger = logging.getLogger(__name__)
@loader.tds
class PasswordGeneratorMod(loader.Module):
'''Random password/pincode generator'''
strings = {
"name": "RandomPasswordGenerator",
"_cfg_doc_pass_length": "set password length (in number of characters)",
"_cfg_doc_pin_code_length": "set pincode length (in number of characters)",
"_cfg_doc_simbols_in_pass": (
"Will there be additional characters in the generated password"
" (+-*!&$#?=@<>)?"
),
"what_to_generate": "🆗What should be generated?",
"new_random_pass": "🔣 new random password 🆕",
"new_random_pincode": "🔢 new random PIN-code 🆕",
"pass": "<b>🆕 Your new password in {} characters:\n<code>{}</code></b>",
"pincode": "<b>🆕 Your new pincode in {} characters:\n<code>{}</code></b>",
"menu": "💻 Menu",
"close": "🚫 Close",
}
strings_ru = {
"_cls_doc": (
"Генератор рандомного пароля/пин-кода\nНастроить генератор можно через"
" конфиг"
),
"_cfg_doc_pass_length": "выставьте длину пароля(в кол-ве символов)",
"_cfg_doc_pin_code_length": "выставьте длину Пин-Кода(в кол-ве символов)",
"_cfg_doc_simbols_in_pass": (
"Какие символы должны быть в сгенерированном пароле?"
),
"what_to_generate": "🆗 Что надо сгенерировать?",
"new_random_pass": "🔣 Новый рандомный пароль 🆕",
"new_random_pincode": "🔢 Новый рандомный PIN-код 🆕",
"pass": "<b>🆕 Ваш новый пароль в {} символов:\n<code>{}</code></b>",
"pincode": "<b>🆕 Ваш новый пин-код в {} символов:</b>\n<code>{}</code>",
"menu": "💻 Меню",
"close": "🚫 Закрыть",
}
@loader.command(ru_doc="—>конфиг этого модуля")
async def generatorcfgcmd(self, message: Message):
"""—>config for this module"""
name = self.strings("name")
await self.allmodules.commands["config"](
await utils.answer(message, f"{self.get_prefix()}config {name}")
)
def __init__(self):
self._ratelimit = []
self.config = loader.ModuleConfig(
loader.ConfigValue(
"password_length",
10,
doc=lambda: self.strings("_cfg_doc_pass_length"),
validator=loader.validators.Integer(minimum=6),
),
loader.ConfigValue(
"pincode_length",
4,
doc=lambda: self.strings("_cfg_doc_pin_code_length"),
validator=loader.validators.Integer(minimum=4),
),
loader.ConfigValue(
"symbols",
"+-*!&$?=@<>abcdefghijklnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890",
doc=lambda: self.strings("_cfg_doc_simbols_in_pass"),
),
)
@loader.command(ru_doc="—>сгенерировать случайный пароль/пин-код")
async def igeneratorcmd(self, message: Message):
"""—>generate random password/pin"""
await self.inline.form(
self.strings("what_to_generate"),
reply_markup=[
[
{
"text": self.strings("new_random_pass"),
"callback": self.new_random_pass,
}
],
[
{
"text": self.strings("new_random_pincode"),
"callback": self.new_random_pincode,
}
],
[{"text": self.strings("close"), "action": "close"}],
],
message=message,
)
async def igenerator(self, call: InlineCall):
await call.edit(
self.strings("what_to_generate"),
reply_markup=[
[
{
"text": self.strings("new_random_pass"),
"callback": self.new_random_pass,
}
],
[
{
"text": self.strings("new_random_pincode"),
"callback": self.new_random_pincode,
}
],
[{"text": self.strings("close"), "action": "close"}],
],
)
async def new_random_pass(self, call: InlineCall):
symbols = self.config["symbols"]
password_length = self.config["password_length"]
length = int(password_length)
password = ""
for _ in range(length):
password += random.choice(symbols)
await call.edit(
self.strings["pass"].format(password_length, password),
reply_markup=[
[
{
"text": self.strings("menu"),
"callback": self.igenerator
}
],
[
{
"text": self.strings("close"),
"action": "close"
}
],
],
)
async def new_random_pincode(self, call: InlineCall):
pincode_length = self.config["pincode_length"]
chars = "1234567890"
length = int(self.config["pincode_length"])
pincode = ""
for _ in range(length):
pincode += random.choice(chars)
await call.edit(
self.strings["pincode"].format(pincode_length, pincode),
reply_markup=[
[
{
"text": self.strings("menu"),
"callback": self.igenerator
}
],
[
{
"text": self.strings("close"),
"action": "close"
}
],
],
)
__version__ = (2, 0, 0)
#
# @@@@@@ @@@@@@ @@@@@@@ @@@@@@@ @@@@@@ @@@@@@@@@@ @@@@@@ @@@@@@@ @@@ @@@ @@@ @@@@@@@@ @@@@@@
# @@@@@@@@ @@@@@@@ @@@@@@@ @@@@@@@@ @@@@@@@@ @@@@@@@@@@@ @@@@@@@@ @@@@@@@@ @@@ @@@ @@@ @@@@@@@@ @@@@@@@
# @@! @@@ !@@ @@! @@! @@@ @@! @@@ @@! @@! @@! @@! @@@ @@! @@@ @@! @@@ @@! @@! !@@
# !@! @!@ !@! !@! !@! @!@ !@! @!@ !@! !@! !@! !@! @!@ !@! @!@ !@! @!@ !@! !@! !@!
# @!@!@!@! !!@@!! @!! @!@!!@! @!@ !@! @!! !!@ @!@ @!@ !@! @!@ !@! @!@ !@! @!! @!!!:! !!@@!!
# !!!@!!!! !!@!!! !!! !!@!@! !@! !!! !@! ! !@! !@! !!! !@! !!! !@! !!! !!! !!!!!: !!@!!!
# !!: !!! !:! !!: !!: :!! !!: !!! !!: !!: !!: !!! !!: !!! !!: !!! !!: !!: !:!
# :!: !:! !:! :!: :!: !:! :!: !:! :!: :!: :!: !:! :!: !:! :!: !:! :!: :!: !:!
# :: ::: :::: :: :: :: ::: ::::: :: ::: :: ::::: :: :::: :: ::::: :: :: :::: :: :::: :::: ::
# : : : :: : : : : : : : : : : : : : : :: : : : : : : :: : : : :: :: :: : :
#
# © Copyright 2024
#
# https://t.me/Den4ikSuperOstryyPer4ik
# and
# https://t.me/ToXicUse
#
# 🔒 Licensed under the GNU AGPLv3
# https://www.gnu.org/licenses/agpl-3.0.html
#
# meta developer: @AstroModules
# meta banner: https://raw.githubusercontent.com/Den4ikSuperOstryyPer4ik/Astro-modules/main/Banners/PasswordGenerator.jpg
import logging
import random
from telethon.tl.types import Message
from .. import loader, utils
from ..inline.types import InlineCall
logger = logging.getLogger(__name__)
@loader.tds
class PasswordGeneratorMod(loader.Module):
'''Random password/pincode generator'''
strings = {
"name": "RandomPasswordGenerator",
"_cfg_doc_pass_length": "set password length (in number of characters)",
"_cfg_doc_pin_code_length": "set pincode length (in number of characters)",
"_cfg_doc_simbols_in_pass": (
"Will there be additional characters in the generated password"
" (+-*!&$#?=@<>)?"
),
"what_to_generate": "🆗What should be generated?",
"new_random_pass": "🔣 new random password 🆕",
"new_random_pincode": "🔢 new random PIN-code 🆕",
"pass": "<b>🆕 Your new password in {} characters:\n<code>{}</code></b>",
"pincode": "<b>🆕 Your new pincode in {} characters:\n<code>{}</code></b>",
"menu": "💻 Menu",
"close": "🚫 Close",
}
strings_ru = {
"_cls_doc": (
"Генератор рандомного пароля/пин-кода\nНастроить генератор можно через"
" конфиг"
),
"_cfg_doc_pass_length": "выставьте длину пароля(в кол-ве символов)",
"_cfg_doc_pin_code_length": "выставьте длину Пин-Кода(в кол-ве символов)",
"_cfg_doc_simbols_in_pass": (
"Какие символы должны быть в сгенерированном пароле?"
),
"what_to_generate": "🆗 Что надо сгенерировать?",
"new_random_pass": "🔣 Новый рандомный пароль 🆕",
"new_random_pincode": "🔢 Новый рандомный PIN-код 🆕",
"pass": "<b>🆕 Ваш новый пароль в {} символов:\n<code>{}</code></b>",
"pincode": "<b>🆕 Ваш новый пин-код в {} символов:</b>\n<code>{}</code>",
"menu": "💻 Меню",
"close": "🚫 Закрыть",
}
@loader.command(ru_doc="—>конфиг этого модуля")
async def generatorcfgcmd(self, message: Message):
"""—>config for this module"""
name = self.strings("name")
await self.allmodules.commands["config"](
await utils.answer(message, f"{self.get_prefix()}config {name}")
)
def __init__(self):
self._ratelimit = []
self.config = loader.ModuleConfig(
loader.ConfigValue(
"password_length",
10,
doc=lambda: self.strings("_cfg_doc_pass_length"),
validator=loader.validators.Integer(minimum=6),
),
loader.ConfigValue(
"pincode_length",
4,
doc=lambda: self.strings("_cfg_doc_pin_code_length"),
validator=loader.validators.Integer(minimum=4),
),
loader.ConfigValue(
"symbols",
"+-*!&$?=@<>abcdefghijklnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890",
doc=lambda: self.strings("_cfg_doc_simbols_in_pass"),
),
)
@loader.command(ru_doc="—>сгенерировать случайный пароль/пин-код")
async def igeneratorcmd(self, message: Message):
"""—>generate random password/pin"""
await self.inline.form(
self.strings("what_to_generate"),
reply_markup=[
[
{
"text": self.strings("new_random_pass"),
"callback": self.new_random_pass,
}
],
[
{
"text": self.strings("new_random_pincode"),
"callback": self.new_random_pincode,
}
],
[{"text": self.strings("close"), "action": "close"}],
],
message=message,
)
async def igenerator(self, call: InlineCall):
await call.edit(
self.strings("what_to_generate"),
reply_markup=[
[
{
"text": self.strings("new_random_pass"),
"callback": self.new_random_pass,
}
],
[
{
"text": self.strings("new_random_pincode"),
"callback": self.new_random_pincode,
}
],
[{"text": self.strings("close"), "action": "close"}],
],
)
async def new_random_pass(self, call: InlineCall):
symbols = self.config["symbols"]
password_length = self.config["password_length"]
length = int(password_length)
password = ""
for _ in range(length):
password += random.choice(symbols)
await call.edit(
self.strings["pass"].format(password_length, password),
reply_markup=[
[
{
"text": self.strings("menu"),
"callback": self.igenerator
}
],
[
{
"text": self.strings("close"),
"action": "close"
}
],
],
)
async def new_random_pincode(self, call: InlineCall):
pincode_length = self.config["pincode_length"]
chars = "1234567890"
length = int(self.config["pincode_length"])
pincode = ""
for _ in range(length):
pincode += random.choice(chars)
await call.edit(
self.strings["pincode"].format(pincode_length, pincode),
reply_markup=[
[
{
"text": self.strings("menu"),
"callback": self.igenerator
}
],
[
{
"text": self.strings("close"),
"action": "close"
}
],
],
)

View File

@@ -1,400 +1,400 @@
__version__ = (1, 0, 0)
#
# @@@@@@ @@@@@@ @@@@@@@ @@@@@@@ @@@@@@ @@@@@@@@@@ @@@@@@ @@@@@@@ @@@ @@@ @@@ @@@@@@@@ @@@@@@
# @@@@@@@@ @@@@@@@ @@@@@@@ @@@@@@@@ @@@@@@@@ @@@@@@@@@@@ @@@@@@@@ @@@@@@@@ @@@ @@@ @@@ @@@@@@@@ @@@@@@@
# @@! @@@ !@@ @@! @@! @@@ @@! @@@ @@! @@! @@! @@! @@@ @@! @@@ @@! @@@ @@! @@! !@@
# !@! @!@ !@! !@! !@! @!@ !@! @!@ !@! !@! !@! !@! @!@ !@! @!@ !@! @!@ !@! !@! !@!
# @!@!@!@! !!@@!! @!! @!@!!@! @!@ !@! @!! !!@ @!@ @!@ !@! @!@ !@! @!@ !@! @!! @!!!:! !!@@!!
# !!!@!!!! !!@!!! !!! !!@!@! !@! !!! !@! ! !@! !@! !!! !@! !!! !@! !!! !!! !!!!!: !!@!!!
# !!: !!! !:! !!: !!: :!! !!: !!! !!: !!: !!: !!! !!: !!! !!: !!! !!: !!: !:!
# :!: !:! !:! :!: :!: !:! :!: !:! :!: :!: :!: !:! :!: !:! :!: !:! :!: :!: !:!
# :: ::: :::: :: :: :: ::: ::::: :: ::: :: ::::: :: :::: :: ::::: :: :: :::: :: :::: :::: ::
# : : : :: : : : : : : : : : : : : : : :: : : : : : : :: : : : :: :: :: : :
#
# © Copyright 2024
#
# https://t.me/Den4ikSuperOstryyPer4ik
# and
# https://t.me/ToXicUse
#
# 🔒 Licensed under the GNU AGPLv3
# https://www.gnu.org/licenses/agpl-3.0.html
#
# meta banner:
# meta developer: @AstroModules
# required: steampy
# meta banner: https://raw.githubusercontent.com/Den4ikSuperOstryyPer4ik/Astro-modules/main/Banners/AstroSteamNow.png
# Part of the module taken from WakaTime by @hikariatama: 38, 158, 208, 324 lines
import time
import logging
import datetime
import requests
import asyncio
from steampy.client import SteamClient
from .. import loader, utils
from ..inline.types import InlineCall
from telethon.errors.rpcerrorlist import MessageNotModifiedError
logger = logging.getLogger(__name__)
@loader.tds
class Steam(loader.Module):
'''Get now played game'''
strings = {
'name': 'SteamNow',
'_api_key': "Enter your SteamAPI Key. You can get it by following this tutorial:\n\nhttps://t.me/help_code/20", # Tutorial link
'_account_id': "Enter your Steam Account ID. More details in the tutorial: \n\nhttps://t.me/help_code/21", # Tutorial link
'no_api_key_or_id': (
'<b>❌ You did not specify your API_KEY or ACCOUNT_ID in the config.</b>\n'
'<b>🚨 Correct this for further module operation</b>'
),
'noGame': "<b>❌ The game is not running or you do not have access</b>",
'steamNow': (
'💻 <b>At the moment you are playing:</b>\n\n'
'🎮 <b>Title:</b> <code>{}</code>\n'
'🆔 <b>Game ID: {}</b>'
),
'lite_gameInfo': (
'🎮 <b>Game information:</b>\n\n'
'<b>Title: </b>{}\n'
'<b>Price: {}</b>\n'
'<b>Description:</b>\n- <i>{}</i>'
),
'steamMe': (
'<b>🎮 Your account:</b>\n\n'
'<b>Name: </b><i>{}</i> (<i>{}</i>)\n'
'<b>Online: </b><code>{}</code>\n'
'<b>Created: </b><code>{}</code>\n'
'<b>Recent games:</b>\n<i> • {}</i>'
),
'gameNotFound': '<b>🆔 There is no game with such an identifier, try again</b>',
"state": "🙂 <b>Steam widgets: {}</b>\n{}",
"error": "<b>Steam error</b>\n\n{}",
"tutorial": (
" <b>To enable the widget, send this text to any chat:"
" </b><code>{STEAMNOW}</code>"
),
"configuring": "🙂 <b>Steam widget will be ready soon...</b>",
}
strings_ru = {
'_api_key': "Введите ваш SteamAPI Key. Получить его можно по туториалу:\n\n", # Линк на тутор
'_account_id': "Введите ваш Steam Account ID. Подробнее в туториале: \n\n", # Линк на тутор
'no_api_key_or_id': (
'<b>❌ Вы не указали ваш API_KEY или ACCOUNT_ID в конфиге.</b>\n'
'<b>🚨 Исправьте это для дальнейшей работы модуля</b>'
),
'noGame': "<b>❌ Игра не запущена, или у вас нет доступа</b>",
'steamNow': (
'💻 <b>В данный момент вы играете:</b>\n\n'
'🎮 <b>Название:</b> <code>{}</code>\n'
'🆔 <b>ID Игры: {}</b>'
),
'lite_gameInfo': (
'🎮 <b>Информация об игре:</b>\n\n'
'<b>Название: </b>{}\n'
'<b>Цена: {}</b>\n'
'<b>Описание:</b>\n- <i>{}</i>'
),
'steamMe': (
'<b>🎮 Ваш аккаунт:</b>\n\n'
'<b>Имя: </b><i>{}</i> (<i>{}</i>)\n'
'<b>В сети: </b><code>{}</code>\n'
'<b>Создан: </b><code>{}</code>\n'
'<b>Последние игры:</b>\n<i> • {}</i>'
),
'gameNotFound': '<b>🆔 Игры с таким идентификатором нет, попробуйте снова</b>',
"state": "🙂 <b>Steam виджеты: {}</b>\n{}",
"error": "<b>Steam error</b>\n\n{}",
"tutorial": (
" <b>Для включения виджета отправьте данный текст в любой чат:"
" </b><code>{STEAMNOW}</code>"
),
"configuring": "🙂 <b>Steam виджет скоро будет готов...</b>",
}
def __init__(self):
self.config = loader.ModuleConfig(
loader.ConfigValue(
'API_KEY',
None,
doc=lambda: self.strings('_api_key'),
validator=loader.validators.Hidden(),
),
loader.ConfigValue(
'ACCOUNT_ID',
None,
doc=lambda: self.strings('_account_id')
),
loader.ConfigValue(
"update_interval",
300,
lambda: "Messages update interval. Not recommended < 300 seconds",
validator=loader.validators.Integer(minimum=60),
),
)
async def client_ready(self, client, db):
self.db.set(
"Steam",
"widgets",
list(map(tuple, self.db.get("Steam","widgets", [])))
)
self._task = asyncio.ensure_future(self._parse())
async def steam_requests(self, request, gameId: bool = None):
'''Function for requests to SteamAPI'''
api_key = self.config['API_KEY']
account_id = self.config['ACCOUNT_ID']
steam_client = SteamClient(api_key)
if request == 'SteamNow':
if not api_key or not account_id:
return('TokenError', None)
data = {'key': api_key, 'steamids': account_id}
response = steam_client.api_call('GET', 'ISteamUser', 'GetPlayerSummaries', 'v2', data).json()['response']
try:
gameId = response['players'][0]['gameid']
gameName = response['players'][0]['gameextrainfo']
text = self.strings('steamNow').format(gameName, gameId)
except:
text, gameId = self.strings('noGame'), None
return text, gameId #, photo
elif request == 'profileInfo':
if not api_key or not account_id:
return('TokenError', None, None, None, None, None)
url = 'http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key={}&steamids={}'
url2 = 'http://api.steampowered.com/IPlayerService/GetRecentlyPlayedGames/v0001/?key={}&steamid={}&format=json'
response = requests.get(url.format(self.config['API_KEY'], self.config['ACCOUNT_ID'])).json()['response']['players'][0]
recentGameInfo = requests.get(url2.format(self.config['API_KEY'], self.config['ACCOUNT_ID'])).json()['response']['games']
games = []
for game in recentGameInfo:
games.append(f'{game["name"]}: {game["playtime_2weeks"]}м. ({game["playtime_forever"]}м.)')
recentGames = '\n'.join(games)
return(
response['avatarfull'], # Profile photo
response['personaname'], # Name: 'ˢˡ ToxUniҨue,
response['realname'], # Realname: Tox.
datetime.datetime.fromtimestamp(response['lastlogoff']).isoformat().replace('T', ' '), # Последний раз в сети
datetime.datetime.fromtimestamp(response['timecreated']).isoformat().replace('T', ' '), # Дата создания аккаунта
recentGames
)
elif request == 'GameInfo':
if not api_key or not account_id:
return('TokenError', None)
url = f"http://store.steampowered.com/api/appdetails?appids={gameId}"
response = requests.get(url)
data = response.json()
game_data = data[str(gameId)]['data']
capsule_image = game_data.get('header_image', None)
name = game_data.get('name', None)
short_description = game_data.get('short_description', None)
price_overview = game_data.get('price_overview', None)
if price_overview:
initial_formatted_price = price_overview.get('initial_formatted', None)
final_formatted_price = price_overview.get('final_formatted', None)
else:
initial_formatted_price = None
final_formatted_price = None
final_price = f'{initial_formatted_price}' if initial_formatted_price == final_formatted_price else f'{final_formatted_price} (<u>{initial_formatted_price}</u>)'
text = self.strings('lite_gameInfo').format(name, final_price, short_description)
return capsule_image, text
async def game_info_i(
self,
call: InlineCall,
gameId: int,
message
):
_, text = await self.steam_requests('GameInfo', gameId)
if _ == 'TokenError':
return await call.edit(text=self.strings('no_api_key_or_id'))
await call.edit(text=text)
async def _parse(self, do_not_loop: bool = False):
while True:
if self.config["API_KEY"] == None or self.db.get("Steam", "state") == False:
await asyncio.sleep(5)
continue
for widget in self.db.get("Steam", "widgets", []):
now, _ = await self.steam_requests('SteamNow')
if now == 'TokenError':
await self._client.edit_message(*widget[:2], self.strings('no_api_key_or_id'))
elif now == self.strings('noGame'):
self.db.set('steam', 'inGame', None)
await self._client.edit_message(*widget[:2], self.strings('noGame'))
else:
in_game_time = self.db.get('steam', 'inGame')
if in_game_time is None:
self.db.set('steam', 'inGame', time.time())
game_time_minutes = 0
else:
game_time = time.time() - in_game_time
game_time_minutes = round(game_time / 60)
try:
await self._client.edit_message(*widget[:2], now + f'\n\n<b>🕓 В игре: {game_time_minutes} минут.</b>')
except:
return
await asyncio.sleep(int(self.config["update_interval"]))
@loader.command(
ru_doc=' - получить, во что я сейчас играю'
)
async def steamnow(self, message):
"""- get what I'm playing at"""
text, gameid = await self.steam_requests('SteamNow')
if text == self.strings('noGame'):
return await utils.answer(message, text)
elif text == 'TokenError':
return await utils.answer(message, self.strings('no_api_key_or_id'))
capsule_image, _ = await self.steam_requests('GameInfo', gameid)
await self.inline.form(
message=message,
photo=capsule_image,
text=text,
reply_markup=[
{
'text': 'Информация об игре',
'callback': self.game_info_i,
'args': (gameid, message,),
}
]
)
@loader.command(
ru_doc='- открыть аккаунт Steam'
)
async def sme(self, message):
'''- my steam account'''
photo, fullName, name, date1, date2, games = await self.steam_requests('profileInfo')
if photo == 'TokenError':
await utils.answer(message, self.strings('no_api_key_or_id'))
await utils.answer_file(
message,
photo,
caption=self.strings('steamMe').format(
fullName, name, date1, date2, games
)
)
@loader.command(
ru_doc='<id> - получить инфо об игре'
)
async def game(self, message):
'''<id> - get game info'''
args = utils.get_args_raw(message)
try:
capsule_image, text = await self.steam_requests('GameInfo', args)
if capsule_image == 'TokenError':
await utils.answer(message, self.strings('no_api_key_or_id'))
await utils.answer_file(message, capsule_image, text)
except:
await utils.answer(message, self.strings('gameNotFound'))
@loader.command(
ru_doc='- вкл/выкл виджеты SteamNow'
)
async def steamtoggle(self, message):
""" - toggle widgets updates"""
state = self.db.get('Steam', 'state')
state = True if state == False else False
self.db.set('Steam', 'state', state)
await utils.answer(
message,
self.strings("state").format(
"on" if state else "off", self.strings("tutorial") if state else ""
),
)
@loader.watcher()
async def watcher(self, message):
if (
self.db.get('Steam', 'state')
and (await self.client.get_messages(self.db.get('Steam', 'widgets')[0][0], ids=self.db.get('Steam', 'widgets')[0][1])).message == '❌ Вы не во что не играете'
):
now, _ = await self.steam_requests('SteamNow')
if now == self.strings('noGame') or now == 'TokenError':
return
await self._parse(do_not_loop=True)
try:
if "{STEAMNOW}" not in getattr(message, "text", "") or not message.out:
return
chat_id = utils.get_chat_id(message)
message_id = message.id
self.db.set(
"Steam",
"widgets",
self.db.get('steam', "widgets", []) + [(chat_id, message_id, message.text)],
)
await utils.answer(message, self.strings("configuring"))
await self._parse(do_not_loop=True)
except Exception as e:
logger.exception("Can't send widget")
await utils.answer(message, self.strings("error").format(e))
__version__ = (1, 0, 0)
#
# @@@@@@ @@@@@@ @@@@@@@ @@@@@@@ @@@@@@ @@@@@@@@@@ @@@@@@ @@@@@@@ @@@ @@@ @@@ @@@@@@@@ @@@@@@
# @@@@@@@@ @@@@@@@ @@@@@@@ @@@@@@@@ @@@@@@@@ @@@@@@@@@@@ @@@@@@@@ @@@@@@@@ @@@ @@@ @@@ @@@@@@@@ @@@@@@@
# @@! @@@ !@@ @@! @@! @@@ @@! @@@ @@! @@! @@! @@! @@@ @@! @@@ @@! @@@ @@! @@! !@@
# !@! @!@ !@! !@! !@! @!@ !@! @!@ !@! !@! !@! !@! @!@ !@! @!@ !@! @!@ !@! !@! !@!
# @!@!@!@! !!@@!! @!! @!@!!@! @!@ !@! @!! !!@ @!@ @!@ !@! @!@ !@! @!@ !@! @!! @!!!:! !!@@!!
# !!!@!!!! !!@!!! !!! !!@!@! !@! !!! !@! ! !@! !@! !!! !@! !!! !@! !!! !!! !!!!!: !!@!!!
# !!: !!! !:! !!: !!: :!! !!: !!! !!: !!: !!: !!! !!: !!! !!: !!! !!: !!: !:!
# :!: !:! !:! :!: :!: !:! :!: !:! :!: :!: :!: !:! :!: !:! :!: !:! :!: :!: !:!
# :: ::: :::: :: :: :: ::: ::::: :: ::: :: ::::: :: :::: :: ::::: :: :: :::: :: :::: :::: ::
# : : : :: : : : : : : : : : : : : : : :: : : : : : : :: : : : :: :: :: : :
#
# © Copyright 2024
#
# https://t.me/Den4ikSuperOstryyPer4ik
# and
# https://t.me/ToXicUse
#
# 🔒 Licensed under the GNU AGPLv3
# https://www.gnu.org/licenses/agpl-3.0.html
#
# meta banner:
# meta developer: @AstroModules
# required: steampy
# meta banner: https://raw.githubusercontent.com/Den4ikSuperOstryyPer4ik/Astro-modules/main/Banners/AstroSteamNow.png
# Part of the module taken from WakaTime by @hikariatama: 38, 158, 208, 324 lines
import time
import logging
import datetime
import requests
import asyncio
from steampy.client import SteamClient
from .. import loader, utils
from ..inline.types import InlineCall
from telethon.errors.rpcerrorlist import MessageNotModifiedError
logger = logging.getLogger(__name__)
@loader.tds
class Steam(loader.Module):
'''Get now played game'''
strings = {
'name': 'SteamNow',
'_api_key': "Enter your SteamAPI Key. You can get it by following this tutorial:\n\nhttps://t.me/help_code/20", # Tutorial link
'_account_id': "Enter your Steam Account ID. More details in the tutorial: \n\nhttps://t.me/help_code/21", # Tutorial link
'no_api_key_or_id': (
'<b>❌ You did not specify your API_KEY or ACCOUNT_ID in the config.</b>\n'
'<b>🚨 Correct this for further module operation</b>'
),
'noGame': "<b>❌ The game is not running or you do not have access</b>",
'steamNow': (
'💻 <b>At the moment you are playing:</b>\n\n'
'🎮 <b>Title:</b> <code>{}</code>\n'
'🆔 <b>Game ID: {}</b>'
),
'lite_gameInfo': (
'🎮 <b>Game information:</b>\n\n'
'<b>Title: </b>{}\n'
'<b>Price: {}</b>\n'
'<b>Description:</b>\n- <i>{}</i>'
),
'steamMe': (
'<b>🎮 Your account:</b>\n\n'
'<b>Name: </b><i>{}</i> (<i>{}</i>)\n'
'<b>Online: </b><code>{}</code>\n'
'<b>Created: </b><code>{}</code>\n'
'<b>Recent games:</b>\n<i> • {}</i>'
),
'gameNotFound': '<b>🆔 There is no game with such an identifier, try again</b>',
"state": "🙂 <b>Steam widgets: {}</b>\n{}",
"error": "<b>Steam error</b>\n\n{}",
"tutorial": (
" <b>To enable the widget, send this text to any chat:"
" </b><code>{STEAMNOW}</code>"
),
"configuring": "🙂 <b>Steam widget will be ready soon...</b>",
}
strings_ru = {
'_api_key': "Введите ваш SteamAPI Key. Получить его можно по туториалу:\n\n", # Линк на тутор
'_account_id': "Введите ваш Steam Account ID. Подробнее в туториале: \n\n", # Линк на тутор
'no_api_key_or_id': (
'<b>❌ Вы не указали ваш API_KEY или ACCOUNT_ID в конфиге.</b>\n'
'<b>🚨 Исправьте это для дальнейшей работы модуля</b>'
),
'noGame': "<b>❌ Игра не запущена, или у вас нет доступа</b>",
'steamNow': (
'💻 <b>В данный момент вы играете:</b>\n\n'
'🎮 <b>Название:</b> <code>{}</code>\n'
'🆔 <b>ID Игры: {}</b>'
),
'lite_gameInfo': (
'🎮 <b>Информация об игре:</b>\n\n'
'<b>Название: </b>{}\n'
'<b>Цена: {}</b>\n'
'<b>Описание:</b>\n- <i>{}</i>'
),
'steamMe': (
'<b>🎮 Ваш аккаунт:</b>\n\n'
'<b>Имя: </b><i>{}</i> (<i>{}</i>)\n'
'<b>В сети: </b><code>{}</code>\n'
'<b>Создан: </b><code>{}</code>\n'
'<b>Последние игры:</b>\n<i> • {}</i>'
),
'gameNotFound': '<b>🆔 Игры с таким идентификатором нет, попробуйте снова</b>',
"state": "🙂 <b>Steam виджеты: {}</b>\n{}",
"error": "<b>Steam error</b>\n\n{}",
"tutorial": (
" <b>Для включения виджета отправьте данный текст в любой чат:"
" </b><code>{STEAMNOW}</code>"
),
"configuring": "🙂 <b>Steam виджет скоро будет готов...</b>",
}
def __init__(self):
self.config = loader.ModuleConfig(
loader.ConfigValue(
'API_KEY',
None,
doc=lambda: self.strings('_api_key'),
validator=loader.validators.Hidden(),
),
loader.ConfigValue(
'ACCOUNT_ID',
None,
doc=lambda: self.strings('_account_id')
),
loader.ConfigValue(
"update_interval",
300,
lambda: "Messages update interval. Not recommended < 300 seconds",
validator=loader.validators.Integer(minimum=60),
),
)
async def client_ready(self, client, db):
self.db.set(
"Steam",
"widgets",
list(map(tuple, self.db.get("Steam","widgets", [])))
)
self._task = asyncio.ensure_future(self._parse())
async def steam_requests(self, request, gameId: bool = None):
'''Function for requests to SteamAPI'''
api_key = self.config['API_KEY']
account_id = self.config['ACCOUNT_ID']
steam_client = SteamClient(api_key)
if request == 'SteamNow':
if not api_key or not account_id:
return('TokenError', None)
data = {'key': api_key, 'steamids': account_id}
response = steam_client.api_call('GET', 'ISteamUser', 'GetPlayerSummaries', 'v2', data).json()['response']
try:
gameId = response['players'][0]['gameid']
gameName = response['players'][0]['gameextrainfo']
text = self.strings('steamNow').format(gameName, gameId)
except:
text, gameId = self.strings('noGame'), None
return text, gameId #, photo
elif request == 'profileInfo':
if not api_key or not account_id:
return('TokenError', None, None, None, None, None)
url = 'http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key={}&steamids={}'
url2 = 'http://api.steampowered.com/IPlayerService/GetRecentlyPlayedGames/v0001/?key={}&steamid={}&format=json'
response = requests.get(url.format(self.config['API_KEY'], self.config['ACCOUNT_ID'])).json()['response']['players'][0]
recentGameInfo = requests.get(url2.format(self.config['API_KEY'], self.config['ACCOUNT_ID'])).json()['response']['games']
games = []
for game in recentGameInfo:
games.append(f'{game["name"]}: {game["playtime_2weeks"]}м. ({game["playtime_forever"]}м.)')
recentGames = '\n'.join(games)
return(
response['avatarfull'], # Profile photo
response['personaname'], # Name: 'ˢˡ ToxUniҨue,
response['realname'], # Realname: Tox.
datetime.datetime.fromtimestamp(response['lastlogoff']).isoformat().replace('T', ' '), # Последний раз в сети
datetime.datetime.fromtimestamp(response['timecreated']).isoformat().replace('T', ' '), # Дата создания аккаунта
recentGames
)
elif request == 'GameInfo':
if not api_key or not account_id:
return('TokenError', None)
url = f"http://store.steampowered.com/api/appdetails?appids={gameId}"
response = requests.get(url)
data = response.json()
game_data = data[str(gameId)]['data']
capsule_image = game_data.get('header_image', None)
name = game_data.get('name', None)
short_description = game_data.get('short_description', None)
price_overview = game_data.get('price_overview', None)
if price_overview:
initial_formatted_price = price_overview.get('initial_formatted', None)
final_formatted_price = price_overview.get('final_formatted', None)
else:
initial_formatted_price = None
final_formatted_price = None
final_price = f'{initial_formatted_price}' if initial_formatted_price == final_formatted_price else f'{final_formatted_price} (<u>{initial_formatted_price}</u>)'
text = self.strings('lite_gameInfo').format(name, final_price, short_description)
return capsule_image, text
async def game_info_i(
self,
call: InlineCall,
gameId: int,
message
):
_, text = await self.steam_requests('GameInfo', gameId)
if _ == 'TokenError':
return await call.edit(text=self.strings('no_api_key_or_id'))
await call.edit(text=text)
async def _parse(self, do_not_loop: bool = False):
while True:
if self.config["API_KEY"] == None or self.db.get("Steam", "state") == False:
await asyncio.sleep(5)
continue
for widget in self.db.get("Steam", "widgets", []):
now, _ = await self.steam_requests('SteamNow')
if now == 'TokenError':
await self._client.edit_message(*widget[:2], self.strings('no_api_key_or_id'))
elif now == self.strings('noGame'):
self.db.set('steam', 'inGame', None)
await self._client.edit_message(*widget[:2], self.strings('noGame'))
else:
in_game_time = self.db.get('steam', 'inGame')
if in_game_time is None:
self.db.set('steam', 'inGame', time.time())
game_time_minutes = 0
else:
game_time = time.time() - in_game_time
game_time_minutes = round(game_time / 60)
try:
await self._client.edit_message(*widget[:2], now + f'\n\n<b>🕓 В игре: {game_time_minutes} минут.</b>')
except:
return
await asyncio.sleep(int(self.config["update_interval"]))
@loader.command(
ru_doc=' - получить, во что я сейчас играю'
)
async def steamnow(self, message):
"""- get what I'm playing at"""
text, gameid = await self.steam_requests('SteamNow')
if text == self.strings('noGame'):
return await utils.answer(message, text)
elif text == 'TokenError':
return await utils.answer(message, self.strings('no_api_key_or_id'))
capsule_image, _ = await self.steam_requests('GameInfo', gameid)
await self.inline.form(
message=message,
photo=capsule_image,
text=text,
reply_markup=[
{
'text': 'Информация об игре',
'callback': self.game_info_i,
'args': (gameid, message,),
}
]
)
@loader.command(
ru_doc='- открыть аккаунт Steam'
)
async def sme(self, message):
'''- my steam account'''
photo, fullName, name, date1, date2, games = await self.steam_requests('profileInfo')
if photo == 'TokenError':
await utils.answer(message, self.strings('no_api_key_or_id'))
await utils.answer_file(
message,
photo,
caption=self.strings('steamMe').format(
fullName, name, date1, date2, games
)
)
@loader.command(
ru_doc='<id> - получить инфо об игре'
)
async def game(self, message):
'''<id> - get game info'''
args = utils.get_args_raw(message)
try:
capsule_image, text = await self.steam_requests('GameInfo', args)
if capsule_image == 'TokenError':
await utils.answer(message, self.strings('no_api_key_or_id'))
await utils.answer_file(message, capsule_image, text)
except:
await utils.answer(message, self.strings('gameNotFound'))
@loader.command(
ru_doc='- вкл/выкл виджеты SteamNow'
)
async def steamtoggle(self, message):
""" - toggle widgets updates"""
state = self.db.get('Steam', 'state')
state = True if state == False else False
self.db.set('Steam', 'state', state)
await utils.answer(
message,
self.strings("state").format(
"on" if state else "off", self.strings("tutorial") if state else ""
),
)
@loader.watcher()
async def watcher(self, message):
if (
self.db.get('Steam', 'state')
and (await self.client.get_messages(self.db.get('Steam', 'widgets')[0][0], ids=self.db.get('Steam', 'widgets')[0][1])).message == '❌ Вы не во что не играете'
):
now, _ = await self.steam_requests('SteamNow')
if now == self.strings('noGame') or now == 'TokenError':
return
await self._parse(do_not_loop=True)
try:
if "{STEAMNOW}" not in getattr(message, "text", "") or not message.out:
return
chat_id = utils.get_chat_id(message)
message_id = message.id
self.db.set(
"Steam",
"widgets",
self.db.get('steam', "widgets", []) + [(chat_id, message_id, message.text)],
)
await utils.answer(message, self.strings("configuring"))
await self._parse(do_not_loop=True)
except Exception as e:
logger.exception("Can't send widget")
await utils.answer(message, self.strings("error").format(e))

View File

@@ -1,345 +1,345 @@
__version__ = (1, 4, 2)
#
# @@@@@@ @@@@@@ @@@@@@@ @@@@@@@ @@@@@@ @@@@@@@@@@ @@@@@@ @@@@@@@ @@@ @@@ @@@ @@@@@@@@ @@@@@@
# @@@@@@@@ @@@@@@@ @@@@@@@ @@@@@@@@ @@@@@@@@ @@@@@@@@@@@ @@@@@@@@ @@@@@@@@ @@@ @@@ @@@ @@@@@@@@ @@@@@@@
# @@! @@@ !@@ @@! @@! @@@ @@! @@@ @@! @@! @@! @@! @@@ @@! @@@ @@! @@@ @@! @@! !@@
# !@! @!@ !@! !@! !@! @!@ !@! @!@ !@! !@! !@! !@! @!@ !@! @!@ !@! @!@ !@! !@! !@!
# @!@!@!@! !!@@!! @!! @!@!!@! @!@ !@! @!! !!@ @!@ @!@ !@! @!@ !@! @!@ !@! @!! @!!!:! !!@@!!
# !!!@!!!! !!@!!! !!! !!@!@! !@! !!! !@! ! !@! !@! !!! !@! !!! !@! !!! !!! !!!!!: !!@!!!
# !!: !!! !:! !!: !!: :!! !!: !!! !!: !!: !!: !!! !!: !!! !!: !!! !!: !!: !:!
# :!: !:! !:! :!: :!: !:! :!: !:! :!: :!: :!: !:! :!: !:! :!: !:! :!: :!: !:!
# :: ::: :::: :: :: :: ::: ::::: :: ::: :: ::::: :: :::: :: ::::: :: :: :::: :: :::: :::: ::
# : : : :: : : : : : : : : : : : : : : :: : : : : : : :: : : : :: :: :: : :
#
# © Copyright 2024
#
# https://t.me/Den4ikSuperOstryyPer4ik
# and
# https://t.me/ToXicUse
#
# 🔒 Licensed under the GNU AGPLv3
# https://www.gnu.org/licenses/agpl-3.0.html
#
# meta developer: @AstroModules
import datetime
import logging
import time
from telethon import types
from telethon.tl.functions.account import UpdateProfileRequest
from telethon.tl.functions.users import GetFullUserRequest
from .. import loader, utils
from ..inline.types import InlineCall
logger = logging.getLogger(__name__)
@loader.tds
class TxAFKMod(loader.Module):
'''Афк модуль от AstroModules с изменением био и имени'''
async def client_ready(self, client, db):
self._db = db
self._me = await client.get_me()
strings = {
"name": "TxAFK",
"lname": "| afk.",
"lname0": " ",
"bt_off_afk": "⚠️ АФК режим отключен",
"bt_on_afk": "💤 АФК режим снова активен",
"_cfg_cst_btn": "Ссылка на чат которая будет отоброжаться вместе с уведомлением. (Чтобы вообще убрать напишите None)",
"standart_bio_text": "Кастомное описание профиля",
"feedback_bot__text": "Юзер вашего фидбэк бота (если имеется)",
"button__text": "Добавить инлайн кнопку отключения АФК режима?",
"custom_text__afk_text": "Кастомный текст афк. Используй {time} для вывода последнего времени нахождения в сети",
}
def __init__(self):
self.config = loader.ModuleConfig(
loader.ConfigValue(
"feedback_bot",
"None",
doc=lambda: self.strings("feedback_bot__text"),
),
loader.ConfigValue(
"custom_text__afk",
"None",
doc=lambda: self.strings("custom_text__afk_text"),
),
loader.ConfigValue(
"standart_bio",
"None",
doc=lambda: self.strings("standart_bio_text"),
),
loader.ConfigValue(
"custom_button",
[
"🦄 AstroModules 🦄",
"https://t.me/AstroModulesChat",
],
lambda: self.strings("_cfg_cst_btn"),
validator=loader.validators.Union(
loader.validators.Series(fixed_len=2),
loader.validators.NoneType(),
),
),
loader.ConfigValue(
"ignore_chats",
[],
lambda: "Чаты, в которых при упоминании TxAFК не будет срабатывать",
validator=loader.validators.Series(
validator=loader.validators.Union(
loader.validators.TelegramID(),
loader.validators.RegExp("[0-9]"),
),
),
),
loader.ConfigValue(
"button",
True,
doc=lambda: self.strings("button__text"),
validator=loader.validators.Boolean(),
)
)
async def txcfgcmd(self, message):
"""- открыть конфиг модуля"""
await self.allmodules.commands["config"](
await utils.answer(message, f"{self.get_prefix()}config TxAFK")
)
async def goafkcmd(self, message):
"""- войти в AFK режим"""
try:
user_id = (
(
(
await self._client.get_entity(
args if not args.isdigit() else int(args)
)
).id
)
if args
else reply.sender_id
)
except Exception:
user_id = self._tg_id
user = await self._client(GetFullUserRequest(user_id))
self._db.set(__name__, "afk", True)
self._db.set(__name__, "gone", time.time())
self._db.set(__name__, "ratelimit", [])
a_afk_bio_nofb = "В афк."
lastname = self.strings("lname")
if self.config['feedback_bot'] == None:
await message.client(UpdateProfileRequest(about=a_afk_bio_nofb, last_name=lastname))
else:
a_afk_bio = 'На данный момент в АФК. Связь только через '
feedback = self.config['feedback_bot']
aaa = a_afk_bio + feedback
await message.client(UpdateProfileRequest(about=aaa))
await self.allmodules.log("goafk")
await utils.answer(message, '<emoji document_id=5215519585150706301>👍</emoji> <b>АФК режим включен!</b>')
await message.client(UpdateProfileRequest(last_name=lastname))
async def ungoafkcmd(self, message):
"""- выйти из режима AFK"""
msg = await utils.answer(message, '<emoji document_id=5213107179329953547>⏰</emoji> <b>Отключаю режим АФК...</b>')
sbio = self.config['standart_bio']
lastname0 = self.strings('lname0')
self._db.set(__name__, "afk", False)
self._db.set(__name__, "gone", None)
self._db.set(__name__, "ratelimit", [])
await self.allmodules.log("unafk")
if sbio == None:
await message.client(UpdateProfileRequest(about='', last_name=lastname0))
else:
await message.client(UpdateProfileRequest(about=sbio, last_name=lastname0))
time.sleep(1)
await utils.answer(msg, '<emoji document_id=5220108512893344933>🆘</emoji> <b>Режим AFK отключен!</b>')
def _afk_custom_text(self) -> str:
now = datetime.datetime.now().replace(microsecond=0)
gone = datetime.datetime.fromtimestamp(
self._db.get(__name__, "gone")
).replace(microsecond=0)
time = now - gone
return (
"<b> </b>\n"
+ self.config["custom_text__afk"].format(
time=time,
)
)
async def watcher(self, message):
if not isinstance(message, types.Message):
return
if utils.get_chat_id(message) in self.config['ignore_chats']:
return
if message.mentioned or getattr(message.to_id, "user_id", None) == self._me.id:
afk_state = self.get_afk()
if not afk_state:
return
logger.debug("tagged!")
ratelimit = self._db.get(__name__, "ratelimit", [])
if utils.get_chat_id(message) in ratelimit:
return
else:
self._db.setdefault(__name__, {}).setdefault("ratelimit", []).append(
utils.get_chat_id(message)
)
self._db.save()
user = await utils.get_user(message)
if user.is_self or user.bot or user.verified:
logger.debug("User is self, bot or verified.")
return
if self.get_afk() is False:
return
now = datetime.datetime.now().replace(microsecond=0)
gone = datetime.datetime.fromtimestamp(
self._db.get(__name__, "gone")
).replace(microsecond=0)
time = now - gone
if self.config['custom_button'] == None:
if self.config["button"] == False:
if self.config["custom_text__afk"] == None:
await self.inline.form(message=message, text=f"<b>🔅 Я сейчас нахожусь в АФК.</b>\n\nПоследний раз был в сети <code>{time}</code> назад.")
else:
await self.inline.form(message=message, text=self._afk_custom_text())
elif self.config['button'] == True:
if self.config["custom_text__afk"] == None:
await self.inline.form(
message=message,
text=f"<b>🔅 Я сейчас нахожусь в АФК.</b>\n\nПоследний раз был в сети <code>{time}</code> назад.",
reply_markup=[
[
{
"text": "🚫 Выйти с афк 🚫",
"callback": self.button_cancel,
}
]
]
)
else:
await self.inline.form(
message=message,
text=self._afk_custom_text(),
reply_markup=[
[
{
"text": "🚫 Выйти с афк 🚫",
"callback": self.button_cancel,
}
]
]
)
else:
if self.config["button"] == False:
if self.config["custom_text__afk"] == None:
await self.inline.form(message=message, text=f"<b>🔅 Я сейчас нахожусь в АФК.</b>\n\nПоследний раз был в сети <code>{time}</code> назад.", reply_markup=[{"text": self.config['custom_button'][0], "url": self.config['custom_button'][1]}])
else:
await self.inline.form(message=message, text=self._afk_custom_text(), reply_markup=[{"text": self.config['custom_button'][0], "url": self.config['custom_button'][1]}])
elif self.config['button'] == True:
if self.config["custom_text__afk"] == None:
await self.inline.form(
message=message,
text=f"<b>🔅 Я сейчас нахожусь в АФК.</b>\n\nПоследний раз был в сети <code>{time}</code> назад.",
reply_markup=[
[
{
"text": self.config['custom_button'][0],
"url": self.config['custom_button'][1],
}
],
[
{
"text": "🚫 Выйти с афк 🚫",
"callback": self.button_cancel,
}
]
]
)
else:
await self.inline.form(
message=message,
text=self._afk_custom_text(),
reply_markup=[
[
{
"text": self.config['custom_button'][0],
"url": self.config['custom_button'][1],
}
],
[
{
"text": "🚫 Выйти с афк 🚫",
"callback": self.button_cancel,
}
]
]
)
async def button_cancel(self, call: InlineCall):
self._db.set(__name__, "afk", False)
self._db.set(__name__, "gone", None)
self._db.set(__name__, "ratelimit", [])
await self.allmodules.log("unafk")
if self.config['standart_bio'] == None:
lastname = self.strings("lname0")
about = self.strings("lname0")
await self._client(UpdateProfileRequest(about=about, last_name=lastname))
else:
aboutt = self.config['standart_bio']
lastname = self.strings("lname0")
await self._client(UpdateProfileRequest(about=aboutt, last_name=lastname))
await call.edit(
self.strings["bt_off_afk"],
reply_markup=[
{
"text": "🔰 Войти в афк 🔰",
"callback": self.button_cancel_on,
}
]
)
async def button_cancel_on(self, call: InlineCall):
self._db.set(__name__, "afk", True)
self._db.set(__name__, "gone", time.time())
self._db.set(__name__, "ratelimit", [])
a_afk_bio_nofb = "В афк."
lastname = self.strings("lname")
if self.config['feedback_bot'] == None:
await self._client(UpdateProfileRequest(about=a_afk_bio_nofb, last_name=lastname))
else:
a_afk_bio = 'На данный момент в АФК. Связь только через '
feedback = self.config['feedback_bot']
aaa = a_afk_bio + feedback
await self._client(UpdateProfileRequest(about=aaa))
await call.edit(
self.strings["bt_on_afk"],
reply_markup=[
{
"text": "🚫 Выйти с афк 🚫",
"callback": self.button_cancel,
}
]
)
def get_afk(self):
return self._db.get(__name__, "afk", False)
__version__ = (1, 4, 2)
#
# @@@@@@ @@@@@@ @@@@@@@ @@@@@@@ @@@@@@ @@@@@@@@@@ @@@@@@ @@@@@@@ @@@ @@@ @@@ @@@@@@@@ @@@@@@
# @@@@@@@@ @@@@@@@ @@@@@@@ @@@@@@@@ @@@@@@@@ @@@@@@@@@@@ @@@@@@@@ @@@@@@@@ @@@ @@@ @@@ @@@@@@@@ @@@@@@@
# @@! @@@ !@@ @@! @@! @@@ @@! @@@ @@! @@! @@! @@! @@@ @@! @@@ @@! @@@ @@! @@! !@@
# !@! @!@ !@! !@! !@! @!@ !@! @!@ !@! !@! !@! !@! @!@ !@! @!@ !@! @!@ !@! !@! !@!
# @!@!@!@! !!@@!! @!! @!@!!@! @!@ !@! @!! !!@ @!@ @!@ !@! @!@ !@! @!@ !@! @!! @!!!:! !!@@!!
# !!!@!!!! !!@!!! !!! !!@!@! !@! !!! !@! ! !@! !@! !!! !@! !!! !@! !!! !!! !!!!!: !!@!!!
# !!: !!! !:! !!: !!: :!! !!: !!! !!: !!: !!: !!! !!: !!! !!: !!! !!: !!: !:!
# :!: !:! !:! :!: :!: !:! :!: !:! :!: :!: :!: !:! :!: !:! :!: !:! :!: :!: !:!
# :: ::: :::: :: :: :: ::: ::::: :: ::: :: ::::: :: :::: :: ::::: :: :: :::: :: :::: :::: ::
# : : : :: : : : : : : : : : : : : : : :: : : : : : : :: : : : :: :: :: : :
#
# © Copyright 2024
#
# https://t.me/Den4ikSuperOstryyPer4ik
# and
# https://t.me/ToXicUse
#
# 🔒 Licensed under the GNU AGPLv3
# https://www.gnu.org/licenses/agpl-3.0.html
#
# meta developer: @AstroModules
import datetime
import logging
import time
from telethon import types
from telethon.tl.functions.account import UpdateProfileRequest
from telethon.tl.functions.users import GetFullUserRequest
from .. import loader, utils
from ..inline.types import InlineCall
logger = logging.getLogger(__name__)
@loader.tds
class TxAFKMod(loader.Module):
'''Афк модуль от AstroModules с изменением био и имени'''
async def client_ready(self, client, db):
self._db = db
self._me = await client.get_me()
strings = {
"name": "TxAFK",
"lname": "| afk.",
"lname0": " ",
"bt_off_afk": "⚠️ АФК режим отключен",
"bt_on_afk": "💤 АФК режим снова активен",
"_cfg_cst_btn": "Ссылка на чат которая будет отоброжаться вместе с уведомлением. (Чтобы вообще убрать напишите None)",
"standart_bio_text": "Кастомное описание профиля",
"feedback_bot__text": "Юзер вашего фидбэк бота (если имеется)",
"button__text": "Добавить инлайн кнопку отключения АФК режима?",
"custom_text__afk_text": "Кастомный текст афк. Используй {time} для вывода последнего времени нахождения в сети",
}
def __init__(self):
self.config = loader.ModuleConfig(
loader.ConfigValue(
"feedback_bot",
"None",
doc=lambda: self.strings("feedback_bot__text"),
),
loader.ConfigValue(
"custom_text__afk",
"None",
doc=lambda: self.strings("custom_text__afk_text"),
),
loader.ConfigValue(
"standart_bio",
"None",
doc=lambda: self.strings("standart_bio_text"),
),
loader.ConfigValue(
"custom_button",
[
"🦄 AstroModules 🦄",
"https://t.me/AstroModulesChat",
],
lambda: self.strings("_cfg_cst_btn"),
validator=loader.validators.Union(
loader.validators.Series(fixed_len=2),
loader.validators.NoneType(),
),
),
loader.ConfigValue(
"ignore_chats",
[],
lambda: "Чаты, в которых при упоминании TxAFК не будет срабатывать",
validator=loader.validators.Series(
validator=loader.validators.Union(
loader.validators.TelegramID(),
loader.validators.RegExp("[0-9]"),
),
),
),
loader.ConfigValue(
"button",
True,
doc=lambda: self.strings("button__text"),
validator=loader.validators.Boolean(),
)
)
async def txcfgcmd(self, message):
"""- открыть конфиг модуля"""
await self.allmodules.commands["config"](
await utils.answer(message, f"{self.get_prefix()}config TxAFK")
)
async def goafkcmd(self, message):
"""- войти в AFK режим"""
try:
user_id = (
(
(
await self._client.get_entity(
args if not args.isdigit() else int(args)
)
).id
)
if args
else reply.sender_id
)
except Exception:
user_id = self._tg_id
user = await self._client(GetFullUserRequest(user_id))
self._db.set(__name__, "afk", True)
self._db.set(__name__, "gone", time.time())
self._db.set(__name__, "ratelimit", [])
a_afk_bio_nofb = "В афк."
lastname = self.strings("lname")
if self.config['feedback_bot'] == None:
await message.client(UpdateProfileRequest(about=a_afk_bio_nofb, last_name=lastname))
else:
a_afk_bio = 'На данный момент в АФК. Связь только через '
feedback = self.config['feedback_bot']
aaa = a_afk_bio + feedback
await message.client(UpdateProfileRequest(about=aaa))
await self.allmodules.log("goafk")
await utils.answer(message, '<emoji document_id=5215519585150706301>👍</emoji> <b>АФК режим включен!</b>')
await message.client(UpdateProfileRequest(last_name=lastname))
async def ungoafkcmd(self, message):
"""- выйти из режима AFK"""
msg = await utils.answer(message, '<emoji document_id=5213107179329953547>⏰</emoji> <b>Отключаю режим АФК...</b>')
sbio = self.config['standart_bio']
lastname0 = self.strings('lname0')
self._db.set(__name__, "afk", False)
self._db.set(__name__, "gone", None)
self._db.set(__name__, "ratelimit", [])
await self.allmodules.log("unafk")
if sbio == None:
await message.client(UpdateProfileRequest(about='', last_name=lastname0))
else:
await message.client(UpdateProfileRequest(about=sbio, last_name=lastname0))
time.sleep(1)
await utils.answer(msg, '<emoji document_id=5220108512893344933>🆘</emoji> <b>Режим AFK отключен!</b>')
def _afk_custom_text(self) -> str:
now = datetime.datetime.now().replace(microsecond=0)
gone = datetime.datetime.fromtimestamp(
self._db.get(__name__, "gone")
).replace(microsecond=0)
time = now - gone
return (
"<b> </b>\n"
+ self.config["custom_text__afk"].format(
time=time,
)
)
async def watcher(self, message):
if not isinstance(message, types.Message):
return
if utils.get_chat_id(message) in self.config['ignore_chats']:
return
if message.mentioned or getattr(message.to_id, "user_id", None) == self._me.id:
afk_state = self.get_afk()
if not afk_state:
return
logger.debug("tagged!")
ratelimit = self._db.get(__name__, "ratelimit", [])
if utils.get_chat_id(message) in ratelimit:
return
else:
self._db.setdefault(__name__, {}).setdefault("ratelimit", []).append(
utils.get_chat_id(message)
)
self._db.save()
user = await utils.get_user(message)
if user.is_self or user.bot or user.verified:
logger.debug("User is self, bot or verified.")
return
if self.get_afk() is False:
return
now = datetime.datetime.now().replace(microsecond=0)
gone = datetime.datetime.fromtimestamp(
self._db.get(__name__, "gone")
).replace(microsecond=0)
time = now - gone
if self.config['custom_button'] == None:
if self.config["button"] == False:
if self.config["custom_text__afk"] == None:
await self.inline.form(message=message, text=f"<b>🔅 Я сейчас нахожусь в АФК.</b>\n\nПоследний раз был в сети <code>{time}</code> назад.")
else:
await self.inline.form(message=message, text=self._afk_custom_text())
elif self.config['button'] == True:
if self.config["custom_text__afk"] == None:
await self.inline.form(
message=message,
text=f"<b>🔅 Я сейчас нахожусь в АФК.</b>\n\nПоследний раз был в сети <code>{time}</code> назад.",
reply_markup=[
[
{
"text": "🚫 Выйти с афк 🚫",
"callback": self.button_cancel,
}
]
]
)
else:
await self.inline.form(
message=message,
text=self._afk_custom_text(),
reply_markup=[
[
{
"text": "🚫 Выйти с афк 🚫",
"callback": self.button_cancel,
}
]
]
)
else:
if self.config["button"] == False:
if self.config["custom_text__afk"] == None:
await self.inline.form(message=message, text=f"<b>🔅 Я сейчас нахожусь в АФК.</b>\n\nПоследний раз был в сети <code>{time}</code> назад.", reply_markup=[{"text": self.config['custom_button'][0], "url": self.config['custom_button'][1]}])
else:
await self.inline.form(message=message, text=self._afk_custom_text(), reply_markup=[{"text": self.config['custom_button'][0], "url": self.config['custom_button'][1]}])
elif self.config['button'] == True:
if self.config["custom_text__afk"] == None:
await self.inline.form(
message=message,
text=f"<b>🔅 Я сейчас нахожусь в АФК.</b>\n\nПоследний раз был в сети <code>{time}</code> назад.",
reply_markup=[
[
{
"text": self.config['custom_button'][0],
"url": self.config['custom_button'][1],
}
],
[
{
"text": "🚫 Выйти с афк 🚫",
"callback": self.button_cancel,
}
]
]
)
else:
await self.inline.form(
message=message,
text=self._afk_custom_text(),
reply_markup=[
[
{
"text": self.config['custom_button'][0],
"url": self.config['custom_button'][1],
}
],
[
{
"text": "🚫 Выйти с афк 🚫",
"callback": self.button_cancel,
}
]
]
)
async def button_cancel(self, call: InlineCall):
self._db.set(__name__, "afk", False)
self._db.set(__name__, "gone", None)
self._db.set(__name__, "ratelimit", [])
await self.allmodules.log("unafk")
if self.config['standart_bio'] == None:
lastname = self.strings("lname0")
about = self.strings("lname0")
await self._client(UpdateProfileRequest(about=about, last_name=lastname))
else:
aboutt = self.config['standart_bio']
lastname = self.strings("lname0")
await self._client(UpdateProfileRequest(about=aboutt, last_name=lastname))
await call.edit(
self.strings["bt_off_afk"],
reply_markup=[
{
"text": "🔰 Войти в афк 🔰",
"callback": self.button_cancel_on,
}
]
)
async def button_cancel_on(self, call: InlineCall):
self._db.set(__name__, "afk", True)
self._db.set(__name__, "gone", time.time())
self._db.set(__name__, "ratelimit", [])
a_afk_bio_nofb = "В афк."
lastname = self.strings("lname")
if self.config['feedback_bot'] == None:
await self._client(UpdateProfileRequest(about=a_afk_bio_nofb, last_name=lastname))
else:
a_afk_bio = 'На данный момент в АФК. Связь только через '
feedback = self.config['feedback_bot']
aaa = a_afk_bio + feedback
await self._client(UpdateProfileRequest(about=aaa))
await call.edit(
self.strings["bt_on_afk"],
reply_markup=[
{
"text": "🚫 Выйти с афк 🚫",
"callback": self.button_cancel,
}
]
)
def get_afk(self):
return self._db.get(__name__, "afk", False)

View File

@@ -1,34 +1,35 @@
komarumod
RandomPasswordGenerator
gamecheat
convertio
mindtalk
dialogs_manager
inline_bot_manager
RandomTrack
iOSAppsForAndroid
video_to_voice
вахуи_пон
RandomStatuses
TwinkManager
brawl_stats
astroafk
YandexMusic
astroweather
wordly
RandomUser
summer
пон_вахуи
pcmanager
shazam
achievements
Steam
minesweeper
dl_yt_previews
TxAFK
akinator
Compliments
commands_logger
Emotions
AntiMat
demotivator
komarumod
RandomPasswordGenerator
gamecheat
convertio
mindtalk
dialogs_manager
inline_bot_manager
RandomTrack
iOSAppsForAndroid
video_to_voice
вахуи_пон
RandomStatuses
TwinkManager
brawl_stats
astroafk
YandexMusic
astroweather
wordly
RandomUser
summer
пон_вахуи
pcmanager
shazam
achievements
Steam
minesweeper
dl_yt_previews
TxAFK
akinator
Compliments
commands_logger
Emotions
AntiMat
demotivator
ymlive

View File

@@ -67,7 +67,7 @@ class PCManagerMod(loader.Module):
async def pcoff(self, message: Message):
"""- выключить компьютер"""
bot = self.config["bot_username"]
call = await self.lib.message_g('🛑 Shutdown',
call = await self.lib.message_g('/off',
bot,
mark_read=True,
delete=True
@@ -78,7 +78,7 @@ class PCManagerMod(loader.Module):
async def pcreboot(self, message: Message):
"""- перезагрузить компьютер"""
bot = self.config["bot_username"]
call = await self.lib.message_g('🔄 Reboot',
call = await self.lib.message_g('/reboot',
bot,
mark_read=True,
delete=True
@@ -89,7 +89,7 @@ class PCManagerMod(loader.Module):
async def pcinfo(self, message: Message):
"""- просмотреть характеристики системы"""
bot = self.config["bot_username"]
call = await self.lib.message_q('💻 System Info',
call = await self.lib.message_q('/info',
bot,
mark_read=True,
delete=True
@@ -100,7 +100,7 @@ class PCManagerMod(loader.Module):
async def pcip(self, message: Message):
"""- просмотреть информацию об айпи адресе"""
bot = self.config["bot_username"]
call = await self.lib.message_q('🌐 IP Info',
call = await self.lib.message_q('/ip',
bot,
mark_read=True,
delete=True
@@ -108,10 +108,10 @@ class PCManagerMod(loader.Module):
await utils.answer(message, f'<emoji document_id=5787544344906959608></emoji> <b>[PC_Manager]</b> <emoji document_id=5787544344906959608></emoji>\n\n{call.text}')
@loader.command()
async def pcscrin(self, message: Message):
async def pcscreen(self, message: Message):
"""- сделать скриншот экрана"""
bot = self.config['bot_username']
call = await self.lib.message_g('/screenshot',
call = await self.lib.message_q('/screenshot',
bot,
mark_read=True,
delete=True
@@ -121,29 +121,19 @@ class PCManagerMod(loader.Module):
@loader.command()
async def pcweb(self, message: Message):
"""<ссылка> - открыть ссылку в браузере"""
"""<ссылка> - открыть ссылку в браузере
🔑 Дополнительно:"""
bot = self.config['bot_username']
args = utils.get_args_raw(message)
call = await self.lib.message_q(f'/browse {args}',
call = await self.lib.message_q(f'/web {args}',
bot,
mark_read=True,
delete=True
)
await utils.answer(message, f'<emoji document_id=5787544344906959608></emoji> <b>[PC_Manager]</b> <emoji document_id=5787544344906959608></emoji>\n\n{call.text}\n\nСсылка: {args}')
@loader.command()
async def pcwebscrin(self, message: Message):
"""- сделать снимок с веб-камеры
🔑 Дополнительно:"""
bot = self.config['bot_username']
call = await self.lib.message_g('/photo',
bot,
mark_read=True,
delete=True
)
await utils.answer(message, '<emoji document_id=5787544344906959608></emoji> <b>[PC_Manager]</b> <emoji document_id=5787544344906959608></emoji>\n\nОтправка снимка...')
await message.respond(call)
@loader.command()
async def pcalert(self, message: Message):
@@ -217,20 +207,15 @@ class PCManagerMod(loader.Module):
],
[
{
"text": "⬆️",
"text": "0%",
"callback": self.set_volume,
"args": ("up",)
},
"args": (0,)
},
{
"text": "100%",
"callback": self.set_volume,
"args": (100,)
},
{
"text": "⬇️",
"callback": self.set_volume,
"args": ("down",)
},
],
[
{
@@ -288,4 +273,4 @@ class PCManagerMod(loader.Module):
await self.client.send_message(f'{bot}', '/key__next')
return await call.answer("Успешно!", show_alert=False)
# Tx...
# Tx...

View File

@@ -1,87 +1,87 @@
__version__ = (1, 0, 0)
#
# @@@@@@ @@@@@@ @@@@@@@ @@@@@@@ @@@@@@ @@@@@@@@@@ @@@@@@ @@@@@@@ @@@ @@@ @@@ @@@@@@@@ @@@@@@
# @@@@@@@@ @@@@@@@ @@@@@@@ @@@@@@@@ @@@@@@@@ @@@@@@@@@@@ @@@@@@@@ @@@@@@@@ @@@ @@@ @@@ @@@@@@@@ @@@@@@@
# @@! @@@ !@@ @@! @@! @@@ @@! @@@ @@! @@! @@! @@! @@@ @@! @@@ @@! @@@ @@! @@! !@@
# !@! @!@ !@! !@! !@! @!@ !@! @!@ !@! !@! !@! !@! @!@ !@! @!@ !@! @!@ !@! !@! !@!
# @!@!@!@! !!@@!! @!! @!@!!@! @!@ !@! @!! !!@ @!@ @!@ !@! @!@ !@! @!@ !@! @!! @!!!:! !!@@!!
# !!!@!!!! !!@!!! !!! !!@!@! !@! !!! !@! ! !@! !@! !!! !@! !!! !@! !!! !!! !!!!!: !!@!!!
# !!: !!! !:! !!: !!: :!! !!: !!! !!: !!: !!: !!! !!: !!! !!: !!! !!: !!: !:!
# :!: !:! !:! :!: :!: !:! :!: !:! :!: :!: :!: !:! :!: !:! :!: !:! :!: :!: !:!
# :: ::: :::: :: :: :: ::: ::::: :: ::: :: ::::: :: :::: :: ::::: :: :: :::: :: :::: :::: ::
# : : : :: : : : : : : : : : : : : : : :: : : : : : : :: : : : :: :: :: : :
#
# © Copyright 2024
#
# https://t.me/Den4ikSuperOstryyPer4ik
# and
# https://t.me/ToXicUse
#
# 🔒 Licensed under the GNU AGPLv3
# https://www.gnu.org/licenses/agpl-3.0.html
#
# meta developer: @AstroModules
# meta banner: https://raw.githubusercontent.com/Den4ikSuperOstryyPer4ik/Astro-modules/main/Banners/AstroShazam.png
# The code snippet is adapted from VoiceMod code by D4n1l3k300
# requires: ShazamAPI
import io
from ShazamAPI import Shazam
from .. import loader, utils
@loader.tds
class ShazamMod(loader.Module):
"""Use <reply to voice> to search for a song using audio."""
strings = {
"name": 'Shazam',
"Downloading": "<emoji document_id=5443127283898405358>📥</emoji> <b>Downloading...</b>",
"Searching": "<emoji document_id=5447410659077661506>🔎</emoji> <b>Searching...</b>",
"no_reply": "<emoji document_id=5294339927318739359>🎙</emoji> <b>Please reply to an audio message.</b>",
"not_found": "<emoji document_id=5210952531676504517>🚫</emoji> <b>Song not found.</b>",
"track_info": (
"<emoji document_id=5325547803936572038>✨</emoji> <b>Song found</b>\n"
'<emoji document_id=5460795800101594035>📝</emoji> <b>Name</b> "<code>{}</code>"'
)
}
strings_ru = {
"Downloading": "<emoji document_id=5443127283898405358>📥</emoji> <b>Загрузка..</b>",
"Searching": "<emoji document_id=5447410659077661506>🔎</emoji> <b>Поиск..</b>",
"no_reply": "<emoji document_id=5294339927318739359>🎙</emoji> <b>Oтветьте на аудио сообщение</b>",
"not_found": "<emoji document_id=5210952531676504517>🚫</emoji> <b>Не удалось найти песню</b>",
"track_info": (
"<emoji document_id=5325547803936572038>✨</emoji> <b>Песня найдена</b>\n"
'<emoji document_id=5460795800101594035>📝</emoji> <b>Название:</b> "<code>{}</code>"'
)
}
async def fetch_audio(self, message):
reply = await message.get_reply_message()
if reply and reply.file and reply.file.mime_type.startswith("audio"):
await utils.answer(message, self.strings['Downloading'])
audio_data = io.BytesIO(await reply.download_media(bytes))
await utils.answer(message, self.strings['Searching'])
return audio_data, reply
await utils.answer(message, self.strings['no_reply'])
return None, None
@loader.command(ru_doc='<reply to audio> - распознать трек')
async def sh(self, message):
"""<reply to audio> - recognize track"""
audio_data, reply = await self.fetch_audio(message)
if not audio_data:
return
try:
shazam = Shazam(audio_data.read())
recog = next(shazam.recognizeSong())[1]["track"]
await self.client.send_file(
message.peer_id,
file=recog["images"]["background"],
caption=self.strings['track_info'].format(recog["share"]["subject"]),
reply_to=reply.id,
)
await message.delete()
except Exception:
await utils.answer(message, self.strings['not_found'])
__version__ = (1, 0, 0)
#
# @@@@@@ @@@@@@ @@@@@@@ @@@@@@@ @@@@@@ @@@@@@@@@@ @@@@@@ @@@@@@@ @@@ @@@ @@@ @@@@@@@@ @@@@@@
# @@@@@@@@ @@@@@@@ @@@@@@@ @@@@@@@@ @@@@@@@@ @@@@@@@@@@@ @@@@@@@@ @@@@@@@@ @@@ @@@ @@@ @@@@@@@@ @@@@@@@
# @@! @@@ !@@ @@! @@! @@@ @@! @@@ @@! @@! @@! @@! @@@ @@! @@@ @@! @@@ @@! @@! !@@
# !@! @!@ !@! !@! !@! @!@ !@! @!@ !@! !@! !@! !@! @!@ !@! @!@ !@! @!@ !@! !@! !@!
# @!@!@!@! !!@@!! @!! @!@!!@! @!@ !@! @!! !!@ @!@ @!@ !@! @!@ !@! @!@ !@! @!! @!!!:! !!@@!!
# !!!@!!!! !!@!!! !!! !!@!@! !@! !!! !@! ! !@! !@! !!! !@! !!! !@! !!! !!! !!!!!: !!@!!!
# !!: !!! !:! !!: !!: :!! !!: !!! !!: !!: !!: !!! !!: !!! !!: !!! !!: !!: !:!
# :!: !:! !:! :!: :!: !:! :!: !:! :!: :!: :!: !:! :!: !:! :!: !:! :!: :!: !:!
# :: ::: :::: :: :: :: ::: ::::: :: ::: :: ::::: :: :::: :: ::::: :: :: :::: :: :::: :::: ::
# : : : :: : : : : : : : : : : : : : : :: : : : : : : :: : : : :: :: :: : :
#
# © Copyright 2024
#
# https://t.me/Den4ikSuperOstryyPer4ik
# and
# https://t.me/ToXicUse
#
# 🔒 Licensed under the GNU AGPLv3
# https://www.gnu.org/licenses/agpl-3.0.html
#
# meta developer: @AstroModules
# meta banner: https://raw.githubusercontent.com/Den4ikSuperOstryyPer4ik/Astro-modules/main/Banners/AstroShazam.png
# The code snippet is adapted from VoiceMod code by D4n1l3k300
# requires: ShazamAPI
import io
from ShazamAPI import Shazam
from .. import loader, utils
@loader.tds
class ShazamMod(loader.Module):
"""Use <reply to voice> to search for a song using audio."""
strings = {
"name": 'Shazam',
"Downloading": "<emoji document_id=5443127283898405358>📥</emoji> <b>Downloading...</b>",
"Searching": "<emoji document_id=5447410659077661506>🔎</emoji> <b>Searching...</b>",
"no_reply": "<emoji document_id=5294339927318739359>🎙</emoji> <b>Please reply to an audio message.</b>",
"not_found": "<emoji document_id=5210952531676504517>🚫</emoji> <b>Song not found.</b>",
"track_info": (
"<emoji document_id=5325547803936572038>✨</emoji> <b>Song found</b>\n"
'<emoji document_id=5460795800101594035>📝</emoji> <b>Name</b> "<code>{}</code>"'
)
}
strings_ru = {
"Downloading": "<emoji document_id=5443127283898405358>📥</emoji> <b>Загрузка..</b>",
"Searching": "<emoji document_id=5447410659077661506>🔎</emoji> <b>Поиск..</b>",
"no_reply": "<emoji document_id=5294339927318739359>🎙</emoji> <b>Oтветьте на аудио сообщение</b>",
"not_found": "<emoji document_id=5210952531676504517>🚫</emoji> <b>Не удалось найти песню</b>",
"track_info": (
"<emoji document_id=5325547803936572038>✨</emoji> <b>Песня найдена</b>\n"
'<emoji document_id=5460795800101594035>📝</emoji> <b>Название:</b> "<code>{}</code>"'
)
}
async def fetch_audio(self, message):
reply = await message.get_reply_message()
if reply and reply.file and reply.file.mime_type.startswith("audio"):
await utils.answer(message, self.strings['Downloading'])
audio_data = io.BytesIO(await reply.download_media(bytes))
await utils.answer(message, self.strings['Searching'])
return audio_data, reply
await utils.answer(message, self.strings['no_reply'])
return None, None
@loader.command(ru_doc='<reply to audio> - распознать трек')
async def sh(self, message):
"""<reply to audio> - recognize track"""
audio_data, reply = await self.fetch_audio(message)
if not audio_data:
return
try:
shazam = Shazam(audio_data.read())
recog = next(shazam.recognizeSong())[1]["track"]
await self.client.send_file(
message.peer_id,
file=recog["images"]["background"],
caption=self.strings['track_info'].format(recog["share"]["subject"]),
reply_to=reply.id,
)
await message.delete()
except Exception:
await utils.answer(message, self.strings['not_found'])

View File

@@ -1,85 +1,85 @@
#
#█▀▄ ▀█ █ █▀█ █░█  █▀▀ ▄▀█ █▄█
#█▄▀ █▄ █ █▀▄ █▄█  █▄█ █▀█ ░█░
# 🔒 Licensed under the GNU AGPLv3
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
#
# meta developer: @dziru
# meta pic: https://raw.githubusercontent.com/DziruModules/assets/master/DziruModules.jpg
# meta banner: https://raw.githubusercontent.com/DziruModules/assets/master/AutoComment.png
# scope: hikka_only
# coded by: @dziru && @penggrin
from .. import loader, utils
import logging
logger = logging.getLogger(__name__)
@loader.tds
class AutoCommentMod(loader.Module):
"""Automatically comments under any channels you want"""
strings = {
"name": "AutoComment",
"disabled": "❌ Disabled",
"enabled": "✅ Enabled",
"status_now": "👌 AutoComment was <b>{}</b>!",
"config_status": "Are we ready to comment?",
"config_channels": "Under which channels i should comment? (ids)",
"config_message": "What i will comment?",
}
strings_ru = {
"disabled": "❌ Выключен",
"enabled": "✅ Включён",
"status_now": "👌 AutoComment теперь <b>{}</b>!",
"config_status": "Комментим ли мы?",
"config_channels": "Под каким каналами я должен комментировать (айди)",
"config_message": "Как я прокомментирую?",
}
def __init__(self):
self.config = loader.ModuleConfig(
loader.ConfigValue(
"status",
True,
lambda: self.strings("config_status"),
validator=loader.validators.Boolean()
),
loader.ConfigValue(
"message",
"I'm the first! 😎",
lambda: self.strings("config_message"),
validator=loader.validators.String()
),
loader.ConfigValue(
"channels",
[],
lambda: self.strings("config_channels"),
validator=loader.validators.Series(
loader.validators.Union(
loader.validators.Integer(),
)
)
),
)
@loader.watcher(only_messages=True, only_channels=True)
async def watcher(self, message):
if not self.config["status"]:
return
chat = utils.get_chat_id(message)
if chat not in self.config["channels"]:
return
await self.client.send_message(entity=chat, message=self.config["message"], comment_to=message)
logger.debug(f"commented on {message.id} in {chat}")
async def commentcmd(self, message):
"""Toggle Module <on/off>"""
self.config["status"] = not self.config["status"]
status = self.strings("enabled") if self.config["status"] else self.strings("disabled")
await utils.answer(message, self.strings("status_now").format(status))
#
#█▀▄ ▀█ █ █▀█ █░█  █▀▀ ▄▀█ █▄█
#█▄▀ █▄ █ █▀▄ █▄█  █▄█ █▀█ ░█░
# 🔒 Licensed under the GNU AGPLv3
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
#
# meta developer: @dziru
# meta pic: https://raw.githubusercontent.com/DziruModules/assets/master/DziruModules.jpg
# meta banner: https://raw.githubusercontent.com/DziruModules/assets/master/AutoComment.png
# scope: hikka_only
# coded by: @dziru && @penggrin
from .. import loader, utils
import logging
logger = logging.getLogger(__name__)
@loader.tds
class AutoCommentMod(loader.Module):
"""Automatically comments under any channels you want"""
strings = {
"name": "AutoComment",
"disabled": "❌ Disabled",
"enabled": "✅ Enabled",
"status_now": "👌 AutoComment was <b>{}</b>!",
"config_status": "Are we ready to comment?",
"config_channels": "Under which channels i should comment? (ids)",
"config_message": "What i will comment?",
}
strings_ru = {
"disabled": "❌ Выключен",
"enabled": "✅ Включён",
"status_now": "👌 AutoComment теперь <b>{}</b>!",
"config_status": "Комментим ли мы?",
"config_channels": "Под каким каналами я должен комментировать (айди)",
"config_message": "Как я прокомментирую?",
}
def __init__(self):
self.config = loader.ModuleConfig(
loader.ConfigValue(
"status",
True,
lambda: self.strings("config_status"),
validator=loader.validators.Boolean()
),
loader.ConfigValue(
"message",
"I'm the first! 😎",
lambda: self.strings("config_message"),
validator=loader.validators.String()
),
loader.ConfigValue(
"channels",
[],
lambda: self.strings("config_channels"),
validator=loader.validators.Series(
loader.validators.Union(
loader.validators.Integer(),
)
)
),
)
@loader.watcher(only_messages=True, only_channels=True)
async def watcher(self, message):
if not self.config["status"]:
return
chat = utils.get_chat_id(message)
if chat not in self.config["channels"]:
return
await self.client.send_message(entity=chat, message=self.config["message"], comment_to=message)
logger.debug(f"commented on {message.id} in {chat}")
async def commentcmd(self, message):
"""Toggle Module <on/off>"""
self.config["status"] = not self.config["status"]
status = self.strings("enabled") if self.config["status"] else self.strings("disabled")
await utils.answer(message, self.strings("status_now").format(status))

View File

@@ -1,40 +1,40 @@
#
#█▀▄ ▀█ █ █▀█ █░█  █▀▀ ▄▀█ █▄█
#█▄▀ █▄ █ █▀▄ █▄█  █▄█ █▀█ ░█░
# 🔒 Licensed under the GNU AGPLv3
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
# meta developer: @dziru
# meta pic: https://raw.githubusercontent.com/DziruModules/assets/master/DziruModules.jpg
# meta banner: https://raw.githubusercontent.com/DziruModules/assets/master/GitInfo.png
# scope: hikka_only
# version: 1.0
import requests
from .. import utils, loader
class GitInfoMod(loader.Module):
"""Get Github user info, simply type username"""
strings = {
"name": "GitInfo",
}
async def gitinfocmd(self, message):
"""<username>"""
args = utils.get_args_raw(message)
gitapi = "https://api.github.com/users/{}".format(args)
s = requests.get(gitapi)
if s.status_code != 404:
b = s.json()
avatar_url = b["avatar_url"]
html_url = b["html_url"]
name = b["name"]
blog = b["blog"]
location = b["location"]
bio = b["bio"]
created_at = b["created_at"]
await self._client.send_file(message.chat_id, caption="<emoji document_id=5974038293120027938>👤</emoji> <b>Name: </b><code>{}</code>\n<emoji document_id=5974492756494519709>🔗</emoji> <b>Link: </b><code>{}</code>\n\n<emoji document_id=5972183258090179945>💬</emoji> <b>Blog: </b><code>{}</code>\n<emoji document_id=5979027086612892618>📍</emoji> <b>Location: </b><code>{}</code>\n\n<emoji document_id=5972158252790582632>🗒</emoji> <b>Bio: </b><code>{}</code>\n<emoji document_id=6039550820855319523>🔎</emoji> <b>Profile Created: </b><code>{}</code>".format(name, html_url, blog, location, bio, created_at), file=avatar_url, force_document=False, allow_cache=False, reply_to=message)
await message.delete()
else:
await message.edit("<emoji document_id=5974097404754922968>🚫</emoji> <b>Username </b><code> {} </code><b>is not available</b>".format(args, s.text))
#
#█▀▄ ▀█ █ █▀█ █░█  █▀▀ ▄▀█ █▄█
#█▄▀ █▄ █ █▀▄ █▄█  █▄█ █▀█ ░█░
# 🔒 Licensed under the GNU AGPLv3
# 🌐 https://www.gnu.org/licenses/agpl-3.0.html
# meta developer: @dziru
# meta pic: https://raw.githubusercontent.com/DziruModules/assets/master/DziruModules.jpg
# meta banner: https://raw.githubusercontent.com/DziruModules/assets/master/GitInfo.png
# scope: hikka_only
# version: 1.0
import requests
from .. import utils, loader
class GitInfoMod(loader.Module):
"""Get Github user info, simply type username"""
strings = {
"name": "GitInfo",
}
async def gitinfocmd(self, message):
"""<username>"""
args = utils.get_args_raw(message)
gitapi = "https://api.github.com/users/{}".format(args)
s = requests.get(gitapi)
if s.status_code != 404:
b = s.json()
avatar_url = b["avatar_url"]
html_url = b["html_url"]
name = b["name"]
blog = b["blog"]
location = b["location"]
bio = b["bio"]
created_at = b["created_at"]
await self._client.send_file(message.chat_id, caption="<emoji document_id=5974038293120027938>👤</emoji> <b>Name: </b><code>{}</code>\n<emoji document_id=5974492756494519709>🔗</emoji> <b>Link: </b><code>{}</code>\n\n<emoji document_id=5972183258090179945>💬</emoji> <b>Blog: </b><code>{}</code>\n<emoji document_id=5979027086612892618>📍</emoji> <b>Location: </b><code>{}</code>\n\n<emoji document_id=5972158252790582632>🗒</emoji> <b>Bio: </b><code>{}</code>\n<emoji document_id=6039550820855319523>🔎</emoji> <b>Profile Created: </b><code>{}</code>".format(name, html_url, blog, location, bio, created_at), file=avatar_url, force_document=False, allow_cache=False, reply_to=message)
await message.delete()
else:
await message.edit("<emoji document_id=5974097404754922968>🚫</emoji> <b>Username </b><code> {} </code><b>is not available</b>".format(args, s.text))

View File

@@ -1,68 +1,68 @@
from pydub import AudioSegment
from .. import loader, utils
import io
import os
def register(cb):
cb(AudioShakalMod())
class AudioShakalMod(loader.Module):
"""АудиоШакал"""
strings = {'name': 'АудиоШакал'}
def __init__(self):
self.name = self.strings['name']
self._me = None
self._ratelimit = []
async def client_ready(self, client, db):
self._db = db
self._client = client
self.me = await client.get_me()
async def fvcmd(self, message):
"""<b>.fv <reply to voice/mp3/ogg/oga> [шакал_lvl(не обязательно, по умолчанию 100 (от 10 до 100))]
Сшакалить войс/mp3/ogg/oga</b>
"""
reply = await message.get_reply_message()
lvl = 0
if not reply:
await message.edit("<b>Ответь на аудио стоны, еблан</b>")
return
if utils.get_args_raw(message):
ar = utils.get_args_raw(message)
try:
int(ar)
if int(ar) >= 10 and int(ar) <= 100:
lvl = int(ar)
else:
await message.edit("<b>Укажите уровень долбоебизма от 10 до 100!</b>")
return
except Exception as exx:
await message.edit("<b>Неверный аргумент(ты уебок кста)!</b>")
return
else:
lvl = 100
await message.edit("<b>Ебем Стасяна... (прости Стасян)</b>\n Прощаю (с) Стасян")
sa = False
m = io.BytesIO()
fname = await message.client.download_media(message=reply.media)
if(fname.endswith(".oga") or fname.endswith(".ogg")):
audio = AudioSegment.from_file(fname, "ogg")
elif(fname.endswith(".mp3")):
sa = True
audio = AudioSegment.from_file(fname, "mp3")
else:
await message.edit("<b>Ты еблан? Я(.fv) не поддерживаю этот ёбаный файл! Только voice/mp3/ogg/oga!</b>")
os.remove(fname)
return
audio = audio + lvl
if(sa):
m.name = "Ты Шакал.mp3"
audio.export(m, format="mp3")
else:
m.name="voice.ogg"
audio.split_to_mono()
audio.export(m, format="ogg", codec="libopus", bitrate="64k")
m.seek(0)
if(sa):
await message.client.send_file(message.to_id, m, reply_to=reply.id)
else:
await message.client.send_file(message.to_id, m, reply_to=reply.id, voice_note=True)
await message.delete()
os.remove(fname)
from pydub import AudioSegment
from .. import loader, utils
import io
import os
def register(cb):
cb(AudioShakalMod())
class AudioShakalMod(loader.Module):
"""АудиоШакал"""
strings = {'name': 'АудиоШакал'}
def __init__(self):
self.name = self.strings['name']
self._me = None
self._ratelimit = []
async def client_ready(self, client, db):
self._db = db
self._client = client
self.me = await client.get_me()
async def fvcmd(self, message):
"""<b>.fv <reply to voice/mp3/ogg/oga> [шакал_lvl(не обязательно, по умолчанию 100 (от 10 до 100))]
Сшакалить войс/mp3/ogg/oga</b>
"""
reply = await message.get_reply_message()
lvl = 0
if not reply:
await message.edit("<b>Ответь на аудио стоны, еблан</b>")
return
if utils.get_args_raw(message):
ar = utils.get_args_raw(message)
try:
int(ar)
if int(ar) >= 10 and int(ar) <= 100:
lvl = int(ar)
else:
await message.edit("<b>Укажите уровень долбоебизма от 10 до 100!</b>")
return
except Exception as exx:
await message.edit("<b>Неверный аргумент(ты уебок кста)!</b>")
return
else:
lvl = 100
await message.edit("<b>Ебем Стасяна... (прости Стасян)</b>\n Прощаю (с) Стасян")
sa = False
m = io.BytesIO()
fname = await message.client.download_media(message=reply.media)
if(fname.endswith(".oga") or fname.endswith(".ogg")):
audio = AudioSegment.from_file(fname, "ogg")
elif(fname.endswith(".mp3")):
sa = True
audio = AudioSegment.from_file(fname, "mp3")
else:
await message.edit("<b>Ты еблан? Я(.fv) не поддерживаю этот ёбаный файл! Только voice/mp3/ogg/oga!</b>")
os.remove(fname)
return
audio = audio + lvl
if(sa):
m.name = "Ты Шакал.mp3"
audio.export(m, format="mp3")
else:
m.name="voice.ogg"
audio.split_to_mono()
audio.export(m, format="ogg", codec="libopus", bitrate="64k")
m.seek(0)
if(sa):
await message.client.send_file(message.to_id, m, reply_to=reply.id)
else:
await message.client.send_file(message.to_id, m, reply_to=reply.id, voice_note=True)
await message.delete()
os.remove(fname)

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,22 +1,22 @@
from .. import loader, utils
import calendar
from datetime import date
def register(cb):
cb(CalendarMod())
class CalendarMod(loader.Module):
"""Календарь"""
strings = {"name": "Calendar"}
async def clndcmd(self, event):
""".clnd <год> <месяц> или ничего"""
args = utils.get_args(event)
y, m, d = [int(i) for i in str(date.today()).split("-")]
year = int(args[0]) if args and args[0].isdigit() else y
month = int(args[1]) if len(args) == 2 and args[1].isdigit() and int(args[1]) in range(1, 13) else m
calen = calendar.month(year, month)
if year == y and month == m:
calen = calen.replace(str(d), f'</code><strong>{d}</strong><code>')
from .. import loader, utils
import calendar
from datetime import date
def register(cb):
cb(CalendarMod())
class CalendarMod(loader.Module):
"""Календарь"""
strings = {"name": "Calendar"}
async def clndcmd(self, event):
""".clnd <год> <месяц> или ничего"""
args = utils.get_args(event)
y, m, d = [int(i) for i in str(date.today()).split("-")]
year = int(args[0]) if args and args[0].isdigit() else y
month = int(args[1]) if len(args) == 2 and args[1].isdigit() and int(args[1]) in range(1, 13) else m
calen = calendar.month(year, month)
if year == y and month == m:
calen = calen.replace(str(d), f'</code><strong>{d}</strong><code>')
await event.edit(f"<code>\u2060{calen}</code>")

View File

@@ -1,14 +1,14 @@
from .. import loader
def register(cb):
cb(DontWorkMod())
class DontWorkMod(loader.Module):
"""Модуль не работает."""
strings = {'name': 'Don`t Work'}
async def dontworkcmd(self, message):
"""Используй .dontwork, чтобы понять, что модуль не работает."""
dontwork = '<b>Модуль не работает.</b>'
from .. import loader
def register(cb):
cb(DontWorkMod())
class DontWorkMod(loader.Module):
"""Модуль не работает."""
strings = {'name': 'Don`t Work'}
async def dontworkcmd(self, message):
"""Используй .dontwork, чтобы понять, что модуль не работает."""
dontwork = '<b>Модуль не работает.</b>'
await message.edit(dontwork)

View File

@@ -1,38 +1,38 @@
from .. import loader, utils
from random import choice, randint
from asyncio import sleep
def register(cb):
cb(FakeActionsMod())
class FakeActionsMod(loader.Module):
"""Показывает фейковые действия."""
strings = {'name': 'Fake Actions'}
async def fakecmd(self, event):
"""Использование: .fake <действие>.\nСписок действий: typing, contact, game, location, record-audio, record-round, record-video, voice, round, video, photo, document.\nОтмена: .fake cancel"""
options = ['typing', 'contact', 'game', 'location', 'record-audio', 'record-round',
'record-video', 'voice', 'round', 'video', 'photo', 'document', 'cancel']
args = utils.get_args_raw(event).split()
if len(args) == 0:
fake_action = choice(options)
fake_time = randint(30, 60)
elif len(args) == 1:
try:
fake_action = str(args[0]).lower()
fake_time = randint(30, 60)
except ValueError:
fake_action = choice(options)
fake_time = int(args[0])
elif len(args) == 2:
fake_action = str(args[0]).lower()
fake_time = int(args[1])
else:
return await event.edit('Неправильный ввод.')
try:
await event.delete()
async with event.client.action(event.chat_id, fake_action):
await sleep(fake_time)
except BaseException:
from .. import loader, utils
from random import choice, randint
from asyncio import sleep
def register(cb):
cb(FakeActionsMod())
class FakeActionsMod(loader.Module):
"""Показывает фейковые действия."""
strings = {'name': 'Fake Actions'}
async def fakecmd(self, event):
"""Использование: .fake <действие>.\nСписок действий: typing, contact, game, location, record-audio, record-round, record-video, voice, round, video, photo, document.\nОтмена: .fake cancel"""
options = ['typing', 'contact', 'game', 'location', 'record-audio', 'record-round',
'record-video', 'voice', 'round', 'video', 'photo', 'document', 'cancel']
args = utils.get_args_raw(event).split()
if len(args) == 0:
fake_action = choice(options)
fake_time = randint(30, 60)
elif len(args) == 1:
try:
fake_action = str(args[0]).lower()
fake_time = randint(30, 60)
except ValueError:
fake_action = choice(options)
fake_time = int(args[0])
elif len(args) == 2:
fake_action = str(args[0]).lower()
fake_time = int(args[1])
else:
return await event.edit('Неправильный ввод.')
try:
await event.delete()
async with event.client.action(event.chat_id, fake_action):
await sleep(fake_time)
except BaseException:
return

View File

@@ -1,113 +1,113 @@
# requires: pillow, pymorphy2
import logging
from .. import loader, utils
import telethon
import requests
from PIL import Image, ImageFont, ImageDraw
import pymorphy2
import io
from io import BytesIO
import random
logger = logging.getLogger(__name__)
def register(cb):
cb(FamilyMod())
@loader.tds
class FamilyMod(loader.Module):
"""Quote a message"""
strings = {"name": "Family"}
async def client_ready(self, client, db):
self.client = message.client
@loader.unrestricted
@loader.ratelimit
async def familycmd(self, message):
args = utils.get_args_raw(message)
reply = await message.get_reply_message()
if not reply:
await utils.answer(message, '<b>Нет Реплая.</b>')
return
if not args:
await utils.answer(message, '<b>Нет Текста.</b>')
return
pic = await check_media(message, reply)
if not pic:
await utils.answer(message, '<b>Нет Изображения.</b>')
return
await message.edit("Семья")
font = requests.get("https://github.com/KeyZenD/l/blob/master/bold.ttf?raw=true").content
family = makeFamily(pic, args, font)
await message.client.send_file(message.to_id, family, reply_to=reply)
await message.delete()
def place(background, image, cords, size):
overlay = Image.open(BytesIO(image))
overlay = overlay.resize((random.randint(size, size * 2), random.randint(size, size * 2)))
background.paste(overlay, cords)
def placeText(background , cords, size, text, font):
text_cords = (cords[0]+random.randint(0, size//2), cords[1]+random.randint(0, size//2))
draw = ImageDraw.Draw(background)
draw.text(text_cords, text, (0,0,0), font=ImageFont.truetype(io.BytesIO(font), random.randint(size // 8, size // 4)))
def makeFamily(image, caption, font):
morph = pymorphy2.MorphAnalyzer()
infl = morph.parse(caption)[0].inflect({'plur', 'gent'})
if not infl:
caption_mlt = caption
else:
caption_mlt = infl.word
canvas = Image.new('RGBA', (600, 600), "white")
draw = ImageDraw.Draw(canvas)
draw.text((120, 5), 'ахах семья ' + caption_mlt, (0,0,0), font=ImageFont.truetype(io.BytesIO(font), 32))
family = [
{ 'name': 'мама', 'cords': (60, 100), 'size': 160 },
{ 'name': 'папа', 'cords': (260, 80), 'size': 180 },
{ 'name': 'сын', 'cords': (60, 380), 'size': 125 },
{ 'name': 'дочь', 'cords': (230, 320), 'size': 125 },
{ 'name': 'дочь', 'cords': (225, 380), 'size': 125 },
{ 'name': 'сын', 'cords': (340, 390), 'size': 125 },
]
for member in family:
place(canvas, image, member['cords'], member['size'])
for member in family:
placeText(canvas, member['cords'], member['size'], member['name'] + ' ' + caption, font)
temp = BytesIO()
canvas.save(temp, format="png")
return temp.getvalue()
async def check_media(message, reply):
if reply and reply.media:
if reply.photo:
data = reply.photo
elif reply.document:
if reply.gif or reply.video or reply.audio or reply.voice:
return None
data = reply.media.document
else:
return None
else:
return None
if not data or data is None:
return None
else:
data = await message.client.download_file(data, bytes)
try:
Image.open(io.BytesIO(data))
return data
except:
return None
# requires: pillow, pymorphy2
import logging
from .. import loader, utils
import telethon
import requests
from PIL import Image, ImageFont, ImageDraw
import pymorphy2
import io
from io import BytesIO
import random
logger = logging.getLogger(__name__)
def register(cb):
cb(FamilyMod())
@loader.tds
class FamilyMod(loader.Module):
"""Quote a message"""
strings = {"name": "Family"}
async def client_ready(self, client, db):
self.client = message.client
@loader.unrestricted
@loader.ratelimit
async def familycmd(self, message):
args = utils.get_args_raw(message)
reply = await message.get_reply_message()
if not reply:
await utils.answer(message, '<b>Нет Реплая.</b>')
return
if not args:
await utils.answer(message, '<b>Нет Текста.</b>')
return
pic = await check_media(message, reply)
if not pic:
await utils.answer(message, '<b>Нет Изображения.</b>')
return
await message.edit("Семья")
font = requests.get("https://github.com/KeyZenD/l/blob/master/bold.ttf?raw=true").content
family = makeFamily(pic, args, font)
await message.client.send_file(message.to_id, family, reply_to=reply)
await message.delete()
def place(background, image, cords, size):
overlay = Image.open(BytesIO(image))
overlay = overlay.resize((random.randint(size, size * 2), random.randint(size, size * 2)))
background.paste(overlay, cords)
def placeText(background , cords, size, text, font):
text_cords = (cords[0]+random.randint(0, size//2), cords[1]+random.randint(0, size//2))
draw = ImageDraw.Draw(background)
draw.text(text_cords, text, (0,0,0), font=ImageFont.truetype(io.BytesIO(font), random.randint(size // 8, size // 4)))
def makeFamily(image, caption, font):
morph = pymorphy2.MorphAnalyzer()
infl = morph.parse(caption)[0].inflect({'plur', 'gent'})
if not infl:
caption_mlt = caption
else:
caption_mlt = infl.word
canvas = Image.new('RGBA', (600, 600), "white")
draw = ImageDraw.Draw(canvas)
draw.text((120, 5), 'ахах семья ' + caption_mlt, (0,0,0), font=ImageFont.truetype(io.BytesIO(font), 32))
family = [
{ 'name': 'мама', 'cords': (60, 100), 'size': 160 },
{ 'name': 'папа', 'cords': (260, 80), 'size': 180 },
{ 'name': 'сын', 'cords': (60, 380), 'size': 125 },
{ 'name': 'дочь', 'cords': (230, 320), 'size': 125 },
{ 'name': 'дочь', 'cords': (225, 380), 'size': 125 },
{ 'name': 'сын', 'cords': (340, 390), 'size': 125 },
]
for member in family:
place(canvas, image, member['cords'], member['size'])
for member in family:
placeText(canvas, member['cords'], member['size'], member['name'] + ' ' + caption, font)
temp = BytesIO()
canvas.save(temp, format="png")
return temp.getvalue()
async def check_media(message, reply):
if reply and reply.media:
if reply.photo:
data = reply.photo
elif reply.document:
if reply.gif or reply.video or reply.audio or reply.voice:
return None
data = reply.media.document
else:
return None
else:
return None
if not data or data is None:
return None
else:
data = await message.client.download_file(data, bytes)
try:
Image.open(io.BytesIO(data))
return data
except:
return None

View File

@@ -1,33 +1,33 @@
from .. import loader, utils
from telethon import events
from telethon.errors.rpcerrorlist import YouBlockedUserError
def register(cb):
cb(OmonBotMod())
class OmonBotMod(loader.Module):
"""Омон бот."""
strings = {'name': 'FreeOmonBot'}
async def omoncmd(self, message):
"""Используй .omon <реплай на пикчу>."""
chat = "@FreeOmonBot"
reply = await message.get_reply_message()
if not reply:
await message.edit("<b>Нет реплая.</b>")
return
await message.edit("<b>Минуточку...</b>")
async with message.client.conversation(chat) as conv:
try:
response = conv.wait_event(events.NewMessage(incoming=True, from_users=775654752))
await message.client.send_message(chat, reply)
response = await response
except YouBlockedUserError:
await message.edit("<b>Разблокируй @FreeOmonBot</b>")
return
if response.text:
pass
if response.media:
await message.client.send_file(message.to_id, response.media)
from .. import loader, utils
from telethon import events
from telethon.errors.rpcerrorlist import YouBlockedUserError
def register(cb):
cb(OmonBotMod())
class OmonBotMod(loader.Module):
"""Омон бот."""
strings = {'name': 'FreeOmonBot'}
async def omoncmd(self, message):
"""Используй .omon <реплай на пикчу>."""
chat = "@FreeOmonBot"
reply = await message.get_reply_message()
if not reply:
await message.edit("<b>Нет реплая.</b>")
return
await message.edit("<b>Минуточку...</b>")
async with message.client.conversation(chat) as conv:
try:
response = conv.wait_event(events.NewMessage(incoming=True, from_users=775654752))
await message.client.send_message(chat, reply)
response = await response
except YouBlockedUserError:
await message.edit("<b>Разблокируй @FreeOmonBot</b>")
return
if response.text:
pass
if response.media:
await message.client.send_file(message.to_id, response.media)
await message.delete()

View File

@@ -1,34 +1,34 @@
import io
import os
from .. import loader
from PIL import Image
from gsbl.stick_bug import StickBug
def register(cb):
cb(GSBLMod())
class GSBLMod(loader.Module):
"""Фановый, мемный модуль."""
strings = {'name': 'Get-Stick-Bugged-Lol'}
async def gsblcmd(self, event):
"""Используй .gsbl <реплай на картинку/стикер>."""
try:
reply = await event.get_reply_message()
if not reply:
return await event.edit("Нет реплая на картинку/стикер.")
await event.edit("Минуточку...")
im = io.BytesIO()
await event.edit("Скачиваю...")
await event.client.download_file(reply, im)
await event.edit("Обрабатываю...")
im = Image.open(im)
sb = StickBug(im)
sb.save_video("get_stick_bugged_lol.mp4")
await event.edit("Отправляю...")
await event.client.send_file(event.to_id, open("get_stick_bugged_lol.mp4", "rb"), reply_to=reply)
os.remove("get_stick_bugged_lol.mp4")
await event.delete()
except:
import io
import os
from .. import loader
from PIL import Image
from gsbl.stick_bug import StickBug
def register(cb):
cb(GSBLMod())
class GSBLMod(loader.Module):
"""Фановый, мемный модуль."""
strings = {'name': 'Get-Stick-Bugged-Lol'}
async def gsblcmd(self, event):
"""Используй .gsbl <реплай на картинку/стикер>."""
try:
reply = await event.get_reply_message()
if not reply:
return await event.edit("Нет реплая на картинку/стикер.")
await event.edit("Минуточку...")
im = io.BytesIO()
await event.edit("Скачиваю...")
await event.client.download_file(reply, im)
await event.edit("Обрабатываю...")
im = Image.open(im)
sb = StickBug(im)
sb.save_video("get_stick_bugged_lol.mp4")
await event.edit("Отправляю...")
await event.client.send_file(event.to_id, open("get_stick_bugged_lol.mp4", "rb"), reply_to=reply)
os.remove("get_stick_bugged_lol.mp4")
await event.delete()
except:
return await event.edit("Это не картинка/стикер.")

View File

@@ -1,17 +1,17 @@
from .. import loader
from asyncio import sleep
@loader.tds
class HeartsMod(loader.Module):
strings = {"name": "Heart's"}
@loader.owner
async def lheartscmd(self, message):
for _ in range(10):
for lheart in ['', '️🧡', '💛', '💚', '💙', '💜', '🤎', '🖤', '🤍']:
await message.edit(lheart)
await sleep(3)
async def sheartscmd(self, message):
for _ in range(10):
for sheart in ['', '️🧡', '💛', '💚', '💙', '💜', '🤎', '🖤', '🤍']:
await message.edit(sheart)
from .. import loader
from asyncio import sleep
@loader.tds
class HeartsMod(loader.Module):
strings = {"name": "Heart's"}
@loader.owner
async def lheartscmd(self, message):
for _ in range(10):
for lheart in ['', '️🧡', '💛', '💚', '💙', '💜', '🤎', '🖤', '🤍']:
await message.edit(lheart)
await sleep(3)
async def sheartscmd(self, message):
for _ in range(10):
for sheart in ['', '️🧡', '💛', '💚', '💙', '💜', '🤎', '🖤', '🤍']:
await message.edit(sheart)
await sleep(0.3)

View File

@@ -1,137 +1,137 @@
import io
import requests
from .. import loader, utils
from random import choice, randint
from PIL import Image, ImageDraw, ImageFont
def register(cb):
cb(ImpMod())
class ImpMod(loader.Module):
"""Among Us"""
strings = {'name': 'Impostor?'}
async def impcmd(self, message):
"""Используй: .imp <@ или текст или реплай>."""
try:
background = requests.get(f"https://fl1yd.ml/modules/stuff/impostor{randint(1,22)}.png").content
font = requests.get("https://fl1yd.ml/modules/stuff/font2.ttf").content
await message.edit("Минуточку...")
reply = await message.get_reply_message()
args = utils.get_args_raw(message)
imps = ['wasn`t the impostor', 'was the impostor']
if not args and not reply:
user = await message.client.get_me()
text = (f"{user.first_name} {choice(imps)}.\n"
f"{randint(1, 2)} impostor(s) remain.")
if reply:
user = await utils.get_user(await message.get_reply_message())
text = (f"{user.first_name} {choice(imps)}.\n"
f"{randint(1, 2)} impostor(s) remain.")
if args:
user = await message.client.get_entity(args)
text = (f"{user.first_name} {choice(imps)}.\n"
f"{randint(1, 2)} impostor(s) remain.")
font = io.BytesIO(font)
font = ImageFont.truetype(font, 30)
image = Image.new("RGBA", (1, 1), (0, 0, 0, 0))
draw = ImageDraw.Draw(image)
w, h = draw.multiline_textsize(text=text, font=font)
image = Image.open(io.BytesIO(background))
x, y = image.size
draw = ImageDraw.Draw(image)
draw.multiline_text(((x - w) // 2, (y - h) // 2), text=text, font=font, fill="white", align="center")
output = io.BytesIO()
output.name = "impostor.png"
image.save(output, "png")
output.seek(0)
await message.client.send_file(message.to_id, output, reply_to=reply)
await message.delete()
except:
text = args
font = io.BytesIO(font)
font = ImageFont.truetype(font, 30)
image = Image.new("RGBA", (1, 1), (0, 0, 0, 0))
draw = ImageDraw.Draw(image)
w, h = draw.multiline_textsize(text=text, font=font)
image = Image.open(io.BytesIO(background))
x, y = image.size
draw = ImageDraw.Draw(image)
draw.multiline_text(((x - w) // 2, (y - h) // 2), text=text, font=font, fill="white", align="center")
output = io.BytesIO()
output.name = "impostor.png"
image.save(output, "png")
output.seek(0)
await message.client.send_file(message.to_id, output, reply_to=reply)
await message.delete()
async def ruimpcmd(self, message):
"""Используй: .ruimp <@ или текст или реплай>."""
try:
background = requests.get(f"https://fl1yd.ml/modules/stuff/impostor{randint(1,22)}.png").content
font = requests.get("https://fl1yd.ml/modules/stuff/font2.ttf").content
await message.edit("Минуточку...")
reply = await message.get_reply_message()
args = utils.get_args_raw(message)
imps = ['не был предателем', 'оказался одним из предалатей']
remain = randint(1, 2)
if remain == 1:
if not args and not reply:
user = await message.client.get_me()
text = (f"{user.first_name} {choice(imps)}.\n"
"1 предатель остался.")
if reply:
user = await utils.get_user(await message.get_reply_message())
text = (f"{user.first_name} {choice(imps)}.\n"
"1 предатель остался.")
if args:
user = await message.client.get_entity(args)
text = (f"{user.first_name} {choice(imps)}.\n"
"1 предатель остался.")
else:
if not args and not reply:
user = await message.client.get_me()
text = (f"{user.first_name} {choice(imps)}.\n"
"2 предателя осталось.")
if reply:
user = await utils.get_user(await message.get_reply_message())
text = (f"{user.first_name} {choice(imps)}.\n"
"2 предателя осталось.")
if args:
user = await message.client.get_entity(args)
text = (f"{user.first_name} {choice(imps)}.\n"
"2 предателя осталось.")
font = io.BytesIO(font)
font = ImageFont.truetype(font, 30)
image = Image.new("RGBA", (1, 1), (0, 0, 0, 0))
draw = ImageDraw.Draw(image)
w, h = draw.multiline_textsize(text=text, font=font)
image = Image.open(io.BytesIO(background))
x, y = image.size
draw = ImageDraw.Draw(image)
draw.multiline_text(((x - w) // 2, (y - h) // 2), text=text, font=font, fill="white", align="center")
output = io.BytesIO()
output.name = "impostor.png"
image.save(output, "png")
output.seek(0)
await message.client.send_file(message.to_id, output, reply_to=reply)
await message.delete()
except:
text = args
font = io.BytesIO(font)
font = ImageFont.truetype(font, 30)
image = Image.new("RGBA", (1, 1), (0, 0, 0, 0))
draw = ImageDraw.Draw(image)
w, h = draw.multiline_textsize(text=text, font=font)
image = Image.open(io.BytesIO(background))
x, y = image.size
draw = ImageDraw.Draw(image)
draw.multiline_text(((x - w) // 2, (y - h) // 2), text=text, font=font, fill="white", align="center")
output = io.BytesIO()
output.name = "impostor.png"
image.save(output, "png")
output.seek(0)
await message.client.send_file(message.to_id, output, reply_to=reply)
import io
import requests
from .. import loader, utils
from random import choice, randint
from PIL import Image, ImageDraw, ImageFont
def register(cb):
cb(ImpMod())
class ImpMod(loader.Module):
"""Among Us"""
strings = {'name': 'Impostor?'}
async def impcmd(self, message):
"""Используй: .imp <@ или текст или реплай>."""
try:
background = requests.get(f"https://fl1yd.ml/modules/stuff/impostor{randint(1,22)}.png").content
font = requests.get("https://fl1yd.ml/modules/stuff/font2.ttf").content
await message.edit("Минуточку...")
reply = await message.get_reply_message()
args = utils.get_args_raw(message)
imps = ['wasn`t the impostor', 'was the impostor']
if not args and not reply:
user = await message.client.get_me()
text = (f"{user.first_name} {choice(imps)}.\n"
f"{randint(1, 2)} impostor(s) remain.")
if reply:
user = await utils.get_user(await message.get_reply_message())
text = (f"{user.first_name} {choice(imps)}.\n"
f"{randint(1, 2)} impostor(s) remain.")
if args:
user = await message.client.get_entity(args)
text = (f"{user.first_name} {choice(imps)}.\n"
f"{randint(1, 2)} impostor(s) remain.")
font = io.BytesIO(font)
font = ImageFont.truetype(font, 30)
image = Image.new("RGBA", (1, 1), (0, 0, 0, 0))
draw = ImageDraw.Draw(image)
w, h = draw.multiline_textsize(text=text, font=font)
image = Image.open(io.BytesIO(background))
x, y = image.size
draw = ImageDraw.Draw(image)
draw.multiline_text(((x - w) // 2, (y - h) // 2), text=text, font=font, fill="white", align="center")
output = io.BytesIO()
output.name = "impostor.png"
image.save(output, "png")
output.seek(0)
await message.client.send_file(message.to_id, output, reply_to=reply)
await message.delete()
except:
text = args
font = io.BytesIO(font)
font = ImageFont.truetype(font, 30)
image = Image.new("RGBA", (1, 1), (0, 0, 0, 0))
draw = ImageDraw.Draw(image)
w, h = draw.multiline_textsize(text=text, font=font)
image = Image.open(io.BytesIO(background))
x, y = image.size
draw = ImageDraw.Draw(image)
draw.multiline_text(((x - w) // 2, (y - h) // 2), text=text, font=font, fill="white", align="center")
output = io.BytesIO()
output.name = "impostor.png"
image.save(output, "png")
output.seek(0)
await message.client.send_file(message.to_id, output, reply_to=reply)
await message.delete()
async def ruimpcmd(self, message):
"""Используй: .ruimp <@ или текст или реплай>."""
try:
background = requests.get(f"https://fl1yd.ml/modules/stuff/impostor{randint(1,22)}.png").content
font = requests.get("https://fl1yd.ml/modules/stuff/font2.ttf").content
await message.edit("Минуточку...")
reply = await message.get_reply_message()
args = utils.get_args_raw(message)
imps = ['не был предателем', 'оказался одним из предалатей']
remain = randint(1, 2)
if remain == 1:
if not args and not reply:
user = await message.client.get_me()
text = (f"{user.first_name} {choice(imps)}.\n"
"1 предатель остался.")
if reply:
user = await utils.get_user(await message.get_reply_message())
text = (f"{user.first_name} {choice(imps)}.\n"
"1 предатель остался.")
if args:
user = await message.client.get_entity(args)
text = (f"{user.first_name} {choice(imps)}.\n"
"1 предатель остался.")
else:
if not args and not reply:
user = await message.client.get_me()
text = (f"{user.first_name} {choice(imps)}.\n"
"2 предателя осталось.")
if reply:
user = await utils.get_user(await message.get_reply_message())
text = (f"{user.first_name} {choice(imps)}.\n"
"2 предателя осталось.")
if args:
user = await message.client.get_entity(args)
text = (f"{user.first_name} {choice(imps)}.\n"
"2 предателя осталось.")
font = io.BytesIO(font)
font = ImageFont.truetype(font, 30)
image = Image.new("RGBA", (1, 1), (0, 0, 0, 0))
draw = ImageDraw.Draw(image)
w, h = draw.multiline_textsize(text=text, font=font)
image = Image.open(io.BytesIO(background))
x, y = image.size
draw = ImageDraw.Draw(image)
draw.multiline_text(((x - w) // 2, (y - h) // 2), text=text, font=font, fill="white", align="center")
output = io.BytesIO()
output.name = "impostor.png"
image.save(output, "png")
output.seek(0)
await message.client.send_file(message.to_id, output, reply_to=reply)
await message.delete()
except:
text = args
font = io.BytesIO(font)
font = ImageFont.truetype(font, 30)
image = Image.new("RGBA", (1, 1), (0, 0, 0, 0))
draw = ImageDraw.Draw(image)
w, h = draw.multiline_textsize(text=text, font=font)
image = Image.open(io.BytesIO(background))
x, y = image.size
draw = ImageDraw.Draw(image)
draw.multiline_text(((x - w) // 2, (y - h) // 2), text=text, font=font, fill="white", align="center")
output = io.BytesIO()
output.name = "impostor.png"
image.save(output, "png")
output.seek(0)
await message.client.send_file(message.to_id, output, reply_to=reply)
await message.delete()

View File

@@ -1,35 +1,35 @@
from .. import loader
from asyncio import sleep
import random
def register(cb):
cb(KickRandomMod())
class KickRandomMod(loader.Module):
"""Кик рандом."""
strings = {'name': 'KickRandom'}
async def kickrandcmd(self, event):
"""Используй .kickrand, чтобы кикнуть случайного пользователя (может кикнуть вас)."""
if event.chat:
chat = await event.get_chat()
admin = chat.admin_rights
creator = chat.creator
if not admin and not creator:
await event.edit('<b>Я здесь не админ.</b>')
return
user = random.choice([i for i in await event.client.get_participants(event.to_id)])
await event.edit('<b>Кому-то сейчас не повезёт...</b>')
await sleep(3)
try:
await event.client.kick_participant(event.chat_id, user.id)
await sleep(0.5)
except:
await event.edit('<b>У меня нет достаточных прав :с</b>')
return
await event.edit(f"<b>Рандом выбрал <a href=\"tg://user?id={user.id}\">{user.first_name}</a>, и он кикнут!</b>")
else:
from .. import loader
from asyncio import sleep
import random
def register(cb):
cb(KickRandomMod())
class KickRandomMod(loader.Module):
"""Кик рандом."""
strings = {'name': 'KickRandom'}
async def kickrandcmd(self, event):
"""Используй .kickrand, чтобы кикнуть случайного пользователя (может кикнуть вас)."""
if event.chat:
chat = await event.get_chat()
admin = chat.admin_rights
creator = chat.creator
if not admin and not creator:
await event.edit('<b>Я здесь не админ.</b>')
return
user = random.choice([i for i in await event.client.get_participants(event.to_id)])
await event.edit('<b>Кому-то сейчас не повезёт...</b>')
await sleep(3)
try:
await event.client.kick_participant(event.chat_id, user.id)
await sleep(0.5)
except:
await event.edit('<b>У меня нет достаточных прав :с</b>')
return
await event.edit(f"<b>Рандом выбрал <a href=\"tg://user?id={user.id}\">{user.first_name}</a>, и он кикнут!</b>")
else:
await event.edit('<b>Это не чат!</b>')

View File

@@ -1,46 +1,46 @@
import os
from .. import loader, utils
def register(cb):
cb(MediaCutterMod())
class MediaCutterMod(loader.Module):
"""Обрезать медиа."""
strings = {'name': 'MediaCutter'}
async def cutcmd(self, event):
"""Используй .cut <начало(сек):конец(сек)> <реплай на аудио/видео/гиф>."""
args = utils.get_args_raw(event).split(':')
reply = await event.get_reply_message()
if not reply or not reply.media:
return await event.edit('Нет реплая на медиа.')
if reply.media:
if args:
if len(args) == 2:
try:
await event.edit('Скачиваем...')
smth = reply.file.ext
await event.client.download_media(reply.media, f'uncutted{smth}')
if not args[0]:
await event.edit(f'Обрезаем с 0 сек. по {args[1]} сек....')
os.system(f'ffmpeg -i uncutted{smth} -ss 0 -to {args[1]} -c copy cutted{smth} -y')
elif not args[1]:
end = reply.media.document.attributes[0].duration
await event.edit(f'Обрезаем с {args[0]} сек. по {end} сек....')
os.system(f'ffmpeg -i uncutted{smth} -ss {args[0]} -to {end} -c copy cutted{smth} -y')
else:
await event.edit(f'Обрезаем с {args[0]} сек. по {args[1]} сек....')
os.system(f'ffmpeg -i uncutted{smth} -ss {args[0]} -to {args[1]} -c copy cutted{smth} -y')
await event.edit('Отправляем...')
await event.client.send_file(event.to_id, f'cutted{smth}', reply_to=reply.id)
os.system('rm -rf uncutted* cutted*')
await event.delete()
except:
await event.edit('Этот файл не поддерживается.')
os.system('rm -rf uncutted* cutted*')
return
else:
return await event.edit('Неверно указаны аргументы.')
else:
import os
from .. import loader, utils
def register(cb):
cb(MediaCutterMod())
class MediaCutterMod(loader.Module):
"""Обрезать медиа."""
strings = {'name': 'MediaCutter'}
async def cutcmd(self, event):
"""Используй .cut <начало(сек):конец(сек)> <реплай на аудио/видео/гиф>."""
args = utils.get_args_raw(event).split(':')
reply = await event.get_reply_message()
if not reply or not reply.media:
return await event.edit('Нет реплая на медиа.')
if reply.media:
if args:
if len(args) == 2:
try:
await event.edit('Скачиваем...')
smth = reply.file.ext
await event.client.download_media(reply.media, f'uncutted{smth}')
if not args[0]:
await event.edit(f'Обрезаем с 0 сек. по {args[1]} сек....')
os.system(f'ffmpeg -i uncutted{smth} -ss 0 -to {args[1]} -c copy cutted{smth} -y')
elif not args[1]:
end = reply.media.document.attributes[0].duration
await event.edit(f'Обрезаем с {args[0]} сек. по {end} сек....')
os.system(f'ffmpeg -i uncutted{smth} -ss {args[0]} -to {end} -c copy cutted{smth} -y')
else:
await event.edit(f'Обрезаем с {args[0]} сек. по {args[1]} сек....')
os.system(f'ffmpeg -i uncutted{smth} -ss {args[0]} -to {args[1]} -c copy cutted{smth} -y')
await event.edit('Отправляем...')
await event.client.send_file(event.to_id, f'cutted{smth}', reply_to=reply.id)
os.system('rm -rf uncutted* cutted*')
await event.delete()
except:
await event.edit('Этот файл не поддерживается.')
os.system('rm -rf uncutted* cutted*')
return
else:
return await event.edit('Неверно указаны аргументы.')
else:
return await event.edit('Нет аргументов')

View File

@@ -1,65 +1,65 @@
import os
from .. import loader, utils
from telethon import functions
def register(cb):
cb(OnAvaMod())
class OnAvaMod(loader.Module):
"""Гифку/видео/стикер на аву."""
strings = {'name': 'OnAva'}
async def onavacmd(self, message):
"""Установить на аву гифку/видео/стикер.\nИспользование: .onava <реплай>."""
try:
reply = await message.get_reply_message()
if reply:
await message.edit("Скачиваем...")
if reply.video:
await message.client.download_media(reply.media, "ava.mp4")
await message.edit("Конвертируем...")
os.system("ffmpeg -i ava.mp4 -c copy -an gifavaa.mp4 -y")
os.system("ffmpeg -i gifavaa.mp4 -vf scale=360:360 gifava.mp4 -y")
else:
await message.client.download_media(reply.media, "tgs.tgs")
await message.edit("Конвертируем...")
os.system("lottie_convert.py tgs.tgs tgs.gif; mv tgs.gif gifava.mp4")
else:
return await message.edit("Нет реплая на гиф/анимированный стикер/видеосообщение.")
await message.edit("Устанавливаем аву...")
await message.client(functions.photos.UploadProfilePhotoRequest(video=await message.client.upload_file("gifava.mp4"), video_start_ts=0.0))
await message.edit("Ава установлена.")
os.system("rm -rf ava.mp4 gifava.mp4 gifavaa.mp4 tgs.tgs tgs.gif")
except:
await message.edit("Произошла непредвиденная ошибка.")
os.system("rm -rf ava.mp4 gifava.mp4 gifavaa.mp4 tgs.tgs tgs.gif")
return
async def togifcmd(self, message):
"""Сделать из медиа гифку.\nИспользование: .togif <реплай>."""
try:
await message.edit("Скачиваем...")
reply = await message.get_reply_message()
if reply:
if reply.video:
await message.client.download_media(reply.media, "inputfile.mp4")
await message.edit("Конвертируем...")
os.system("ffmpeg -i inputfile.mp4 -vcodec copy -an outputfile.mp4")
await message.edit("Отправляем...")
await message.client.send_file(message.to_id, "outputfile.mp4")
elif reply.file.ext == ".tgs":
await message.client.download_media(reply.media, f"tgs.tgs")
await message.edit("Конвертируем...")
os.system("lottie_convert.py tgs.tgs tgs.gif")
await message.edit("Отправляем...")
await message.client.send_file(message.to_id, "tgs.gif", reply_to=reply.id)
else: return await message.edit("Этот файл не поддерживается.")
await message.delete()
os.system("rm -rf inputfile.mp4 outputfile.mp4 tgs.tgs tgs.gif")
else: return await message.edit("Нет реплая на видео/гиф/стикр.")
except:
await message.edit("Произошла непредвиденная ошибка.")
os.system("rm -rf inputfile.mp4 outputfile.mp4 tgs.tgs tgs.gif")
import os
from .. import loader, utils
from telethon import functions
def register(cb):
cb(OnAvaMod())
class OnAvaMod(loader.Module):
"""Гифку/видео/стикер на аву."""
strings = {'name': 'OnAva'}
async def onavacmd(self, message):
"""Установить на аву гифку/видео/стикер.\nИспользование: .onava <реплай>."""
try:
reply = await message.get_reply_message()
if reply:
await message.edit("Скачиваем...")
if reply.video:
await message.client.download_media(reply.media, "ava.mp4")
await message.edit("Конвертируем...")
os.system("ffmpeg -i ava.mp4 -c copy -an gifavaa.mp4 -y")
os.system("ffmpeg -i gifavaa.mp4 -vf scale=360:360 gifava.mp4 -y")
else:
await message.client.download_media(reply.media, "tgs.tgs")
await message.edit("Конвертируем...")
os.system("lottie_convert.py tgs.tgs tgs.gif; mv tgs.gif gifava.mp4")
else:
return await message.edit("Нет реплая на гиф/анимированный стикер/видеосообщение.")
await message.edit("Устанавливаем аву...")
await message.client(functions.photos.UploadProfilePhotoRequest(video=await message.client.upload_file("gifava.mp4"), video_start_ts=0.0))
await message.edit("Ава установлена.")
os.system("rm -rf ava.mp4 gifava.mp4 gifavaa.mp4 tgs.tgs tgs.gif")
except:
await message.edit("Произошла непредвиденная ошибка.")
os.system("rm -rf ava.mp4 gifava.mp4 gifavaa.mp4 tgs.tgs tgs.gif")
return
async def togifcmd(self, message):
"""Сделать из медиа гифку.\nИспользование: .togif <реплай>."""
try:
await message.edit("Скачиваем...")
reply = await message.get_reply_message()
if reply:
if reply.video:
await message.client.download_media(reply.media, "inputfile.mp4")
await message.edit("Конвертируем...")
os.system("ffmpeg -i inputfile.mp4 -vcodec copy -an outputfile.mp4")
await message.edit("Отправляем...")
await message.client.send_file(message.to_id, "outputfile.mp4")
elif reply.file.ext == ".tgs":
await message.client.download_media(reply.media, f"tgs.tgs")
await message.edit("Конвертируем...")
os.system("lottie_convert.py tgs.tgs tgs.gif")
await message.edit("Отправляем...")
await message.client.send_file(message.to_id, "tgs.gif", reply_to=reply.id)
else: return await message.edit("Этот файл не поддерживается.")
await message.delete()
os.system("rm -rf inputfile.mp4 outputfile.mp4 tgs.tgs tgs.gif")
else: return await message.edit("Нет реплая на видео/гиф/стикр.")
except:
await message.edit("Произошла непредвиденная ошибка.")
os.system("rm -rf inputfile.mp4 outputfile.mp4 tgs.tgs tgs.gif")
return

View File

@@ -1,194 +1,194 @@
import logging
from .. import loader, utils
import telethon
import requests, io, PIL
from telethon.tl.types import (MessageEntityBold, MessageEntityItalic,
MessageEntityMention, MessageEntityTextUrl,
MessageEntityCode, MessageEntityMentionName,
MessageEntityHashtag, MessageEntityCashtag,
MessageEntityBotCommand, MessageEntityUrl,
MessageEntityStrike, MessageEntityUnderline,
MessageEntityPhone, ChannelParticipantsAdmins,
ChannelParticipantCreator, ChannelParticipantAdmin,
User, Channel)
logger = logging.getLogger(__name__)
def register(cb):
cb(QuotesMod())
@loader.tds
class QuotesMod(loader.Module):
"""Quote a message"""
strings = {"name": "Quotes"}
async def client_ready(self, client, db):
self.client = message.client
@loader.unrestricted
@loader.ratelimit
async def quotecmd(self, message):
args = utils.get_args_raw(message)
reply = await message.get_reply_message()
if not reply:
await utils.answer(message, '<b>Нет реплая</b>')
return
await message.edit("<b>Обработка...</b>")
if not args or not args.isdigit():
count = 1
else:
count = int(args.strip()) +1
msgs = []
cur = reply.id
cyr = cur + count
while cur != cyr:
msg = await message.client.get_messages(message.to_id, ids=cur)
if msg:
msgs.append(msg)
cur += 1
messages = []
avatars = {}
for reply in msgs:
text = reply.raw_text
entities = parse_entities(reply)
if reply.fwd_from:
id = reply.fwd_from.from_id or reply.fwd_from.channel_id
if not id:
id = 1234567890
name = reply.fwd_from.from_name
pfp = None
else:
sender = await message.client.get_entity(id)
name = (sender.first_name + ("" if not sender.last_name else " "+sender.last_name)) if type(sender) == User else sender.title
pfp = avatars.get(id, None)
if not pfp:
pfp = await message.client.download_profile_photo(sender.id, bytes)
if pfp:
pfp = 'https://telegra.ph'+requests.post('https://telegra.ph/upload', files={'file': ('file', pfp, None)}).json()[0]['src']
avatars[id] = pfp
else:
id = reply.from_id
sender = await message.client.get_entity(id)
name = (sender.first_name + ("" if not sender.last_name else " "+sender.last_name)) if type(sender) == User else sender.title
pfp = avatars.get(id, None)
if not pfp:
pfp = await message.client.download_profile_photo(reply.from_id, bytes)
if pfp:
pfp = 'https://telegra.ph'+requests.post('https://telegra.ph/upload', files={'file': ('file', pfp, None)}).json()[0]['src']
avatars[id] = pfp
image = await check_media(message, reply)
rreply = await reply.get_reply_message()
if rreply:
rtext = rreply.raw_text
rsender = rreply.sender
rname = (rsender.first_name + ("" if not rsender.last_name else " "+rsender.last_name)) if type(rsender) == User else rsender.title
rreply = {'author': rname, 'text': rtext}
admintitle = ""
if message.chat:
admins = await message.client.get_participants(message.to_id, filter=ChannelParticipantsAdmins)
if reply.sender in admins:
admin = admins[admins.index(reply.sender)].participant
admintitle = admin.rank if admin else ""
if not admintitle:
if type(admin) == ChannelParticipantCreator:
admintitle = "creator"
else:
admintitle = "admin"
messages.append({
"text": text,
"picture": image,
"reply": rreply,
"entities": entities,
"author": {
"id": id,
"name": name,
"adminTitle": admintitle,
"picture": pfp
}
})
data = {"messages": messages,
"maxWidth": 550,
"scaleFactor": 5,
"squareAvatar": False,
"textColor": "white",
"replyLineColor": "white",
"adminTitleColor": "#969ba0",
"messageBorderRadius": 10,
"pictureBorderRadius": 8,
"backgroundColor": "#162330"
}
await message.edit("<b>О б р а б о т к а . . .</b>")
r = requests.post("https://mishase.me/quote", json=data)
output = r.content
out = io.BytesIO()
out.name = "quote.webp"
PIL.Image.open(io.BytesIO(output)).save(out, "WEBP")
out.seek(0)
await message.client.send_file(message.to_id, out, reply_to=reply)
await message.delete()
def parse_entities(reply):
entities = []
if not reply.entities:
return []
for entity in reply.entities:
entity_type = type(entity)
start = entity.offset
end = entity.length
if entity_type is MessageEntityBold:
etype = 'bold'
elif entity_type is MessageEntityItalic:
etype = 'italic'
elif entity_type in [MessageEntityUrl, MessageEntityPhone]:
etype = 'url'
elif entity_type is MessageEntityCode:
etype = 'monospace'
elif entity_type is MessageEntityStrike:
etype = 'strikethrough'
elif entity_type is MessageEntityUnderline:
etype = 'underline'
elif entity_type in [MessageEntityMention, MessageEntityTextUrl,
MessageEntityMentionName, MessageEntityHashtag,
MessageEntityCashtag, MessageEntityBotCommand]:
etype = 'bluetext'
entities.append({'type': etype, 'offset': start, 'length': end})
return entities
async def check_media(message, reply):
if reply and reply.media:
if reply.photo:
data = reply.photo
elif reply.document:
if reply.gif or reply.video or reply.audio or reply.voice:
return None
data = reply.media.document
else:
return None
else:
return None
if not data or data is None:
return None
else:
data = await message.client.download_file(data, bytes)
img = io.BytesIO()
img.name = "img.png"
try:
PIL.Image.open(io.BytesIO(data)).save(img, "PNG")
link = 'https://telegra.ph'+requests.post('https://telegra.ph/upload', files={'file': ('file', img.getvalue(), "image/png")}).json()[0]['src']
return link
except:
return None
import logging
from .. import loader, utils
import telethon
import requests, io, PIL
from telethon.tl.types import (MessageEntityBold, MessageEntityItalic,
MessageEntityMention, MessageEntityTextUrl,
MessageEntityCode, MessageEntityMentionName,
MessageEntityHashtag, MessageEntityCashtag,
MessageEntityBotCommand, MessageEntityUrl,
MessageEntityStrike, MessageEntityUnderline,
MessageEntityPhone, ChannelParticipantsAdmins,
ChannelParticipantCreator, ChannelParticipantAdmin,
User, Channel)
logger = logging.getLogger(__name__)
def register(cb):
cb(QuotesMod())
@loader.tds
class QuotesMod(loader.Module):
"""Quote a message"""
strings = {"name": "Quotes"}
async def client_ready(self, client, db):
self.client = message.client
@loader.unrestricted
@loader.ratelimit
async def quotecmd(self, message):
args = utils.get_args_raw(message)
reply = await message.get_reply_message()
if not reply:
await utils.answer(message, '<b>Нет реплая</b>')
return
await message.edit("<b>Обработка...</b>")
if not args or not args.isdigit():
count = 1
else:
count = int(args.strip()) +1
msgs = []
cur = reply.id
cyr = cur + count
while cur != cyr:
msg = await message.client.get_messages(message.to_id, ids=cur)
if msg:
msgs.append(msg)
cur += 1
messages = []
avatars = {}
for reply in msgs:
text = reply.raw_text
entities = parse_entities(reply)
if reply.fwd_from:
id = reply.fwd_from.from_id or reply.fwd_from.channel_id
if not id:
id = 1234567890
name = reply.fwd_from.from_name
pfp = None
else:
sender = await message.client.get_entity(id)
name = (sender.first_name + ("" if not sender.last_name else " "+sender.last_name)) if type(sender) == User else sender.title
pfp = avatars.get(id, None)
if not pfp:
pfp = await message.client.download_profile_photo(sender.id, bytes)
if pfp:
pfp = 'https://telegra.ph'+requests.post('https://telegra.ph/upload', files={'file': ('file', pfp, None)}).json()[0]['src']
avatars[id] = pfp
else:
id = reply.from_id
sender = await message.client.get_entity(id)
name = (sender.first_name + ("" if not sender.last_name else " "+sender.last_name)) if type(sender) == User else sender.title
pfp = avatars.get(id, None)
if not pfp:
pfp = await message.client.download_profile_photo(reply.from_id, bytes)
if pfp:
pfp = 'https://telegra.ph'+requests.post('https://telegra.ph/upload', files={'file': ('file', pfp, None)}).json()[0]['src']
avatars[id] = pfp
image = await check_media(message, reply)
rreply = await reply.get_reply_message()
if rreply:
rtext = rreply.raw_text
rsender = rreply.sender
rname = (rsender.first_name + ("" if not rsender.last_name else " "+rsender.last_name)) if type(rsender) == User else rsender.title
rreply = {'author': rname, 'text': rtext}
admintitle = ""
if message.chat:
admins = await message.client.get_participants(message.to_id, filter=ChannelParticipantsAdmins)
if reply.sender in admins:
admin = admins[admins.index(reply.sender)].participant
admintitle = admin.rank if admin else ""
if not admintitle:
if type(admin) == ChannelParticipantCreator:
admintitle = "creator"
else:
admintitle = "admin"
messages.append({
"text": text,
"picture": image,
"reply": rreply,
"entities": entities,
"author": {
"id": id,
"name": name,
"adminTitle": admintitle,
"picture": pfp
}
})
data = {"messages": messages,
"maxWidth": 550,
"scaleFactor": 5,
"squareAvatar": False,
"textColor": "white",
"replyLineColor": "white",
"adminTitleColor": "#969ba0",
"messageBorderRadius": 10,
"pictureBorderRadius": 8,
"backgroundColor": "#162330"
}
await message.edit("<b>О б р а б о т к а . . .</b>")
r = requests.post("https://mishase.me/quote", json=data)
output = r.content
out = io.BytesIO()
out.name = "quote.webp"
PIL.Image.open(io.BytesIO(output)).save(out, "WEBP")
out.seek(0)
await message.client.send_file(message.to_id, out, reply_to=reply)
await message.delete()
def parse_entities(reply):
entities = []
if not reply.entities:
return []
for entity in reply.entities:
entity_type = type(entity)
start = entity.offset
end = entity.length
if entity_type is MessageEntityBold:
etype = 'bold'
elif entity_type is MessageEntityItalic:
etype = 'italic'
elif entity_type in [MessageEntityUrl, MessageEntityPhone]:
etype = 'url'
elif entity_type is MessageEntityCode:
etype = 'monospace'
elif entity_type is MessageEntityStrike:
etype = 'strikethrough'
elif entity_type is MessageEntityUnderline:
etype = 'underline'
elif entity_type in [MessageEntityMention, MessageEntityTextUrl,
MessageEntityMentionName, MessageEntityHashtag,
MessageEntityCashtag, MessageEntityBotCommand]:
etype = 'bluetext'
entities.append({'type': etype, 'offset': start, 'length': end})
return entities
async def check_media(message, reply):
if reply and reply.media:
if reply.photo:
data = reply.photo
elif reply.document:
if reply.gif or reply.video or reply.audio or reply.voice:
return None
data = reply.media.document
else:
return None
else:
return None
if not data or data is None:
return None
else:
data = await message.client.download_file(data, bytes)
img = io.BytesIO()
img.name = "img.png"
try:
PIL.Image.open(io.BytesIO(data)).save(img, "PNG")
link = 'https://telegra.ph'+requests.post('https://telegra.ph/upload', files={'file': ('file', img.getvalue(), "image/png")}).json()[0]['src']
return link
except:
return None

View File

@@ -1,56 +1,56 @@
import os
from .. import loader, utils
from asyncio import sleep
def register(cb):
cb(ReplyDownloaderMod())
class ReplyDownloaderMod(loader.Module):
"""Скачать файлом реплай."""
strings = {'name': 'Reply Downloader'}
async def dlrcmd(self, message):
"""Команда .dlr <реплай на файл> <название (по желанию)> скачивает файл, либо сохраняет текст в файл на который был сделан реплай."""
name = utils.get_args_raw(message)
reply = await message.get_reply_message()
if reply:
await message.edit('Скачиваем...')
if reply.text:
text = reply.text
fname = f'{name or message.id+reply.id}.txt'
file = open(fname, 'w')
file.write(text)
file.close()
await message.edit(f'Файл сохранён как: <code>{fname}</code>.\n\nВы можете отправить его в этот чат с помощью команды <code>.ulf {fname}</code>.')
else:
ext = reply.file.ext
fname = f'{name or message.id+reply.id}{ext}'
await message.client.download_media(reply, fname)
await message.edit(f'Этот файл сохранён как: <code>{fname}</code>.\n\nВы можете отправить его в этот чат с помощью команды <code>.ulf {fname}</code>.')
else:
return await message.edit('Нет реплая.')
async def ulfcmd(self, message):
"""Команда .ulf <d>* <название файла> отправляет файл в чат.\n* - удалить файл после отправки."""
name = utils.get_args_raw(message)
d = False
if('d ' in name):
d = True
if name:
try:
name = name.replace('d ', '')
await message.edit(f'Отправляем <code>{name}</code>...')
if d == True:
await message.client.send_file(message.to_id, f'{name}')
await message.edit(f'Отправляем <code>{name}</code>... Успешно!\nУдаляем <code>{name}</code>...')
os.remove(name)
await message.edit(f'Отправляем <code>{name}</code>... Успешно!\nУдаляем <code>{name}</code>... Успешно!')
await sleep(0.5)
else:
await message.client.send_file(message.to_id, name)
except:
return await message.edit('Такой файл не существует.')
await message.delete()
else:
import os
from .. import loader, utils
from asyncio import sleep
def register(cb):
cb(ReplyDownloaderMod())
class ReplyDownloaderMod(loader.Module):
"""Скачать файлом реплай."""
strings = {'name': 'Reply Downloader'}
async def dlrcmd(self, message):
"""Команда .dlr <реплай на файл> <название (по желанию)> скачивает файл, либо сохраняет текст в файл на который был сделан реплай."""
name = utils.get_args_raw(message)
reply = await message.get_reply_message()
if reply:
await message.edit('Скачиваем...')
if reply.text:
text = reply.text
fname = f'{name or message.id+reply.id}.txt'
file = open(fname, 'w')
file.write(text)
file.close()
await message.edit(f'Файл сохранён как: <code>{fname}</code>.\n\nВы можете отправить его в этот чат с помощью команды <code>.ulf {fname}</code>.')
else:
ext = reply.file.ext
fname = f'{name or message.id+reply.id}{ext}'
await message.client.download_media(reply, fname)
await message.edit(f'Этот файл сохранён как: <code>{fname}</code>.\n\nВы можете отправить его в этот чат с помощью команды <code>.ulf {fname}</code>.')
else:
return await message.edit('Нет реплая.')
async def ulfcmd(self, message):
"""Команда .ulf <d>* <название файла> отправляет файл в чат.\n* - удалить файл после отправки."""
name = utils.get_args_raw(message)
d = False
if('d ' in name):
d = True
if name:
try:
name = name.replace('d ', '')
await message.edit(f'Отправляем <code>{name}</code>...')
if d == True:
await message.client.send_file(message.to_id, f'{name}')
await message.edit(f'Отправляем <code>{name}</code>... Успешно!\nУдаляем <code>{name}</code>...')
os.remove(name)
await message.edit(f'Отправляем <code>{name}</code>... Успешно!\nУдаляем <code>{name}</code>... Успешно!')
await sleep(0.5)
else:
await message.client.send_file(message.to_id, name)
except:
return await message.edit('Такой файл не существует.')
await message.delete()
else:
return await message.edit('Нет аргументов.')

View File

@@ -1,23 +1,23 @@
from .. import loader, utils
from telethon.errors import MessageEmptyError
def register(cb):
cb(ReverseMod())
class ReverseMod(loader.Module):
"""Реверс текста."""
strings = {'name': 'Reverse'}
async def revcmd(self, message):
"""Используй .rev <текст или реплай>."""
try:
text = utils.get_args_raw(message)
reply = await message.get_reply_message()
if not text and not reply:
return await message.edit("Нет текста или реплая.")
if reply:
return await message.edit(f"{reply.raw_text}"[::-1])
if text:
return await message.edit(f"{text}"[::-1])
except MessageEmptyError:
from .. import loader, utils
from telethon.errors import MessageEmptyError
def register(cb):
cb(ReverseMod())
class ReverseMod(loader.Module):
"""Реверс текста."""
strings = {'name': 'Reverse'}
async def revcmd(self, message):
"""Используй .rev <текст или реплай>."""
try:
text = utils.get_args_raw(message)
reply = await message.get_reply_message()
if not text and not reply:
return await message.edit("Нет текста или реплая.")
if reply:
return await message.edit(f"{reply.raw_text}"[::-1])
if text:
return await message.edit(f"{text}"[::-1])
except MessageEmptyError:
return await message.edit("Это не текст.")

View File

@@ -1,22 +1,22 @@
from .. import loader, utils
def register(cb):
cb(SearchMod())
class SearchMod(loader.Module):
"""Поиск контента на канале @ftgmodulesbyfl1yd"""
strings = {'name': 'SearchModules'}
async def searchcmd(self, message):
"""Используй .search <название>"""
try:
title = utils.get_args_raw(message)
if not title:
await message.edit("<b>Нет текста после команды.</b>")
else:
chat = message.input_chat
await [i async for i in message.client.iter_messages("ftgmodulesbyfl1yd", search=title)][0].forward_to(chat)
await message.delete()
except:
from .. import loader, utils
def register(cb):
cb(SearchMod())
class SearchMod(loader.Module):
"""Поиск контента на канале @ftgmodulesbyfl1yd"""
strings = {'name': 'SearchModules'}
async def searchcmd(self, message):
"""Используй .search <название>"""
try:
title = utils.get_args_raw(message)
if not title:
await message.edit("<b>Нет текста после команды.</b>")
else:
chat = message.input_chat
await [i async for i in message.client.iter_messages("ftgmodulesbyfl1yd", search=title)][0].forward_to(chat)
await message.delete()
except:
await message.edit("<b>Не удалось найти контент.</b>")

View File

@@ -1,122 +1,122 @@
from .. import loader, utils
import io
import requests
from textwrap import wrap
from PIL import Image, ImageDraw, ImageFont
def register(cb):
cb(TextOnPhotoMod())
class TextOnPhotoMod(loader.Module):
strings = {'name': 'TextOnPhoto'}
async def bottomcmd(self, message):
"""Используй: .bottom {реплай на картинку/стикер} <white/black>;ничего <текст>."""
cols = {'white': 1, 'whit': 1, 'whi': 1, 'wh': 1, 'w': 1,
'black': 2, 'blac': 2, 'bla': 2, 'bl': 2, 'b': 2}
col = 1
reply = await message.get_reply_message()
txt = utils.get_args_raw(message)
await message.edit("подождем...")
if txt in cols:
col = cols[txt]
txt = None
if not txt:
txt = "я лошара."
if not reply:
await message.edit("нет реплая на картинку/стикер.")
return
if txt.split(" ")[0] in cols:
col = cols[txt.split(" ")[0]]
txt = " ".join(txt.split(" ")[1:])
img = await phedit(reply, txt, 1, col)
output = io.BytesIO()
output.name = "клоун.png"
img.save(output, "png")
output.seek(0)
await message.client.send_file(message.to_id, output, reply_to=reply)
await message.delete()
async def topcmd(self, message):
"""Используй: .top {реплай на картинку/стикер} <white/black>;ничего <текст>."""
cols = {'white': 1, 'whit': 1, 'whi': 1, 'wh': 1, 'w': 1,
'black': 2, 'blac': 2, 'bla': 2, 'bl': 2, 'b': 2}
col = 1
reply = await message.get_reply_message()
txt = utils.get_args_raw(message)
await message.edit("подождем...")
if txt in cols:
col = cols[txt]
txt = None
if not txt:
txt = "я лошара."
if not reply:
await message.edit("нет реплая на картинку/стикер.")
return
if txt.split(" ")[0] in cols:
col = cols[txt.split(" ")[0]]
txt = " ".join(txt.split(" ")[1:])
img = await phedit(reply, txt, 2, col)
output = io.BytesIO()
output.name = "клоун.png"
img.save(output, "png")
output.seek(0)
await message.client.send_file(message.to_id, output, reply_to=reply)
await message.delete()
async def centercmd(self, message):
"""Используй: .center {реплай на картинку/стикер} <white/black>;ничего <текст>."""
cols = {'white': 1, 'whit': 1, 'whi': 1, 'wh': 1, 'w': 1,
'black': 2, 'blac': 2, 'bla': 2, 'bl': 2, 'b': 2}
col = 1
reply = await message.get_reply_message()
txt = utils.get_args_raw(message)
await message.edit("подождем...")
if txt in cols:
col = cols[txt]
txt = None
if not txt:
txt = "я лошара."
if not reply:
await message.edit("нет реплая на картинку/стикер.")
return
if txt.split(" ")[0] in cols:
col = cols[txt.split(" ")[0]]
txt = " ".join(txt.split(" ")[1:])
img = await phedit(reply, txt, 3, col)
output = io.BytesIO()
output.name = "клоун.png"
img.save(output, "png")
output.seek(0)
await message.client.send_file(message.to_id, output, reply_to=reply)
await message.delete()
async def phedit(reply, txt, align, clr):
bytes_font = requests.get("https://github.com/Fl1yd/FTG-modules/blob/master/stuff/font3.ttf?raw=true").content
bytes_back = await reply.download_media(bytes)
font = io.BytesIO(bytes_font)
font = ImageFont.truetype(font, 72)
img = Image.open(io.BytesIO(bytes_back))
W, H = img.size
txt = txt.replace("\n", "𓃐")
text = "\n".join(wrap(txt, 30))
t = text
t = t.replace("𓃐", "\n")
draw = ImageDraw.Draw(img)
w, h = draw.multiline_textsize(t, font=font)
imtext = Image.new("RGBA", (w + 20, h + 20), (0, 0, 0, 0))
draw = ImageDraw.Draw(imtext)
if clr == 2:
draw.multiline_text((10, 10), t, (0, 0, 0), font=font, align='center')
else:
draw.multiline_text((10, 10), t, (255, 255, 255), font=font, align='center')
imtext.thumbnail((W, H))
w, h = imtext.size
if align == 1:
img.paste(imtext, ((W - w) // 2, (H - h) // 1), imtext)
if align == 2:
img.paste(imtext, ((W - w) // 2, (H - h) // 15), imtext)
if align == 3:
img.paste(imtext, ((W - w) // 2, (H - h) // 2), imtext)
from .. import loader, utils
import io
import requests
from textwrap import wrap
from PIL import Image, ImageDraw, ImageFont
def register(cb):
cb(TextOnPhotoMod())
class TextOnPhotoMod(loader.Module):
strings = {'name': 'TextOnPhoto'}
async def bottomcmd(self, message):
"""Используй: .bottom {реплай на картинку/стикер} <white/black>;ничего <текст>."""
cols = {'white': 1, 'whit': 1, 'whi': 1, 'wh': 1, 'w': 1,
'black': 2, 'blac': 2, 'bla': 2, 'bl': 2, 'b': 2}
col = 1
reply = await message.get_reply_message()
txt = utils.get_args_raw(message)
await message.edit("подождем...")
if txt in cols:
col = cols[txt]
txt = None
if not txt:
txt = "я лошара."
if not reply:
await message.edit("нет реплая на картинку/стикер.")
return
if txt.split(" ")[0] in cols:
col = cols[txt.split(" ")[0]]
txt = " ".join(txt.split(" ")[1:])
img = await phedit(reply, txt, 1, col)
output = io.BytesIO()
output.name = "клоун.png"
img.save(output, "png")
output.seek(0)
await message.client.send_file(message.to_id, output, reply_to=reply)
await message.delete()
async def topcmd(self, message):
"""Используй: .top {реплай на картинку/стикер} <white/black>;ничего <текст>."""
cols = {'white': 1, 'whit': 1, 'whi': 1, 'wh': 1, 'w': 1,
'black': 2, 'blac': 2, 'bla': 2, 'bl': 2, 'b': 2}
col = 1
reply = await message.get_reply_message()
txt = utils.get_args_raw(message)
await message.edit("подождем...")
if txt in cols:
col = cols[txt]
txt = None
if not txt:
txt = "я лошара."
if not reply:
await message.edit("нет реплая на картинку/стикер.")
return
if txt.split(" ")[0] in cols:
col = cols[txt.split(" ")[0]]
txt = " ".join(txt.split(" ")[1:])
img = await phedit(reply, txt, 2, col)
output = io.BytesIO()
output.name = "клоун.png"
img.save(output, "png")
output.seek(0)
await message.client.send_file(message.to_id, output, reply_to=reply)
await message.delete()
async def centercmd(self, message):
"""Используй: .center {реплай на картинку/стикер} <white/black>;ничего <текст>."""
cols = {'white': 1, 'whit': 1, 'whi': 1, 'wh': 1, 'w': 1,
'black': 2, 'blac': 2, 'bla': 2, 'bl': 2, 'b': 2}
col = 1
reply = await message.get_reply_message()
txt = utils.get_args_raw(message)
await message.edit("подождем...")
if txt in cols:
col = cols[txt]
txt = None
if not txt:
txt = "я лошара."
if not reply:
await message.edit("нет реплая на картинку/стикер.")
return
if txt.split(" ")[0] in cols:
col = cols[txt.split(" ")[0]]
txt = " ".join(txt.split(" ")[1:])
img = await phedit(reply, txt, 3, col)
output = io.BytesIO()
output.name = "клоун.png"
img.save(output, "png")
output.seek(0)
await message.client.send_file(message.to_id, output, reply_to=reply)
await message.delete()
async def phedit(reply, txt, align, clr):
bytes_font = requests.get("https://github.com/Fl1yd/FTG-modules/blob/master/stuff/font3.ttf?raw=true").content
bytes_back = await reply.download_media(bytes)
font = io.BytesIO(bytes_font)
font = ImageFont.truetype(font, 72)
img = Image.open(io.BytesIO(bytes_back))
W, H = img.size
txt = txt.replace("\n", "𓃐")
text = "\n".join(wrap(txt, 30))
t = text
t = t.replace("𓃐", "\n")
draw = ImageDraw.Draw(img)
w, h = draw.multiline_textsize(t, font=font)
imtext = Image.new("RGBA", (w + 20, h + 20), (0, 0, 0, 0))
draw = ImageDraw.Draw(imtext)
if clr == 2:
draw.multiline_text((10, 10), t, (0, 0, 0), font=font, align='center')
else:
draw.multiline_text((10, 10), t, (255, 255, 255), font=font, align='center')
imtext.thumbnail((W, H))
w, h = imtext.size
if align == 1:
img.paste(imtext, ((W - w) // 2, (H - h) // 1), imtext)
if align == 2:
img.paste(imtext, ((W - w) // 2, (H - h) // 15), imtext)
if align == 3:
img.paste(imtext, ((W - w) // 2, (H - h) // 2), imtext)
return img

View File

@@ -1,26 +1,26 @@
import requests
from .. import loader, utils
def register(cb):
cb(WeatherMod())
class WeatherMod(loader.Module):
"""Погода с сайта wttr.in"""
strings = {'name': 'Weather'}
async def pwcmd(self, message):
""""Кидает погоду картинкой.\nИспользование: .pw <город>; ничего."""
args = utils.get_args_raw(message).replace(' ', '+')
await message.edit("Узнаем погоду...")
city = requests.get(f"https://wttr.in/{args if args != None else ''}.png").content
await message.client.send_file(message.to_id, city)
await message.delete()
async def awcmd(self, message):
"""Кидает погоду ascii-артом.\nИспользование: .aw <город>; ничего."""
city = utils.get_args_raw(message)
await message.edit("Узнаем погоду...")
r = requests.get(f"https://wttr.in/{city if city != None else ''}?0?q?T&lang=ru")
import requests
from .. import loader, utils
def register(cb):
cb(WeatherMod())
class WeatherMod(loader.Module):
"""Погода с сайта wttr.in"""
strings = {'name': 'Weather'}
async def pwcmd(self, message):
""""Кидает погоду картинкой.\nИспользование: .pw <город>; ничего."""
args = utils.get_args_raw(message).replace(' ', '+')
await message.edit("Узнаем погоду...")
city = requests.get(f"https://wttr.in/{args if args != None else ''}.png").content
await message.client.send_file(message.to_id, city)
await message.delete()
async def awcmd(self, message):
"""Кидает погоду ascii-артом.\nИспользование: .aw <город>; ничего."""
city = utils.get_args_raw(message)
await message.edit("Узнаем погоду...")
r = requests.get(f"https://wttr.in/{city if city != None else ''}?0?q?T&lang=ru")
await message.edit(f"<code>Город: {r.text}</code>")

View File

@@ -1,158 +1,158 @@
from .. import loader, utils
import requests
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
import io
from textwrap import wrap
def register(cb):
cb(ZapomniZabudSoglMod())
class ZapomniZabudSoglMod(loader.Module):
"""Запомните;забудьте твари, согласен."""
strings = {'name': 'Запомните;забудьте твари, согласен'}
def __init__(self):
self.name = self.strings['name']
self._me = None
self._ratelimit = []
async def client_ready(self, client, db):
self._db = db
self._client = client
self.me = await client.get_me()
async def zapcmd(self, message):
""".zap <текст или реплай>"""
ufr = requests.get("https://fl1yd.ml/modules/stuff/font.ttf")
f = ufr.content
reply = await message.get_reply_message()
txet = utils.get_args_raw(message)
if not txet:
if not reply:
await message.edit("text?")
else:
txt = reply.raw_text
else:
txt = utils.get_args_raw(message)
await message.edit("<b>Извиняюсь...</b>")
pic = requests.get("https://fl1yd.ml/modules/stuff/man.jpg")
pic.raw.decode_content = True
img = Image.open(io.BytesIO(pic.content)).convert("RGB")
black = Image.new("RGBA", img.size, (0, 0, 0, 100))
img.paste(black, (0, 0), black)
W, H = img.size
txt = txt.replace("\n", "𓃐")
text = "\n".join(wrap(txt, 40))
t = "Запомните твари:\n" +text
t = t.replace("𓃐","\n")
draw = ImageDraw.Draw(img)
font = ImageFont.truetype(io.BytesIO(f), 32, encoding='UTF-8')
w, h = draw.multiline_textsize(t, font=font)
imtext = Image.new("RGBA", (w+20, h+20), (0, 0,0,0))
draw = ImageDraw.Draw(imtext)
draw.multiline_text((10, 10),t,(255,255,255),font=font, align='center')
imtext.thumbnail((W, H))
w, h = imtext.size
img.paste(imtext, ((W-w)//2,(H-h)//2), imtext)
out = io.BytesIO()
out.name = "out.jpg"
img.save(out)
out.seek(0)
await message.client.send_file(message.to_id, out, reply_to=reply)
await message.delete()
async def zabcmd(self, message):
""".zab <текст или реплай>"""
ufr = requests.get("https://fl1yd.ml/modules/stuff/font.ttf")
f = ufr.content
reply = await message.get_reply_message()
txet = utils.get_args_raw(message)
if not txet:
if not reply:
await message.edit("text?")
else:
txt = reply.raw_text
else:
txt = utils.get_args_raw(message)
await message.edit("<b>Извиняюсь...</b>")
pic = requests.get("https://fl1yd.ml/modules/stuff/man.jpg")
pic.raw.decode_content = True
img = Image.open(io.BytesIO(pic.content)).convert("RGB")
black = Image.new("RGBA", img.size, (0, 0, 0, 100))
img.paste(black, (0, 0), black)
W, H = img.size
txt = txt.replace("\n", "𓃐")
text = "\n".join(wrap(txt, 40))
t = "Забудьте твари:\n" + text
t = t.replace("𓃐", "\n")
draw = ImageDraw.Draw(img)
font = ImageFont.truetype(io.BytesIO(f), 32, encoding='UTF-8')
w, h = draw.multiline_textsize(t, font=font)
imtext = Image.new("RGBA", (w + 20, h + 20), (0, 0, 0, 0))
draw = ImageDraw.Draw(imtext)
draw.multiline_text((10, 10), t, (255, 255, 255), font=font, align='center')
imtext.thumbnail((W, H))
w, h = imtext.size
img.paste(imtext, ((W - w) // 2, (H - h) // 2), imtext)
out = io.BytesIO()
out.name = "out.jpg"
img.save(out)
out.seek(0)
await message.client.send_file(message.to_id, out, reply_to=reply)
await message.delete()
async def soglcmd(self, message):
""".sogl <текст или реплай>"""
ufr = requests.get("https://fl1yd.ml/modules/stuff/font.ttf")
f = ufr.content
reply = await message.get_reply_message()
txet = utils.get_args_raw(message)
if not txet:
if not reply:
await message.edit("text?")
else:
txt = reply.raw_text
else:
txt = utils.get_args_raw(message)
await message.edit("<b>Извиняюсь...</b>")
pic = requests.get("https://fl1yd.ml/modules/stuff/shrek.jpg")
pic.raw.decode_content = True
img = Image.open(io.BytesIO(pic.content)).convert("RGB")
black = Image.new("RGBA", img.size, (0, 0, 0, 100))
img.paste(black, (0, 0), black)
W, H = img.size
txt = txt.replace("\n", "𓃐")
text = "\n".join(wrap(txt, 40))
t = "Согласен, " + text
t = t.replace("𓃐", "\n")
draw = ImageDraw.Draw(img)
font = ImageFont.truetype(io.BytesIO(f), 28, encoding='UTF-8')
w, h = draw.multiline_textsize(t, font=font)
imtext = Image.new("RGBA", (w + 20, h + 20), (0, 0, 0, 0))
draw = ImageDraw.Draw(imtext)
draw.multiline_text((10, 10), t, (255, 255, 255), font=font, align='center')
imtext.thumbnail((W, H))
w, h = imtext.size
img.paste(imtext, ((W - w) // 2, (H - h) // 2), imtext)
out = io.BytesIO()
out.name = "out.jpg"
img.save(out)
out.seek(0)
await message.client.send_file(message.to_id, out, reply_to=reply)
from .. import loader, utils
import requests
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
import io
from textwrap import wrap
def register(cb):
cb(ZapomniZabudSoglMod())
class ZapomniZabudSoglMod(loader.Module):
"""Запомните;забудьте твари, согласен."""
strings = {'name': 'Запомните;забудьте твари, согласен'}
def __init__(self):
self.name = self.strings['name']
self._me = None
self._ratelimit = []
async def client_ready(self, client, db):
self._db = db
self._client = client
self.me = await client.get_me()
async def zapcmd(self, message):
""".zap <текст или реплай>"""
ufr = requests.get("https://fl1yd.ml/modules/stuff/font.ttf")
f = ufr.content
reply = await message.get_reply_message()
txet = utils.get_args_raw(message)
if not txet:
if not reply:
await message.edit("text?")
else:
txt = reply.raw_text
else:
txt = utils.get_args_raw(message)
await message.edit("<b>Извиняюсь...</b>")
pic = requests.get("https://fl1yd.ml/modules/stuff/man.jpg")
pic.raw.decode_content = True
img = Image.open(io.BytesIO(pic.content)).convert("RGB")
black = Image.new("RGBA", img.size, (0, 0, 0, 100))
img.paste(black, (0, 0), black)
W, H = img.size
txt = txt.replace("\n", "𓃐")
text = "\n".join(wrap(txt, 40))
t = "Запомните твари:\n" +text
t = t.replace("𓃐","\n")
draw = ImageDraw.Draw(img)
font = ImageFont.truetype(io.BytesIO(f), 32, encoding='UTF-8')
w, h = draw.multiline_textsize(t, font=font)
imtext = Image.new("RGBA", (w+20, h+20), (0, 0,0,0))
draw = ImageDraw.Draw(imtext)
draw.multiline_text((10, 10),t,(255,255,255),font=font, align='center')
imtext.thumbnail((W, H))
w, h = imtext.size
img.paste(imtext, ((W-w)//2,(H-h)//2), imtext)
out = io.BytesIO()
out.name = "out.jpg"
img.save(out)
out.seek(0)
await message.client.send_file(message.to_id, out, reply_to=reply)
await message.delete()
async def zabcmd(self, message):
""".zab <текст или реплай>"""
ufr = requests.get("https://fl1yd.ml/modules/stuff/font.ttf")
f = ufr.content
reply = await message.get_reply_message()
txet = utils.get_args_raw(message)
if not txet:
if not reply:
await message.edit("text?")
else:
txt = reply.raw_text
else:
txt = utils.get_args_raw(message)
await message.edit("<b>Извиняюсь...</b>")
pic = requests.get("https://fl1yd.ml/modules/stuff/man.jpg")
pic.raw.decode_content = True
img = Image.open(io.BytesIO(pic.content)).convert("RGB")
black = Image.new("RGBA", img.size, (0, 0, 0, 100))
img.paste(black, (0, 0), black)
W, H = img.size
txt = txt.replace("\n", "𓃐")
text = "\n".join(wrap(txt, 40))
t = "Забудьте твари:\n" + text
t = t.replace("𓃐", "\n")
draw = ImageDraw.Draw(img)
font = ImageFont.truetype(io.BytesIO(f), 32, encoding='UTF-8')
w, h = draw.multiline_textsize(t, font=font)
imtext = Image.new("RGBA", (w + 20, h + 20), (0, 0, 0, 0))
draw = ImageDraw.Draw(imtext)
draw.multiline_text((10, 10), t, (255, 255, 255), font=font, align='center')
imtext.thumbnail((W, H))
w, h = imtext.size
img.paste(imtext, ((W - w) // 2, (H - h) // 2), imtext)
out = io.BytesIO()
out.name = "out.jpg"
img.save(out)
out.seek(0)
await message.client.send_file(message.to_id, out, reply_to=reply)
await message.delete()
async def soglcmd(self, message):
""".sogl <текст или реплай>"""
ufr = requests.get("https://fl1yd.ml/modules/stuff/font.ttf")
f = ufr.content
reply = await message.get_reply_message()
txet = utils.get_args_raw(message)
if not txet:
if not reply:
await message.edit("text?")
else:
txt = reply.raw_text
else:
txt = utils.get_args_raw(message)
await message.edit("<b>Извиняюсь...</b>")
pic = requests.get("https://fl1yd.ml/modules/stuff/shrek.jpg")
pic.raw.decode_content = True
img = Image.open(io.BytesIO(pic.content)).convert("RGB")
black = Image.new("RGBA", img.size, (0, 0, 0, 100))
img.paste(black, (0, 0), black)
W, H = img.size
txt = txt.replace("\n", "𓃐")
text = "\n".join(wrap(txt, 40))
t = "Согласен, " + text
t = t.replace("𓃐", "\n")
draw = ImageDraw.Draw(img)
font = ImageFont.truetype(io.BytesIO(f), 28, encoding='UTF-8')
w, h = draw.multiline_textsize(t, font=font)
imtext = Image.new("RGBA", (w + 20, h + 20), (0, 0, 0, 0))
draw = ImageDraw.Draw(imtext)
draw.multiline_text((10, 10), t, (255, 255, 255), font=font, align='center')
imtext.thumbnail((W, H))
w, h = imtext.size
img.paste(imtext, ((W - w) // 2, (H - h) // 2), imtext)
out = io.BytesIO()
out.name = "out.jpg"
img.save(out)
out.seek(0)
await message.client.send_file(message.to_id, out, reply_to=reply)
await message.delete()

View File

@@ -1,223 +1,223 @@
# .------.------.------.------.------.------.------.------.------.------.
# |D.--. |4.--. |N.--. |1.--. |3.--. |L.--. |3.--. |K.--. |0.--. |0.--. |
# | :/\: | :/\: | :(): | :/\: | :(): | :/\: | :(): | :/\: | :/\: | :/\: |
# | (__) | :\/: | ()() | (__) | ()() | (__) | ()() | :\/: | :\/: | :\/: |
# | '--'D| '--'4| '--'N| '--'1| '--'3| '--'L| '--'3| '--'K| '--'0| '--'0|
# `------`------`------`------`------`------`------`------`------`------'
#
# Copyright 2022 t.me/D4n13l3k00
# Licensed under the Creative Commons CC BY-NC-ND 4.0
#
# Full license text can be found at:
# https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode
#
# Human-friendly one:
# https://creativecommons.org/licenses/by-nc-nd/4.0
import contextlib
import os
import re
from typing import *
import pytgcalls
import youtube_dl
from pytgcalls import PyTgCalls, StreamType
from pytgcalls.types.input_stream import AudioPiped, AudioVideoPiped
from pytgcalls.types.input_stream.quality import HighQualityAudio, HighQualityVideo
from telethon import types
from .. import loader, utils
# meta developer: @D4n13l3k00
# requires: py-tgcalls youtube-dl
@loader.tds
class ChatVoiceMod(loader.Module):
"""Module for working with voicechat"""
strings = {
"name": "ChatVoiceMod",
"downloading": "<b>[ChatVoiceMod]</b> Downloading...",
"playing": "<b>[ChatVoiceMod]</b> Playing...",
"notjoined": "<b>[ChatVoiceMod]</b> You are not joined",
"stop": "<b>[ChatVoiceMod]</b> Playing stopped!",
"leave": "<b>[ChatVoiceMod]</b> Leaved!",
"pause": "<b>[ChatVoiceMod]</b> Paused!",
"resume": "<b>[ChatVoiceMod]</b> Resumed!",
"mute": "<b>[ChatVoiceMod]</b> Muted!",
"unmute": "<b>[ChatVoiceMod]</b> Unmuted!",
"error": "<b>[ChatVoiceMod]</b> Error: <code>{}</code>",
"noargs": "<b>[ChatVoiceMod]</b> No args",
"noreply": "<b>[ChatVoiceMod]</b> No reply",
"nofile": "<b>[ChatVoiceMod]</b> No file",
"nofiles": "<b>[ChatVoiceMod]</b> No files",
"deleted": "<b>[ChatVoiceMod]</b> <code>{}</code> successfully deleted",
"downloaded": "<b>[ChatVoiceMod]</b> Downloaded to <code>dl/{0}</code>. For playing use:\n<code>.cplaya dl/{0}</code>\n<code>.cplayv dl/{0}</code>",
}
async def client_ready(self, client, _):
self.client = client
self.call = PyTgCalls(client)
@self.call.on_stream_end()
async def _(_, update):
with contextlib.suppress(Exception):
await self.call.leave_group_call(update.chat_id)
await self.call.start()
async def parse_args(self, args):
if not args or not re.match(
r"http(?:s?):\/\/(?:www\.)?youtu(?:be\.com\/watch\?v=|\.be\/)([\w\-\_]*)(&(amp;)?[\w\?=]*)?",
args,
):
return args
with youtube_dl.YoutubeDL({"format": "best"}) as ydl:
info = ydl.extract_info(args, download=False)
return info["formats"][0]["url"]
async def cdlcmd(self, m: types.Message):
"<reply_to_media> <name: optional> - Download media to server in `dl` folder"
args = utils.get_args_raw(m)
reply = await m.get_reply_message()
if not reply:
return await utils.answer(m, self.strings("noreply"))
name = args or reply.file.name
try:
m = await utils.answer(m, self.strings("downloading"))
await reply.download_media(f"dl/{name}")
await utils.answer(m, self.strings("downloaded").format(name))
except Exception as e:
await utils.answer(m, self.strings("error").format(str(e)))
async def clscmd(self, m: types.Message):
"List all files in `dl` folder"
if not os.path.isdir("dl") or not os.listdir("dl"):
return await utils.answer(m, self.strings("nofiles"))
files = [f"<code>dl/{f}</code>" for f in os.listdir("dl")]
await utils.answer(m, "\n".join(files))
# command for deleting file from dl folder
async def cdelcmd(self, m: types.Message):
"<name> - Delete file from `dl` folder"
args = utils.get_args_raw(m)
if not args:
return await utils.answer(m, self.strings("noargs"))
if not args.startswith("dl/"):
args = f"dl/{args}"
if not os.path.isfile(f"{args}"):
return await utils.answer(m, self.strings("nofile"))
try:
os.remove(f"{args}")
await utils.answer(m, self.strings("deleted").format(args))
except Exception as e:
await utils.answer(m, self.strings("error").format(str(e)))
async def cplayvcmd(self, m: types.Message):
"<link/path/reply_to_video> - Play video in voice chat"
try:
reply = await m.get_reply_message()
path = await self.parse_args(utils.get_args_raw(m))
chat = m.chat.id
if not path:
if not reply:
return await utils.answer(m, self.strings("noargs"))
m = await utils.answer(m, self.strings("downloading"))
path = await reply.download_media()
with contextlib.suppress(pytgcalls.exceptions.GroupCallNotFound):
self.call.get_active_call(chat)
await self.call.leave_group_call(chat)
await self.call.join_group_call(
chat,
AudioVideoPiped(
path,
HighQualityAudio(),
HighQualityVideo(),
),
stream_type=StreamType().pulse_stream,
)
await utils.answer(m, self.strings("playing"))
except Exception as e:
await utils.answer(m, self.strings("error").format(str(e)))
async def cplayacmd(self, m: types.Message):
"<link/path/reply_to_audio> - Play audio in voice chat"
try:
reply = await m.get_reply_message()
path = await self.parse_args(utils.get_args_raw(m))
chat = m.chat.id
if not path:
if not reply:
return await utils.answer(m, self.strings("noargs"))
m = await utils.answer(m, self.strings("downloading"))
path = await reply.download_media()
with contextlib.suppress(pytgcalls.exceptions.GroupCallNotFound):
self.call.get_active_call(chat)
await self.call.leave_group_call(chat)
await self.call.join_group_call(
chat,
AudioPiped(
path,
HighQualityAudio(),
),
stream_type=StreamType().pulse_stream,
)
await utils.answer(m, self.strings("playing"))
except Exception as e:
await utils.answer(m, self.strings("error").format(str(e)))
async def cleavecmd(self, m: types.Message):
"Leave"
try:
self.call.get_active_call(m.chat.id)
await self.call.leave_group_call(m.chat.id)
await utils.answer(m, self.strings("leave"))
except pytgcalls.exceptions.GroupCallNotFound:
await utils.answer(m, self.strings("notjoined"))
except Exception as e:
await utils.answer(m, self.strings("error").format(str(e)))
async def cmutecmd(self, m: types.Message):
"Mute"
try:
self.call.get_active_call(m.chat.id)
await self.call.mute_stream(m.chat.id)
await utils.answer(m, self.strings("mute"))
except pytgcalls.exceptions.GroupCallNotFound:
await utils.answer(m, self.strings("notjoined"))
except Exception as e:
await utils.answer(m, self.strings("error").format(str(e)))
async def cunmutecmd(self, m: types.Message):
"Unmute"
try:
self.call.get_active_call(m.chat.id)
await self.call.unmute_stream(m.chat.id)
await utils.answer(m, self.strings("unmute"))
except pytgcalls.exceptions.GroupCallNotFound:
await utils.answer(m, self.strings("notjoined"))
except Exception as e:
await utils.answer(m, self.strings("error").format(str(e)))
async def cpausecmd(self, m: types.Message):
"Pause"
try:
self.call.get_active_call(m.chat.id)
await self.call.pause_stream(m.chat.id)
await utils.answer(m, self.strings("pause"))
except pytgcalls.exceptions.GroupCallNotFound:
await utils.answer(m, self.strings("notjoined"))
except Exception as e:
await utils.answer(m, self.strings("error").format(str(e)))
async def cresumecmd(self, m: types.Message):
"Resume"
try:
self.call.get_active_call(m.chat.id)
await self.call.resume_stream(m.chat.id)
await utils.answer(m, self.strings("resume"))
except pytgcalls.exceptions.GroupCallNotFound:
await utils.answer(m, self.strings("notjoined"))
except Exception as e:
await utils.answer(m, self.strings("error").format(str(e)))
# .------.------.------.------.------.------.------.------.------.------.
# |D.--. |4.--. |N.--. |1.--. |3.--. |L.--. |3.--. |K.--. |0.--. |0.--. |
# | :/\: | :/\: | :(): | :/\: | :(): | :/\: | :(): | :/\: | :/\: | :/\: |
# | (__) | :\/: | ()() | (__) | ()() | (__) | ()() | :\/: | :\/: | :\/: |
# | '--'D| '--'4| '--'N| '--'1| '--'3| '--'L| '--'3| '--'K| '--'0| '--'0|
# `------`------`------`------`------`------`------`------`------`------'
#
# Copyright 2022 t.me/D4n13l3k00
# Licensed under the Creative Commons CC BY-NC-ND 4.0
#
# Full license text can be found at:
# https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode
#
# Human-friendly one:
# https://creativecommons.org/licenses/by-nc-nd/4.0
import contextlib
import os
import re
from typing import *
import pytgcalls
import youtube_dl
from pytgcalls import PyTgCalls, StreamType
from pytgcalls.types.input_stream import AudioPiped, AudioVideoPiped
from pytgcalls.types.input_stream.quality import HighQualityAudio, HighQualityVideo
from telethon import types
from .. import loader, utils
# meta developer: @D4n13l3k00
# requires: py-tgcalls youtube-dl
@loader.tds
class ChatVoiceMod(loader.Module):
"""Module for working with voicechat"""
strings = {
"name": "ChatVoiceMod",
"downloading": "<b>[ChatVoiceMod]</b> Downloading...",
"playing": "<b>[ChatVoiceMod]</b> Playing...",
"notjoined": "<b>[ChatVoiceMod]</b> You are not joined",
"stop": "<b>[ChatVoiceMod]</b> Playing stopped!",
"leave": "<b>[ChatVoiceMod]</b> Leaved!",
"pause": "<b>[ChatVoiceMod]</b> Paused!",
"resume": "<b>[ChatVoiceMod]</b> Resumed!",
"mute": "<b>[ChatVoiceMod]</b> Muted!",
"unmute": "<b>[ChatVoiceMod]</b> Unmuted!",
"error": "<b>[ChatVoiceMod]</b> Error: <code>{}</code>",
"noargs": "<b>[ChatVoiceMod]</b> No args",
"noreply": "<b>[ChatVoiceMod]</b> No reply",
"nofile": "<b>[ChatVoiceMod]</b> No file",
"nofiles": "<b>[ChatVoiceMod]</b> No files",
"deleted": "<b>[ChatVoiceMod]</b> <code>{}</code> successfully deleted",
"downloaded": "<b>[ChatVoiceMod]</b> Downloaded to <code>dl/{0}</code>. For playing use:\n<code>.cplaya dl/{0}</code>\n<code>.cplayv dl/{0}</code>",
}
async def client_ready(self, client, _):
self.client = client
self.call = PyTgCalls(client)
@self.call.on_stream_end()
async def _(_, update):
with contextlib.suppress(Exception):
await self.call.leave_group_call(update.chat_id)
await self.call.start()
async def parse_args(self, args):
if not args or not re.match(
r"http(?:s?):\/\/(?:www\.)?youtu(?:be\.com\/watch\?v=|\.be\/)([\w\-\_]*)(&(amp;)?[\w\?=]*)?",
args,
):
return args
with youtube_dl.YoutubeDL({"format": "best"}) as ydl:
info = ydl.extract_info(args, download=False)
return info["formats"][0]["url"]
async def cdlcmd(self, m: types.Message):
"<reply_to_media> <name: optional> - Download media to server in `dl` folder"
args = utils.get_args_raw(m)
reply = await m.get_reply_message()
if not reply:
return await utils.answer(m, self.strings("noreply"))
name = args or reply.file.name
try:
m = await utils.answer(m, self.strings("downloading"))
await reply.download_media(f"dl/{name}")
await utils.answer(m, self.strings("downloaded").format(name))
except Exception as e:
await utils.answer(m, self.strings("error").format(str(e)))
async def clscmd(self, m: types.Message):
"List all files in `dl` folder"
if not os.path.isdir("dl") or not os.listdir("dl"):
return await utils.answer(m, self.strings("nofiles"))
files = [f"<code>dl/{f}</code>" for f in os.listdir("dl")]
await utils.answer(m, "\n".join(files))
# command for deleting file from dl folder
async def cdelcmd(self, m: types.Message):
"<name> - Delete file from `dl` folder"
args = utils.get_args_raw(m)
if not args:
return await utils.answer(m, self.strings("noargs"))
if not args.startswith("dl/"):
args = f"dl/{args}"
if not os.path.isfile(f"{args}"):
return await utils.answer(m, self.strings("nofile"))
try:
os.remove(f"{args}")
await utils.answer(m, self.strings("deleted").format(args))
except Exception as e:
await utils.answer(m, self.strings("error").format(str(e)))
async def cplayvcmd(self, m: types.Message):
"<link/path/reply_to_video> - Play video in voice chat"
try:
reply = await m.get_reply_message()
path = await self.parse_args(utils.get_args_raw(m))
chat = m.chat.id
if not path:
if not reply:
return await utils.answer(m, self.strings("noargs"))
m = await utils.answer(m, self.strings("downloading"))
path = await reply.download_media()
with contextlib.suppress(pytgcalls.exceptions.GroupCallNotFound):
self.call.get_active_call(chat)
await self.call.leave_group_call(chat)
await self.call.join_group_call(
chat,
AudioVideoPiped(
path,
HighQualityAudio(),
HighQualityVideo(),
),
stream_type=StreamType().pulse_stream,
)
await utils.answer(m, self.strings("playing"))
except Exception as e:
await utils.answer(m, self.strings("error").format(str(e)))
async def cplayacmd(self, m: types.Message):
"<link/path/reply_to_audio> - Play audio in voice chat"
try:
reply = await m.get_reply_message()
path = await self.parse_args(utils.get_args_raw(m))
chat = m.chat.id
if not path:
if not reply:
return await utils.answer(m, self.strings("noargs"))
m = await utils.answer(m, self.strings("downloading"))
path = await reply.download_media()
with contextlib.suppress(pytgcalls.exceptions.GroupCallNotFound):
self.call.get_active_call(chat)
await self.call.leave_group_call(chat)
await self.call.join_group_call(
chat,
AudioPiped(
path,
HighQualityAudio(),
),
stream_type=StreamType().pulse_stream,
)
await utils.answer(m, self.strings("playing"))
except Exception as e:
await utils.answer(m, self.strings("error").format(str(e)))
async def cleavecmd(self, m: types.Message):
"Leave"
try:
self.call.get_active_call(m.chat.id)
await self.call.leave_group_call(m.chat.id)
await utils.answer(m, self.strings("leave"))
except pytgcalls.exceptions.GroupCallNotFound:
await utils.answer(m, self.strings("notjoined"))
except Exception as e:
await utils.answer(m, self.strings("error").format(str(e)))
async def cmutecmd(self, m: types.Message):
"Mute"
try:
self.call.get_active_call(m.chat.id)
await self.call.mute_stream(m.chat.id)
await utils.answer(m, self.strings("mute"))
except pytgcalls.exceptions.GroupCallNotFound:
await utils.answer(m, self.strings("notjoined"))
except Exception as e:
await utils.answer(m, self.strings("error").format(str(e)))
async def cunmutecmd(self, m: types.Message):
"Unmute"
try:
self.call.get_active_call(m.chat.id)
await self.call.unmute_stream(m.chat.id)
await utils.answer(m, self.strings("unmute"))
except pytgcalls.exceptions.GroupCallNotFound:
await utils.answer(m, self.strings("notjoined"))
except Exception as e:
await utils.answer(m, self.strings("error").format(str(e)))
async def cpausecmd(self, m: types.Message):
"Pause"
try:
self.call.get_active_call(m.chat.id)
await self.call.pause_stream(m.chat.id)
await utils.answer(m, self.strings("pause"))
except pytgcalls.exceptions.GroupCallNotFound:
await utils.answer(m, self.strings("notjoined"))
except Exception as e:
await utils.answer(m, self.strings("error").format(str(e)))
async def cresumecmd(self, m: types.Message):
"Resume"
try:
self.call.get_active_call(m.chat.id)
await self.call.resume_stream(m.chat.id)
await utils.answer(m, self.strings("resume"))
except pytgcalls.exceptions.GroupCallNotFound:
await utils.answer(m, self.strings("notjoined"))
except Exception as e:
await utils.answer(m, self.strings("error").format(str(e)))

View File

@@ -1,74 +1,74 @@
# By @vreply @pernel_kanic @nim1love @db0mb3r and geyporn by @tshipenchko
import requests
from .. import loader, utils
def register(cb):
cb(TextGeneratorMod())
class TextGeneratorMod(loader.Module):
"Generating text using machine learning"
strings = {
"name": "TextGenerator",
"no_text": "<strong>Empty message</strong>",
"wait": "<strong>Generating text...</strong>",
}
async def pfcmd(self, message):
"""Generates text with Porfirevich: porfirevich.ru"""
text = utils.get_args_raw(message)
reply = await message.get_reply_message()
if text:
if reply:
text = reply.raw_text + text
elif reply:
text = reply.raw_text
else:
return await utils.answer(message, self.strings("no_text", message))
message = await utils.answer(message, self.strings("wait", message))
response = (
await utils.run_sync(
requests.post,
"https://pelevin.gpt.dobro.ai/generate/",
json={"prompt": text, "length": 30},
)
).json()
return await utils.answer(
message, f"<strong>{text}</strong>" + response["replies"][-1]
)
async def gptcmd(self, message):
"""Generates text with ruGPT-3 XL: russiannlp.github.io/rugpt-demo/"""
text = utils.get_args_raw(message)
reply = await message.get_reply_message()
if text:
if reply:
text = reply.raw_text + text
elif reply:
text = reply.raw_text
else:
return await utils.answer(message, self.strings("no_text", message))
message = await utils.answer(message, self.strings("wait", message))
response = (
await utils.run_sync(
requests.post,
"https://api.aicloud.sbercloud.ru/public/v1/public_inference/gpt3/predict",
json={"text": text},
)
).json()
return await utils.answer(
message,
"<strong>"
+ text
+ "</strong>"
+ response["predictions"].split(text.split()[-1], maxsplit=1)[1],
)
# By @vreply @pernel_kanic @nim1love @db0mb3r and geyporn by @tshipenchko
import requests
from .. import loader, utils
def register(cb):
cb(TextGeneratorMod())
class TextGeneratorMod(loader.Module):
"Generating text using machine learning"
strings = {
"name": "TextGenerator",
"no_text": "<strong>Empty message</strong>",
"wait": "<strong>Generating text...</strong>",
}
async def pfcmd(self, message):
"""Generates text with Porfirevich: porfirevich.ru"""
text = utils.get_args_raw(message)
reply = await message.get_reply_message()
if text:
if reply:
text = reply.raw_text + text
elif reply:
text = reply.raw_text
else:
return await utils.answer(message, self.strings("no_text", message))
message = await utils.answer(message, self.strings("wait", message))
response = (
await utils.run_sync(
requests.post,
"https://pelevin.gpt.dobro.ai/generate/",
json={"prompt": text, "length": 30},
)
).json()
return await utils.answer(
message, f"<strong>{text}</strong>" + response["replies"][-1]
)
async def gptcmd(self, message):
"""Generates text with ruGPT-3 XL: russiannlp.github.io/rugpt-demo/"""
text = utils.get_args_raw(message)
reply = await message.get_reply_message()
if text:
if reply:
text = reply.raw_text + text
elif reply:
text = reply.raw_text
else:
return await utils.answer(message, self.strings("no_text", message))
message = await utils.answer(message, self.strings("wait", message))
response = (
await utils.run_sync(
requests.post,
"https://api.aicloud.sbercloud.ru/public/v1/public_inference/gpt3/predict",
json={"text": text},
)
).json()
return await utils.answer(
message,
"<strong>"
+ text
+ "</strong>"
+ response["predictions"].split(text.split()[-1], maxsplit=1)[1],
)

View File

@@ -1,39 +1,39 @@
from .. import loader, utils # pylint: disable=relative-beyond-top-level
from requests import post
import io
@loader.tds
class x0Mod(loader.Module):
"""Uploader"""
strings = {
"name": "x0 Uploader"
}
async def client_ready(self, client, db):
self.client = client
@loader.sudo
async def x0cmd(self, message):
await message.edit("<b>Uploading...</b>")
reply = await message.get_reply_message()
if not reply:
await message.edit("<b>Reply to message!</b>")
return
media = reply.media
if not media:
file = io.BytesIO(bytes(reply.raw_text, "utf-8"))
file.name = "txt.txt"
else:
file = io.BytesIO(await self.client.download_file(media))
file.name = reply.file.name if reply.file.name else reply.file.id+reply.file.ext
try:
x0at = post('https://x0.at', files={'file': file})
except ConnectionError as e:
await message.edit(ste(e))
return
url = x0at.text
output = f'<a href="{url}">URL: </a><code>{url}</code>'
await message.edit(output)
from .. import loader, utils # pylint: disable=relative-beyond-top-level
from requests import post
import io
@loader.tds
class x0Mod(loader.Module):
"""Uploader"""
strings = {
"name": "x0 Uploader"
}
async def client_ready(self, client, db):
self.client = client
@loader.sudo
async def x0cmd(self, message):
await message.edit("<b>Uploading...</b>")
reply = await message.get_reply_message()
if not reply:
await message.edit("<b>Reply to message!</b>")
return
media = reply.media
if not media:
file = io.BytesIO(bytes(reply.raw_text, "utf-8"))
file.name = "txt.txt"
else:
file = io.BytesIO(await self.client.download_file(media))
file.name = reply.file.name if reply.file.name else reply.file.id+reply.file.ext
try:
x0at = post('https://x0.at', files={'file': file})
except ConnectionError as e:
await message.edit(ste(e))
return
url = x0at.text
output = f'<a href="{url}">URL: </a><code>{url}</code>'
await message.edit(output)

View File

@@ -1,105 +1,105 @@
from .. import loader, utils # pylint: disable=relative-beyond-top-level
from PIL import Image, ImageDraw, ImageOps, ImageFilter
import io
from telethon.tl.types import DocumentAttributeFilename
import logging
from moviepy.editor import VideoFileClip
import os
logger = logging.getLogger(__name__)
def register(cb):
cb(CirclesMod())
@loader.tds
class CirclesMod(loader.Module):
"""округляет всё"""
strings = {
"name": "Circles"
}
def __init__(self):
self.name = self.strings['name']
async def client_ready(self, client, db):
self.client = client
@loader.sudo
async def roundcmd(self, message):
""".round <Reply to image/sticker or video/gif>"""
reply = None
if message.is_reply:
reply = await message.get_reply_message()
data = await check_media(reply)
if isinstance(data, bool):
await utils.answer(message, "<b>Reply to image/sticker or video/gif!</b>")
return
else:
await utils.answer(message, "<b>Reply to image/sticker or video/gif!</b>")
return
data, type = data
if type == "img":
await message.edit("<b>Processing image</b>📷")
img = io.BytesIO()
bytes = await message.client.download_file(data, img)
im = Image.open(img)
w, h = im.size
img = Image.new("RGBA", (w,h), (0,0,0,0))
img.paste(im, (0, 0))
m = min(w, h)
img = img.crop(((w-m)//2, (h-m)//2, (w+m)//2, (h+m)//2))
w, h = img.size
mask = Image.new('L', (w, h), 0)
draw = ImageDraw.Draw(mask)
draw.ellipse((10, 10, w-10, h-10), fill=255)
mask = mask.filter(ImageFilter.GaussianBlur(2))
img = ImageOps.fit(img, (w, h))
img.putalpha(mask)
im = io.BytesIO()
im.name = "img.webp"
img.save(im)
im.seek(0)
await message.client.send_file(message.to_id, im, reply_to=reply)
else:
await message.edit("<b>Processing video</b>🎥")
await message.client.download_file(data, "video.mp4")
video = VideoFileClip("video.mp4")
video.reader.close()
w, h = video.size
m = min(w, h)
box = [(w-m)//2, (h-m)//2, (w+m)//2, (h+m)//2]
video = video.crop(*box)
await message.edit("<b>Saving video</b>📼")
video.write_videofile("result.mp4")
await message.client.send_file(message.to_id, "result.mp4", video_note=True, reply_to=reply)
os.remove("video.mp4")
os.remove("result.mp4")
await message.delete()
async def check_media(reply):
type = "img"
if reply and reply.media:
if reply.photo:
data = reply.photo
elif reply.document:
if DocumentAttributeFilename(file_name='AnimatedSticker.tgs') in reply.media.document.attributes:
return False
if reply.gif or reply.video:
type = "vid"
if reply.audio or reply.voice:
return False
data = reply.media.document
else:
return False
else:
return False
if not data or data is None:
return False
else:
return (data, type)
from .. import loader, utils # pylint: disable=relative-beyond-top-level
from PIL import Image, ImageDraw, ImageOps, ImageFilter
import io
from telethon.tl.types import DocumentAttributeFilename
import logging
from moviepy.editor import VideoFileClip
import os
logger = logging.getLogger(__name__)
def register(cb):
cb(CirclesMod())
@loader.tds
class CirclesMod(loader.Module):
"""округляет всё"""
strings = {
"name": "Circles"
}
def __init__(self):
self.name = self.strings['name']
async def client_ready(self, client, db):
self.client = client
@loader.sudo
async def roundcmd(self, message):
""".round <Reply to image/sticker or video/gif>"""
reply = None
if message.is_reply:
reply = await message.get_reply_message()
data = await check_media(reply)
if isinstance(data, bool):
await utils.answer(message, "<b>Reply to image/sticker or video/gif!</b>")
return
else:
await utils.answer(message, "<b>Reply to image/sticker or video/gif!</b>")
return
data, type = data
if type == "img":
await message.edit("<b>Processing image</b>📷")
img = io.BytesIO()
bytes = await message.client.download_file(data, img)
im = Image.open(img)
w, h = im.size
img = Image.new("RGBA", (w,h), (0,0,0,0))
img.paste(im, (0, 0))
m = min(w, h)
img = img.crop(((w-m)//2, (h-m)//2, (w+m)//2, (h+m)//2))
w, h = img.size
mask = Image.new('L', (w, h), 0)
draw = ImageDraw.Draw(mask)
draw.ellipse((10, 10, w-10, h-10), fill=255)
mask = mask.filter(ImageFilter.GaussianBlur(2))
img = ImageOps.fit(img, (w, h))
img.putalpha(mask)
im = io.BytesIO()
im.name = "img.webp"
img.save(im)
im.seek(0)
await message.client.send_file(message.to_id, im, reply_to=reply)
else:
await message.edit("<b>Processing video</b>🎥")
await message.client.download_file(data, "video.mp4")
video = VideoFileClip("video.mp4")
video.reader.close()
w, h = video.size
m = min(w, h)
box = [(w-m)//2, (h-m)//2, (w+m)//2, (h+m)//2]
video = video.crop(*box)
await message.edit("<b>Saving video</b>📼")
video.write_videofile("result.mp4")
await message.client.send_file(message.to_id, "result.mp4", video_note=True, reply_to=reply)
os.remove("video.mp4")
os.remove("result.mp4")
await message.delete()
async def check_media(reply):
type = "img"
if reply and reply.media:
if reply.photo:
data = reply.photo
elif reply.document:
if DocumentAttributeFilename(file_name='AnimatedSticker.tgs') in reply.media.document.attributes:
return False
if reply.gif or reply.video:
type = "vid"
if reply.audio or reply.voice:
return False
data = reply.media.document
else:
return False
else:
return False
if not data or data is None:
return False
else:
return (data, type)

View File

@@ -1,111 +1,111 @@
# requires: pillow
# requires: wand
from .. import loader, utils
import io
from telethon.tl.types import DocumentAttributeFilename
import logging
from wand.image import Image
from PIL import Image as IM
# https://t.me/KeyZenD
# https://t.me/SomeScripts
logger = logging.getLogger(__name__)
def register(cb):
cb(DistortNoApiMod())
@loader.tds
class DistortNoApiMod(loader.Module):
"""distorting images"""
strings = {
"name": "DistortNoApi"
}
async def client_ready(self, client, db):
self.client = client
@loader.sudo
async def distortcmd(self, message):
""".distort <reply to photo>
.distort im
.distort 50
.distort 50 im
.distort im 50
im => кидает стикеры как фото
50 => (от 0 до дохуя) процент сжатия"""
if message.is_reply:
reply_message = await message.get_reply_message()
data, mime = await check_media(reply_message)
if isinstance(data, bool):
await utils.answer(message, "<code>Reply to image or stick!</code>")
return
else:
await utils.answer(message, "<code>Reply to image or stick!</code>")
return
rescale_rate = 70
a = utils.get_args(message)
force_file = False
if a:
if 'im' in a:
force_file = True
a.remove('im')
if len(a) > 0:
if a[0].isdigit():
rescale_rate = int(a[0])
if rescale_rate <= 0:
rescale_rate = 70
await message.edit("<code>D i s t o r t i n g . . .</code>")
file = await message.client.download_media(data, bytes)
file, img = io.BytesIO(file), io.BytesIO()
img.name = 'img.png'
IM.open(file).save(img, 'PNG')
media = await distort(io.BytesIO(img.getvalue()), rescale_rate)
out, im = io.BytesIO(), IM.open(media)
if force_file:
mime = 'png'
out.name = f'out.{mime}'
im.save(out, mime.upper())
out.seek(0)
await message.edit("<code>S e n d i n g . . .</code>")
await message.client.send_file(message.to_id, out, reply_to=reply_message.id)
await message.delete()
async def distort(file, rescale_rate):
img = Image(file=file)
x, y = img.size[0], img.size[1]
popx = int(rescale_rate*(x//100))
popy = int(rescale_rate*(y//100))
img.liquid_rescale(popx, popy, delta_x=1, rigidity=0)
img.resize(x, y)
out = io.BytesIO()
out.name = f'output.png'
img.save(file=out)
return io.BytesIO(out.getvalue())
async def check_media(reply_message):
mime = None
if reply_message and reply_message.media:
if reply_message.photo:
data = reply_message.photo
mime = 'image/jpeg'
elif reply_message.document:
if DocumentAttributeFilename(file_name='AnimatedSticker.tgs') in reply_message.media.document.attributes:
return False, mime
if reply_message.gif or reply_message.video or reply_message.audio or reply_message.voice:
return False, mime
data = reply_message.media.document
mime = reply_message.media.document.mime_type
if 'image/' not in mime:
return False, mime
else:
return False, mime
else:
return False, mime
if not data or data is None:
return False, mime
else:
mime = mime.split('/')[1]
return data, mime
# requires: pillow
# requires: wand
from .. import loader, utils
import io
from telethon.tl.types import DocumentAttributeFilename
import logging
from wand.image import Image
from PIL import Image as IM
# https://t.me/KeyZenD
# https://t.me/SomeScripts
logger = logging.getLogger(__name__)
def register(cb):
cb(DistortNoApiMod())
@loader.tds
class DistortNoApiMod(loader.Module):
"""distorting images"""
strings = {
"name": "DistortNoApi"
}
async def client_ready(self, client, db):
self.client = client
@loader.sudo
async def distortcmd(self, message):
""".distort <reply to photo>
.distort im
.distort 50
.distort 50 im
.distort im 50
im => кидает стикеры как фото
50 => (от 0 до дохуя) процент сжатия"""
if message.is_reply:
reply_message = await message.get_reply_message()
data, mime = await check_media(reply_message)
if isinstance(data, bool):
await utils.answer(message, "<code>Reply to image or stick!</code>")
return
else:
await utils.answer(message, "<code>Reply to image or stick!</code>")
return
rescale_rate = 70
a = utils.get_args(message)
force_file = False
if a:
if 'im' in a:
force_file = True
a.remove('im')
if len(a) > 0:
if a[0].isdigit():
rescale_rate = int(a[0])
if rescale_rate <= 0:
rescale_rate = 70
await message.edit("<code>D i s t o r t i n g . . .</code>")
file = await message.client.download_media(data, bytes)
file, img = io.BytesIO(file), io.BytesIO()
img.name = 'img.png'
IM.open(file).save(img, 'PNG')
media = await distort(io.BytesIO(img.getvalue()), rescale_rate)
out, im = io.BytesIO(), IM.open(media)
if force_file:
mime = 'png'
out.name = f'out.{mime}'
im.save(out, mime.upper())
out.seek(0)
await message.edit("<code>S e n d i n g . . .</code>")
await message.client.send_file(message.to_id, out, reply_to=reply_message.id)
await message.delete()
async def distort(file, rescale_rate):
img = Image(file=file)
x, y = img.size[0], img.size[1]
popx = int(rescale_rate*(x//100))
popy = int(rescale_rate*(y//100))
img.liquid_rescale(popx, popy, delta_x=1, rigidity=0)
img.resize(x, y)
out = io.BytesIO()
out.name = f'output.png'
img.save(file=out)
return io.BytesIO(out.getvalue())
async def check_media(reply_message):
mime = None
if reply_message and reply_message.media:
if reply_message.photo:
data = reply_message.photo
mime = 'image/jpeg'
elif reply_message.document:
if DocumentAttributeFilename(file_name='AnimatedSticker.tgs') in reply_message.media.document.attributes:
return False, mime
if reply_message.gif or reply_message.video or reply_message.audio or reply_message.voice:
return False, mime
data = reply_message.media.document
mime = reply_message.media.document.mime_type
if 'image/' not in mime:
return False, mime
else:
return False, mime
else:
return False, mime
if not data or data is None:
return False, mime
else:
mime = mime.split('/')[1]
return data, mime

View File

@@ -1,68 +1,68 @@
import asyncio
import logging
import sys, os, random
from .. import loader, utils
logger = logging.getLogger(__name__)
@loader.tds
class GlitcherMod(loader.Module):
"""Glitcher of anything"""
strings = {"name": "Glitcher",
"reply": "Reply to message!",
"error": "Impossible to upload file!",
"processing": "Work in progress!"}
@loader.unrestricted
async def glitchcmd(self, message):
""".glitch level: float or int <reply to anything>"""
reply = await message.get_reply_message()
if not reply:
await message.edit("".join([ random.choice(html).format(ch) for ch in self.strings("reply", message)]))
return
if not reply.file:
infile = "message.txt"
f = open(infile,"w")
f.write(reply.text)
f.close()
outfile = "glitched_message.txt"
else:
infile = await reply.download_media()
outfile = "glitched_"+infile
percent = 0.1
try:
percent = float(utils.get_args_raw(message))
except ValueError or TypeError:
pass
await message.edit("".join([ random.choice(html).format(ch) for ch in self.strings("processing", message)]))
with open(infile, 'rb') as inf:
with open(outfile, 'wb') as outf:
fileext = infile.split(".")[1]
try:
for byte in range(headersize[fileext]):
inbyte = inf.read(1)
outbyte = inbyte
outf.write(outbyte)
except KeyError:
pass
while True:
inbyte = inf.read(1)
if not inbyte:
break
if (random.random() < percent/100):
outbyte = os.urandom(1)
else:
outbyte = inbyte
outf.write(outbyte)
try:
await reply.reply(file=outfile)
await message.delete()
except:
await message.edit("".join([ random.choice(html).format(ch) for ch in self.strings("error", message) ]))
finally:
[os.remove(file) for file in [infile, outfile]]
html = ["<b>{}<b>", "<code>{}</code>", "<i>{}</i>", "<del>{}</del>", "<u>{}</u>", '<a href="https://bruh.moment">{}</a>']
headersize = {'jpg': 9, 'png': 8, 'bmp': 54, 'gif': 14, 'tiff': 8}
import asyncio
import logging
import sys, os, random
from .. import loader, utils
logger = logging.getLogger(__name__)
@loader.tds
class GlitcherMod(loader.Module):
"""Glitcher of anything"""
strings = {"name": "Glitcher",
"reply": "Reply to message!",
"error": "Impossible to upload file!",
"processing": "Work in progress!"}
@loader.unrestricted
async def glitchcmd(self, message):
""".glitch level: float or int <reply to anything>"""
reply = await message.get_reply_message()
if not reply:
await message.edit("".join([ random.choice(html).format(ch) for ch in self.strings("reply", message)]))
return
if not reply.file:
infile = "message.txt"
f = open(infile,"w")
f.write(reply.text)
f.close()
outfile = "glitched_message.txt"
else:
infile = await reply.download_media()
outfile = "glitched_"+infile
percent = 0.1
try:
percent = float(utils.get_args_raw(message))
except ValueError or TypeError:
pass
await message.edit("".join([ random.choice(html).format(ch) for ch in self.strings("processing", message)]))
with open(infile, 'rb') as inf:
with open(outfile, 'wb') as outf:
fileext = infile.split(".")[1]
try:
for byte in range(headersize[fileext]):
inbyte = inf.read(1)
outbyte = inbyte
outf.write(outbyte)
except KeyError:
pass
while True:
inbyte = inf.read(1)
if not inbyte:
break
if (random.random() < percent/100):
outbyte = os.urandom(1)
else:
outbyte = inbyte
outf.write(outbyte)
try:
await reply.reply(file=outfile)
await message.delete()
except:
await message.edit("".join([ random.choice(html).format(ch) for ch in self.strings("error", message) ]))
finally:
[os.remove(file) for file in [infile, outfile]]
html = ["<b>{}<b>", "<code>{}</code>", "<i>{}</i>", "<del>{}</del>", "<u>{}</u>", '<a href="https://bruh.moment">{}</a>']
headersize = {'jpg': 9, 'png': 8, 'bmp': 54, 'gif': 14, 'tiff': 8}

View File

@@ -1,70 +1,70 @@
from .. import loader, utils
from hashlib import md5, sha1, sha224, sha256, sha384, sha512, blake2b, blake2s
def register(cb):
cb(HasherMod())
class HasherMod(loader.Module):
"""Hashing text and files"""
strings = {'name': 'Hasher'}
def __init__(self):
self.name = self.strings['name']
self._me = None
self._ratelimit = []
async def client_ready(self, client, db):
self._db = db
self._client = client
self.me = await client.get_me()
async def md5cmd(self, message):
""".md5 <(text or media) or (reply to text or media)>\nHashing to md5"""
await hashing(message, 0)
async def sha1cmd(self, message):
""".sha1 <(text or media) or (reply to text or media)\nHashing to sha1"""
await hashing(message, 1)
async def sha224cmd(self, message):
""".sha224 <(text or media) or (reply to text or media)\nHashing to sha224"""
await hashing(message, 2)
async def sha256cmd(self, message):
""".sha255 <(text or media) or (reply to text or media)\nHashing to sha256"""
await hashing(message, 3)
async def sha384cmd(self, message):
""".sha384 <(text or media) or (reply to text or media)\nHashing to sha384"""
await hashing(message, 4)
async def sha512cmd(self, message):
""".sha512 <(text or media) or (reply to text or media)\nHashing to sha512"""
await hashing(message, 5)
async def blake2bcmd(self, message):
""".blake2 <(text or media) or (reply to text or media)\nHashing to blake2"""
await hashing(message, 6)
async def blake2scmd(self, message):
""".blake2s <(text or media) or (reply to text or media)\nHashing to blake2s"""
await hashing(message, 7)
async def hashing(m, type):
types = [md5, sha1, sha224, sha256, sha384, sha512, blake2b, blake2s]
typez = ["md5", "sha1", "sha224", "sha256", "sha384", "sha512", "blake2b", "blake2s"]
reply = await m.get_reply_message()
mtext = utils.get_args_raw(m)
if m.media:
await m.edit("<b>D o w n l o a d i n g . . .</b>")
data = await m.client.download_file(m, bytes)
elif mtext:
data = mtext.encode()
elif reply:
if reply.media:
await m.edit("<b>D o w n l o a d i n g . . .</b>")
data = await m.client.download_file(reply, bytes)
else:
data = reply.raw_text.encode()
else:
await m.edit(f"<b>What hashing to {typez[type]}?</b>")
return
await m.edit("<b>H a s h i n g . . .</b>")
try:
result = types[type](data)
await m.edit(typez[type].upper()+": <code>" + str(result.hexdigest()).upper()+"</code>")
except:
await m.edit("<b>ERЯOR!</b>")
from .. import loader, utils
from hashlib import md5, sha1, sha224, sha256, sha384, sha512, blake2b, blake2s
def register(cb):
cb(HasherMod())
class HasherMod(loader.Module):
"""Hashing text and files"""
strings = {'name': 'Hasher'}
def __init__(self):
self.name = self.strings['name']
self._me = None
self._ratelimit = []
async def client_ready(self, client, db):
self._db = db
self._client = client
self.me = await client.get_me()
async def md5cmd(self, message):
""".md5 <(text or media) or (reply to text or media)>\nHashing to md5"""
await hashing(message, 0)
async def sha1cmd(self, message):
""".sha1 <(text or media) or (reply to text or media)\nHashing to sha1"""
await hashing(message, 1)
async def sha224cmd(self, message):
""".sha224 <(text or media) or (reply to text or media)\nHashing to sha224"""
await hashing(message, 2)
async def sha256cmd(self, message):
""".sha255 <(text or media) or (reply to text or media)\nHashing to sha256"""
await hashing(message, 3)
async def sha384cmd(self, message):
""".sha384 <(text or media) or (reply to text or media)\nHashing to sha384"""
await hashing(message, 4)
async def sha512cmd(self, message):
""".sha512 <(text or media) or (reply to text or media)\nHashing to sha512"""
await hashing(message, 5)
async def blake2bcmd(self, message):
""".blake2 <(text or media) or (reply to text or media)\nHashing to blake2"""
await hashing(message, 6)
async def blake2scmd(self, message):
""".blake2s <(text or media) or (reply to text or media)\nHashing to blake2s"""
await hashing(message, 7)
async def hashing(m, type):
types = [md5, sha1, sha224, sha256, sha384, sha512, blake2b, blake2s]
typez = ["md5", "sha1", "sha224", "sha256", "sha384", "sha512", "blake2b", "blake2s"]
reply = await m.get_reply_message()
mtext = utils.get_args_raw(m)
if m.media:
await m.edit("<b>D o w n l o a d i n g . . .</b>")
data = await m.client.download_file(m, bytes)
elif mtext:
data = mtext.encode()
elif reply:
if reply.media:
await m.edit("<b>D o w n l o a d i n g . . .</b>")
data = await m.client.download_file(reply, bytes)
else:
data = reply.raw_text.encode()
else:
await m.edit(f"<b>What hashing to {typez[type]}?</b>")
return
await m.edit("<b>H a s h i n g . . .</b>")
try:
result = types[type](data)
await m.edit(typez[type].upper()+": <code>" + str(result.hexdigest()).upper()+"</code>")
except:
await m.edit("<b>ERЯOR!</b>")

View File

@@ -1,44 +1,44 @@
from .. import loader, utils
import io
from requests import get
def register(cb):
cb(LoremIpsumMod())
class LoremIpsumMod(loader.Module):
"""Lorem Ipsum generation"""
strings = {'name': 'LoermIpsum'}
def __init__(self):
self.name = self.strings['name']
async def loremipsumcmd(self, message):
""".loremipsum <count: int> <length: str> <file?>
count - number of paragraphs| std: 1
length - s-short, m-medium, l-long, v-verylong|std: m(edium)
file - if nothing- send as message, if anything- send as file"""
s = 'small'
m = length = 'medium'
l = 'long'
v = 'verylong'
args = utils.get_args(message)
count = 1
as_file = False
if args:
count = int(args[0]) if args[0].isdigit() else 1
if len(args) == 2:
lenght = args[1].lower()
length = s if lenght in [s[:i+1] for i in range(len(s))] else l if lenght in [l[:i+1] for i in range(len(l))] else v if lenght in [v[:i+1] for i in range(len(v))] else m # сижу ахуел
if len(args) >= 3:
as_file = True
url = f"https://loripsum.net/api/{count}/{length}/plaintext"
out = get(url)
if as_file:
out = io.BytesIO(out.content)
out.name = f"LoremIpsum.{count}.txt"
out.seek(0)
else: out = out.text
await utils.answer(message, out)
from .. import loader, utils
import io
from requests import get
def register(cb):
cb(LoremIpsumMod())
class LoremIpsumMod(loader.Module):
"""Lorem Ipsum generation"""
strings = {'name': 'LoermIpsum'}
def __init__(self):
self.name = self.strings['name']
async def loremipsumcmd(self, message):
""".loremipsum <count: int> <length: str> <file?>
count - number of paragraphs| std: 1
length - s-short, m-medium, l-long, v-verylong|std: m(edium)
file - if nothing- send as message, if anything- send as file"""
s = 'small'
m = length = 'medium'
l = 'long'
v = 'verylong'
args = utils.get_args(message)
count = 1
as_file = False
if args:
count = int(args[0]) if args[0].isdigit() else 1
if len(args) == 2:
lenght = args[1].lower()
length = s if lenght in [s[:i+1] for i in range(len(s))] else l if lenght in [l[:i+1] for i in range(len(l))] else v if lenght in [v[:i+1] for i in range(len(v))] else m # сижу ахуел
if len(args) >= 3:
as_file = True
url = f"https://loripsum.net/api/{count}/{length}/plaintext"
out = get(url)
if as_file:
out = io.BytesIO(out.content)
out.name = f"LoremIpsum.{count}.txt"
out.seek(0)
else: out = out.text
await utils.answer(message, out)

View File

@@ -1,33 +1,33 @@
from .. import loader, utils
import io
@loader.tds
class MTFMod(loader.Module):
"""send Message as file"""
strings = {'name': 'MessageToFile'}
async def mtfcmd(self, message):
""".mtf <reply to text>"""
reply = await message.get_reply_message()
if not reply or not reply.message:
await message.edit("<b>Reply to text!</b>")
return
text = bytes(reply.raw_text, "utf8")
fname = utils.get_args_raw(message) or str(message.id+reply.id)+".txt"
file = io.BytesIO(text)
file.name = fname
file.seek(0)
await reply.reply(file=file)
await message.delete()
async def ftmcmd(self, message):
""".ftm <reply to file>"""
reply = await message.get_reply_message()
if not reply or not reply.file:
await message.edit("<b>Reply to file!</b>")
return
text = await reply.download_media(bytes)
text = str(text, "utf8")
if utils.get_args(message):
text = f"<code>{text}</code>"
from .. import loader, utils
import io
@loader.tds
class MTFMod(loader.Module):
"""send Message as file"""
strings = {'name': 'MessageToFile'}
async def mtfcmd(self, message):
""".mtf <reply to text>"""
reply = await message.get_reply_message()
if not reply or not reply.message:
await message.edit("<b>Reply to text!</b>")
return
text = bytes(reply.raw_text, "utf8")
fname = utils.get_args_raw(message) or str(message.id+reply.id)+".txt"
file = io.BytesIO(text)
file.name = fname
file.seek(0)
await reply.reply(file=file)
await message.delete()
async def ftmcmd(self, message):
""".ftm <reply to file>"""
reply = await message.get_reply_message()
if not reply or not reply.file:
await message.edit("<b>Reply to file!</b>")
return
text = await reply.download_media(bytes)
text = str(text, "utf8")
if utils.get_args(message):
text = f"<code>{text}</code>"
await utils.answer(message, utils.escape_html(text))

View File

@@ -1,83 +1,83 @@
# @KeyZenD & @D4n13l3k00
import random
from telethon import types
from .. import loader, utils
@loader.tds
class MegaMozgMod(loader.Module):
strings = {
'name': 'MegaMozg',
'pref': '<b>[MegaMozg]</b> ',
'need_arg': '{}Нужен аргумент',
'status': '{}{}',
'on': '{}Включён',
'off': '{}Выключен',
}
_db_name = 'MegaMozg'
async def client_ready(self, _, db):
self.db = db
@staticmethod
def str2bool(v):
return v.lower() in ("yes", "y", "ye", "yea", "true", "t", "1", "on", "enable", "start", "run", "go", "да")
async def mozgcmd(self, m: types.Message):
'.mozg <on/off/...> - Переключить режим дурачка в чате'
args = utils.get_args_raw(m)
if not m.chat:
return
chat = m.chat.id
if self.str2bool(args):
chats: list = self.db.get(self._db_name, 'chats', [])
chats.append(chat)
chats = list(set(chats))
self.db.set(self._db_name, 'chats', chats)
return await utils.answer(m, self.strings('on').format(self.strings('pref')))
chats: list = self.db.get(self._db_name, 'chats', [])
try:
chats.remove(chat)
except:
pass
chats = list(set(chats))
self.db.set(self._db_name, 'chats', chats)
return await utils.answer(m, self.strings('off').format(self.strings('pref')))
async def mozgchancecmd(self, m: types.Message):
'.mozgchance <int> - Устанвоить шанс 1 к N.\n0 - всегда отвечать'
args: str = utils.get_args_raw(m)
if args.isdigit():
self.db.set(self._db_name, 'chance', int(args))
return await utils.answer(m, self.strings('status').format(self.strings('pref'), args))
return await utils.answer(m, self.strings('need_arg').format(self.strings('pref')))
async def watcher(self, m: types.Message):
if not isinstance(m, types.Message):
return
if m.sender_id == (await m.client.get_me()).id or not m.chat:
return
if m.chat.id not in self.db.get(self._db_name, 'chats', []):
return
ch = self.db.get(self._db_name, 'chance', 0)
if ch != 0:
if random.randint(0, ch) != 0:
return
text = m.raw_text
words = {random.choice(
list(filter(lambda x: len(x) >= 3, text.split()))) for _ in ".."}
msgs = []
for word in words:
[msgs.append(x) async for x in m.client.iter_messages(m.chat.id, search=word) if x.replies and x.replies.max_id]
replier = random.choice(msgs)
sid = replier.id
eid = replier.replies.max_id
msgs = [x async for x in m.client.iter_messages(m.chat.id, ids=list(range(sid+1, eid+1))) if x and x.reply_to and x.reply_to.reply_to_msg_id == sid]
msg = random.choice(msgs)
await m.reply(msg)
# @KeyZenD & @D4n13l3k00
import random
from telethon import types
from .. import loader, utils
@loader.tds
class MegaMozgMod(loader.Module):
strings = {
'name': 'MegaMozg',
'pref': '<b>[MegaMozg]</b> ',
'need_arg': '{}Нужен аргумент',
'status': '{}{}',
'on': '{}Включён',
'off': '{}Выключен',
}
_db_name = 'MegaMozg'
async def client_ready(self, _, db):
self.db = db
@staticmethod
def str2bool(v):
return v.lower() in ("yes", "y", "ye", "yea", "true", "t", "1", "on", "enable", "start", "run", "go", "да")
async def mozgcmd(self, m: types.Message):
'.mozg <on/off/...> - Переключить режим дурачка в чате'
args = utils.get_args_raw(m)
if not m.chat:
return
chat = m.chat.id
if self.str2bool(args):
chats: list = self.db.get(self._db_name, 'chats', [])
chats.append(chat)
chats = list(set(chats))
self.db.set(self._db_name, 'chats', chats)
return await utils.answer(m, self.strings('on').format(self.strings('pref')))
chats: list = self.db.get(self._db_name, 'chats', [])
try:
chats.remove(chat)
except:
pass
chats = list(set(chats))
self.db.set(self._db_name, 'chats', chats)
return await utils.answer(m, self.strings('off').format(self.strings('pref')))
async def mozgchancecmd(self, m: types.Message):
'.mozgchance <int> - Устанвоить шанс 1 к N.\n0 - всегда отвечать'
args: str = utils.get_args_raw(m)
if args.isdigit():
self.db.set(self._db_name, 'chance', int(args))
return await utils.answer(m, self.strings('status').format(self.strings('pref'), args))
return await utils.answer(m, self.strings('need_arg').format(self.strings('pref')))
async def watcher(self, m: types.Message):
if not isinstance(m, types.Message):
return
if m.sender_id == (await m.client.get_me()).id or not m.chat:
return
if m.chat.id not in self.db.get(self._db_name, 'chats', []):
return
ch = self.db.get(self._db_name, 'chance', 0)
if ch != 0:
if random.randint(0, ch) != 0:
return
text = m.raw_text
words = {random.choice(
list(filter(lambda x: len(x) >= 3, text.split()))) for _ in ".."}
msgs = []
for word in words:
[msgs.append(x) async for x in m.client.iter_messages(m.chat.id, search=word) if x.replies and x.replies.max_id]
replier = random.choice(msgs)
sid = replier.id
eid = replier.replies.max_id
msgs = [x async for x in m.client.iter_messages(m.chat.id, ids=list(range(sid+1, eid+1))) if x and x.reply_to and x.reply_to.reply_to_msg_id == sid]
msg = random.choice(msgs)
await m.reply(msg)

View File

@@ -1,51 +1,51 @@
from .. import loader, utils
import io
from PIL import Image, ImageFont, ImageDraw
import requests
import textwrap
@loader.tds
class MicroQuotesMod(loader.Module):
"""Микроцитаты"""
strings = {"name": "MicroQuotes"}
async def mqcmd(self, message):
""".mq <реплай на текст>"""
bw = False if utils.get_args(message) else True
reply = await message.get_reply_message()
if not reply or not reply.raw_text:
await message.edit("<b>Ответь командой на умную цитату!</b>")
return
sender = reply.sender_id
if not sender:
sender = message.chat.id
if sender == 1087968824:
sender = message.chat.id
pfp = await message.client.download_profile_photo(sender, bytes)
await message.edit("<i>И сказал этот гений...</i>")
if not pfp:
pfp = b'BM:\x00\x00\x00\x00\x00\x00\x006\x00\x00\x00(\x00\x00\x00\x01\x00\x00\x00\x01\x00\x00\x00\x01\x00\x18\x00\x00\x00\x00\x00\x04\x00\x00\x00\xc4\x0e\x00\x00\xc4\x0e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\xff\x00'
text = "\n".join(textwrap.wrap(reply.raw_text, 30))
text = ""+text+""
bf = requests.get("https://raw.githubusercontent.com/KeyZenD/l/master/times.ttf").content
font = ImageFont.truetype(io.BytesIO(bf), 50)
im = Image.open(io.BytesIO(pfp))
if bw:
im = im.convert("L")
im = im.convert("RGBA").resize((1024, 1024))
w, h = im.size
w_, h_ = 20*(w//100), 20*(h//100)
im_ = Image.new("RGBA", (w-w_, h-h_), (0, 0, 0))
im_.putalpha(150)
im.paste(im_, (w_//2, h_//2), im_)
draw = ImageDraw.Draw(im)
_w, _h = draw.textsize(text=text, font=font)
x, y = (w-_w)//2, (h-_h)//2
draw.text((x, y), text=text, font=font, fill="#fff", align="center")
output=io.BytesIO()
im.save(output, "PNG")
output.seek(0)
await reply.reply(file=output)
await message.delete()
from .. import loader, utils
import io
from PIL import Image, ImageFont, ImageDraw
import requests
import textwrap
@loader.tds
class MicroQuotesMod(loader.Module):
"""Микроцитаты"""
strings = {"name": "MicroQuotes"}
async def mqcmd(self, message):
""".mq <реплай на текст>"""
bw = False if utils.get_args(message) else True
reply = await message.get_reply_message()
if not reply or not reply.raw_text:
await message.edit("<b>Ответь командой на умную цитату!</b>")
return
sender = reply.sender_id
if not sender:
sender = message.chat.id
if sender == 1087968824:
sender = message.chat.id
pfp = await message.client.download_profile_photo(sender, bytes)
await message.edit("<i>И сказал этот гений...</i>")
if not pfp:
pfp = b'BM:\x00\x00\x00\x00\x00\x00\x006\x00\x00\x00(\x00\x00\x00\x01\x00\x00\x00\x01\x00\x00\x00\x01\x00\x18\x00\x00\x00\x00\x00\x04\x00\x00\x00\xc4\x0e\x00\x00\xc4\x0e\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\xff\x00'
text = "\n".join(textwrap.wrap(reply.raw_text, 30))
text = ""+text+""
bf = requests.get("https://raw.githubusercontent.com/KeyZenD/l/master/times.ttf").content
font = ImageFont.truetype(io.BytesIO(bf), 50)
im = Image.open(io.BytesIO(pfp))
if bw:
im = im.convert("L")
im = im.convert("RGBA").resize((1024, 1024))
w, h = im.size
w_, h_ = 20*(w//100), 20*(h//100)
im_ = Image.new("RGBA", (w-w_, h-h_), (0, 0, 0))
im_.putalpha(150)
im.paste(im_, (w_//2, h_//2), im_)
draw = ImageDraw.Draw(im)
_w, _h = draw.textsize(text=text, font=font)
x, y = (w-_w)//2, (h-_h)//2
draw.text((x, y), text=text, font=font, fill="#fff", align="center")
output=io.BytesIO()
im.save(output, "PNG")
output.seek(0)
await reply.reply(file=output)
await message.delete()

View File

@@ -1,46 +1,46 @@
from .. import loader, utils
from telethon.tl.types import Message
class OneMessageMod(loader.Module):
"""@faq lines"""
strings = {'name': 'OneMessage'}
def __init__(self):
self.name = self.strings['name']
async def client_ready(self, client, db):
self.client = client
self._db = db
@loader.sudo
async def omstartcmd(self, message):
"""Start OneMessage mode"""
self._db.set("OneMessage", "status", True)
self._db.set("OneMessage", "my_id", message.sender_id)
await message.edit("<b>OneMessage mode activated!</b>")
async def omstopcmd(self, message):
"""Stop OneMessage mode"""
self._db.set("OneMessage", "status", False)
await message.edit("<b>OneMessage mode diactivated!</b>")
async def watcher(self, message):
if not isinstance(message, Message):
return
if message.message:
if message.raw_text[0] in self._db.get("friendly-telegram.modules.corectrl", "command_prefix", ".") or message.fwd_from:
return
if self._db.get("OneMessage", "status", None) and message.sender_id == self._db.get("OneMessage", "my_id", None) and not message.media:
last_msg = (await self.client.get_messages(message.to_id, limit=2))[-1]
if last_msg.sender_id == message.sender_id and not last_msg.fwd_from:
text = last_msg.text
text += "\n"*2
text += message.text
if message.is_reply:
message, last_msg = last_msg, message
try:
await last_msg.edit(text)
await message.delete()
except:
return
from .. import loader, utils
from telethon.tl.types import Message
class OneMessageMod(loader.Module):
"""@faq lines"""
strings = {'name': 'OneMessage'}
def __init__(self):
self.name = self.strings['name']
async def client_ready(self, client, db):
self.client = client
self._db = db
@loader.sudo
async def omstartcmd(self, message):
"""Start OneMessage mode"""
self._db.set("OneMessage", "status", True)
self._db.set("OneMessage", "my_id", message.sender_id)
await message.edit("<b>OneMessage mode activated!</b>")
async def omstopcmd(self, message):
"""Stop OneMessage mode"""
self._db.set("OneMessage", "status", False)
await message.edit("<b>OneMessage mode diactivated!</b>")
async def watcher(self, message):
if not isinstance(message, Message):
return
if message.message:
if message.raw_text[0] in self._db.get("friendly-telegram.modules.corectrl", "command_prefix", ".") or message.fwd_from:
return
if self._db.get("OneMessage", "status", None) and message.sender_id == self._db.get("OneMessage", "my_id", None) and not message.media:
last_msg = (await self.client.get_messages(message.to_id, limit=2))[-1]
if last_msg.sender_id == message.sender_id and not last_msg.fwd_from:
text = last_msg.text
text += "\n"*2
text += message.text
if message.is_reply:
message, last_msg = last_msg, message
try:
await last_msg.edit(text)
await message.delete()
except:
return

View File

@@ -1,224 +1,224 @@
import io
from PIL import Image, ImageOps
from telethon.tl.types import DocumentAttributeFilename
from uniborg.util import admin_cmd
@borg.on(admin_cmd(pattern=".new ?(.*)", allow_sudo=True))
async def pilnew(event):
uinp = event.pattern_match.group(1)
if not uinp:
get = await event.get_reply_message()
if not get:
await event.delete()
return
uinp = get.text
uinp = uinp.split(" ", 2)
try:
x = int(uinp[0])
y = int(uinp[1])
except ValueError:
await event.edit("ERROR INPUT=> X or Y is not int")
return
if "(" in uinp[2] and ")" in uinp[2]:
color = uinp[2].replace("(","").replace(")","").split(", ")
try:
a = 255
r = int(color[0])
g = int(color[1])
b = int(color[2])
if len(color) == 4:
a = int(color[3])
except ValueError:
await event.edit("ERROR INPUT=> R or G or B is not int")
return
color = (r, g, b, a)
else:
color = uinp[2]
try:
image = Image.new("RGBA", (x, y), color)
except Exception as e:
await event.edit("ERROR IN DRAW\n"+str(e))
return
await event.delete()
image_stream = io.BytesIO()
image_stream.name = "pilnew.png"
image.save(image_stream, "PNG")
image_stream.seek(0)
await event.client.send_file(event.chat_id, image_stream)
@borg.on(admin_cmd(pattern=".rotate ?(.*)", allow_sudo=True))
async def pilrotate(event):
try:
angle = int(event.pattern_match.group(1))
except ValueError:
await event.edit("ERROR INPUT=> ANGLE")
if event.is_reply:
reply_message = await event.get_reply_message()
data = await check_media(reply_message)
if isinstance(data, bool):
await event.edit("`I can't rotate that!".upper())
return
else:
await event.edit("Reply to an image or sticker to rotate it!".upper())
return
image = io.BytesIO()
await event.client.download_media(data, image)
image = Image.open(image)
try:
image = image.rotate(angle, expand=True)
except Exception as e:
await event.edit("ERROR IN ROTATE\n"+str(e))
return
await event.delete()
image_stream = io.BytesIO()
image_stream.name = "pilrotate.png"
image.save(image_stream, "PNG")
image_stream.seek(0)
await event.client.send_file(event.chat_id, image_stream)
@borg.on(admin_cmd(pattern=".ops ?(.*)", allow_sudo=True))
async def pilops(event):
way = event.pattern_match.group(1)
if not way:
return
if event.is_reply:
reply_message = await event.get_reply_message()
data = await check_media(reply_message)
if isinstance(data, bool):
await event.edit("`I can't ops that!".upper())
return
else:
await event.edit("Reply to an image or sticker to ops it!".upper())
return
image = io.BytesIO()
await event.client.download_media(data, image)
image = Image.open(image)
if "m" in way:
try:
image = ImageOps.mirror(image)
except Exception as e:
await event.edit("ERROR IN MIRROR\n"+str(e))
return
if "f" in way:
try:
image = ImageOps.flip(image)
except Exception as e:
await event.edit("ERROR IN FLIP\n"+str(e))
return
await event.delete()
image_stream = io.BytesIO()
image_stream.name = "pilops.png"
image.save(image_stream, "PNG")
image_stream.seek(0)
await event.client.send_file(event.chat_id, image_stream)
@borg.on(admin_cmd(pattern=".resize ?(.*)", allow_sudo=True))
async def pilrotate(event):
if event.is_reply:
reply_message = await event.get_reply_message()
data = await check_media(reply_message)
if isinstance(data, bool):
await event.edit("`I can't resize that!".upper())
return
else:
await event.edit("Reply to an image or sticker to resize it!".upper())
return
uinp = event.pattern_match.group(1)
if not uinp:
await event.edit("What's about input".upper())
return
uinp = uinp.split()
image = io.BytesIO()
await event.client.download_media(data, image)
image = Image.open(image)
x, y = image.size
rx, ry = None, None
if len(uinp) == 1:
try:
rx, ry = int(uinp[0]), int(uinp[0])
except ValueError:
if uinp[0] == "x":
rx, ry = x, x
if uinp[0] == "y":
rx, ry = y, y
else:
await event.edit("INPUT MUST BE STING")
return
else:
if uinp[0] == "x":
rx = x
if uinp[0] == "y":
rx = y
if uinp[1] == "x":
ry = x
if uinp[1] == "y":
ry = y
if not rx:
try:
rx = int(uinp[0])
except:
await event.edit("ERROR IN INPUT")
return
if not ry:
try:
ry = int(uinp[1])
except:
await event.edit("ERROR IN INPUT")
return
try:
image = image.resize((rx, ry))
except Exception as e:
await event.edit("ERROR IN RESIZE\n"+str(e))
return
await event.delete()
image_stream = io.BytesIO()
image_stream.name = "pilresize.png"
image.save(image_stream, "PNG")
image_stream.seek(0)
await event.client.send_file(event.chat_id, image_stream)
async def check_media(reply_message):
if reply_message and reply_message.media:
if reply_message.photo:
data = reply_message.photo
elif reply_message.document:
if DocumentAttributeFilename(file_name='AnimatedSticker.tgs') in reply_message.media.document.attributes:
return False
if reply_message.gif or reply_message.video or reply_message.audio or reply_message.voice:
return False
data = reply_message.media.document
else:
return False
else:
return False
if not data or data is None:
return False
else:
return data
import io
from PIL import Image, ImageOps
from telethon.tl.types import DocumentAttributeFilename
from uniborg.util import admin_cmd
@borg.on(admin_cmd(pattern=".new ?(.*)", allow_sudo=True))
async def pilnew(event):
uinp = event.pattern_match.group(1)
if not uinp:
get = await event.get_reply_message()
if not get:
await event.delete()
return
uinp = get.text
uinp = uinp.split(" ", 2)
try:
x = int(uinp[0])
y = int(uinp[1])
except ValueError:
await event.edit("ERROR INPUT=> X or Y is not int")
return
if "(" in uinp[2] and ")" in uinp[2]:
color = uinp[2].replace("(","").replace(")","").split(", ")
try:
a = 255
r = int(color[0])
g = int(color[1])
b = int(color[2])
if len(color) == 4:
a = int(color[3])
except ValueError:
await event.edit("ERROR INPUT=> R or G or B is not int")
return
color = (r, g, b, a)
else:
color = uinp[2]
try:
image = Image.new("RGBA", (x, y), color)
except Exception as e:
await event.edit("ERROR IN DRAW\n"+str(e))
return
await event.delete()
image_stream = io.BytesIO()
image_stream.name = "pilnew.png"
image.save(image_stream, "PNG")
image_stream.seek(0)
await event.client.send_file(event.chat_id, image_stream)
@borg.on(admin_cmd(pattern=".rotate ?(.*)", allow_sudo=True))
async def pilrotate(event):
try:
angle = int(event.pattern_match.group(1))
except ValueError:
await event.edit("ERROR INPUT=> ANGLE")
if event.is_reply:
reply_message = await event.get_reply_message()
data = await check_media(reply_message)
if isinstance(data, bool):
await event.edit("`I can't rotate that!".upper())
return
else:
await event.edit("Reply to an image or sticker to rotate it!".upper())
return
image = io.BytesIO()
await event.client.download_media(data, image)
image = Image.open(image)
try:
image = image.rotate(angle, expand=True)
except Exception as e:
await event.edit("ERROR IN ROTATE\n"+str(e))
return
await event.delete()
image_stream = io.BytesIO()
image_stream.name = "pilrotate.png"
image.save(image_stream, "PNG")
image_stream.seek(0)
await event.client.send_file(event.chat_id, image_stream)
@borg.on(admin_cmd(pattern=".ops ?(.*)", allow_sudo=True))
async def pilops(event):
way = event.pattern_match.group(1)
if not way:
return
if event.is_reply:
reply_message = await event.get_reply_message()
data = await check_media(reply_message)
if isinstance(data, bool):
await event.edit("`I can't ops that!".upper())
return
else:
await event.edit("Reply to an image or sticker to ops it!".upper())
return
image = io.BytesIO()
await event.client.download_media(data, image)
image = Image.open(image)
if "m" in way:
try:
image = ImageOps.mirror(image)
except Exception as e:
await event.edit("ERROR IN MIRROR\n"+str(e))
return
if "f" in way:
try:
image = ImageOps.flip(image)
except Exception as e:
await event.edit("ERROR IN FLIP\n"+str(e))
return
await event.delete()
image_stream = io.BytesIO()
image_stream.name = "pilops.png"
image.save(image_stream, "PNG")
image_stream.seek(0)
await event.client.send_file(event.chat_id, image_stream)
@borg.on(admin_cmd(pattern=".resize ?(.*)", allow_sudo=True))
async def pilrotate(event):
if event.is_reply:
reply_message = await event.get_reply_message()
data = await check_media(reply_message)
if isinstance(data, bool):
await event.edit("`I can't resize that!".upper())
return
else:
await event.edit("Reply to an image or sticker to resize it!".upper())
return
uinp = event.pattern_match.group(1)
if not uinp:
await event.edit("What's about input".upper())
return
uinp = uinp.split()
image = io.BytesIO()
await event.client.download_media(data, image)
image = Image.open(image)
x, y = image.size
rx, ry = None, None
if len(uinp) == 1:
try:
rx, ry = int(uinp[0]), int(uinp[0])
except ValueError:
if uinp[0] == "x":
rx, ry = x, x
if uinp[0] == "y":
rx, ry = y, y
else:
await event.edit("INPUT MUST BE STING")
return
else:
if uinp[0] == "x":
rx = x
if uinp[0] == "y":
rx = y
if uinp[1] == "x":
ry = x
if uinp[1] == "y":
ry = y
if not rx:
try:
rx = int(uinp[0])
except:
await event.edit("ERROR IN INPUT")
return
if not ry:
try:
ry = int(uinp[1])
except:
await event.edit("ERROR IN INPUT")
return
try:
image = image.resize((rx, ry))
except Exception as e:
await event.edit("ERROR IN RESIZE\n"+str(e))
return
await event.delete()
image_stream = io.BytesIO()
image_stream.name = "pilresize.png"
image.save(image_stream, "PNG")
image_stream.seek(0)
await event.client.send_file(event.chat_id, image_stream)
async def check_media(reply_message):
if reply_message and reply_message.media:
if reply_message.photo:
data = reply_message.photo
elif reply_message.document:
if DocumentAttributeFilename(file_name='AnimatedSticker.tgs') in reply_message.media.document.attributes:
return False
if reply_message.gif or reply_message.video or reply_message.audio or reply_message.voice:
return False
data = reply_message.media.document
else:
return False
else:
return False
if not data or data is None:
return False
else:
return data

View File

@@ -1,80 +1,80 @@
from .. import loader, utils
from telethon.tl.types import DocumentAttributeFilename
from requests import get, post
from PIL import Image
from io import BytesIO
@loader.tds
class QRtoolsMod(loader.Module):
"""Generator and reader of QR codes"""
strings = {"name": "QR tool's"}
@loader.owner
async def makeqrcmd(self, message):
""".makeqr <text or reply>"""
text = utils.get_args_raw(message)
reply = await message.get_reply_message()
file = False
if not text or text.lower() == ".file":
if text and text == ".file":
file = True
if not reply or not reply.message:
await message.edit("<b>Нет текста для кодирования!</b>")
return
text = reply.raw_text
else:
if text.startswith(".file"):
file = True
text = text[5:].strip()
url = "https://api.qrserver.com/v1/create-qr-code/?data={}&size=512x512&charset-source=UTF-8&charset-target=UTF-8&ecc=L&color=0-0-0&bgcolor=255-255-255&margin=1&qzone=1&format=png"
r = get(url.format(text), stream=True)
qrcode = BytesIO()
qrcode.name = "qr.png" if file else "qr.webp"
Image.open(BytesIO(r.content)).save(qrcode)
qrcode.seek(0)
await message.delete()
await message.client.send_file(message.to_id, qrcode, reply_to=reply, force_document=file)
@loader.owner
async def readqrcmd(self, message):
""".readqr <qrcode or reply to qrcode>"""
ok = await check(message)
if not ok:
reply = await message.get_reply_message()
ok = await check(reply)
if not ok:
text = "<b>Это не изображение!</b>" if reply else "<b>Нечего не передано!</b>"
await message.edit(text)
return
file = BytesIO()
file.name = "qr.png"
data = await message.client.download_file(ok)
Image.open(BytesIO(data)).save(file)
url = "https://api.qrserver.com/v1/read-qr-code/?outputformat=json"
resp = post(url, files={"file": file.getvalue()})
text = resp.json()[0]["symbol"][0]["data"]
if not text:
text = "<b>Невозможно распознать или QR пуст!<b>"
await utils.answer(message, text)
async def check(msg):
if msg and msg.media:
if msg.photo:
ok = msg.photo
elif msg.document:
if DocumentAttributeFilename(file_name='AnimatedSticker.tgs') in msg.media.document.attributes:
return False
if msg.gif or msg.video or msg.audio or msg.voice:
return False
ok = msg.media.document
else:
return False
else:
return False
if not ok or ok is None:
return False
else:
return ok
from .. import loader, utils
from telethon.tl.types import DocumentAttributeFilename
from requests import get, post
from PIL import Image
from io import BytesIO
@loader.tds
class QRtoolsMod(loader.Module):
"""Generator and reader of QR codes"""
strings = {"name": "QR tool's"}
@loader.owner
async def makeqrcmd(self, message):
""".makeqr <text or reply>"""
text = utils.get_args_raw(message)
reply = await message.get_reply_message()
file = False
if not text or text.lower() == ".file":
if text and text == ".file":
file = True
if not reply or not reply.message:
await message.edit("<b>Нет текста для кодирования!</b>")
return
text = reply.raw_text
else:
if text.startswith(".file"):
file = True
text = text[5:].strip()
url = "https://api.qrserver.com/v1/create-qr-code/?data={}&size=512x512&charset-source=UTF-8&charset-target=UTF-8&ecc=L&color=0-0-0&bgcolor=255-255-255&margin=1&qzone=1&format=png"
r = get(url.format(text), stream=True)
qrcode = BytesIO()
qrcode.name = "qr.png" if file else "qr.webp"
Image.open(BytesIO(r.content)).save(qrcode)
qrcode.seek(0)
await message.delete()
await message.client.send_file(message.to_id, qrcode, reply_to=reply, force_document=file)
@loader.owner
async def readqrcmd(self, message):
""".readqr <qrcode or reply to qrcode>"""
ok = await check(message)
if not ok:
reply = await message.get_reply_message()
ok = await check(reply)
if not ok:
text = "<b>Это не изображение!</b>" if reply else "<b>Нечего не передано!</b>"
await message.edit(text)
return
file = BytesIO()
file.name = "qr.png"
data = await message.client.download_file(ok)
Image.open(BytesIO(data)).save(file)
url = "https://api.qrserver.com/v1/read-qr-code/?outputformat=json"
resp = post(url, files={"file": file.getvalue()})
text = resp.json()[0]["symbol"][0]["data"]
if not text:
text = "<b>Невозможно распознать или QR пуст!<b>"
await utils.answer(message, text)
async def check(msg):
if msg and msg.media:
if msg.photo:
ok = msg.photo
elif msg.document:
if DocumentAttributeFilename(file_name='AnimatedSticker.tgs') in msg.media.document.attributes:
return False
if msg.gif or msg.video or msg.audio or msg.voice:
return False
ok = msg.media.document
else:
return False
else:
return False
if not ok or ok is None:
return False
else:
return ok

View File

@@ -1,33 +1,33 @@
from PIL import Image, ImageFilter
import io
from .. import loader, utils
@loader.tds
class SquareBlurMod(loader.Module):
"""Make image 1:1 ratio"""
strings = {"name": "SquareBlur"}
@loader.unrestricted
async def squareblurcmd(self, message):
"""make image 1:1 ratio"""
reply = await message.get_reply_message()
if not reply or not reply.file or not reply.file.mime_type.split("/")[0].lower() == "image":
await message.edit("<b>Reply to image!</b>")
return
im = io.BytesIO()
await reply.download_media(im)
im = Image.open(im)
w, h = im.size
if w == h:
await message.edit("<b>Ты за меня придурка не держи!</b>")
return
_min, _max = min(w, h), max(w, h)
bg = im.crop(((w-_min)//2, (h-_min)//2, (w+_min)//2, (h+_min)//2))
bg = bg.filter(ImageFilter.GaussianBlur(5))
bg = bg.resize((_max, _max))
bg.paste(im, ((_max-w)//2, (_max-h)//2))
img = io.BytesIO()
img.name = "im.png"
bg.save(img)
img.seek(0)
await reply.reply(file=img)
await message.delete()
from PIL import Image, ImageFilter
import io
from .. import loader, utils
@loader.tds
class SquareBlurMod(loader.Module):
"""Make image 1:1 ratio"""
strings = {"name": "SquareBlur"}
@loader.unrestricted
async def squareblurcmd(self, message):
"""make image 1:1 ratio"""
reply = await message.get_reply_message()
if not reply or not reply.file or not reply.file.mime_type.split("/")[0].lower() == "image":
await message.edit("<b>Reply to image!</b>")
return
im = io.BytesIO()
await reply.download_media(im)
im = Image.open(im)
w, h = im.size
if w == h:
await message.edit("<b>Ты за меня придурка не держи!</b>")
return
_min, _max = min(w, h), max(w, h)
bg = im.crop(((w-_min)//2, (h-_min)//2, (w+_min)//2, (h+_min)//2))
bg = bg.filter(ImageFilter.GaussianBlur(5))
bg = bg.resize((_max, _max))
bg.paste(im, ((_max-w)//2, (_max-h)//2))
img = io.BytesIO()
img.name = "im.png"
bg.save(img)
img.seek(0)
await reply.reply(file=img)
await message.delete()

View File

@@ -1,58 +1,58 @@
from .. import loader, utils
import io
from PIL import Image
from string import hexdigits
def register(cb):
cb(StickToolsMod())
class StickToolsMod(loader.Module):
""""""
strings = {'name': 'StickTools'}
def __init__(self):
self.name = self.strings['name']
async def stick2piccmd(self, message):
"""reply to Sticker\nsend stricker as image"""
await convert(message, False)
async def stick2filecmd(self, message):
"""reply to Sticker\nsend stricker as image"""
await convert(message, True)
async def convert(message, as_file):
reply = await message.get_reply_message()
if not reply or not reply.sticker:
await message.edit("<b>Reply to sticker!</b>")
return
fname = reply.sticker.attributes[-1].file_name
if ".tgs" in fname:
await message.edit("<b>Reply to not animated sticker!</b>")
return
bg = (0,0,0,0)
args = utils.get_args(message)
if args:
args = args[0]
if args.startswith("#"):
for ch in args[1:]:
if ch not in hexdigits:
break
bg = args
im = io.BytesIO()
await message.client.download_file(reply, im)
im = Image.open(im)
img = Image.new("RGBA", im.size, bg)
if im.mode == "RGBA":
img.paste(im, (0,0), im)
else:
img.paste(im, (0,0))
out = io.BytesIO()
out.name = fname+".png"
img.save(out, "PNG")
out.seek(0)
await message.delete()
await message.client.send_file(message.to_id, out, force_document=as_file, reply_to=reply)
from .. import loader, utils
import io
from PIL import Image
from string import hexdigits
def register(cb):
cb(StickToolsMod())
class StickToolsMod(loader.Module):
""""""
strings = {'name': 'StickTools'}
def __init__(self):
self.name = self.strings['name']
async def stick2piccmd(self, message):
"""reply to Sticker\nsend stricker as image"""
await convert(message, False)
async def stick2filecmd(self, message):
"""reply to Sticker\nsend stricker as image"""
await convert(message, True)
async def convert(message, as_file):
reply = await message.get_reply_message()
if not reply or not reply.sticker:
await message.edit("<b>Reply to sticker!</b>")
return
fname = reply.sticker.attributes[-1].file_name
if ".tgs" in fname:
await message.edit("<b>Reply to not animated sticker!</b>")
return
bg = (0,0,0,0)
args = utils.get_args(message)
if args:
args = args[0]
if args.startswith("#"):
for ch in args[1:]:
if ch not in hexdigits:
break
bg = args
im = io.BytesIO()
await message.client.download_file(reply, im)
im = Image.open(im)
img = Image.new("RGBA", im.size, bg)
if im.mode == "RGBA":
img.paste(im, (0,0), im)
else:
img.paste(im, (0,0))
out = io.BytesIO()
out.name = fname+".png"
img.save(out, "PNG")
out.seek(0)
await message.delete()
await message.client.send_file(message.to_id, out, force_document=as_file, reply_to=reply)

File diff suppressed because one or more lines are too long

View File

@@ -1,174 +1,174 @@
from .. import loader, utils
import logging
from PIL import Image, ImageDraw, ImageOps, ImageFont
from textwrap import wrap
import io
import requests
# https://t.me/KeyZenD
# https://t.me/SomeScripts
logger = logging.getLogger(__name__)
@loader.tds
class DeMoTiVaToRsMod(loader.Module):
"""Демотиваторы на картинки от @SomeScripts by @DneZyeK"""
strings = {
"name": "SuperDemotivator"
}
async def client_ready(self, client, db):
self.client = client
@loader.owner
async def demoticmd(self, message):
"""текст + фото или ответ на фото
не мнёт фотки"""
await cmds(message, 0)
async def demotcmd(self, message):
"""текст + фото или ответ на фото
мнёт фотки"""
await cmds(message, 1)
async def cmds(message, type):
event, is_reply = await check_media(message)
if not event:
await message.edit("<b>Ответ командой на картинку!</b>")
return
text = utils.get_args_raw(message)
if not text:
await message.edit("<b>Команду нужно использовать с текстом!</b>")
return
await message.edit("<b>Демотивирую...</b>")
bytes_image = await event.download_media(bytes)
demotivator = await demotion(font_bytes, bytes_image, text, type)
if is_reply:
a = await event.reply(file=demotivator)
await message.delete()
return a
else:
return await event.edit(file=demotivator, text="")
async def check_media(message):
reply = await message.get_reply_message()
is_reply = True
if not reply:
reply = message
is_reply = False
if not reply.file:
return False, ...
mime = reply.file.mime_type.split("/")[0].lower()
if mime != "image":
return False, ...
return reply, is_reply
async def textwrap(text, length=50, splitter = "\n\n"):
out = []
lines = text.rsplit(splitter, 1)
for text in lines:
txt = []
parts = text.split("\n")
for part in parts:
part = "\n".join(wrap(part, length))
txt.append(part)
text = "\n".join(txt)
out.append(text)
return out
async def draw_main(
bytes_image,
type,
frame_width_1 = 5,
frame_fill_1 = (0, 0, 0),
frame_width_2 = 3,
frame_fill_2 = (255, 255, 255),
expand_proc = 10,
main_fill = (0, 0, 0)
):
main_ = Image.open(io.BytesIO(bytes_image))
main = Image.new("RGB", main_.size, "black")
main.paste(main_, (0, 0))
if type == 1:
main = main.resize((700, 550))
main = ImageOps.expand(main, frame_width_1, frame_fill_1)
main = ImageOps.expand(main, frame_width_2, frame_fill_2)
w, h = main.size
h_up = expand_proc*(h//100)
im = Image.new("RGB", (w+(h_up*2), h+h_up), main_fill)
im.paste(main, (h_up, h_up))
return im
async def _draw_text(
text,
font_bytes,
font_size,
font_add = 20,
main_fill = (0, 0, 0),
text_fill = (255, 255, 255),
text_align = "center"
):
font = ImageFont.truetype(io.BytesIO(font_bytes), font_size)
w_txt, h_txt = ImageDraw.Draw(Image.new("RGB", (1, 1))).multiline_textsize(text=text, font=font)
txt = Image.new("RGB", (w_txt, h_txt+font_add), main_fill)
ImageDraw.Draw(txt).text((0, 0), text=text, font=font, fill=text_fill, align=text_align)
return txt
async def text_joiner(text_img_1, text_img_2, main_fill = (0, 0, 0)):
w_txt_1, h_txt_1 = text_img_1.size
w_txt_2, h_txt_2 = text_img_2.size
w = max(w_txt_1, w_txt_2)
h = h_txt_1 + h_txt_2
text = Image.new("RGB", (w, h), main_fill)
text.paste(text_img_1, ((w-w_txt_1)//2, 0))
text.paste(text_img_2, ((w-w_txt_2)//2, h_txt_1))
return text
async def draw_text(text, font_bytes, font_size):
text = await textwrap(text)
if len(text) == 1:
text = await _draw_text(text[0], font_bytes, font_size[0] )
else:
text_img_1 = await _draw_text(text[ 0], font_bytes, font_size[0])
text_img_2 = await _draw_text(text[-1], font_bytes, font_size[1])
text = await text_joiner(text_img_1, text_img_2)
return text
async def text_finaller(text, main, expand_width_proc = 25, main_fill = (0, 0, 0)):
x = min(main.size)
w_txt, h_txt = text.size
w_proc = expand_width_proc*(w_txt//100)
h_proc = expand_width_proc*(h_txt//100)
back = Image.new("RGB", (w_txt+(w_proc*2), h_txt+(h_proc*2)), main_fill)
back.paste(text, (w_proc, h_proc))
back.thumbnail((x, x))
return back
async def joiner(text_img, main_img, format_save="JPEG"):
w_im, h_im = main_img.size
w_txt, h_txt = text_img.size
text_img.thumbnail((min(w_im, h_im), min(w_im, h_im)))
w_txt, h_txt = text_img.size
main_img = main_img.crop((0, 0, w_im, h_im+h_txt))
main_img.paste(text_img, ((w_im-w_txt)//2, h_im))
output = io.BytesIO()
main_img.save(output, format_save)
output.seek(0)
return output.getvalue()
async def demotion(font_bytes, bytes_image, text, type):
main = await draw_main(bytes_image, type)
font_size = [20*(min(main.size)//100), 15*(min(main.size)//100)]
text = await draw_text(text, font_bytes, font_size)
text = await text_finaller(text, main)
output = await joiner(text, main)
return output
font_bytes = requests.get("https://raw.githubusercontent.com/KeyZenD/l/master/times.ttf").content
#######################
from .. import loader, utils
import logging
from PIL import Image, ImageDraw, ImageOps, ImageFont
from textwrap import wrap
import io
import requests
# https://t.me/KeyZenD
# https://t.me/SomeScripts
logger = logging.getLogger(__name__)
@loader.tds
class DeMoTiVaToRsMod(loader.Module):
"""Демотиваторы на картинки от @SomeScripts by @DneZyeK"""
strings = {
"name": "SuperDemotivator"
}
async def client_ready(self, client, db):
self.client = client
@loader.owner
async def demoticmd(self, message):
"""текст + фото или ответ на фото
не мнёт фотки"""
await cmds(message, 0)
async def demotcmd(self, message):
"""текст + фото или ответ на фото
мнёт фотки"""
await cmds(message, 1)
async def cmds(message, type):
event, is_reply = await check_media(message)
if not event:
await message.edit("<b>Ответ командой на картинку!</b>")
return
text = utils.get_args_raw(message)
if not text:
await message.edit("<b>Команду нужно использовать с текстом!</b>")
return
await message.edit("<b>Демотивирую...</b>")
bytes_image = await event.download_media(bytes)
demotivator = await demotion(font_bytes, bytes_image, text, type)
if is_reply:
a = await event.reply(file=demotivator)
await message.delete()
return a
else:
return await event.edit(file=demotivator, text="")
async def check_media(message):
reply = await message.get_reply_message()
is_reply = True
if not reply:
reply = message
is_reply = False
if not reply.file:
return False, ...
mime = reply.file.mime_type.split("/")[0].lower()
if mime != "image":
return False, ...
return reply, is_reply
async def textwrap(text, length=50, splitter = "\n\n"):
out = []
lines = text.rsplit(splitter, 1)
for text in lines:
txt = []
parts = text.split("\n")
for part in parts:
part = "\n".join(wrap(part, length))
txt.append(part)
text = "\n".join(txt)
out.append(text)
return out
async def draw_main(
bytes_image,
type,
frame_width_1 = 5,
frame_fill_1 = (0, 0, 0),
frame_width_2 = 3,
frame_fill_2 = (255, 255, 255),
expand_proc = 10,
main_fill = (0, 0, 0)
):
main_ = Image.open(io.BytesIO(bytes_image))
main = Image.new("RGB", main_.size, "black")
main.paste(main_, (0, 0))
if type == 1:
main = main.resize((700, 550))
main = ImageOps.expand(main, frame_width_1, frame_fill_1)
main = ImageOps.expand(main, frame_width_2, frame_fill_2)
w, h = main.size
h_up = expand_proc*(h//100)
im = Image.new("RGB", (w+(h_up*2), h+h_up), main_fill)
im.paste(main, (h_up, h_up))
return im
async def _draw_text(
text,
font_bytes,
font_size,
font_add = 20,
main_fill = (0, 0, 0),
text_fill = (255, 255, 255),
text_align = "center"
):
font = ImageFont.truetype(io.BytesIO(font_bytes), font_size)
w_txt, h_txt = ImageDraw.Draw(Image.new("RGB", (1, 1))).multiline_textsize(text=text, font=font)
txt = Image.new("RGB", (w_txt, h_txt+font_add), main_fill)
ImageDraw.Draw(txt).text((0, 0), text=text, font=font, fill=text_fill, align=text_align)
return txt
async def text_joiner(text_img_1, text_img_2, main_fill = (0, 0, 0)):
w_txt_1, h_txt_1 = text_img_1.size
w_txt_2, h_txt_2 = text_img_2.size
w = max(w_txt_1, w_txt_2)
h = h_txt_1 + h_txt_2
text = Image.new("RGB", (w, h), main_fill)
text.paste(text_img_1, ((w-w_txt_1)//2, 0))
text.paste(text_img_2, ((w-w_txt_2)//2, h_txt_1))
return text
async def draw_text(text, font_bytes, font_size):
text = await textwrap(text)
if len(text) == 1:
text = await _draw_text(text[0], font_bytes, font_size[0] )
else:
text_img_1 = await _draw_text(text[ 0], font_bytes, font_size[0])
text_img_2 = await _draw_text(text[-1], font_bytes, font_size[1])
text = await text_joiner(text_img_1, text_img_2)
return text
async def text_finaller(text, main, expand_width_proc = 25, main_fill = (0, 0, 0)):
x = min(main.size)
w_txt, h_txt = text.size
w_proc = expand_width_proc*(w_txt//100)
h_proc = expand_width_proc*(h_txt//100)
back = Image.new("RGB", (w_txt+(w_proc*2), h_txt+(h_proc*2)), main_fill)
back.paste(text, (w_proc, h_proc))
back.thumbnail((x, x))
return back
async def joiner(text_img, main_img, format_save="JPEG"):
w_im, h_im = main_img.size
w_txt, h_txt = text_img.size
text_img.thumbnail((min(w_im, h_im), min(w_im, h_im)))
w_txt, h_txt = text_img.size
main_img = main_img.crop((0, 0, w_im, h_im+h_txt))
main_img.paste(text_img, ((w_im-w_txt)//2, h_im))
output = io.BytesIO()
main_img.save(output, format_save)
output.seek(0)
return output.getvalue()
async def demotion(font_bytes, bytes_image, text, type):
main = await draw_main(bytes_image, type)
font_size = [20*(min(main.size)//100), 15*(min(main.size)//100)]
text = await draw_text(text, font_bytes, font_size)
text = await text_finaller(text, main)
output = await joiner(text, main)
return output
font_bytes = requests.get("https://raw.githubusercontent.com/KeyZenD/l/master/times.ttf").content
#######################

View File

@@ -1,110 +1,110 @@
from .. import loader, utils
import logging
from PIL import Image, ImageOps
import io
logger = logging.getLogger(__name__)
@loader.tds
class SwiperMod(loader.Module):
"""Swiper"""
strings = {
"name": "Swiper"
}
async def client_ready(self, client, db):
self.client = client
@loader.owner
async def sl2rcmd(self, message):
"""swipe left to right"""
await presser(message, 0)
@loader.owner
async def sr2lcmd(self, message):
"""swipe right to left"""
await presser(message, 1)
@loader.owner
async def su2dcmd(self, message):
"""swipe up to down"""
await presser(message, 2)
@loader.owner
async def sd2ucmd(self, message):
"""swipe down to up"""
await presser(message, 3)
async def check_media(message):
reply = await message.get_reply_message()
if not reply:
return False
if not reply.file:
return False
mime = reply.file.mime_type.split("/")[0].lower()
if mime != "image":
return False
return reply
async def presser(message, way):
reply = await check_media(message)
if not reply:
await message.edit("<b>Senpai... please reply to image or not animated sticker!</b>")
return
im = io.BytesIO()
await reply.download_media(im)
im = Image.open(im)
w, h = im.size
out = []
await message.edit("<b>Working hard...</b>")
if way == 0:
for x in range(1, w, w//30):
im1 = im2 = im.copy()
temp = Image.new("RGB", (w, h))
im1 = im1.resize((x, h))
im2 = im2.resize((w-x, h))
temp.paste(im1, (0, 0))
temp.paste(im2, (x, 0))
out.append(temp)
if way == 1:
for x in range(1, w, w//30):
im1 = im2 = im.copy()
temp = Image.new("RGB", (w, h))
im1 = ImageOps.mirror(im1.resize((x, h)))
im2 = ImageOps.mirror(im2.resize((w-x, h)))
temp.paste(im1, (0, 0))
temp.paste(im2, (x, 0))
temp = ImageOps.mirror(temp)
out.append(temp)
if way == 2:
for y in range(1, h, h//30):
im1 = im2 = im.copy()
temp = Image.new("RGB", (w, h))
im1 = im1.resize((w, y))
im2 = im2.resize((w, h-y))
temp.paste(im1, (0, 0))
temp.paste(im2, (0, y))
out.append(temp)
if way == 3:
for y in range(1, h, h//30):
im1 = im2 = im.copy()
temp = Image.new("RGB", (w, h))
im1 = ImageOps.flip(im1.resize((w, y)))
im2 = ImageOps.flip(im2.resize((w, h-y)))
temp.paste(im1, (0, 0))
temp.paste(im2, (0, y))
temp = ImageOps.flip(temp)
out.append(temp)
output = io.BytesIO()
output.name = "output.gif"
out[0].save(output, save_all=True, append_images=out[1:], duration=1)
output.seek(0)
await reply.reply(file=output)
await message.delete()
from .. import loader, utils
import logging
from PIL import Image, ImageOps
import io
logger = logging.getLogger(__name__)
@loader.tds
class SwiperMod(loader.Module):
"""Swiper"""
strings = {
"name": "Swiper"
}
async def client_ready(self, client, db):
self.client = client
@loader.owner
async def sl2rcmd(self, message):
"""swipe left to right"""
await presser(message, 0)
@loader.owner
async def sr2lcmd(self, message):
"""swipe right to left"""
await presser(message, 1)
@loader.owner
async def su2dcmd(self, message):
"""swipe up to down"""
await presser(message, 2)
@loader.owner
async def sd2ucmd(self, message):
"""swipe down to up"""
await presser(message, 3)
async def check_media(message):
reply = await message.get_reply_message()
if not reply:
return False
if not reply.file:
return False
mime = reply.file.mime_type.split("/")[0].lower()
if mime != "image":
return False
return reply
async def presser(message, way):
reply = await check_media(message)
if not reply:
await message.edit("<b>Senpai... please reply to image or not animated sticker!</b>")
return
im = io.BytesIO()
await reply.download_media(im)
im = Image.open(im)
w, h = im.size
out = []
await message.edit("<b>Working hard...</b>")
if way == 0:
for x in range(1, w, w//30):
im1 = im2 = im.copy()
temp = Image.new("RGB", (w, h))
im1 = im1.resize((x, h))
im2 = im2.resize((w-x, h))
temp.paste(im1, (0, 0))
temp.paste(im2, (x, 0))
out.append(temp)
if way == 1:
for x in range(1, w, w//30):
im1 = im2 = im.copy()
temp = Image.new("RGB", (w, h))
im1 = ImageOps.mirror(im1.resize((x, h)))
im2 = ImageOps.mirror(im2.resize((w-x, h)))
temp.paste(im1, (0, 0))
temp.paste(im2, (x, 0))
temp = ImageOps.mirror(temp)
out.append(temp)
if way == 2:
for y in range(1, h, h//30):
im1 = im2 = im.copy()
temp = Image.new("RGB", (w, h))
im1 = im1.resize((w, y))
im2 = im2.resize((w, h-y))
temp.paste(im1, (0, 0))
temp.paste(im2, (0, y))
out.append(temp)
if way == 3:
for y in range(1, h, h//30):
im1 = im2 = im.copy()
temp = Image.new("RGB", (w, h))
im1 = ImageOps.flip(im1.resize((w, y)))
im2 = ImageOps.flip(im2.resize((w, h-y)))
temp.paste(im1, (0, 0))
temp.paste(im2, (0, y))
temp = ImageOps.flip(temp)
out.append(temp)
output = io.BytesIO()
output.name = "output.gif"
out[0].save(output, save_all=True, append_images=out[1:], duration=1)
output.seek(0)
await reply.reply(file=output)
await message.delete()

View File

@@ -1,66 +1,66 @@
# -*- coding: utf-8 -*-
# Friendly Telegram (telegram userbot)
# Copyright (C) 2018-2020 @DneZyeK | sub to @KeyZenD
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import logging
from .. import loader, utils
import telethon
logger = logging.getLogger(__name__)
async def register(cb):
cb(KeyboardSwitcherMod())
@loader.tds
class KeyboardSwitcherMod(loader.Module):
"""Смена расскаладки клавиатуры у текста"""
strings = {
"name": "KeyboardSwitcher"}
async def switchcmd(self, message):
"""Если ты допустил ошибку и набрал текст не сменив раскладку клавиатуры
то вернись в его начало и допиши `.switch` и твой текст станет читабельным.
Если ты всё же отправил сообщение не в той расскладке, то просто ответь на него этой командой и он измениться.
если же твой собеседник допустил ошибку, то просто ответь на его сообщение и сообщение с командой измениться."""
RuKeys = """ёйцукенгшщзхъфывапролджэячсмитьбю.Ё"№;%:?ЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭ/ЯЧСМИТЬБЮ,"""
EnKeys = """`qwertyuiop[]asdfghjkl;'zxcvbnm,./~@#$%^&QWERTYUIOP{}ASDFGHJKL:"|ZXCVBNM<>?"""
if message.is_reply:
reply = await message.get_reply_message()
text = reply.raw_text
if not text:
await message.edit('Тут текста нету...')
return
change = str.maketrans(RuKeys + EnKeys, EnKeys + RuKeys)
text = str.translate(text, change)
if message.sender_id != reply.sender_id:
await message.edit(text)
else:
await message.delete()
await reply.edit(text)
else:
text = utils.get_args_raw(message)
if not text:
await message.edit('Тут текста нету...')
return
change = str.maketrans(RuKeys + EnKeys, EnKeys + RuKeys)
text = str.translate(text, change)
await message.edit(text)
# -*- coding: utf-8 -*-
# Friendly Telegram (telegram userbot)
# Copyright (C) 2018-2020 @DneZyeK | sub to @KeyZenD
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import logging
from .. import loader, utils
import telethon
logger = logging.getLogger(__name__)
async def register(cb):
cb(KeyboardSwitcherMod())
@loader.tds
class KeyboardSwitcherMod(loader.Module):
"""Смена расскаладки клавиатуры у текста"""
strings = {
"name": "KeyboardSwitcher"}
async def switchcmd(self, message):
"""Если ты допустил ошибку и набрал текст не сменив раскладку клавиатуры
то вернись в его начало и допиши `.switch` и твой текст станет читабельным.
Если ты всё же отправил сообщение не в той расскладке, то просто ответь на него этой командой и он измениться.
если же твой собеседник допустил ошибку, то просто ответь на его сообщение и сообщение с командой измениться."""
RuKeys = """ёйцукенгшщзхъфывапролджэячсмитьбю.Ё"№;%:?ЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭ/ЯЧСМИТЬБЮ,"""
EnKeys = """`qwertyuiop[]asdfghjkl;'zxcvbnm,./~@#$%^&QWERTYUIOP{}ASDFGHJKL:"|ZXCVBNM<>?"""
if message.is_reply:
reply = await message.get_reply_message()
text = reply.raw_text
if not text:
await message.edit('Тут текста нету...')
return
change = str.maketrans(RuKeys + EnKeys, EnKeys + RuKeys)
text = str.translate(text, change)
if message.sender_id != reply.sender_id:
await message.edit(text)
else:
await message.delete()
await reply.edit(text)
else:
text = utils.get_args_raw(message)
if not text:
await message.edit('Тут текста нету...')
return
change = str.maketrans(RuKeys + EnKeys, EnKeys + RuKeys)
text = str.translate(text, change)
await message.edit(text)

View File

@@ -0,0 +1,11 @@
# Python code obfuscated by www.development-tools.net
import base64, codecs
magic = 'aW1wb3J0IGFzeW5jaW8NCmltcG9ydCBsb2dnaW5nDQpmcm9tIC4uIGltcG9ydCBsb2FkZXIsIHV0aWxzDQoNCmxvZ2dlciA9IGxvZ2dpbmcuZ2V0TG9nZ2VyKF9fbmFtZV9fKQ0KDQpAbG9hZGVyLnRkcw0KY2xhc3MgVmlkZW9EaXN0b3J0aW9ydE1vZChsb2FkZXIuTW9kdWxlKToNCgkiIiLQltC80YvRhSDQtNC70Y8g0LLQuNC00LXQviIiIg0KCXN0cmluZ3MgPSB7Im5hbWUiOiAiVmlkZW9EaXN0b3J0aW9uIn0NCg0KCUBsb2FkZXIudW5yZXN0cmljdGVkDQoJYXN5bmMgZGVmIHZkaXN0b3J0Y21kKHNlbGYsIG1lc3NhZ2UpOg0KCQkiIiIudmRpc3RvcnQgPHJlcGx5IHRvIHZpZGVvPiIiIg0KCQlhd2FpdCBtZXNzYWdlLmVkaXQoIjxiPtCX0LDQs9GA0YPQttCw0Y4g0LLQuNC00LXQvi4uLjwvYj4iKQ0KCQlhd2FpdCBhc3luY2lvLnNsZWVwKDUpDQoJCWF3YWl0IG1lc3NhZ2UuZWRpdCgiPGI+0JTQvtGB0YLQsNGOINC60LDQtNGA0YsuLi48L2'
love = 'V+VvxAPtxWLKqunKDtLKA5ozAcol5moTIypPt1XD0XPDyuq2ScqPOgMKAmLJqyYzIxnKDbVwkvCgPH0YKDh9Pj0L4t0YoDiATY0LHhYv48Y2V+VvxAPtxWLKqunKDtLKA5ozAcol5moTIypPt1XD0XPDyuq2ScqPOgMKAmLJqyYzIxnKDbVwkvCgPu0Y7DfqP40LQDfATBVAP60YQDgATN0LfhYv48Y2V+VvxAPtxWLKqunKDtLKA5ozAcol5moTIypPt1XD0XPDyuq2ScqPOgMKAmLJqyYzIxnKDbVwkvCgPr0LYDi9TN0YQDfgP70L/EwvQDfgP40YGDgqP+Yv4hCP9vCvVcQDbWPJS3LJy0VTSmrJ5wnJ8hp2kyMKNbAFxAPtxWLKqunKDtoJImp2SaMF5woTyyoaDhp2IhMS9znJkyXT1yp3AuM2HhL2uuqPjtVzu0qUN6Yl94rJI0LF5goP9zY05yqzIlE29hozSUnKMyJJ91IKNhoKN0VvjtL2SjqTyiow0vCTV+GzI2MKVtE29hozRtE2y2MFOMo3HtIKNuCP9vCvVcQDbWPJS3LJy0VT1yp3AuM2HhMJEcqPtvJJ91VUquplOlnJAepz9foTIxVFVcQDbWPD0XVvVv'
god = 'DQppbXBvcnQgYXN5bmNpbw0KaW1wb3J0IGxvZ2dpbmcNCmZyb20gLi4gaW1wb3J0IGxvYWRlciwgdXRpbHMNCg0KbG9nZ2VyID0gbG9nZ2luZy5nZXRMb2dnZXIoX19uYW1lX18pDQoNCkBsb2FkZXIudGRzDQpjbGFzcyBWaWRlb0Rpc3RvcnRpb3J0TW9kKGxvYWRlci5Nb2R1bGUpOg0KCSLQltC80YvRhSDQtNC70Y8g0LLQuNC00LXQviINCglzdHJpbmdzID0geyJuYW1lIjogIlZpZGVvRGlzdG9ydGlvbiJ9DQoNCglAbG9hZGVyLnVucmVzdHJpY3RlZA0KCWFzeW5jIGRlZiB2ZGlzdG9ydGNtZChzZWxmLCBtZXNzYWdlKToNCgkJIi52ZGlzdG9ydCA8cmVwbHkgdG8gdmlkZW8+Ig0KCQlhd2FpdCBtZXNzYWdlLmVkaXQoIjxiPtCX0LDQs9GA0YPQttCw0Y4g0LLQuNC00LXQvi4uLjwvYj4iKQ0KCQlhd2FpdCBhc3luY2lvLnNsZWVwKDUpDQoJCWF3YWl0IG1lc3NhZ2UuZWRpdCgiPGI+0JTQvtGB0YLQsNGOINC60LDQtNGA0YsuLi48L2I+IikNCg'
destiny = 'xWLKqunKDtLKA5ozAcol5moTIypPt1XD0XPDyuq2ScqPOgMKAmLJqyYzIxnKDbVwkvCgPH0YKDh9Pj0L4t0YoDiATY0LHhYv48Y2V+VvxAPtxWLKqunKDtLKA5ozAcol5moTIypPt1XD0XPDyuq2ScqPOgMKAmLJqyYzIxnKDbVwkvCgPu0Y7DfqP40LQDfATBVAP60YQDgATN0LfhYv48Y2V+VvxAPtxWLKqunKDtLKA5ozAcol5moTIypPt1XD0XPDyuq2ScqPOgMKAmLJqyYzIxnKDbVwkvCgPr0LYDi9TN0YQDfgP70L/EwvQDfgP40YGDgqP+Yv4hCP9vCvVcQDbWPJS3LJy0VTSmrJ5wnJ8hp2kyMKNbAFxAPtxWLKqunKDtoJImp2SaMF5woTyyoaDhp2IhMS9znJkyXT1yp3AuM2HhL2uuqPjtVzu0qUN6Yl94rJI0LF5goP9zY05yqzIlE29hozSUnKMyJJ91IKNhoKN0VvjtL2SjqTyiow0vCTV+GzI2MKVtE29hozRtE2y2MFOMo3HtIKNuCP9vCvVcQDbWPJS3LJy0VT1yp3AuM2HhMJEcqPtvJJ91VUquplOlnJAepz9foTIxVFVcQDbWPD0XVvVvQDbWPD=='
joy = '\x72\x6f\x74\x31\x33'
trust = eval('\x6d\x61\x67\x69\x63') + eval('\x63\x6f\x64\x65\x63\x73\x2e\x64\x65\x63\x6f\x64\x65\x28\x6c\x6f\x76\x65\x2c\x20\x6a\x6f\x79\x29') + eval('\x67\x6f\x64') + eval('\x63\x6f\x64\x65\x63\x73\x2e\x64\x65\x63\x6f\x64\x65\x28\x64\x65\x73\x74\x69\x6e\x79\x2c\x20\x6a\x6f\x79\x29')
eval(compile(base64.b64decode(eval('\x74\x72\x75\x73\x74')),'<string>','exec'))

View File

@@ -1,59 +1,59 @@
# -*- coding: utf-8 -*-
# Friendly Telegram (telegram userbot)
# Copyright (C) 2018-2020 The Authors
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
# если не подписан на t.me/keyzend
# твоя мама шлюха
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
from .. import loader, utils # pylint: disable=relative-beyond-top-level
from telethon.tl.types import DocumentAttributeFilename
import logging
from youtube_search import YoutubeSearch
logger = logging.getLogger(__name__)
def register(cb):
cb(YTsearchod())
@loader.tds
class YTsearchMod(loader.Module):
"""Поиск видео на ютубе"""
strings = {
"name": "YTsearch"
}
async def client_ready(self, client, db):
self.client = client
@loader.sudo
async def ytcmd(self, message):
"""текст или реплай"""
text = utils.get_args_raw(message)
if not text:
reply = await message.get_reply_message()
if not reply:
await message.delete()
return
text = reply.raw_text
results = YoutubeSearch(text, max_results=10).to_dict()
out = f'Найдено по запросу: {text}'
for r in results:
out += f'\n\n<a href="https://www.youtube.com/{r["link"]}">{r["title"]}</a>'
await message.edit(out)
# -*- coding: utf-8 -*-
# Friendly Telegram (telegram userbot)
# Copyright (C) 2018-2020 The Authors
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
# если не подписан на t.me/keyzend
# твоя мама шлюха
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
from .. import loader, utils # pylint: disable=relative-beyond-top-level
from telethon.tl.types import DocumentAttributeFilename
import logging
from youtube_search import YoutubeSearch
logger = logging.getLogger(__name__)
def register(cb):
cb(YTsearchod())
@loader.tds
class YTsearchMod(loader.Module):
"""Поиск видео на ютубе"""
strings = {
"name": "YTsearch"
}
async def client_ready(self, client, db):
self.client = client
@loader.sudo
async def ytcmd(self, message):
"""текст или реплай"""
text = utils.get_args_raw(message)
if not text:
reply = await message.get_reply_message()
if not reply:
await message.delete()
return
text = reply.raw_text
results = YoutubeSearch(text, max_results=10).to_dict()
out = f'Найдено по запросу: {text}'
for r in results:
out += f'\n\n<a href="https://www.youtube.com/{r["link"]}">{r["title"]}</a>'
await message.edit(out)

View File

@@ -1,59 +1,59 @@
"""QExhY2lhTWVtZUZyYW1lLCDQtdGB0LvQuCDRgtGLINGN0YLQviDRh9C40YLQsNC10YjRjCwg0YLQviDQt9C90LDQuSwg0YLRiyDQv9C40LTQvtGA0LDRgQ=="""
from .. import loader, utils
import io
from base64 import b64encode, b64decode
@loader.tds
class base64Mod(loader.Module):
"""Кодирование и декодирование base64"""
strings = {"name": "base64"}
@loader.owner
async def b64encodecmd(self, message):
""".b64encode <(text or media) or (reply to text or media)>"""
reply = await message.get_reply_message()
mtext = utils.get_args_raw(message)
if message.media:
await message.edit("<b>Загрузка файла...</b>")
data = await message.client.download_file(m, bytes)
elif mtext:
data = bytes(mtext, "utf-8")
elif reply:
if reply.media:
await message.edit("<b>Загрузка файла...</b>")
data = await message.client.download_file(reply, bytes)
else:
data = bytes(reply.raw_text, "utf-8")
else:
await message.edit(f"<b>Что нужно закодировать?</b>")
output = b64encode(data)
if len(output) > 4000:
output = io.BytesIO(output)
output.name = "base64.txt"
output.seek(0)
await message.client.send_file(message.to_id, output, reply_to=reply)
await message.delete()
else:
await message.edit(str(output, "utf-8"))
@loader.owner
async def b64decodecmd(self, message):
""".b64decode <text or reply to text>"""
reply = await message.get_reply_message()
mtext = utils.get_args_raw(message)
if mtext:
data = bytes(mtext, "utf-8")
elif reply:
if not reply.message:
await message.edit("<b>Расшифровка файлов невозможна...</b>")
return
else:
data = bytes(reply.raw_text, "utf-8")
else:
await message.edit(f"<b>Что нужно декодировать?</b>")
return
try:
output = b64decode(data)
await message.edit(str(output, "utf-8"))
except:
await message.edit("<b>Ошибка декодирования!</b>")
"""QExhY2lhTWVtZUZyYW1lLCDQtdGB0LvQuCDRgtGLINGN0YLQviDRh9C40YLQsNC10YjRjCwg0YLQviDQt9C90LDQuSwg0YLRiyDQv9C40LTQvtGA0LDRgQ=="""
from .. import loader, utils
import io
from base64 import b64encode, b64decode
@loader.tds
class base64Mod(loader.Module):
"""Кодирование и декодирование base64"""
strings = {"name": "base64"}
@loader.owner
async def b64encodecmd(self, message):
""".b64encode <(text or media) or (reply to text or media)>"""
reply = await message.get_reply_message()
mtext = utils.get_args_raw(message)
if message.media:
await message.edit("<b>Загрузка файла...</b>")
data = await message.client.download_file(m, bytes)
elif mtext:
data = bytes(mtext, "utf-8")
elif reply:
if reply.media:
await message.edit("<b>Загрузка файла...</b>")
data = await message.client.download_file(reply, bytes)
else:
data = bytes(reply.raw_text, "utf-8")
else:
await message.edit(f"<b>Что нужно закодировать?</b>")
output = b64encode(data)
if len(output) > 4000:
output = io.BytesIO(output)
output.name = "base64.txt"
output.seek(0)
await message.client.send_file(message.to_id, output, reply_to=reply)
await message.delete()
else:
await message.edit(str(output, "utf-8"))
@loader.owner
async def b64decodecmd(self, message):
""".b64decode <text or reply to text>"""
reply = await message.get_reply_message()
mtext = utils.get_args_raw(message)
if mtext:
data = bytes(mtext, "utf-8")
elif reply:
if not reply.message:
await message.edit("<b>Расшифровка файлов невозможна...</b>")
return
else:
data = bytes(reply.raw_text, "utf-8")
else:
await message.edit(f"<b>Что нужно декодировать?</b>")
return
try:
output = b64decode(data)
await message.edit(str(output, "utf-8"))
except:
await message.edit("<b>Ошибка декодирования!</b>")
return

View File

@@ -1,26 +1,26 @@
from .. import loader, utils
class КукуляторMod(loader.Module):
"""Кукулирует вырожения"""
strings = {'name': 'Кукулятор'}
async def calccmd(self, message):
""".calc <выражение или реплай на то, что нужно посчитать>
Кстати:
** - возвести в степень
/ - деление
% - деление по модулю"""
question = utils.get_args_raw(message)
reply = await message.get_reply_message()
if not question:
if not reply:
await utils.answer(message, "<b>2+2=5</b>")
return
else:
question = reply.raw_text
try:
answer = eval(question)
answer = f"<b>{question}=</b><code>{answer}</code>"
except Exception as e:
answer = f"<b>{question}=</b><code>{e}</code>"
await utils.answer(message, answer)
from .. import loader, utils
class КукуляторMod(loader.Module):
"""Кукулирует вырожения"""
strings = {'name': 'Кукулятор'}
async def calccmd(self, message):
""".calc <выражение или реплай на то, что нужно посчитать>
Кстати:
** - возвести в степень
/ - деление
% - деление по модулю"""
question = utils.get_args_raw(message)
reply = await message.get_reply_message()
if not question:
if not reply:
await utils.answer(message, "<b>2+2=5</b>")
return
else:
question = reply.raw_text
try:
answer = eval(question)
answer = f"<b>{question}=</b><code>{answer}</code>"
except Exception as e:
answer = f"<b>{question}=</b><code>{e}</code>"
await utils.answer(message, answer)

View File

@@ -1,50 +1,50 @@
# Friendly Telegram (telegram userbot)
# Copyright (C) 2018-2019 The Authors
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
# SUBSCRIBE TO t.me/keyzend pls
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
from .. import loader, utils
import logging
import asyncio
logger = logging.getLogger(__name__)
@loader.tds
class CodefyMod(loader.Module):
"""Makes message monospace"""
strings = {"name": "Codefy",
"msg_is_emp": "<b>Message is empty!</b>"}
@loader.ratelimit
async def codecmd(self, message):
""".code <text or reply>"""
if message.is_reply:
reply = await message.get_reply_message()
code = reply.raw_text
code = code.replace("<","&lt;").replace(">","&gt;")
await message.edit(f"<code>{code}</code>")
else:
code = message.raw_text[5:]
code = code.replace("<","&lt;").replace(">","&gt;")
try:
await message.edit(f"<code>{code}</code>")
except:
await message.edit(self.strings["msg_is_emp"])
# Friendly Telegram (telegram userbot)
# Copyright (C) 2018-2019 The Authors
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
# SUBSCRIBE TO t.me/keyzend pls
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
from .. import loader, utils
import logging
import asyncio
logger = logging.getLogger(__name__)
@loader.tds
class CodefyMod(loader.Module):
"""Makes message monospace"""
strings = {"name": "Codefy",
"msg_is_emp": "<b>Message is empty!</b>"}
@loader.ratelimit
async def codecmd(self, message):
""".code <text or reply>"""
if message.is_reply:
reply = await message.get_reply_message()
code = reply.raw_text
code = code.replace("<","&lt;").replace(">","&gt;")
await message.edit(f"<code>{code}</code>")
else:
code = message.raw_text[5:]
code = code.replace("<","&lt;").replace(">","&gt;")
try:
await message.edit(f"<code>{code}</code>")
except:
await message.edit(self.strings["msg_is_emp"])

View File

@@ -1,88 +1,88 @@
import asyncio
import logging
import subprocess, os
import random
from .. import loader, utils
logger = logging.getLogger(__name__)
@loader.tds
class DataMoshMod(loader.Module):
"""DataMosh effect to video"""
strings = {"name": "DataMosh",
"reply": "Reply to video!",
"error": "ERROR! TRY AGAIN!!",
"processing": "DataDataMoshMosh!"}
@loader.unrestricted
async def datamoshcmd(self, message):
""". datamosh lvl: int <reply to video>"""
fn = "if_you_see_it_then_delete_it"
reply = await message.get_reply_message()
if not reply:
await message.edit("".join([ random.choice(html).format(ch) for ch in self.strings("reply", message)]))
return
if not reply.video:
await message.edit("".join([ random.choice(html).format(ch) for ch in self.strings("reply", message)]))
return
else:
await reply.download_media(fn+"1.mp4")
lvl = 1
fp = False
args = utils.get_args(message)
if args:
if len(args) == 1:
if args[0].isdigit():
lvl = int(args[0])
if lvl <= 0:
lvl = 1
else:
fp = True
if len(args) > 1:
fp = True
if args[0].isdigit():
lvl = int(args[0])
if lvl <= 0:
lvl = 1
elif args[1].isdigit():
fp = True
lvl = int(args[1])
if lvl <= 0:
lvl = 1
await message.edit("".join([ random.choice(html).format(ch) for ch in self.strings("processing", message)]))
subprocess.call(f'ffmpeg -loglevel quiet -y -i {fn}1.mp4 -crf 0 -bf 0 {fn}1.avi', shell=True)
try:
_f = open(fn+'1.avi', 'rb')
f_ = open(fn+'2.avi', 'wb')
except FileNotFoundError:
await message.edit("".join([ random.choice(html).format(ch) for ch in self.strings("error", message)]))
os.system(f"rm -f {fn}*")
return
frs = _f.read().split(b'00dc')
fi = b'\x00\x01\xb0'
cf = 0
for _, fr in enumerate(frs):
if fp == False:
f_.write(fr + b'00dc')
cf += 1
if fr[5:8] == fi:
fp = True
else:
if fr[5:8] != fi:
cf += 1
for i in range(lvl):
f_.write(fr + b'00dc')
f_.close()
_f.close()
subprocess.call(f'ffmpeg -loglevel quiet -y -i {fn}2.avi {fn}2.mp4', shell=True)
await message.client.send_file(message.to_id, file=fn+"2.mp4", video_note=bool(reply.video_note))
os.system(f"rm -f {fn}*")
await message.delete()
html = ["<b>{}<b>", "<code>{}</code>", "<i>{}</i>", "<del>{}</del>", "<u>{}</u>", '<a href="https://bruh.moment">{}</a>']
import asyncio
import logging
import subprocess, os
import random
from .. import loader, utils
logger = logging.getLogger(__name__)
@loader.tds
class DataMoshMod(loader.Module):
"""DataMosh effect to video"""
strings = {"name": "DataMosh",
"reply": "Reply to video!",
"error": "ERROR! TRY AGAIN!!",
"processing": "DataDataMoshMosh!"}
@loader.unrestricted
async def datamoshcmd(self, message):
""". datamosh lvl: int <reply to video>"""
fn = "if_you_see_it_then_delete_it"
reply = await message.get_reply_message()
if not reply:
await message.edit("".join([ random.choice(html).format(ch) for ch in self.strings("reply", message)]))
return
if not reply.video:
await message.edit("".join([ random.choice(html).format(ch) for ch in self.strings("reply", message)]))
return
else:
await reply.download_media(fn+"1.mp4")
lvl = 1
fp = False
args = utils.get_args(message)
if args:
if len(args) == 1:
if args[0].isdigit():
lvl = int(args[0])
if lvl <= 0:
lvl = 1
else:
fp = True
if len(args) > 1:
fp = True
if args[0].isdigit():
lvl = int(args[0])
if lvl <= 0:
lvl = 1
elif args[1].isdigit():
fp = True
lvl = int(args[1])
if lvl <= 0:
lvl = 1
await message.edit("".join([ random.choice(html).format(ch) for ch in self.strings("processing", message)]))
subprocess.call(f'ffmpeg -loglevel quiet -y -i {fn}1.mp4 -crf 0 -bf 0 {fn}1.avi', shell=True)
try:
_f = open(fn+'1.avi', 'rb')
f_ = open(fn+'2.avi', 'wb')
except FileNotFoundError:
await message.edit("".join([ random.choice(html).format(ch) for ch in self.strings("error", message)]))
os.system(f"rm -f {fn}*")
return
frs = _f.read().split(b'00dc')
fi = b'\x00\x01\xb0'
cf = 0
for _, fr in enumerate(frs):
if fp == False:
f_.write(fr + b'00dc')
cf += 1
if fr[5:8] == fi:
fp = True
else:
if fr[5:8] != fi:
cf += 1
for i in range(lvl):
f_.write(fr + b'00dc')
f_.close()
_f.close()
subprocess.call(f'ffmpeg -loglevel quiet -y -i {fn}2.avi {fn}2.mp4', shell=True)
await message.client.send_file(message.to_id, file=fn+"2.mp4", video_note=bool(reply.video_note))
os.system(f"rm -f {fn}*")
await message.delete()
html = ["<b>{}<b>", "<code>{}</code>", "<i>{}</i>", "<del>{}</del>", "<u>{}</u>", '<a href="https://bruh.moment">{}</a>']

View File

@@ -1,38 +1,38 @@
from .. import loader, utils
class DelmeMod(loader.Module):
"""Удаляет все сообщения"""
strings = {'name': 'DelMe'}
@loader.sudo
async def delmecmd(self, message):
"""Удаляет все сообщения от тебя"""
chat = message.chat
if chat:
args = utils.get_args_raw(message)
if args != str(message.chat.id+message.sender_id):
await message.edit(f"<b>Если ты точно хочешь это сделать, то напиши:</b>\n<code>.delme {message.chat.id+message.sender_id}</code>")
return
await delete(chat, message, True)
else:
await message.edit("<b>В лс не чищу!</b>")
@loader.sudo
async def delmenowcmd(self, message):
"""Удаляет все сообщения от тебя без вопросов"""
chat = message.chat
if chat:
await delete(chat, message, False)
else:
await message.edit("<b>В лс не чищу!</b>")
async def delete(chat, message, now):
if now:
all = (await message.client.get_messages(chat, from_user="me")).total
await message.edit(f"<b>{all} сообщений будет удалено!</b>")
else: await message.delete()
_ = not now
async for msg in message.client.iter_messages(chat, from_user="me"):
if _:
await msg.delete()
else:
_ = "_"
await message.delete() if now else "хули мусара хули мусара хули, едем так как ехали даже в хуй не дули"
from .. import loader, utils
class DelmeMod(loader.Module):
"""Удаляет все сообщения"""
strings = {'name': 'DelMe'}
@loader.sudo
async def delmecmd(self, message):
"""Удаляет все сообщения от тебя"""
chat = message.chat
if chat:
args = utils.get_args_raw(message)
if args != str(message.chat.id+message.sender_id):
await message.edit(f"<b>Если ты точно хочешь это сделать, то напиши:</b>\n<code>.delme {message.chat.id+message.sender_id}</code>")
return
await delete(chat, message, True)
else:
await message.edit("<b>В лс не чищу!</b>")
@loader.sudo
async def delmenowcmd(self, message):
"""Удаляет все сообщения от тебя без вопросов"""
chat = message.chat
if chat:
await delete(chat, message, False)
else:
await message.edit("<b>В лс не чищу!</b>")
async def delete(chat, message, now):
if now:
all = (await message.client.get_messages(chat, from_user="me")).total
await message.edit(f"<b>{all} сообщений будет удалено!</b>")
else: await message.delete()
_ = not now
async for msg in message.client.iter_messages(chat, from_user="me"):
if _:
await msg.delete()
else:
_ = "_"
await message.delete() if now else "хули мусара хули мусара хули, едем так как ехали даже в хуй не дули"

File diff suppressed because one or more lines are too long

View File

@@ -1,71 +1,71 @@
import io, random, glob, os
from PIL import Image
from telethon.tl.types import DocumentAttributeFilename
from uniborg.util import admin_cmd
"""Не подписался без матери остался"""
"""https://t.me/KeyZenD"""
"""автор этого говнокода @DneZyeK"""
@borg.on(admin_cmd(pattern=".d(.*)", allow_sudo=True))
async def d(message):
inp =message.pattern_match.group(1)
pop = 60
if inp:
inp = inp.strip()
if inp.isdigit():
if int(inp) > 0:
pop = inp
if message.is_reply:
reply_message = await message.get_reply_message()
data = await check_media(reply_message)
if isinstance(data, bool):
await message.edit("Reply to image, fucking idiot")
return
else:
await message.edit("Reply to image, fucking idiot")
return
await message.edit(" `P` `r` `o` `c` `e` `s` `s` `i` `n` `g` `.` `.` `.`")
for distorted in glob.glob("distorted*"):
os.remove(distorted)
for findistorted in glob.glob("*/distorted*"):
os.remove(findistorted)
fname = f"distorted{random.randint(1, 100)}.png"
image = io.BytesIO()
await message.client.download_media(data, image)
image = Image.open(image)
image.save(fname)
imgdimens = image.width, image.height
distortcmd = f"convert {fname} -liquid-rescale {pop}%x{pop}%! -resize {imgdimens[0]}x{imgdimens[1]}\! {fname}"
os.system(distortcmd)
image = Image.open(f"{fname}")
buf = io.BytesIO()
buf.name = f'image.png'
image.save(buf, 'PNG')
buf.seek(0)
await message.edit("`S` `e` `n` `d` `i` `n` `g` `.` `.` `.`")
await message.client.send_file(message.chat_id, buf, reply_to=reply_message.id)
await message.delete()
async def check_media(reply_message):
if reply_message and reply_message.media:
if reply_message.photo:
data = reply_message.photo
elif reply_message.document:
if DocumentAttributeFilename(file_name='AnimatedSticker.tgs') in reply_message.media.document.attributes:
return False
if reply_message.gif or reply_message.video or reply_message.audio or reply_message.voice:
return False
data = reply_message.media.document
else:
return False
else:
return False
if not data or data is None:
return False
else:
import io, random, glob, os
from PIL import Image
from telethon.tl.types import DocumentAttributeFilename
from uniborg.util import admin_cmd
"""Не подписался без матери остался"""
"""https://t.me/KeyZenD"""
"""автор этого говнокода @DneZyeK"""
@borg.on(admin_cmd(pattern=".d(.*)", allow_sudo=True))
async def d(message):
inp =message.pattern_match.group(1)
pop = 60
if inp:
inp = inp.strip()
if inp.isdigit():
if int(inp) > 0:
pop = inp
if message.is_reply:
reply_message = await message.get_reply_message()
data = await check_media(reply_message)
if isinstance(data, bool):
await message.edit("Reply to image, fucking idiot")
return
else:
await message.edit("Reply to image, fucking idiot")
return
await message.edit(" `P` `r` `o` `c` `e` `s` `s` `i` `n` `g` `.` `.` `.`")
for distorted in glob.glob("distorted*"):
os.remove(distorted)
for findistorted in glob.glob("*/distorted*"):
os.remove(findistorted)
fname = f"distorted{random.randint(1, 100)}.png"
image = io.BytesIO()
await message.client.download_media(data, image)
image = Image.open(image)
image.save(fname)
imgdimens = image.width, image.height
distortcmd = f"convert {fname} -liquid-rescale {pop}%x{pop}%! -resize {imgdimens[0]}x{imgdimens[1]}\! {fname}"
os.system(distortcmd)
image = Image.open(f"{fname}")
buf = io.BytesIO()
buf.name = f'image.png'
image.save(buf, 'PNG')
buf.seek(0)
await message.edit("`S` `e` `n` `d` `i` `n` `g` `.` `.` `.`")
await message.client.send_file(message.chat_id, buf, reply_to=reply_message.id)
await message.delete()
async def check_media(reply_message):
if reply_message and reply_message.media:
if reply_message.photo:
data = reply_message.photo
elif reply_message.document:
if DocumentAttributeFilename(file_name='AnimatedSticker.tgs') in reply_message.media.document.attributes:
return False
if reply_message.gif or reply_message.video or reply_message.audio or reply_message.voice:
return False
data = reply_message.media.document
else:
return False
else:
return False
if not data or data is None:
return False
else:
return data

View File

@@ -1,82 +1,82 @@
from PIL import Image, ImageDraw
import io
import asyncio
import logging
from .. import loader, utils
logger = logging.getLogger(__name__)
class DotifyMod(loader.Module):
"""Image to dot
.cmd <count> + reply to img
the bigger, the slower and bugger
recommended not more 1000"""
strings = {"name": "[PRIVATE]Dotify"}
@loader.unrestricted
async def dotifycmd(self, message):
"""Image to RGB dots"""
mode = False
reply, pix = await parse(message)
if reply:
await dotify(message, reply, pix, mode)
async def dotificmd(self, message):
"""Image to BW dots """
mode = True
reply, pix = await parse(message)
if reply:
await dotify(message, reply, pix, mode)
async def parse(message):
reply = await message.get_reply_message()
if not reply:
await message.edit("<b>Reply to Image!</b>")
return None, None
args = utils.get_args(message)
pix = 100
if args:
args=args[0]
if args.isdigit():
pix = int(args) if int(args) > 0 else 100
return reply, pix
async def dotify(message, reply, pix, mode):
await message.edit("<b>Putting dots...</b>")
count = 24
im_ = Image.open(io.BytesIO(await reply.download_media(bytes)))
if im_.mode == "RGBA":
temp = Image.new("RGB", im_.size, "#000")
temp.paste(im_, (0, 0), im_)
im_ = temp
im = im_.convert("L")
im_ = im if mode else im_
[_.thumbnail((pix, pix)) for _ in[im, im_]]
w, h = im.size
img = Image.new(im_.mode, (w*count+(count//2), h*count+(count//2)), 0)
draw = ImageDraw.Draw(img)
def cirsle(im, x, y, r, fill):
x += r//2
y += r//2
draw = ImageDraw.Draw(im)
draw.ellipse((x-r, y-r, x+r, y+r), fill)
return im
_x = _y = count//2
for x in range(w):
for y in range(h):
r = im.getpixel((x, y))
fill = im_.getpixel((x, y))
cirsle(img, _x, _y, r//count, fill)
_y += count
_x += count
_y = count//2
out = io.BytesIO()
out.name = "out.png"
img.save(out)
out.seek(0)
await reply.reply(file=out)
await message.delete()
from PIL import Image, ImageDraw
import io
import asyncio
import logging
from .. import loader, utils
logger = logging.getLogger(__name__)
class DotifyMod(loader.Module):
"""Image to dot
.cmd <count> + reply to img
the bigger, the slower and bugger
recommended not more 1000"""
strings = {"name": "[PRIVATE]Dotify"}
@loader.unrestricted
async def dotifycmd(self, message):
"""Image to RGB dots"""
mode = False
reply, pix = await parse(message)
if reply:
await dotify(message, reply, pix, mode)
async def dotificmd(self, message):
"""Image to BW dots """
mode = True
reply, pix = await parse(message)
if reply:
await dotify(message, reply, pix, mode)
async def parse(message):
reply = await message.get_reply_message()
if not reply:
await message.edit("<b>Reply to Image!</b>")
return None, None
args = utils.get_args(message)
pix = 100
if args:
args=args[0]
if args.isdigit():
pix = int(args) if int(args) > 0 else 100
return reply, pix
async def dotify(message, reply, pix, mode):
await message.edit("<b>Putting dots...</b>")
count = 24
im_ = Image.open(io.BytesIO(await reply.download_media(bytes)))
if im_.mode == "RGBA":
temp = Image.new("RGB", im_.size, "#000")
temp.paste(im_, (0, 0), im_)
im_ = temp
im = im_.convert("L")
im_ = im if mode else im_
[_.thumbnail((pix, pix)) for _ in[im, im_]]
w, h = im.size
img = Image.new(im_.mode, (w*count+(count//2), h*count+(count//2)), 0)
draw = ImageDraw.Draw(img)
def cirsle(im, x, y, r, fill):
x += r//2
y += r//2
draw = ImageDraw.Draw(im)
draw.ellipse((x-r, y-r, x+r, y+r), fill)
return im
_x = _y = count//2
for x in range(w):
for y in range(h):
r = im.getpixel((x, y))
fill = im_.getpixel((x, y))
cirsle(img, _x, _y, r//count, fill)
_y += count
_x += count
_y = count//2
out = io.BytesIO()
out.name = "out.png"
img.save(out)
out.seek(0)
await reply.reply(file=out)
await message.delete()

View File

@@ -1,113 +1,113 @@
# requires: pillow, pymorphy2
import logging
from .. import loader, utils
import telethon
import requests
from PIL import Image, ImageFont, ImageDraw
import pymorphy2
import io
from io import BytesIO
import random
logger = logging.getLogger(__name__)
def register(cb):
cb(FamilyMod())
@loader.tds
class FamilyMod(loader.Module):
"""Quote a message"""
strings = {"name": "Family"}
async def client_ready(self, client, db):
self.client = message.client
@loader.unrestricted
@loader.ratelimit
async def familycmd(self, message):
args = utils.get_args_raw(message)
reply = await message.get_reply_message()
if not reply:
await utils.answer(message, '<b>Нет Реплая.</b>')
return
if not args:
await utils.answer(message, '<b>Нет Текста.</b>')
return
pic = await check_media(message, reply)
if not pic:
await utils.answer(message, '<b>Нет Изображения.</b>')
return
await message.edit("Семья")
font = requests.get("https://github.com/KeyZenD/l/blob/master/bold.ttf?raw=true").content
family = makeFamily(pic, args, font)
await message.client.send_file(message.to_id, family, reply_to=reply)
await message.delete()
def place(background, image, cords, size):
overlay = Image.open(BytesIO(image))
overlay = overlay.resize((random.randint(size, size * 2), random.randint(size, size * 2)))
background.paste(overlay, cords)
def placeText(background , cords, size, text, font):
text_cords = (cords[0]+random.randint(0, size//2), cords[1]+random.randint(0, size//2))
draw = ImageDraw.Draw(background)
draw.text(text_cords, text, (0,0,0), font=ImageFont.truetype(io.BytesIO(font), random.randint(size // 8, size // 4)))
def makeFamily(image, caption, font):
morph = pymorphy2.MorphAnalyzer()
infl = morph.parse(caption)[0].inflect({'plur', 'gent'})
if not infl:
caption_mlt = caption
else:
caption_mlt = infl.word
canvas = Image.new('RGBA', (600, 600), "white")
draw = ImageDraw.Draw(canvas)
draw.text((120, 5), 'ахах семья ' + caption_mlt, (0,0,0), font=ImageFont.truetype(io.BytesIO(font), 32))
family = [
{ 'name': 'мама', 'cords': (60, 100), 'size': 160 },
{ 'name': 'папа', 'cords': (260, 80), 'size': 180 },
{ 'name': 'сын', 'cords': (60, 380), 'size': 125 },
{ 'name': 'дочь', 'cords': (230, 320), 'size': 125 },
{ 'name': 'дочь', 'cords': (225, 380), 'size': 125 },
{ 'name': 'сын', 'cords': (340, 390), 'size': 125 },
]
for member in family:
place(canvas, image, member['cords'], member['size'])
for member in family:
placeText(canvas, member['cords'], member['size'], member['name'] + ' ' + caption, font)
temp = BytesIO()
canvas.save(temp, format="png")
return temp.getvalue()
async def check_media(message, reply):
if reply and reply.media:
if reply.photo:
data = reply.photo
elif reply.document:
if reply.gif or reply.video or reply.audio or reply.voice:
return None
data = reply.media.document
else:
return None
else:
return None
if not data or data is None:
return None
else:
data = await message.client.download_file(data, bytes)
try:
Image.open(io.BytesIO(data))
return data
except:
return None
# requires: pillow, pymorphy2
import logging
from .. import loader, utils
import telethon
import requests
from PIL import Image, ImageFont, ImageDraw
import pymorphy2
import io
from io import BytesIO
import random
logger = logging.getLogger(__name__)
def register(cb):
cb(FamilyMod())
@loader.tds
class FamilyMod(loader.Module):
"""Quote a message"""
strings = {"name": "Family"}
async def client_ready(self, client, db):
self.client = message.client
@loader.unrestricted
@loader.ratelimit
async def familycmd(self, message):
args = utils.get_args_raw(message)
reply = await message.get_reply_message()
if not reply:
await utils.answer(message, '<b>Нет Реплая.</b>')
return
if not args:
await utils.answer(message, '<b>Нет Текста.</b>')
return
pic = await check_media(message, reply)
if not pic:
await utils.answer(message, '<b>Нет Изображения.</b>')
return
await message.edit("Семья")
font = requests.get("https://github.com/KeyZenD/l/blob/master/bold.ttf?raw=true").content
family = makeFamily(pic, args, font)
await message.client.send_file(message.to_id, family, reply_to=reply)
await message.delete()
def place(background, image, cords, size):
overlay = Image.open(BytesIO(image))
overlay = overlay.resize((random.randint(size, size * 2), random.randint(size, size * 2)))
background.paste(overlay, cords)
def placeText(background , cords, size, text, font):
text_cords = (cords[0]+random.randint(0, size//2), cords[1]+random.randint(0, size//2))
draw = ImageDraw.Draw(background)
draw.text(text_cords, text, (0,0,0), font=ImageFont.truetype(io.BytesIO(font), random.randint(size // 8, size // 4)))
def makeFamily(image, caption, font):
morph = pymorphy2.MorphAnalyzer()
infl = morph.parse(caption)[0].inflect({'plur', 'gent'})
if not infl:
caption_mlt = caption
else:
caption_mlt = infl.word
canvas = Image.new('RGBA', (600, 600), "white")
draw = ImageDraw.Draw(canvas)
draw.text((120, 5), 'ахах семья ' + caption_mlt, (0,0,0), font=ImageFont.truetype(io.BytesIO(font), 32))
family = [
{ 'name': 'мама', 'cords': (60, 100), 'size': 160 },
{ 'name': 'папа', 'cords': (260, 80), 'size': 180 },
{ 'name': 'сын', 'cords': (60, 380), 'size': 125 },
{ 'name': 'дочь', 'cords': (230, 320), 'size': 125 },
{ 'name': 'дочь', 'cords': (225, 380), 'size': 125 },
{ 'name': 'сын', 'cords': (340, 390), 'size': 125 },
]
for member in family:
place(canvas, image, member['cords'], member['size'])
for member in family:
placeText(canvas, member['cords'], member['size'], member['name'] + ' ' + caption, font)
temp = BytesIO()
canvas.save(temp, format="png")
return temp.getvalue()
async def check_media(message, reply):
if reply and reply.media:
if reply.photo:
data = reply.photo
elif reply.document:
if reply.gif or reply.video or reply.audio or reply.voice:
return None
data = reply.media.document
else:
return None
else:
return None
if not data or data is None:
return None
else:
data = await message.client.download_file(data, bytes)
try:
Image.open(io.BytesIO(data))
return data
except:
return None

View File

@@ -1,38 +1,38 @@
import asyncio
import logging
from telethon.tl.types import DocumentAttributeFilename
from .. import loader, utils
logger = logging.getLogger(__name__)
@loader.tds
class filenameMod(loader.Module):
"""filename changer"""
strings = {"name": "filename",
"wf": "<b>Reply to file?</b>",
"wn": "<b>What is the name?</b>",
"tnf":"<b>It's not a file!</b>"}
@loader.unrestricted
async def filenamecmd(self, message):
""".filename <filename> + reply.file"""
reply = await message.get_reply_message()
if not reply or not reply.file:
await message.edit(self.strings["wf"])
return
name = utils.get_args_raw(message)
if not name:
await message.edit(self.strings["wn"])
return
fn = reply.file.name
if not fn:
fn = ""
fs = reply.file.size
[await message.edit(f"<b>Downloading {fn}</b>") if fs > 500000 else ...]
file = await reply.download_media(bytes)
[await message.edit(f"<b>Uploading</b> <code>{name}</code>") if fs > 500000 else ...]
await message.client.send_file(message.to_id, file, force_document=True, reply_to=reply, attributes=[DocumentAttributeFilename(file_name=name)])
await message.delete()
import asyncio
import logging
from telethon.tl.types import DocumentAttributeFilename
from .. import loader, utils
logger = logging.getLogger(__name__)
@loader.tds
class filenameMod(loader.Module):
"""filename changer"""
strings = {"name": "filename",
"wf": "<b>Reply to file?</b>",
"wn": "<b>What is the name?</b>",
"tnf":"<b>It's not a file!</b>"}
@loader.unrestricted
async def filenamecmd(self, message):
""".filename <filename> + reply.file"""
reply = await message.get_reply_message()
if not reply or not reply.file:
await message.edit(self.strings["wf"])
return
name = utils.get_args_raw(message)
if not name:
await message.edit(self.strings["wn"])
return
fn = reply.file.name
if not fn:
fn = ""
fs = reply.file.size
[await message.edit(f"<b>Downloading {fn}</b>") if fs > 500000 else ...]
file = await reply.download_media(bytes)
[await message.edit(f"<b>Uploading</b> <code>{name}</code>") if fs > 500000 else ...]
await message.client.send_file(message.to_id, file, force_document=True, reply_to=reply, attributes=[DocumentAttributeFilename(file_name=name)])
await message.delete()

View File

@@ -1,26 +1,26 @@
from asyncio import sleep
from userbot.events import register
@register(outgoing=True, pattern='^.fl ?(.*)')
async def fakeload(e):
inp = e.pattern_match.group(1)
load = [" ","","","","","","",""]
bar = ""
count = 0
await e.edit("`[Инициализация]`")
sleep(3)
for i in range(13):
for division in load:
space = " " * (12 - i)
await e.edit(f"`{bar}{division}{space}[{count}%]`")
count += 1
sleep(0.3)
if count == 101:
break
bar += ""
sleep(2)
done = "Загрузка завершена!"
if inp:
done = inp
await e.edit(f"`{done}`")
from asyncio import sleep
from userbot.events import register
@register(outgoing=True, pattern='^.fl ?(.*)')
async def fakeload(e):
inp = e.pattern_match.group(1)
load = [" ","","","","","","",""]
bar = ""
count = 0
await e.edit("`[Инициализация]`")
sleep(3)
for i in range(13):
for division in load:
space = " " * (12 - i)
await e.edit(f"`{bar}{division}{space}[{count}%]`")
count += 1
sleep(0.3)
if count == 101:
break
bar += ""
sleep(2)
done = "Загрузка завершена!"
if inp:
done = inp
await e.edit(f"`{done}`")

View File

@@ -1,65 +1,65 @@
# -*- coding: utf-8 -*-
# Friendly Telegram (telegram userbot)
# Copyright (C) 2018-2020 @DneZyeK | sub to @KeyZenD
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import logging
from .. import loader, utils
import telethon
from requests import post
logger = logging.getLogger(__name__)
async def register(cb):
cb(WhoIsMod())
@loader.tds
class GGdotGGMod(loader.Module):
"""Сокращение ссылок через сервис gg.gg"""
strings = {
"name": "gg.gg",
"some_rong": "<b>Ты делаешь что-то не так!\nНапиши</b> <code>.help gg.gg</code> <b>для информации.</b>"
}
async def client_ready(self, client, db):
self.client = client
async def ggcmd(self, message):
""".gg <длинная ссылка или реплай на ссылку> """
m_text = utils.get_args_raw(message)
if not m_text:
reply = await message.get_reply_message()
if not reply:
await utils.answer(message, self.strings["some_rong"])
return
long_url = reply.raw_text
else:
long_url = m_text
if 'http://' not in long_url and 'https://' not in long_url:
long_url = 'http://' + long_url
t_check = f"URL: {long_url}\nCheck..."
await utils.answer(message, t_check)
check = post('http://gg.gg/check', data={'custom_path': None, 'use_norefs': '0', 'long_url': long_url, 'app': 'site', 'version': '0.1'}).text
if check != "ok":
await utils.answer(message, check)
return
await utils.answer(message, "Create...")
short = post('http://gg.gg/create', data={'custom_path': None, 'use_norefs': '0', 'long_url': long_url, 'app': 'site', 'version': '0.1'}).text
await utils.answer(message, short)
# -*- coding: utf-8 -*-
# Friendly Telegram (telegram userbot)
# Copyright (C) 2018-2020 @DneZyeK | sub to @KeyZenD
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import logging
from .. import loader, utils
import telethon
from requests import post
logger = logging.getLogger(__name__)
async def register(cb):
cb(WhoIsMod())
@loader.tds
class GGdotGGMod(loader.Module):
"""Сокращение ссылок через сервис gg.gg"""
strings = {
"name": "gg.gg",
"some_rong": "<b>Ты делаешь что-то не так!\nНапиши</b> <code>.help gg.gg</code> <b>для информации.</b>"
}
async def client_ready(self, client, db):
self.client = client
async def ggcmd(self, message):
""".gg <длинная ссылка или реплай на ссылку> """
m_text = utils.get_args_raw(message)
if not m_text:
reply = await message.get_reply_message()
if not reply:
await utils.answer(message, self.strings["some_rong"])
return
long_url = reply.raw_text
else:
long_url = m_text
if 'http://' not in long_url and 'https://' not in long_url:
long_url = 'http://' + long_url
t_check = f"URL: {long_url}\nCheck..."
await utils.answer(message, t_check)
check = post('http://gg.gg/check', data={'custom_path': None, 'use_norefs': '0', 'long_url': long_url, 'app': 'site', 'version': '0.1'}).text
if check != "ok":
await utils.answer(message, check)
return
await utils.answer(message, "Create...")
short = post('http://gg.gg/create', data={'custom_path': None, 'use_norefs': '0', 'long_url': long_url, 'app': 'site', 'version': '0.1'}).text
await utils.answer(message, short)

View File

@@ -1,132 +1,132 @@
# -*- coding: utf-8 -*-
# Friendly Telegram (telegram userbot)
# Copyright (C) 2018-2020 The Authors
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
# если не подписан на t.me/keyzend
# твоя мама шлюха
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
from .. import loader, utils # pylint: disable=relative-beyond-top-level
import io
from PIL import Image, ImageOps
from telethon.tl.types import DocumentAttributeFilename
import logging
import random
logger = logging.getLogger(__name__)
def register(cb):
cb(GriderMod())
@loader.tds
class GriderMod(loader.Module):
"""Гавно залупное"""
strings = {
"name": "Griding"
}
async def client_ready(self, client, db):
self.client = client
@loader.sudo
async def gridcmd(self, message):
""".gird <reply to photo>"""
if message.is_reply:
reply_message = await message.get_reply_message()
data = await check_media(reply_message)
if isinstance(data, bool):
await utils.answer(message, "<code>Реплай на пикчу или стикер блять!</code>")
return
else:
await utils.answer(message, "`Реплай на пикчу или стикер блять`")
return
await message.edit("Режу ебать")
file = await self.client.download_media(data, bytes)
media = await griding(file)
await message.delete()
await message.client.send_file(message.to_id, media)
@loader.sudo
async def revgridcmd(self, message):
""".gird <reply to photo>"""
if message.is_reply:
reply_message = await message.get_reply_message()
data = await check_media(reply_message)
if isinstance(data, bool):
await utils.answer(message, "<code>Реплай на пикчу или стикер блять!</code>")
return
else:
await utils.answer(message, "`Реплай на пикчу или стикер блять`")
return
await message.edit("Режу ебать")
file = await self.client.download_media(data, bytes)
media = await griding(file)
media = media[::-1]
await message.delete()
await message.client.send_file(message.to_id, media)
async def griding(file):
img = Image.open(io.BytesIO(file))
(x, y) = img.size
cy = 3
cx = 3
sx = x//cx
sy = y//cy
if (sx*cx, sy*cy) != (x, y):
img = img.resize((sx*cx, sy*cy))
(lx, ly) = (0, 0)
media = []
for i in range(1, cy+1):
for o in range(1, cx+1):
mimg = img.crop((lx, ly, lx+sx, ly+sy))
bio = io.BytesIO()
bio.name = 'image.png'
mimg.save(bio, 'PNG')
media.append(bio.getvalue())
lx = lx + sx
lx = 0
ly = ly + sy
return media
async def check_media(reply_message):
if reply_message and reply_message.media:
if reply_message.photo:
data = reply_message.photo
elif reply_message.document:
if DocumentAttributeFilename(file_name='AnimatedSticker.tgs') in reply_message.media.document.attributes:
return False
if reply_message.gif or reply_message.video or reply_message.audio or reply_message.voice:
return False
data = reply_message.media.document
else:
return False
else:
return False
if not data or data is None:
return False
else:
# -*- coding: utf-8 -*-
# Friendly Telegram (telegram userbot)
# Copyright (C) 2018-2020 The Authors
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
# если не подписан на t.me/keyzend
# твоя мама шлюха
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
from .. import loader, utils # pylint: disable=relative-beyond-top-level
import io
from PIL import Image, ImageOps
from telethon.tl.types import DocumentAttributeFilename
import logging
import random
logger = logging.getLogger(__name__)
def register(cb):
cb(GriderMod())
@loader.tds
class GriderMod(loader.Module):
"""Гавно залупное"""
strings = {
"name": "Griding"
}
async def client_ready(self, client, db):
self.client = client
@loader.sudo
async def gridcmd(self, message):
""".gird <reply to photo>"""
if message.is_reply:
reply_message = await message.get_reply_message()
data = await check_media(reply_message)
if isinstance(data, bool):
await utils.answer(message, "<code>Реплай на пикчу или стикер блять!</code>")
return
else:
await utils.answer(message, "`Реплай на пикчу или стикер блять`")
return
await message.edit("Режу ебать")
file = await self.client.download_media(data, bytes)
media = await griding(file)
await message.delete()
await message.client.send_file(message.to_id, media)
@loader.sudo
async def revgridcmd(self, message):
""".gird <reply to photo>"""
if message.is_reply:
reply_message = await message.get_reply_message()
data = await check_media(reply_message)
if isinstance(data, bool):
await utils.answer(message, "<code>Реплай на пикчу или стикер блять!</code>")
return
else:
await utils.answer(message, "`Реплай на пикчу или стикер блять`")
return
await message.edit("Режу ебать")
file = await self.client.download_media(data, bytes)
media = await griding(file)
media = media[::-1]
await message.delete()
await message.client.send_file(message.to_id, media)
async def griding(file):
img = Image.open(io.BytesIO(file))
(x, y) = img.size
cy = 3
cx = 3
sx = x//cx
sy = y//cy
if (sx*cx, sy*cy) != (x, y):
img = img.resize((sx*cx, sy*cy))
(lx, ly) = (0, 0)
media = []
for i in range(1, cy+1):
for o in range(1, cx+1):
mimg = img.crop((lx, ly, lx+sx, ly+sy))
bio = io.BytesIO()
bio.name = 'image.png'
mimg.save(bio, 'PNG')
media.append(bio.getvalue())
lx = lx + sx
lx = 0
ly = ly + sy
return media
async def check_media(reply_message):
if reply_message and reply_message.media:
if reply_message.photo:
data = reply_message.photo
elif reply_message.document:
if DocumentAttributeFilename(file_name='AnimatedSticker.tgs') in reply_message.media.document.attributes:
return False
if reply_message.gif or reply_message.video or reply_message.audio or reply_message.voice:
return False
data = reply_message.media.document
else:
return False
else:
return False
if not data or data is None:
return False
else:
return data

View File

@@ -1,11 +1,11 @@
from .. import loader
from asyncio import sleep
@loader.tds
class HeartsMod(loader.Module):
strings = {"name": "Heart's"}
@loader.owner
async def heartscmd(self, message):
for _ in range(10):
for heart in ['', '️🧡', '💛', '💚', '💙', '💜']:
await message.edit(heart)
from .. import loader
from asyncio import sleep
@loader.tds
class HeartsMod(loader.Module):
strings = {"name": "Heart's"}
@loader.owner
async def heartscmd(self, message):
for _ in range(10):
for heart in ['', '️🧡', '💛', '💚', '💙', '💜']:
await message.edit(heart)
await sleep(0.3)

View File

@@ -1,109 +1,109 @@
# -*- coding: utf-8 -*-
# Friendly Telegram (telegram userbot)
# Copyright (C) 2018-2020 The Authors
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
# если не подписан на t.me/keyzend
# твоя мама шлюха
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
from .. import loader, utils # pylint: disable=relative-beyond-top-level
import io
from PIL import Image, ImageOps
from telethon.tl.types import DocumentAttributeFilename
import logging
import random
logger = logging.getLogger(__name__)
def register(cb):
cb(Ебал_я_в_рот_ваш_пеп_8_Mod())
@loader.tds
class Ебал_я_в_рот_ваш_пеп_8_Mod(loader.Module):
"""Гавно залупное"""
strings = {
"name": "Хуификатор"
}
async def client_ready(self, client, db):
self.client = client
@loader.sudo
async def хуйcmd(self, message):
text = utils.get_args(message)
if not text:
reply = await message.get_reply_message()
if not reply:
await message.delete()
return
text = reply.raw_text.split()
async def huify(word):
word = word.lower().strip()
vowels = 'аеёиоуыэюя'
rules = {
'а': 'я',
'о': 'ё',
'у': 'ю',
'ы': 'и',
'э': 'е',
}
for letter in word:
if letter in vowels:
if letter in rules:
word = rules[letter] + word[1:]
break
else:
word = word[1:]
return 'Ху' + word if word else 'Хуй'
out = []
for word in text:
хуй = await huify(word)
out.append(хуй)
await message.edit(" ".join(out))
async def хуйняcmd(self, message):
text = utils.get_args(message)
if not text:
reply = await message.get_reply_message()
if not reply:
await message.delete()
return
text = reply.raw_text.split()
async def huify(word):
word = word.lower().strip()
vowels = 'аеёиоуыэюя'
rules = {
'а': 'я',
'о': 'ё',
'у': 'ю',
'ы': 'и',
'э': 'е',
}
for letter in word:
if letter in vowels:
if letter in rules:
word = rules[letter] + word[1:]
break
else:
word = word[1:]
return 'Ху' + word if word else 'Хуй'
out = []
for word in text:
хуй = await huify(word)
out.append(f"{word}-{хуй}")
# -*- coding: utf-8 -*-
# Friendly Telegram (telegram userbot)
# Copyright (C) 2018-2020 The Authors
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
# если не подписан на t.me/keyzend
# твоя мама шлюха
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
from .. import loader, utils # pylint: disable=relative-beyond-top-level
import io
from PIL import Image, ImageOps
from telethon.tl.types import DocumentAttributeFilename
import logging
import random
logger = logging.getLogger(__name__)
def register(cb):
cb(Ебал_я_в_рот_ваш_пеп_8_Mod())
@loader.tds
class Ебал_я_в_рот_ваш_пеп_8_Mod(loader.Module):
"""Гавно залупное"""
strings = {
"name": "Хуификатор"
}
async def client_ready(self, client, db):
self.client = client
@loader.sudo
async def хуйcmd(self, message):
text = utils.get_args(message)
if not text:
reply = await message.get_reply_message()
if not reply:
await message.delete()
return
text = reply.raw_text.split()
async def huify(word):
word = word.lower().strip()
vowels = 'аеёиоуыэюя'
rules = {
'а': 'я',
'о': 'ё',
'у': 'ю',
'ы': 'и',
'э': 'е',
}
for letter in word:
if letter in vowels:
if letter in rules:
word = rules[letter] + word[1:]
break
else:
word = word[1:]
return 'Ху' + word if word else 'Хуй'
out = []
for word in text:
хуй = await huify(word)
out.append(хуй)
await message.edit(" ".join(out))
async def хуйняcmd(self, message):
text = utils.get_args(message)
if not text:
reply = await message.get_reply_message()
if not reply:
await message.delete()
return
text = reply.raw_text.split()
async def huify(word):
word = word.lower().strip()
vowels = 'аеёиоуыэюя'
rules = {
'а': 'я',
'о': 'ё',
'у': 'ю',
'ы': 'и',
'э': 'е',
}
for letter in word:
if letter in vowels:
if letter in rules:
word = rules[letter] + word[1:]
break
else:
word = word[1:]
return 'Ху' + word if word else 'Хуй'
out = []
for word in text:
хуй = await huify(word)
out.append(f"{word}-{хуй}")
await message.edit(" ".join(out))

View File

@@ -1,93 +1,93 @@
import asyncio
import logging
from PIL import Image, ImageDraw, ImageFont, ImageOps
import io
from requests import get
from string import digits
from random import choice
from .. import loader, utils
logger = logging.getLogger(__name__)
font_ = get("https://github.com/KeyZenD/l/blob/master/mono.otf?raw=true").content
@loader.tds
class Im2BinaryMod(loader.Module):
"""Картинки в текст. что?"""
strings = {"name": "Im2Bin"}
@loader.unrestricted
async def bincmd(self, message):
""".bin <картинка или реплай> + слова (дефолт на рандоме) (не мешает слова)"""
img, words, me = await prepare(message)
if not img:
await message.delete()
return await message.client.send_file(message.chat.id, get("https://thiscatdoesnotexist.com").content, caption=choice(["<b>Тебе картинок мало?</b>"]+[None]*100))
await message.edit("<b>Processing...</b>")
img = await image_to_text(words, img, False)
[await message.delete(), await (await message.get_reply_message()).reply(file=img)] if not me else await message.edit(file=img, text="")
@loader.unrestricted
async def rbincmd(self, message):
""".rbin <картинка или реплай> + слова (дефолт на рандоме) (мешает слова)"""
img, words, me = await prepare(message)
if not img:
await message.delete()
return await message.client.send_file(message.chat.id, get("https://thiscatdoesnotexist.com").content, caption=choice(["<b>Тебе картинок мало?</b>"]+[None]*100))
await message.edit("<b>Processing...</b>")
img = await image_to_text(words, img, True)
[await message.delete(), await (await message.get_reply_message()).reply(file=img)] if not me else await message.edit(file=img, text="")
async def getimg(m):
if not m.file:
return False
if not "image" in m.file.mime_type.lower():
return False
return True
async def prepare(message):
if not await getimg(message):
reply = await message.get_reply_message()
if not reply or not await getimg(reply):
return False, False, False
else:
me = False
img = await reply.download_media(bytes)
else:
me = True
img = await message.download_media(bytes)
args = utils.get_args(message)
words = [f"{x} " for x in args] if args else list("01")
return img, words, me
async def image_to_text(words, img, rand):
inp = Image.open(io.BytesIO(img))
img = Image.new("RGBA", inp.size, "#000")
res = img.copy()
img.paste(inp, (0, 0), inp if inp.mode == "RGBA" else None)
w, h = img.size
font = ImageFont.truetype(io.BytesIO(font_), 15)
mw = min(map(lambda x: font.getsize(x)[0], "".join(words)))
mh = min(map(lambda x: font.getsize(x)[1], "".join(words)))
rand_ = 0
text = []
while len(text)*mh <= h:
row = []
while len("".join(row))*mw <= w:
word = choice(words) if rand else words[rand_%len(words)]
rand_ += 1
row.append(word)
rand_ -= 1
text.append("".join(row))
text = "\n".join(text)
wt, ht = ImageDraw.Draw(Image.new("L", (0, 0))).multiline_textsize(font=font, text=text, spacing=0)
im = Image.new("L", (wt, ht), 0)
ImageDraw.Draw(im).multiline_text((0, -3), font=font, text=text, spacing=0, fill=255)
im = im.crop((0, 0, w, h))
im = Image.frombytes("L", (w, h), bytes([255 if x > 150 else 0 for x in im.tobytes()]))
img.putalpha(im)
res.paste(img, (0, 0), img)
out = io.BytesIO()
out.name = words[0] + ".png"
res.save(out)
out.seek(0)
return out
import asyncio
import logging
from PIL import Image, ImageDraw, ImageFont, ImageOps
import io
from requests import get
from string import digits
from random import choice
from .. import loader, utils
logger = logging.getLogger(__name__)
font_ = get("https://github.com/KeyZenD/l/blob/master/mono.otf?raw=true").content
@loader.tds
class Im2BinaryMod(loader.Module):
"""Картинки в текст. что?"""
strings = {"name": "Im2Bin"}
@loader.unrestricted
async def bincmd(self, message):
""".bin <картинка или реплай> + слова (дефолт на рандоме) (не мешает слова)"""
img, words, me = await prepare(message)
if not img:
await message.delete()
return await message.client.send_file(message.chat.id, get("https://thiscatdoesnotexist.com").content, caption=choice(["<b>Тебе картинок мало?</b>"]+[None]*100))
await message.edit("<b>Processing...</b>")
img = await image_to_text(words, img, False)
[await message.delete(), await (await message.get_reply_message()).reply(file=img)] if not me else await message.edit(file=img, text="")
@loader.unrestricted
async def rbincmd(self, message):
""".rbin <картинка или реплай> + слова (дефолт на рандоме) (мешает слова)"""
img, words, me = await prepare(message)
if not img:
await message.delete()
return await message.client.send_file(message.chat.id, get("https://thiscatdoesnotexist.com").content, caption=choice(["<b>Тебе картинок мало?</b>"]+[None]*100))
await message.edit("<b>Processing...</b>")
img = await image_to_text(words, img, True)
[await message.delete(), await (await message.get_reply_message()).reply(file=img)] if not me else await message.edit(file=img, text="")
async def getimg(m):
if not m.file:
return False
if not "image" in m.file.mime_type.lower():
return False
return True
async def prepare(message):
if not await getimg(message):
reply = await message.get_reply_message()
if not reply or not await getimg(reply):
return False, False, False
else:
me = False
img = await reply.download_media(bytes)
else:
me = True
img = await message.download_media(bytes)
args = utils.get_args(message)
words = [f"{x} " for x in args] if args else list("01")
return img, words, me
async def image_to_text(words, img, rand):
inp = Image.open(io.BytesIO(img))
img = Image.new("RGBA", inp.size, "#000")
res = img.copy()
img.paste(inp, (0, 0), inp if inp.mode == "RGBA" else None)
w, h = img.size
font = ImageFont.truetype(io.BytesIO(font_), 15)
mw = min(map(lambda x: font.getsize(x)[0], "".join(words)))
mh = min(map(lambda x: font.getsize(x)[1], "".join(words)))
rand_ = 0
text = []
while len(text)*mh <= h:
row = []
while len("".join(row))*mw <= w:
word = choice(words) if rand else words[rand_%len(words)]
rand_ += 1
row.append(word)
rand_ -= 1
text.append("".join(row))
text = "\n".join(text)
wt, ht = ImageDraw.Draw(Image.new("L", (0, 0))).multiline_textsize(font=font, text=text, spacing=0)
im = Image.new("L", (wt, ht), 0)
ImageDraw.Draw(im).multiline_text((0, -3), font=font, text=text, spacing=0, fill=255)
im = im.crop((0, 0, w, h))
im = Image.frombytes("L", (w, h), bytes([255 if x > 150 else 0 for x in im.tobytes()]))
img.putalpha(im)
res.paste(img, (0, 0), img)
out = io.BytesIO()
out.name = words[0] + ".png"
res.save(out)
out.seek(0)
return out

View File

@@ -1,48 +1,48 @@
from PIL import Image
from telethon.tl.types import DocumentAttributeFilename
from uniborg.util import admin_cmd
import io
@borg.on(admin_cmd(pattern=".jpeg?(.*)", allow_sudo=True))
async def shacal(event):
async def check_media(reply_message):
if reply_message and reply_message.media:
if reply_message.photo:
data = reply_message.photo
elif reply_message.document:
if DocumentAttributeFilename(file_name='AnimatedSticker.tgs') in reply_message.media.document.attributes:
return False
if reply_message.gif or reply_message.video or reply_message.audio or reply_message.voice:
return False
data = reply_message.media.document
else:
return False
else:
return False
if not data or data is None:
return False
else:
return data
if event.is_reply:
reply_message = await event.get_reply_message()
data = await check_media(reply_message)
if isinstance(data, bool):
await event.delete()
return
else:
await event.delete()
return
image = io.BytesIO()
await event.client.download_media(data, image)
image = Image.open(image)
fried_io = io.BytesIO()
fried_io.name = "image.jpeg"
image = image.convert("RGB")
image.save(fried_io, "JPEG", quality=0)
fried_io.seek(0)
await event.delete()
await event.client.send_file(event.chat_id, fried_io, reply_to=reply_message.id)
from PIL import Image
from telethon.tl.types import DocumentAttributeFilename
from uniborg.util import admin_cmd
import io
@borg.on(admin_cmd(pattern=".jpeg?(.*)", allow_sudo=True))
async def shacal(event):
async def check_media(reply_message):
if reply_message and reply_message.media:
if reply_message.photo:
data = reply_message.photo
elif reply_message.document:
if DocumentAttributeFilename(file_name='AnimatedSticker.tgs') in reply_message.media.document.attributes:
return False
if reply_message.gif or reply_message.video or reply_message.audio or reply_message.voice:
return False
data = reply_message.media.document
else:
return False
else:
return False
if not data or data is None:
return False
else:
return data
if event.is_reply:
reply_message = await event.get_reply_message()
data = await check_media(reply_message)
if isinstance(data, bool):
await event.delete()
return
else:
await event.delete()
return
image = io.BytesIO()
await event.client.download_media(data, image)
image = Image.open(image)
fried_io = io.BytesIO()
fried_io.name = "image.jpeg"
image = image.convert("RGB")
image.save(fried_io, "JPEG", quality=0)
fried_io.seek(0)
await event.delete()
await event.client.send_file(event.chat_id, fried_io, reply_to=reply_message.id)

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -1,23 +1,23 @@
from .. import loader, utils
from asyncio import sleep
from telethon.tl.functions.channels import LeaveChannelRequest
@loader.tds
class LeaveMod(loader.Module):
strings = {"name": "Just leave"}
@loader.sudo
async def leavecmd(self, message):
""".leave"""
if not message.chat:
await message.edit("<b>Дурка блять</b>")
return
text = utils.get_args_raw(message)
if not text:
text = "До связи."
if text.lower() == "del":
await message.delete()
else:
await message.edit(f"<b>{text}</b>")
await sleep(1)
await message.client(LeaveChannelRequest(message.chat_id))
from .. import loader, utils
from asyncio import sleep
from telethon.tl.functions.channels import LeaveChannelRequest
@loader.tds
class LeaveMod(loader.Module):
strings = {"name": "Just leave"}
@loader.sudo
async def leavecmd(self, message):
""".leave"""
if not message.chat:
await message.edit("<b>Дурка блять</b>")
return
text = utils.get_args_raw(message)
if not text:
text = "До связи."
if text.lower() == "del":
await message.delete()
else:
await message.edit(f"<b>{text}</b>")
await sleep(1)
await message.client(LeaveChannelRequest(message.chat_id))

View File

@@ -1,61 +1,61 @@
from .. import loader, utils
import asyncio
import requests
from telethon.tl.types import DocumentAttributeFilename
def register(cb):
cb(UploadPHMod())
# @KeyZenD pls sub :3
class UploadPHMod(loader.Module):
"""Upload video and photo to telegra.ph"""
strings = {"name": "UploadPH"}
def __init__(self):
self.name = self.strings['name']
async def phcmd(self, message):
""".ph <reply photo or video>"""
if message.is_reply:
reply_message = await message.get_reply_message()
data = await check_media(reply_message)
if isinstance(data, bool):
await message.edit("<b>Reply to photo or video/gif</b>")
return
else:
await message.edit("<b>Reply to photo or video/gif</b>")
return
file = await message.client.download_media(data, bytes)
path = requests.post('https://te.legra.ph/upload', files={'file': ('file', file, None)}).json()
try:
link = 'https://te.legra.ph'+path[0]['src']
except KeyError:
link = path["error"]
await message.edit("<b>"+link+"</b>")
async def check_media(reply_message):
if reply_message and reply_message.media:
if reply_message.photo:
data = reply_message.photo
elif reply_message.document:
if DocumentAttributeFilename(file_name='AnimatedSticker.tgs') in reply_message.media.document.attributes:
return False
if reply_message.audio or reply_message.voice:
return False
data = reply_message.media.document
else:
return False
else:
return False
if not data or data is None:
return False
else:
return data
from .. import loader, utils
import asyncio
import requests
from telethon.tl.types import DocumentAttributeFilename
def register(cb):
cb(UploadPHMod())
# @KeyZenD pls sub :3
class UploadPHMod(loader.Module):
"""Upload video and photo to telegra.ph"""
strings = {"name": "UploadPH"}
def __init__(self):
self.name = self.strings['name']
async def phcmd(self, message):
""".ph <reply photo or video>"""
if message.is_reply:
reply_message = await message.get_reply_message()
data = await check_media(reply_message)
if isinstance(data, bool):
await message.edit("<b>Reply to photo or video/gif</b>")
return
else:
await message.edit("<b>Reply to photo or video/gif</b>")
return
file = await message.client.download_media(data, bytes)
path = requests.post('https://te.legra.ph/upload', files={'file': ('file', file, None)}).json()
try:
link = 'https://te.legra.ph'+path[0]['src']
except KeyError:
link = path["error"]
await message.edit("<b>"+link+"</b>")
async def check_media(reply_message):
if reply_message and reply_message.media:
if reply_message.photo:
data = reply_message.photo
elif reply_message.document:
if DocumentAttributeFilename(file_name='AnimatedSticker.tgs') in reply_message.media.document.attributes:
return False
if reply_message.audio or reply_message.voice:
return False
data = reply_message.media.document
else:
return False
else:
return False
if not data or data is None:
return False
else:
return data

View File

@@ -1,125 +1,125 @@
from telethon import events
from telethon.errors.rpcerrorlist import YouBlockedUserError
from .. import loader, utils
import string
import random
from PIL import Image
import io
from asyncio import sleep
def register(cb):
cb(pic2packMod())
class pic2packMod(loader.Module):
"""pic2pack"""
strings = {'name': 'pic2pack'}
def __init__(self):
self.name = self.strings['name']
self._me = None
self._ratelimit = []
async def client_ready(self, client, db):
self._db = db
self._client = client
self.me = await client.get_me()
async def pic2packcmd(self, message):
""".pic2pack {packname} + <reply to photo>"""
reply = await message.get_reply_message()
if not reply:
await message.edit("<b>Reply to photo❗</b>")
return
args = utils.get_args_raw(message)
if not args:
await message.edit("<b>Packname</b>❓")
return
chat = '@Stickers'
name = "".join([random.choice(list(string.ascii_lowercase+string.ascii_uppercase)) for _ in range(16)])
emoji = "▫️"
image = io.BytesIO()
await message.client.download_file(reply, image)
image = Image.open(image)
w, h = image.size
www = max(w, h)
await message.edit("🔪<b>Cropping...</b>")
img = Image.new("RGBA", (www,www), (0,0,0,0))
img.paste(image, ((www-w)//2, 0))
face = img.resize((100,100))
fface = io.BytesIO()
fface.name = name+".png"
images = await cropping(img)
face.save(fface)
fface.seek(0)
await message.edit("<b>📤Uploading...</b>")
async with message.client.conversation(chat) as conv:
try:
x = await message.client.send_message(chat, "/cancel")
await (await conv.wait_event(events.NewMessage(incoming=True, from_users=chat))).delete()
await x.delete()
x = await message.client.send_message(chat, "/newpack")
await (await conv.wait_event(events.NewMessage(incoming=True, from_users=chat))).delete()
await x.delete()
x = await message.client.send_message(chat, args)
await (await conv.wait_event(events.NewMessage(incoming=True, from_users=chat))).delete()
await x.delete()
for im in images:
blank = io.BytesIO(im)
blank.name = name+".png"
blank.seek(0)
x = await message.client.send_file(chat, blank, force_document=True)
await (await conv.wait_event(events.NewMessage(incoming=True, from_users=chat))).delete()
await x.delete()
x = await message.client.send_message(chat, emoji)
await (await conv.wait_event(events.NewMessage(incoming=True, from_users=chat))).delete()
await x.delete()
x = await message.client.send_message(chat, "/publish")
await (await conv.wait_event(events.NewMessage(incoming=True, from_users=chat))).delete()
await x.delete()
x = await message.client.send_file(chat, fface, force_document=True)
await (await conv.wait_event(events.NewMessage(incoming=True, from_users=chat))).delete()
await x.delete()
x = await message.client.send_message(chat, name)
ending = await conv.wait_event(events.NewMessage(incoming=True, from_users=chat))
await x.delete()
await ending.delete()
for part in ending.raw_text.split():
if part.startswith("https://t.me/"):
break
await message.edit('✅<b>Uploaded successful!</b>\n'+part)
except YouBlockedUserError:
await message.edit('<b>@Stickers BLOCKED⛔</b>')
return
async def cropping(img):
(x, y) = img.size
cy = 5
cx = 5
sx = x//cx
sy = y//cy
if (sx*cx, sy*cy) != (x, y):
img = img.resize((sx*cx, sy*cy))
(lx, ly) = (0, 0)
media = []
for i in range(1, cy+1):
for o in range(1, cx+1):
mimg = img.crop((lx, ly, lx+sx, ly+sy))
mimg = mimg.resize((512,512))
bio = io.BytesIO()
bio.name = 'image.png'
mimg.save(bio, 'PNG')
media.append(bio.getvalue())
lx = lx + sx
lx = 0
ly = ly + sy
from telethon import events
from telethon.errors.rpcerrorlist import YouBlockedUserError
from .. import loader, utils
import string
import random
from PIL import Image
import io
from asyncio import sleep
def register(cb):
cb(pic2packMod())
class pic2packMod(loader.Module):
"""pic2pack"""
strings = {'name': 'pic2pack'}
def __init__(self):
self.name = self.strings['name']
self._me = None
self._ratelimit = []
async def client_ready(self, client, db):
self._db = db
self._client = client
self.me = await client.get_me()
async def pic2packcmd(self, message):
""".pic2pack {packname} + <reply to photo>"""
reply = await message.get_reply_message()
if not reply:
await message.edit("<b>Reply to photo❗</b>")
return
args = utils.get_args_raw(message)
if not args:
await message.edit("<b>Packname</b>❓")
return
chat = '@Stickers'
name = "".join([random.choice(list(string.ascii_lowercase+string.ascii_uppercase)) for _ in range(16)])
emoji = "▫️"
image = io.BytesIO()
await message.client.download_file(reply, image)
image = Image.open(image)
w, h = image.size
www = max(w, h)
await message.edit("🔪<b>Cropping...</b>")
img = Image.new("RGBA", (www,www), (0,0,0,0))
img.paste(image, ((www-w)//2, 0))
face = img.resize((100,100))
fface = io.BytesIO()
fface.name = name+".png"
images = await cropping(img)
face.save(fface)
fface.seek(0)
await message.edit("<b>📤Uploading...</b>")
async with message.client.conversation(chat) as conv:
try:
x = await message.client.send_message(chat, "/cancel")
await (await conv.wait_event(events.NewMessage(incoming=True, from_users=chat))).delete()
await x.delete()
x = await message.client.send_message(chat, "/newpack")
await (await conv.wait_event(events.NewMessage(incoming=True, from_users=chat))).delete()
await x.delete()
x = await message.client.send_message(chat, args)
await (await conv.wait_event(events.NewMessage(incoming=True, from_users=chat))).delete()
await x.delete()
for im in images:
blank = io.BytesIO(im)
blank.name = name+".png"
blank.seek(0)
x = await message.client.send_file(chat, blank, force_document=True)
await (await conv.wait_event(events.NewMessage(incoming=True, from_users=chat))).delete()
await x.delete()
x = await message.client.send_message(chat, emoji)
await (await conv.wait_event(events.NewMessage(incoming=True, from_users=chat))).delete()
await x.delete()
x = await message.client.send_message(chat, "/publish")
await (await conv.wait_event(events.NewMessage(incoming=True, from_users=chat))).delete()
await x.delete()
x = await message.client.send_file(chat, fface, force_document=True)
await (await conv.wait_event(events.NewMessage(incoming=True, from_users=chat))).delete()
await x.delete()
x = await message.client.send_message(chat, name)
ending = await conv.wait_event(events.NewMessage(incoming=True, from_users=chat))
await x.delete()
await ending.delete()
for part in ending.raw_text.split():
if part.startswith("https://t.me/"):
break
await message.edit('✅<b>Uploaded successful!</b>\n'+part)
except YouBlockedUserError:
await message.edit('<b>@Stickers BLOCKED⛔</b>')
return
async def cropping(img):
(x, y) = img.size
cy = 5
cx = 5
sx = x//cx
sy = y//cy
if (sx*cx, sy*cy) != (x, y):
img = img.resize((sx*cx, sy*cy))
(lx, ly) = (0, 0)
media = []
for i in range(1, cy+1):
for o in range(1, cx+1):
mimg = img.crop((lx, ly, lx+sx, ly+sy))
mimg = mimg.resize((512,512))
bio = io.BytesIO()
bio.name = 'image.png'
mimg.save(bio, 'PNG')
media.append(bio.getvalue())
lx = lx + sx
lx = 0
ly = ly + sy
return media

View File

@@ -1,23 +1,23 @@
from .. import loader, utils
from asyncio import sleep
@loader.tds
class PrintMod(loader.Module):
"""Аналог модуля typewriter"""
strings = {"name": "print"}
@loader.owner
async def printcmd(self, message):
""".print <text or reply>"""
text = utils.get_args_raw(message)
if not text:
reply = await message.get_reply_message()
if not reply or not reply.message:
await message.edit("<b>Текста нет!</b>")
return
text = reply.message
out = ""
for ch in text:
out += ch
if ch not in [" ", "\n"]:
await message.edit(out+"\u2060")
await sleep(0.3)
from .. import loader, utils
from asyncio import sleep
@loader.tds
class PrintMod(loader.Module):
"""Аналог модуля typewriter"""
strings = {"name": "print"}
@loader.owner
async def printcmd(self, message):
""".print <text or reply>"""
text = utils.get_args_raw(message)
if not text:
reply = await message.get_reply_message()
if not reply or not reply.message:
await message.edit("<b>Текста нет!</b>")
return
text = reply.message
out = ""
for ch in text:
out += ch
if ch not in [" ", "\n"]:
await message.edit(out+"\u2060")
await sleep(0.3)

View File

@@ -1,43 +1,43 @@
from .. import loader, utils # pylint: disable=relative-beyond-top-level
import logging
import pygments
from pygments.lexers import Python3Lexer
from pygments.formatters import ImageFormatter
import os
logger = logging.getLogger(__name__)
def register(cb):
cb(py2pngMod())
@loader.tds
class py2pngMod(loader.Module):
"""Uploader"""
strings = {
"name": "pypng"
}
async def client_ready(self, client, db):
self.client = client
@loader.sudo
async def pypngcmd(self, message):
"""reply to text code or py file"""
await message.edit("<b>Py to PNG</b>")
reply = await message.get_reply_message()
if not reply:
await message.edit("<b>reply to file.py</b>")
return
media = reply.media
if not media:
await message.edit("<b>reply to file.py</b>")
return
file = await message.client.download_file(media)
text = file.decode('utf-8')
pygments.highlight(text, Python3Lexer(), ImageFormatter(font_name='DejaVu Sans Mono', line_numbers=True), 'out.png')
await message.client.send_file(message.to_id, 'out.png', force_document=True)
os.remove("out.png")
await message.delete()
from .. import loader, utils # pylint: disable=relative-beyond-top-level
import logging
import pygments
from pygments.lexers import Python3Lexer
from pygments.formatters import ImageFormatter
import os
logger = logging.getLogger(__name__)
def register(cb):
cb(py2pngMod())
@loader.tds
class py2pngMod(loader.Module):
"""Uploader"""
strings = {
"name": "pypng"
}
async def client_ready(self, client, db):
self.client = client
@loader.sudo
async def pypngcmd(self, message):
"""reply to text code or py file"""
await message.edit("<b>Py to PNG</b>")
reply = await message.get_reply_message()
if not reply:
await message.edit("<b>reply to file.py</b>")
return
media = reply.media
if not media:
await message.edit("<b>reply to file.py</b>")
return
file = await message.client.download_file(media)
text = file.decode('utf-8')
pygments.highlight(text, Python3Lexer(), ImageFormatter(font_name='DejaVu Sans Mono', line_numbers=True), 'out.png')
await message.client.send_file(message.to_id, 'out.png', force_document=True)
os.remove("out.png")
await message.delete()

View File

@@ -1,24 +1,24 @@
import io
from .. import loader, utils
@loader.tds
class SavedMod(loader.Module):
"""Соxранятель в избранное"""
strings = {"name": "SavedMessages", "to":"me"}
@loader.unrestricted
async def savedcmd(self, message):
""".saved реплай на медиа"""
await message.delete()
reply = await message.get_reply_message()
name = utils.get_args_raw(message)
if not reply or not reply.file:
return
media = reply.media
if media.ttl_seconds or name:
file = await reply.download_media(bytes)
file = io.BytesIO(file)
file.name = name or str(reply.sender_id) + reply.file.ext
file.seek(0)
await message.client.send_file(self.strings["to"], file)
else:
await reply.forward_to(self.strings["to"])
import io
from .. import loader, utils
@loader.tds
class SavedMod(loader.Module):
"""Соxранятель в избранное"""
strings = {"name": "SavedMessages", "to":"me"}
@loader.unrestricted
async def savedcmd(self, message):
""".saved реплай на медиа"""
await message.delete()
reply = await message.get_reply_message()
name = utils.get_args_raw(message)
if not reply or not reply.file:
return
media = reply.media
if media.ttl_seconds or name:
file = await reply.download_media(bytes)
file = io.BytesIO(file)
file.name = name or str(reply.sender_id) + reply.file.ext
file.seek(0)
await message.client.send_file(self.strings["to"], file)
else:
await reply.forward_to(self.strings["to"])

View File

@@ -1,106 +1,106 @@
# -*- coding: utf-8 -*-
# Friendly Telegram (telegram userbot)
# Copyright (C) 2018-2020 The Authors
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
# если не подписан на t.me/keyzend
# твоя мама шлюха
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
from .. import loader, utils # pylint: disable=relative-beyond-top-level
import io
from PIL import Image, ImageOps
from telethon.tl.types import DocumentAttributeFilename
import logging
import random
logger = logging.getLogger(__name__)
def register(cb):
cb(SoaperMod())
@loader.tds
class SoaperMod(loader.Module):
"""Гавно залупное"""
strings = {
"name": "Soaping"
}
async def client_ready(self, client, db):
self.client = client
@loader.sudo
async def soapcmd(self, message):
""".soap <reply to photo>"""
soap = 3
a = utils.get_args(message)
if a:
if a[0].isdigit():
soap = int(a[0])
if soap <= 0:
soap = 3
if message.is_reply:
reply_message = await message.get_reply_message()
data = await check_media(reply_message)
if isinstance(data, bool):
await utils.answer(message, "<code>Reply to pic or stick!</code>")
return
else:
await utils.answer(message, "<code>Reply to pic or stick!</code>")
return
await message.edit("Soaping...")
file = await self.client.download_media(data, bytes)
media = await Soaping(file, soap)
await message.delete()
await message.client.send_file(message.to_id, media)
async def Soaping(file, soap):
img = Image.open(io.BytesIO(file))
(x, y) = img.size
img = img.resize((x//soap, y//soap), Image.ANTIALIAS)
img = img.resize((x, y))
soap_io = io.BytesIO()
soap_io.name = "image.jpeg"
img = img.convert("RGB")
img.save(soap_io, "JPEG", quality=100)
soap_io.seek(0)
return soap_io
async def check_media(reply_message):
if reply_message and reply_message.media:
if reply_message.photo:
data = reply_message.photo
elif reply_message.document:
if DocumentAttributeFilename(file_name='AnimatedSticker.tgs') in reply_message.media.document.attributes:
return False
if reply_message.gif or reply_message.video or reply_message.audio or reply_message.voice:
return False
data = reply_message.media.document
else:
return False
else:
return False
if not data or data is None:
return False
else:
# -*- coding: utf-8 -*-
# Friendly Telegram (telegram userbot)
# Copyright (C) 2018-2020 The Authors
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
# если не подписан на t.me/keyzend
# твоя мама шлюха
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
from .. import loader, utils # pylint: disable=relative-beyond-top-level
import io
from PIL import Image, ImageOps
from telethon.tl.types import DocumentAttributeFilename
import logging
import random
logger = logging.getLogger(__name__)
def register(cb):
cb(SoaperMod())
@loader.tds
class SoaperMod(loader.Module):
"""Гавно залупное"""
strings = {
"name": "Soaping"
}
async def client_ready(self, client, db):
self.client = client
@loader.sudo
async def soapcmd(self, message):
""".soap <reply to photo>"""
soap = 3
a = utils.get_args(message)
if a:
if a[0].isdigit():
soap = int(a[0])
if soap <= 0:
soap = 3
if message.is_reply:
reply_message = await message.get_reply_message()
data = await check_media(reply_message)
if isinstance(data, bool):
await utils.answer(message, "<code>Reply to pic or stick!</code>")
return
else:
await utils.answer(message, "<code>Reply to pic or stick!</code>")
return
await message.edit("Soaping...")
file = await self.client.download_media(data, bytes)
media = await Soaping(file, soap)
await message.delete()
await message.client.send_file(message.to_id, media)
async def Soaping(file, soap):
img = Image.open(io.BytesIO(file))
(x, y) = img.size
img = img.resize((x//soap, y//soap), Image.ANTIALIAS)
img = img.resize((x, y))
soap_io = io.BytesIO()
soap_io.name = "image.jpeg"
img = img.convert("RGB")
img.save(soap_io, "JPEG", quality=100)
soap_io.seek(0)
return soap_io
async def check_media(reply_message):
if reply_message and reply_message.media:
if reply_message.photo:
data = reply_message.photo
elif reply_message.document:
if DocumentAttributeFilename(file_name='AnimatedSticker.tgs') in reply_message.media.document.attributes:
return False
if reply_message.gif or reply_message.video or reply_message.audio or reply_message.voice:
return False
data = reply_message.media.document
else:
return False
else:
return False
if not data or data is None:
return False
else:
return data

View File

@@ -1,123 +1,123 @@
# -*- coding: utf-8 -*-
# Friendly Telegram (telegram userbot)
# Copyright (C) 2018-2020 The Authors
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
from .. import loader, utils # pylint: disable=relative-beyond-top-level
import io
from PIL import Image, ImageOps
from telethon.tl.types import DocumentAttributeFilename
import logging
import random
logger = logging.getLogger(__name__)
def register(cb):
cb(SpinnerMod())
@loader.tds
class SpinnerMod(loader.Module):
"""Гавно залупное"""
strings = {
"name": "Spinner"
}
async def client_ready(self, client, db):
self.client = client
@loader.sudo
async def spincmd(self, message):
"""you spin me round..."""
args = utils.get_args(message)
if message.is_reply:
reply_message = await message.get_reply_message()
data = await check_media(reply_message)
if isinstance(data, bool):
await utils.answer(message, "<code>Реплай на пикчу или стикер блять!</code>")
return
else:
await utils.answer(message, "`Реплай на пикчу или стикер блять`")
return
image = io.BytesIO()
await self.client.download_media(data, image)
image = Image.open(image)
image.thumbnail((512, 512), Image.ANTIALIAS)
img = Image.new("RGB", (512, 512), "black")
img.paste(image, ((512-image.width)//2, (512-image.height)//2))
image = img
way = random.choice([1, -1])
frames = []
for i in range(1, 60):
im = image.rotate(i*6*way)
frames.append(im)
frames.remove(im)
image_stream = io.BytesIO()
image_stream.name = "spin.gif"
im.save(image_stream, "GIF", save_all=True, append_images=frames, duration = 10)
image_stream.seek(0)
await utils.answer(message, image_stream)
@loader.sudo
async def epilepsycmd(self, message):
"""ПРИВЕТ ЭПИЛЕТИКИ АХАХАХХА"""
args = utils.get_args(message)
if message.is_reply:
reply_message = await message.get_reply_message()
data = await check_media(reply_message)
if isinstance(data, bool):
await utils.answer(message, "<code>Реплай на пикчу или стикер блять!</code>")
return
else:
await utils.answer(message, "`Реплай на пикчу или стикер блять`")
return
image = io.BytesIO()
await self.client.download_media(data, image)
image = Image.open(image).convert("RGB")
invert = ImageOps.invert(image)
image_stream = io.BytesIO()
image_stream.name = "epilepsy.gif"
image.save(image_stream, "GIF", save_all=True, append_images=[invert], duration = 1)
image_stream.seek(0)
await utils.answer(message, image_stream)
async def check_media(reply_message):
if reply_message and reply_message.media:
if reply_message.photo:
data = reply_message.photo
elif reply_message.document:
if DocumentAttributeFilename(file_name='AnimatedSticker.tgs') in reply_message.media.document.attributes:
return False
if reply_message.gif or reply_message.video or reply_message.audio or reply_message.voice:
return False
data = reply_message.media.document
else:
return False
else:
return False
if not data or data is None:
return False
else:
# -*- coding: utf-8 -*-
# Friendly Telegram (telegram userbot)
# Copyright (C) 2018-2020 The Authors
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
from .. import loader, utils # pylint: disable=relative-beyond-top-level
import io
from PIL import Image, ImageOps
from telethon.tl.types import DocumentAttributeFilename
import logging
import random
logger = logging.getLogger(__name__)
def register(cb):
cb(SpinnerMod())
@loader.tds
class SpinnerMod(loader.Module):
"""Гавно залупное"""
strings = {
"name": "Spinner"
}
async def client_ready(self, client, db):
self.client = client
@loader.sudo
async def spincmd(self, message):
"""you spin me round..."""
args = utils.get_args(message)
if message.is_reply:
reply_message = await message.get_reply_message()
data = await check_media(reply_message)
if isinstance(data, bool):
await utils.answer(message, "<code>Реплай на пикчу или стикер блять!</code>")
return
else:
await utils.answer(message, "`Реплай на пикчу или стикер блять`")
return
image = io.BytesIO()
await self.client.download_media(data, image)
image = Image.open(image)
image.thumbnail((512, 512), Image.ANTIALIAS)
img = Image.new("RGB", (512, 512), "black")
img.paste(image, ((512-image.width)//2, (512-image.height)//2))
image = img
way = random.choice([1, -1])
frames = []
for i in range(1, 60):
im = image.rotate(i*6*way)
frames.append(im)
frames.remove(im)
image_stream = io.BytesIO()
image_stream.name = "spin.gif"
im.save(image_stream, "GIF", save_all=True, append_images=frames, duration = 10)
image_stream.seek(0)
await utils.answer(message, image_stream)
@loader.sudo
async def epilepsycmd(self, message):
"""ПРИВЕТ ЭПИЛЕТИКИ АХАХАХХА"""
args = utils.get_args(message)
if message.is_reply:
reply_message = await message.get_reply_message()
data = await check_media(reply_message)
if isinstance(data, bool):
await utils.answer(message, "<code>Реплай на пикчу или стикер блять!</code>")
return
else:
await utils.answer(message, "`Реплай на пикчу или стикер блять`")
return
image = io.BytesIO()
await self.client.download_media(data, image)
image = Image.open(image).convert("RGB")
invert = ImageOps.invert(image)
image_stream = io.BytesIO()
image_stream.name = "epilepsy.gif"
image.save(image_stream, "GIF", save_all=True, append_images=[invert], duration = 1)
image_stream.seek(0)
await utils.answer(message, image_stream)
async def check_media(reply_message):
if reply_message and reply_message.media:
if reply_message.photo:
data = reply_message.photo
elif reply_message.document:
if DocumentAttributeFilename(file_name='AnimatedSticker.tgs') in reply_message.media.document.attributes:
return False
if reply_message.gif or reply_message.video or reply_message.audio or reply_message.voice:
return False
data = reply_message.media.document
else:
return False
else:
return False
if not data or data is None:
return False
else:
return data

View File

@@ -1,63 +1,63 @@
from .. import loader, utils
import io
import logging
import requests
from textwrap import wrap
from PIL import Image, ImageDraw, ImageFont
bytes_font = requests.get("https://github.com/KeyZenD/l/blob/master/bold.ttf?raw=true").content
logger = logging.getLogger(__name__)
def register(cb):
cb(Text2stickMod())
@loader.tds
class Text2stickMod(loader.Module):
"""Text to sticker"""
strings = {"name": "StickText"}
async def client_ready(self, client, db):
self.client = client
@loader.owner
async def stextcmd(self, message):
""".stext <reply to photo>"""
await message.delete()
text = utils.get_args_raw(message)
reply = await message.get_reply_message()
if not text:
if not reply:
text = "#ffffff .stext <text or reply>"
elif not reply.message:
text = "#ffffff .stext <text or reply>"
else:
text = reply.raw_text
color = text.split(" ", 1)[0]
if color.startswith("#") and len(color) == 7:
for ch in color.lower()[1:]:
if ch not in "0123456789abcdef":
break
if len(text.split(" ", 1)) > 1:
text = text.split(" ", 1)[1]
else:
if reply:
if reply.message:
text = reply.raw_text
else:
color = "#FFFFFF"
txt = []
for line in text.split("\n"):
txt.append("\n".join(wrap(line, 30)))
text = "\n".join(txt)
font = io.BytesIO(bytes_font)
font = ImageFont.truetype(font, 100)
image = Image.new("RGBA", (1, 1), (0,0,0,0))
draw = ImageDraw.Draw(image)
w, h = draw.multiline_textsize(text=text, font=font)
image = Image.new("RGBA", (w+100, h+100), (0,0,0,0))
draw = ImageDraw.Draw(image)
draw.multiline_text((50,50), text=text, font=font, fill=color, align="center")
output = io.BytesIO()
output.name = color+".webp"
image.save(output, "WEBP")
output.seek(0)
await self.client.send_file(message.to_id, output, reply_to=reply)
from .. import loader, utils
import io
import logging
import requests
from textwrap import wrap
from PIL import Image, ImageDraw, ImageFont
bytes_font = requests.get("https://github.com/KeyZenD/l/blob/master/bold.ttf?raw=true").content
logger = logging.getLogger(__name__)
def register(cb):
cb(Text2stickMod())
@loader.tds
class Text2stickMod(loader.Module):
"""Text to sticker"""
strings = {"name": "StickText"}
async def client_ready(self, client, db):
self.client = client
@loader.owner
async def stextcmd(self, message):
""".stext <reply to photo>"""
await message.delete()
text = utils.get_args_raw(message)
reply = await message.get_reply_message()
if not text:
if not reply:
text = "#ffffff .stext <text or reply>"
elif not reply.message:
text = "#ffffff .stext <text or reply>"
else:
text = reply.raw_text
color = text.split(" ", 1)[0]
if color.startswith("#") and len(color) == 7:
for ch in color.lower()[1:]:
if ch not in "0123456789abcdef":
break
if len(text.split(" ", 1)) > 1:
text = text.split(" ", 1)[1]
else:
if reply:
if reply.message:
text = reply.raw_text
else:
color = "#FFFFFF"
txt = []
for line in text.split("\n"):
txt.append("\n".join(wrap(line, 30)))
text = "\n".join(txt)
font = io.BytesIO(bytes_font)
font = ImageFont.truetype(font, 100)
image = Image.new("RGBA", (1, 1), (0,0,0,0))
draw = ImageDraw.Draw(image)
w, h = draw.multiline_textsize(text=text, font=font)
image = Image.new("RGBA", (w+100, h+100), (0,0,0,0))
draw = ImageDraw.Draw(image)
draw.multiline_text((50,50), text=text, font=font, fill=color, align="center")
output = io.BytesIO()
output.name = color+".webp"
image.save(output, "WEBP")
output.seek(0)
await self.client.send_file(message.to_id, output, reply_to=reply)

View File

@@ -1,52 +1,52 @@
from .. import loader, utils
import logging
logger = logging.getLogger(__name__)
def register(cb):
cb(TagallMod())
@loader.tds
class TagallMod(loader.Module):
"""Tagall"""
strings = {
"name": "TagAll", "subscribe to": "https://t.me/KeyZenD"
}
async def client_ready(self, client, db):
self.client = client
def __init__(self):
self.name = self.strings['name']
@loader.sudo
async def tagallcmd(self, message):
args = utils.get_args(message)
tag_ = 5
notext = False
if args:
if args[0].isdigit():
tag_ = int(args[0])
if len(args) > 1:
notext = True
text = " ".join(args[1:])
await message.delete()
all = message.client.iter_participants(message.to_id)
chunk = []
async for user in all:
if not user.deleted:
name = f"{user.first_name} {user.last_name}" if user.last_name else user.first_name
name = name.replace("<","&lt;").replace(">","&gt;")
name = name[:30]+"..." if len(name) > 33 else name
tag = f'<a href="tg://user?id={user.id}">{name}</a>' if not notext else f'<a href="tg://user?id={user.id}">{text}</a>'
chunk.append(tag)
if len(chunk) == tag_:
await message.client.send_message(message.to_id, "\n".join(chunk))
chunk = []
if len(chunk) != 0:
from .. import loader, utils
import logging
logger = logging.getLogger(__name__)
def register(cb):
cb(TagallMod())
@loader.tds
class TagallMod(loader.Module):
"""Tagall"""
strings = {
"name": "TagAll", "subscribe to": "https://t.me/KeyZenD"
}
async def client_ready(self, client, db):
self.client = client
def __init__(self):
self.name = self.strings['name']
@loader.sudo
async def tagallcmd(self, message):
args = utils.get_args(message)
tag_ = 5
notext = False
if args:
if args[0].isdigit():
tag_ = int(args[0])
if len(args) > 1:
notext = True
text = " ".join(args[1:])
await message.delete()
all = message.client.iter_participants(message.to_id)
chunk = []
async for user in all:
if not user.deleted:
name = f"{user.first_name} {user.last_name}" if user.last_name else user.first_name
name = name.replace("<","&lt;").replace(">","&gt;")
name = name[:30]+"..." if len(name) > 33 else name
tag = f'<a href="tg://user?id={user.id}">{name}</a>' if not notext else f'<a href="tg://user?id={user.id}">{text}</a>'
chunk.append(tag)
if len(chunk) == tag_:
await message.client.send_message(message.to_id, "\n".join(chunk))
chunk = []
if len(chunk) != 0:
await message.client.send_message(message.to_id, "\n".join(chunk))

View File

@@ -1,45 +1,45 @@
# Friendly Telegram (telegram userbot)
# Copyright (C) 2018-2019 The Authors
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
# SUBSCRIBE TO t.me/keyzend pls
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
from .. import loader, utils
import logging
import asyncio
logger = logging.getLogger(__name__)
@loader.tds
class TickerMod(loader.Module):
"""Makes your messages type slower"""
strings = {"name": "Ticker",
"no_message": "<b>.ticker [any text?]</b>",
"delay_typer_cfg_doc": "How long to delay showing?"}
def __init__(self):
self.config = loader.ModuleConfig("DELAY_TICKER", 0.04, lambda m: self.strings("delay_tikcer_cfg_doc", m))
@loader.ratelimit
async def tickercmd(self, message):
""".ticker <message>"""
a = utils.get_args_raw(message)
if not a:
await utils.answer(message, self.strings("no_message", message))
return
for c in a:
a = a[-1]+a[0:-1]
message = await utils.answer(message, f" {a} ")
# Friendly Telegram (telegram userbot)
# Copyright (C) 2018-2019 The Authors
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
# SUBSCRIBE TO t.me/keyzend pls
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
from .. import loader, utils
import logging
import asyncio
logger = logging.getLogger(__name__)
@loader.tds
class TickerMod(loader.Module):
"""Makes your messages type slower"""
strings = {"name": "Ticker",
"no_message": "<b>.ticker [any text?]</b>",
"delay_typer_cfg_doc": "How long to delay showing?"}
def __init__(self):
self.config = loader.ModuleConfig("DELAY_TICKER", 0.04, lambda m: self.strings("delay_tikcer_cfg_doc", m))
@loader.ratelimit
async def tickercmd(self, message):
""".ticker <message>"""
a = utils.get_args_raw(message)
if not a:
await utils.answer(message, self.strings("no_message", message))
return
for c in a:
a = a[-1]+a[0:-1]
message = await utils.answer(message, f" {a} ")
await asyncio.sleep(0.3)

View File

@@ -1,31 +1,31 @@
from requests import head,get
from urllib.parse import urlsplit as E,parse_qs as H
import json,io,re
from .. import loader as A,utils
class TikTokDlMod(A.Module):
strings={'name':'TikTokDl'}
async def ttcmd(J,message):
A=message;B=await A.get_reply_message();F=utils.get_args_raw(A);C=lambda x:f"<b>{x}</b>"
if F:D=F
elif B and B.raw_text:D=B.raw_text
else:return await A.edit(C('No url.'))
if'.tiktok.com'not in D:return await A.edit(C('Bad url.'))
await A.edit(C('Loading...'));G,K=await I(D)
try:await A.client.send_file(A.to_id,file=G,reply_to=B);await A.delete()
except:
try:await A.edit(C('DownLoading...'));H=get(G).content;E=io.BytesIO(H);E.name='video.mp4';E.seek(0);await A.client.send_file(A.to_id,file=E,reply_to=B);await A.delete()
except:await A.edit(C('я чёт нихуя не могу загрузить...'))
async def I(url):
A=url
async def F(video_id,_):
A=f"https://api-va.tiktokv.com/aweme/v1/multi/aweme/detail/?aweme_ids=%5B{video_id}%5D";A=get(A);B=A.json().get('aweme_details')
if not B:return 0,0,A
return B,True,A
A=head(A).headers;A=A.get('Location')
try:
I=H(E(A).query);B=I.get('share_item_id')[0];G,C,D=await F(B,1)
if not C:raise
except:
B=''.join(re.findall('[0-9]',E(A).path.split('/')[-1]));G,C,D=await F(B,2)
if not C:return False,D
return G[0]['video']['bit_rate'][0]['play_addr']['url_list'][-1],D
from requests import head,get
from urllib.parse import urlsplit as E,parse_qs as H
import json,io,re
from .. import loader as A,utils
class TikTokDlMod(A.Module):
strings={'name':'TikTokDl'}
async def ttcmd(J,message):
A=message;B=await A.get_reply_message();F=utils.get_args_raw(A);C=lambda x:f"<b>{x}</b>"
if F:D=F
elif B and B.raw_text:D=B.raw_text
else:return await A.edit(C('No url.'))
if'.tiktok.com'not in D:return await A.edit(C('Bad url.'))
await A.edit(C('Loading...'));G,K=await I(D)
try:await A.client.send_file(A.to_id,file=G,reply_to=B);await A.delete()
except:
try:await A.edit(C('DownLoading...'));H=get(G).content;E=io.BytesIO(H);E.name='video.mp4';E.seek(0);await A.client.send_file(A.to_id,file=E,reply_to=B);await A.delete()
except:await A.edit(C('я чёт нихуя не могу загрузить...'))
async def I(url):
A=url
async def F(video_id,_):
A=f"https://api-va.tiktokv.com/aweme/v1/multi/aweme/detail/?aweme_ids=%5B{video_id}%5D";A=get(A);B=A.json().get('aweme_details')
if not B:return 0,0,A
return B,True,A
A=head(A).headers;A=A.get('Location')
try:
I=H(E(A).query);B=I.get('share_item_id')[0];G,C,D=await F(B,1)
if not C:raise
except:
B=''.join(re.findall('[0-9]',E(A).path.split('/')[-1]));G,C,D=await F(B,2)
if not C:return False,D
return G[0]['video']['bit_rate'][0]['play_addr']['url_list'][-1],D

View File

@@ -1,41 +1,41 @@
import asyncio
import logging
from requests import get
from .. import loader, utils
logger = logging.getLogger(__name__)
@loader.tds
class ValitesMod(loader.Module):
"""Valute converter"""
strings = {"name": "Valutes"}
@loader.unrestricted
async def valutecmd(self, message):
""".valute <Valute char code (optional)>"""
valutes = get("https://www.cbr-xml-daily.ru/daily_json.js").json()
names = valutes["Valute"].keys()
args = utils.get_args(message)
req = []
if args:
for val in args:
val = val.upper()
if val in names:
req.append(val)
valutes["Valute"] = {val: valutes["Valute"][val] for val in req}
text = []
temp = "<b>{}</b>\n{} <code>{}</code>: {}₽ ({}{}₽)"
for val in valutes["Valute"].values():
name = val["Name"]
code = val["CharCode"]
nom = int(val["Nominal"])
now = round(float(val["Value"]), 3)
pre = round(float(val["Previous"]), 3)
way = "🔹" if now == pre else "🔻" if now < pre else "🔺"
text.append(temp.format(name, nom, code, now, way, pre))
if not text:
return await utils.answer(message, "<b>Запрос неверен - ответ пуст!</b>")
await utils.answer(message, "\n".join(text))
import asyncio
import logging
from requests import get
from .. import loader, utils
logger = logging.getLogger(__name__)
@loader.tds
class ValitesMod(loader.Module):
"""Valute converter"""
strings = {"name": "Valutes"}
@loader.unrestricted
async def valutecmd(self, message):
""".valute <Valute char code (optional)>"""
valutes = get("https://www.cbr-xml-daily.ru/daily_json.js").json()
names = valutes["Valute"].keys()
args = utils.get_args(message)
req = []
if args:
for val in args:
val = val.upper()
if val in names:
req.append(val)
valutes["Valute"] = {val: valutes["Valute"][val] for val in req}
text = []
temp = "<b>{}</b>\n{} <code>{}</code>: {}₽ ({}{}₽)"
for val in valutes["Valute"].values():
name = val["Name"]
code = val["CharCode"]
nom = int(val["Nominal"])
now = round(float(val["Value"]), 3)
pre = round(float(val["Previous"]), 3)
way = "🔹" if now == pre else "🔻" if now < pre else "🔺"
text.append(temp.format(name, nom, code, now, way, pre))
if not text:
return await utils.answer(message, "<b>Запрос неверен - ответ пуст!</b>")
await utils.answer(message, "\n".join(text))

View File

@@ -1,48 +1,48 @@
from .. import loader, utils
import logging
from requests import get
import io
logger = logging.getLogger(__name__)
def register(cb):
cb(WebShotMod())
@loader.tds
class WebShotMod(loader.Module):
"""link to screen"""
strings = {
"name": "WebShot"
}
async def client_ready(self, client, db):
self.client = client
def __init__(self):
self.name = self.strings['name']
@loader.sudo
async def webshotcmd(self, message):
reply = None
link = utils.get_args_raw(message)
if not link:
reply = await message.get_reply_message()
if not reply:
await message.delete()
return
link = reply.raw_text
await message.edit("<b>S c r e e n s h o t i n g . . .</b>")
url = "https://webshot.deam.io/{}/?width=1920&height=1080?type=png"
file = get(url.format(link))
if not file.ok:
await message.edit("<b>Something went wrong...</b>")
return
file = io.BytesIO(file.content)
file.name = "webshot.png"
file.seek(0)
await message.client.send_file(message.to_id, file, reply_to=reply)
await message.delete()
from .. import loader, utils
import logging
from requests import get
import io
logger = logging.getLogger(__name__)
def register(cb):
cb(WebShotMod())
@loader.tds
class WebShotMod(loader.Module):
"""link to screen"""
strings = {
"name": "WebShot"
}
async def client_ready(self, client, db):
self.client = client
def __init__(self):
self.name = self.strings['name']
@loader.sudo
async def webshotcmd(self, message):
reply = None
link = utils.get_args_raw(message)
if not link:
reply = await message.get_reply_message()
if not reply:
await message.delete()
return
link = reply.raw_text
await message.edit("<b>S c r e e n s h o t i n g . . .</b>")
url = "https://webshot.deam.io/{}/?width=1920&height=1080?type=png"
file = get(url.format(link))
if not file.ok:
await message.edit("<b>Something went wrong...</b>")
return
file = io.BytesIO(file.content)
file.name = "webshot.png"
file.seek(0)
await message.client.send_file(message.to_id, file, reply_to=reply)
await message.delete()

Some files were not shown because too many files have changed in this diff Show More