Commited backup

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

View File

@@ -0,0 +1,63 @@
from .. import loader, utils
from telethon.tl.functions.contacts import BlockRequest
from telethon.tl.functions.messages import ReportSpamRequest
def register(cb):
cb(AutoBlackListMod())
class AutoBlackListMod(loader.Module):
"""Кидает всех неконтактов в ЧС."""
strings = {'name': 'AutoBlackList'}
async def client_ready(self, client, db):
self.db = db
async def autoblcmd(self, message):
"""Включить/выключить режим AutoBlackList"""
args = utils.get_args_raw(message)
autobl = self.db.get("AutoBlackList", "status", False)
if args:
self.db.set("AutoBlackList", "status", True)
self.db.set("AutoBlackList", "message", str(args))
return await message.edit("<b>[AutoBlackList Mode]</b> Активирован!")
if autobl == False:
self.db.set("AutoBlackList", "status", True)
self.db.set("AutoBlackList", "message", "<b>Привет, я не принимаю личные сообщение. К сожалению, ты летишь в ЧС + RP.</b>")
return await message.edit("<b>[AutoBlackList Mode]</b> Активирован!")
self.db.set("AutoBlackList", "status", False)
return await message.edit("<b>[AutoBlackList Mode]</b> Деактивирован!")
async def autoblstatuscmd(self, message):
"""Проверить статус AutoBlackList"""
await message.edit(f"<b>[AutoBlackList Mode - Status]</b>\n\n"
f"<b>Кидать в ЧС</b> - {self.db.get('AutoBlackList', 'status')}\n"
f"<b>Удалять чаты</b> - {self.db.get('AutoBlackList', 'delchat')}")
async def autodelchatcmd(self, message):
"""Автоматически удаляет диалог после того, как кинет в ЧС"""
autodel = self.db.get("AutoBlackList", "delchat", False)
if autodel == False:
self.db.set("AutoBlackList", "delchat", True)
return await message.edit("<b>[AutoBlackList Mode - DelChat]</b> Активирован!")
self.db.set("AutoBlackList", "delchat", False)
return await message.edit("<b>[AutoBlackList Mode - DelChat]</b> Деактивирован!")
async def watcher(self, message):
"""Вау, это watcher, я что-то смог из него сделать. Поздравьте меня)"""
try:
if message.sender_id == (await message.client.get_me()).id: return
if self.db.get("AutoBlackList", "status", True):
if message.is_private and message.sender_id != 777000:
user = await message.client.get_entity(message.chat_id)
if user.contact == False and user.bot == False:
await message.client.send_message(message.chat_id, (self.db.get("AutoBlackList", "message")))
await message.client(BlockRequest(message.chat_id))
await message.client(ReportSpamRequest(message.chat_id))
if self.db.get("AutoBlackList", "delchat") == True:
await message.client.delete_dialog(message.chat_id)
except (AttributeError, TypeError): pass

View File

@@ -0,0 +1,117 @@
#module author: Yahikoro
from telethon import functions
from .. import loader, utils
@loader.tds
class ConthelperMod(loader.Module):
"""
Commands:
"""
strings = {"name": "Conthelper",
"blocked": "<b>{} was blacklisted.</b>",
"unblocked": "<b>{} removed from the blacklist.</b>",
"delcontact": "<b>{} was removed from contacts.</b>",
"who_to_block": "<b>Indicate, who to block.</b>",
"who_to_unblock": "<b>Indicate, who to unblock.</b>",
"who_to_delcontact": "<b>Indicate, who to remove from contacts.</b>"}
def __init__(self):
self.me = None
async def client_ready(self, client, db):
self.db = db
self.client = client
self.me = await client.get_me(True)
async def reportcmd(self, message):
""" User report for spam. """
args = utils.get_args_raw(message)
reply = await message.get_reply_message()
if message.chat_id != (await message.client.get_me()).id and message.is_private:
user = await message.client.get_entity(message.chat_id)
else:
if args:
user = await message.client.get_entity(args if not args.isnumeric() else int(args))
if reply:
user = await message.client.get_entity(reply.sender_id)
else:
return await message.edit("<b>Who I must report?</b>")
await message.client(functions.messages.ReportSpamRequest(peer=user.id))
await message.edit("<b>You get report for spam!</b>")
async def blockcmd(self, message):
"""Use: .block to block this user."""
args = utils.get_args_raw(message)
reply = await message.get_reply_message()
if message.chat_id != (await message.client.get_me()).id and message.is_private:
user = await message.client.get_entity(message.chat_id)
else:
if reply:
user = await message.client.get_entity(reply.sender_id)
else:
user = await message.client.get_entity(int(args) if args.isnumeric() else args)
if not user:
await utils.answer(message, self.strings["who_to_block"])
return
await message.client(functions.contacts.BlockRequest(user))
await utils.answer(message, self.strings["blocked"].format(user.first_name))
async def unblockcmd(self, message):
"""Use: .unblock to unblock this user."""
args = utils.get_args_raw(message)
reply = await message.get_reply_message()
if message.chat_id != (await message.client.get_me()).id and message.is_private:
user = await message.client.get_entity(message.chat_id)
else:
if reply:
user = await message.client.get_entity(reply.sender_id)
else:
user = await message.client.get_entity(int(args) if args.isnumeric() else args)
if not user:
await utils.answer(message, self.strings["who_to_unblock"])
return
await message.client(functions.contacts.UnblockRequest(user))
await utils.answer(message, self.strings["unblocked"].format(user.first_name))
async def delcontcmd(self, message):
"""Use: .delcont to remove a user from contacts."""
args = utils.get_args(message)
reply = await message.get_reply_message()
if message.chat_id != (await message.client.get_me()).id and message.is_private:
user = await message.client.get_entity(message.chat_id)
else:
if reply:
user = await message.client.get_entity(reply.sender_id)
else:
user = await message.client.get_entity(int(args) if args.isnumeric() else args)
if not user:
await utils.answer(message, self.strings["who_to_delcontact"])
return
await message.client(functions.contacts.DeleteContactsRequest(id=[user.id]))
await utils.answer(message, self.strings["delcontact"].format(user.first_name))
async def addcontcmd(self, message):
"""Use: .addcont to add somebody in contacts."""
args = utils.get_args_raw(message)
reply = await message.get_reply_message()
if not args:
return await message.edit("<b>Where args?.</b>")
if not reply:
return await message.edit("<b>Where reply?</b>")
else:
user = await message.client.get_entity(reply.sender_id)
try:
await message.client(functions.contacts.AddContactRequest(id=user.id,
first_name=args,
last_name=' ',
phone='phone',
add_phone_privacy_exception=False))
await message.edit(f"<code>{user.id}</code> added to contacts <code>{args}</code>")
except:
return await message.edit("<b>Something went wrong (come up with different reasons).</b>")

View File

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

View File

@@ -0,0 +1,98 @@
# -*- coding: utf-8 -*-
from .. import loader, utils
import logging
import base64
import os
import requests
import json
from requests.exceptions import MissingSchema, ChunkedEncodingError
logger = logging.getLogger(__name__)
def register(cb):
cb(GitaddMod())
@loader.tds
class GitaddMod(loader.Module):
"""Загружает файлы на репозиторий GitHub"""
strings = {"name": "GitUploader",
"reply_to_file": "<b>Ответьте на файл</b>",
"error_file": "Формат не поддерживается",
"connection_error": "<i>Ошибка соединения</i>",
"repo_error": "<i>Ошибка репозитория</i>",
"token_error": "<i>Ошибка токена</i>",
"exist_422": "<b>Не удалось загрузить файл. Возможная причина: файл с таким названием уже существует в репозитории.</b>",
"cfg_token": "Токен GitHub",
"token_not_found": "Токен не найден",
"username_not_found": "Имя пользователя GitHub не указано",
"repo_not_found": "Репозиторий не указан",
"cfg_gh_user": "Имя пользователя на GitHub",
"cfg_gh_repo": "Репозиторий, куда нужно загружать модули"}
def __init__(self):
self.config = loader.ModuleConfig("GH_TOKEN", "TOKEN", lambda m: self.strings("cfg_token", m),
"GH_USERNAME", "USERNAME", lambda m: self.strings("cfg_gh_user", m),
"GH_REPO", "REPOSITORY", lambda m: self.strings("cfg_gh_repo", m))
async def client_ready(self, client, db):
self.client = client
@loader.owner
async def gitaddcmd(self, message):
if self.config["GH_TOKEN"] == "TOKEN":
await utils.answer(message, self.strings("token_not_found", message))
return
if self.config["GH_USERNAME"] == "USERNAME":
await utils.answer(message, self.strings("username_not_found", message))
return
if self.config["GH_REPO"] == "REPOSITORY":
await utils.answer(message, self.strings("repo_not_found", message))
return
reply = await message.get_reply_message()
if not reply:
await utils.answer(message, self.strings("reply_to_file", message))
return
media = reply.media
if not media:
await utils.answer(message, self.strings("reply_to_file", message))
return
try:
fname=(reply.media.document.attributes[0]).file_name
except AttributeError:
await utils.answer(message, self.strings("error_file", message))
return
try:
file = await message.client.download_file(media)
encoded_string = base64.b64encode(file)
stout = encoded_string.decode("utf-8")
TOKEN = self.config["GH_TOKEN"]
USERNAME = self.config["GH_USERNAME"]
REPO = self.config["GH_REPO"]
#url = f'{self.config["GH_REPO"]}{fname}'
url = f'https://api.github.com/repos/{USERNAME}/{REPO}/contents/{fname}'
head = {"Authorization": f"token {TOKEN}", "Accept": "application/vnd.github.v3+json"}
git_data = '{"message": "Upload file", "content":' + '"' + stout + '"' + '}'
r = requests.put(url, headers=head, data=git_data)
if int(r.status_code) == 201:
uploaded_to = f'https://github.com/{USERNAME}/{REPO}'
uploaded_to_raw = '/'.join(r.json()["content"].get("download_url").split('/')[:-1]+[fname.replace(' ', '%20')])
await utils.answer(message, f"Файл <code>{fname}</code> успешно загружен на <a href=\f'{uploaded_to}\'>репозиторий!</a>\n\nПрямая ссылка: <code>{uploaded_to_raw}</code>")
return
elif int(r.status_code) == 422:
await utils.answer(message, self.strings("exist_422", message))
return
else:
json_resp = json.loads(r.text)
git_resp = json_resp["message"]
await utils.answer(message, f"Произошла неизвестная ошибка! Ответ сервера:\n <code>{git_resp}</code>")
return
except ConnectionError:
await utils.answer(message, self.strings("connection_error", message))
return
except MissingSchema:
await utils.answer(message, self.strings("repo_error", message))
return
except ChunkedEncodingError:
await utils.answer(message, self.strings("token_error", message))
return

View File

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

View File

@@ -0,0 +1,29 @@
from .. import loader, utils
class MafiaDrawingMod(loader.Module):
"""Модуль ловли подарков в True Mafia News."""
strings = {'name': 'MafiaDrawing'}
async def client_ready(self, client, db):
self.db = db
self.db.set("MafiaDrawing", "status", True)
async def mdcmd(self, message):
"""Используй: .md чтобы включить/выключить ловлю подарков."""
status = self.db.get("MafiaDrawing", "status")
if status is not True:
await message.edit("<b>Ловля подарков:</b> <code>Включена</code>")
self.db.set("MafiaDrawing", "status", True)
else:
await message.edit("<b>Ловля подарков:</b> <code>Отключена</code>")
self.db.set("MafiaDrawing", "status", False)
async def watcher(self, message):
try:
status = self.db.get("MafiaDrawing", "status")
me = (await message.client.get_me()).id
if status:
if message.chat_id == -1001169391811:
click = (await message.click(0)).message
await message.client.send_message(me, f"Словлен подарок:\n\n{click}")
except: pass

View File

@@ -0,0 +1,3 @@
# Friendly-Telegram Modules
## FTG Modules for [GeekTG/Friendly-Telegram](https://github.com/GeekTG/Friendly-Telegram)

View File

@@ -0,0 +1,146 @@
from .. import loader, utils
from datetime import datetime, date, time
from asyncio import sleep
import os, io, asyncio, pytz, requests
@loader.tds
class SeeChatMod(loader.Module):
"""tracking in all PM chats."""
strings={"name": "SeeChat"}
async def client_ready(self, message, db):
self.db = db
self.db.set("SeeChat", "seechat", True)
self.di = "SeeChat/"
if not os.path.exists(self.di):
os.mkdir(self.di)
async def seechatcmd(self, message):
"""use: .seechat | to enable tracking in all PM chats."""
if self.db.get("SeeChat", "seechat") is not True:
await utils.answer(message, "[SeeChat] turned <b>on</b> succesfully.")
self.db.set("SeeChat", "seechat", True)
else:
await utils.answer(message, "[SeeChat] turned <b>off</b> succesfully.")
self.db.set("SeeChat", "seechat", False)
async def setchatcmd(self, message):
"""use: .setchat | to set this chat as a track chat."""
chat = await message.client.get_entity(message.to_id)
self.db.set("SeeChat", "log", str(chat.id))
await utils.answer(message, f"<b>this chat was set as a chat for tracks.</b>")
async def seechatscmd(self, message):
"""use: .seechats | to see the list of tracking people."""
await utils.answer(message, "wait a second..")
chats = ""
for userId in enumerate(os.listdir(self.di)):
try:
user = await message.client.get_entity(int(userId[1][:-4]))
except: pass
if not user.deleted:
chats += f"{userId[0]+1} • <a href=tg://user?id={user.id}>{user.first_name}</a> ID: [<code>{user.id}</code>]\n"
else:
chats += f"{userId[0]+1} • deleted account ID: [<code>{user.id}</code>]\n"
await utils.answer(message, "<b>Tracking users:</b>\n\n" + chats)
async def gseecmd(self, message):
"""use: .gsee {id} | to get the tracked file."""
args = utils.get_args_raw(message)
if not args:
return await utils.answer(message, "<b>what about args?</b>")
try:
user = await message.client.get_entity(int(args))
await utils.answer(message, f"<b>PM file with: <code>{user.first_name}</code></b>")
await message.client.send_file(message.to_id, f"{self.di}{args}.txt")
except: return await utils.answer(message, "<b>file is empty.</b>")
async def delseecmd(self, message):
"""use: .delsee {id} | to delete the tracked file."""
args = utils.get_args_raw(message)
if not args:
return await utils.answer(message, "<b>what about args?</b>")
if args == "all":
os.system(f"rm -rf {self.di}*")
await utils.answer(message, "<b>all PM chats file has been successfully deleted.</b>")
else:
try:
user = await message.client.get_entity(int(args))
await utils.answer(message, f"<b>the chat file has been deleted with: <code>{user.first_name}</code></b>")
os.remove(f"{self.di}{args}.txt")
except: return await utils.answer(message, "<b>file can't be deleted.</b>")
async def excseecmd(self, message):
"""use: .excsee {id} | to add / remove user from exclude tracking."""
exception = self.db.get("SeeChat", "exception", [])
args = utils.get_args_raw(message)
if not args:
return await utils.answer(message, "<b>what about args?</b>")
if args == "clear":
self.db.set("SeeChat", "exception", [])
return await utils.answer(message, "<b>the exclusion list was cleared successfully.</b>")
try:
user = await message.client.get_entity(int(args))
if str(user.id) not in exception:
exception.append(str(user.id))
await utils.answer(message, f"<b>{user.first_name}, has been added to the list of exclusions.</b>")
os.remove(f"{self.di}{user.id}.txt")
else:
exception.remove(str(user.id))
await utils.answer(message, f"<b>{user.first_name}, has been removed from the list of exclusions.</b>")
self.db.set("SeeChat", "exception", exception)
except: return await utils.answer(message, "<b>failed to remove user from the list of exclusions</b>")
async def exclistcmd(self, message):
"""use: .exclist | to see the list of exceptions."""
exception = self.db.get("SeeChat", "exception", [])
users = ""
try:
for exc in enumerate(exception):
user = await message.client.get_entity(int(exc[1]))
users += f"{exc[0]+1} • <a href=tg://user?id={user.id}>{user.first_name}</a> ID: [<code>{user.id}</code>]\n"
await utils.answer(message, "<b>List of exclusions:</b>\n\n" + users)
except Exception as e: return await utils.answer(message, f"<b>the list of users is empty.</b> {e}")
async def watcher(self, message):
me = await message.client.get_me()
seechat = self.db.get("SeeChat", "seechat")
exception = self.db.get("SeeChat", "exception", [])
log = self.db.get("SeeChat", "log", str(me.id))
chat = await message.client.get_entity(int(log))
timezone = "Europe/Kiev"
vremya = datetime.now(pytz.timezone(timezone)).strftime("[%Y-%m-%d %H:%M:%S]")
user = await message.client.get_entity(message.chat_id)
userid = str(user.id)
try:
if message.sender_id == me.id: user.first_name = me.first_name
except: pass
if message.is_private and seechat and userid not in exception and not user.bot and not user.verified:
if message.text:
file = open(f"{self.di}{user.id}.txt", "a", encoding='utf-8')
file.write(f"{user.first_name} >> {message.text} << {vremya}\n\n")
if message.sender_id == me.id:
return
if message.video:
try:
await message.forward_to(chat.id)
except:
file = message.file.name or "huita" + message.file.ext
await message.download_media(file)
await message.client.send_message(chat.id, f"<b>Video from</b> <a href='tg://user?id={user.id}'>{user.first_name}</a>:")
await message.client.send_file(chat.id, file)
os.remove(file)
elif message.photo:
file = io.BytesIO()
file.name = message.file.name or f"SeeChat{message.file.ext}"
await message.client.download_file(message, file)
file.seek(0)
await message.client.send_message(chat.id, f"<b>Picture from</b> <a href='tg://user?id={user.id}'>{user.first_name}</a>:")
await message.client.send_file(chat.id, file, force_document=False)
elif message.voice or message.audio or message.video_note or message.document:
await message.client.send_message(chat.id, f"<b>Media from</b> <a href='tg://user?id={user.id}'>{user.first_name}</a>:")
await message.forward_to(chat.id)

View File

@@ -0,0 +1,274 @@
# Coded by D4n1l3k300 #
# supplemented by Yahikor0 #
# This code under AGPL-3.0 #
# requires: ffmpeg-python pytgcalls[telethon] youtube-dl ShazamAPI
import io
import os
import re
import logging
import ffmpeg
import pytgcalls
from ShazamAPI import Shazam
from youtube_dl import YoutubeDL
from pytgcalls import GroupCallFactory
from pytgcalls.implementation.group_call_file import GroupCallFile
from telethon import types
from typing import *
from .. import loader, utils
@loader.unrestricted
@loader.ratelimit
@loader.tds
class VoiceMod(loader.Module):
"""Module for working with voicechat
"""
strings = {
"name": "VoiceMod",
"downloading": "<b>[VoiceMod]</b> Downloading...",
"converting": "<b>[VoiceMod]</b> Converting...",
"playing": "<b>[VoiceMod]</b> Playing...",
"plsjoin": "<b>[VoiceMod]</b> You are not joined (type .vjoin)",
"stop": "<b>[VoiceMod]</b> Playing stopped!",
"join": "<b>[VoiceMod]</b> Joined!",
"leave": "<b>[VoiceMod]</b> Leaved!",
"pause": "<b>[VoiceMod]</b> Paused!",
"resume": "<b>[VoiceMod]</b> Resumed!",
"mute": "<b>[VoiceMod]</b> Muted!",
"unmute": "<b>[VoiceMod]</b> Unmuted!",
"replay": "<b>[VoiceMod]</b> Replaying...",
"error": "<b>[VoiceMod]</b> Error: <code>{}</code>",
}
ytdlopts = {
'format': 'bestaudio',
'addmetadata': True,
'key': 'FFmpegMetadata',
'writethumbnail': True,
'prefer_ffmpeg': True,
'geo_bypass': True,
'nocheckcertificate': True,
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '320',
}],
'outtmpl': 'ytdl_out.mp3',
'quiet': True,
'logtostderr': False
}
group_calls: Dict[int, GroupCallFile] = {}
tag = "<b>[Shazam]</b> "
async def get_chat(self, m: types.Message):
args = utils.get_args_raw(m)
if not args:
chat = m.chat.id
else:
try:
chat = int(args)
except:
chat = args
try:
chat = (await m.client.get_entity(chat)).id
except Exception as e:
await utils.answer(m, self.strings('error').format(str(e)))
return None
return chat
def _call(self, m: types.Message, chat: int):
if str(chat) not in self.group_calls:
self.group_calls[str(chat)] = GroupCallFactory(
m.client, pytgcalls.GroupCallFactory.MTPROTO_CLIENT_TYPE.TELETHON).get_file_group_call()
async def vplaycmd(self, m: types.Message):
""".vplay [chat (optional)] <link/reply_to_audio>
Play audio in VC"""
args = utils.get_args_raw(m)
r = await m.get_reply_message()
chat = from_file = link = None
if args:
_ = re.match(r'(-?\d+|@[A-Za-z0-9_]{5,})\s+(.*)', args)
__ = re.match(r'(-?\d+|@[A-Za-z0-9_]{5,})', args)
if _:
chat = _.group(1)
link = _.group(2)
elif __:
chat = __.group(1)
else:
chat = m.chat.id
link = args or None
try:
chat = int(chat)
except:
chat = chat
try:
chat = (await m.client.get_entity(chat)).id
except Exception as e:
return await utils.answer(m, self.strings('error').format(str(e)))
else:
chat = m.chat.id
if r and r.audio and not link:
from_file = True
if not link and (not r or not r.audio):
return utils.answer(m, 'no audio/link')
if str(chat) not in self.group_calls:
return await utils.answer(m, self.strings('plsjoin'))
self._call(m, chat)
input_file = f'{chat}.raw'
m = await utils.answer(m, self.strings('downloading'))
if from_file:
audio_original = await r.download_media()
else:
try:
with YoutubeDL(self.ytdlopts) as rip:
rip.extract_info(link)
except Exception as e:
return await utils.answer(m, self.strings('error').format(str(e)))
audio_original = 'ytdl_out.mp3'
m = await utils.answer(m, self.strings('converting'))
ffmpeg.input(audio_original).output(
input_file, format='s16le', acodec='pcm_s16le', ac=2, ar='48k'
).overwrite_output().run()
os.remove(audio_original)
await utils.answer(m, self.strings('playing'))
self.group_calls[str(chat)].input_filename = input_file
async def vjoincmd(self, m: types.Message):
""".vjoin
Join to the VC"""
chat = await self.get_chat(m)
if not chat:
return
self._call(m, chat)
await self.group_calls[str(chat)].start(chat)
await utils.answer(m, self.strings('join'))
async def vleavecmd(self, m: types.Message):
""".vleave
Leave from the VC"""
chat = await self.get_chat(m)
if not chat:
return
self._call(m, chat)
await self.group_calls[str(chat)].stop()
del self.group_calls[str(chat)]
try:
os.remove(f'{chat}.raw')
except:
pass
await utils.answer(m, self.strings('leave'))
async def vreplaycmd(self, m: types.Message):
""".vreplay
Replay audio in VC"""
chat = await self.get_chat(m)
if not chat:
return
self._call(m, chat)
self.group_calls[str(chat)].restart_playout()
await utils.answer(m, self.strings('replay'))
async def vstopcmd(self, m: types.Message):
""".vstop
Stop play in VC"""
chat = await self.get_chat(m)
if not chat:
return
self._call(m, chat)
self.group_calls[str(chat)].stop_playout()
await utils.answer(m, self.strings('stop'))
async def vmutecmd(self, m: types.Message):
""".vmute
Mute player in VC"""
chat = await self.get_chat(m)
if not chat:
return
self._call(m, chat)
self.group_calls[str(chat)].set_is_mute(True)
await utils.answer(m, self.strings('unmute'))
async def vunmutecmd(self, m: types.Message):
""".vmute
Unmute player in VC"""
chat = await self.get_chat(m)
if not chat:
return
self._call(m, chat)
self.group_calls[str(chat)].set_is_mute(False)
await utils.answer(m, self.strings('mute'))
async def vpausecmd(self, m: types.Message):
""".vpause
Pause player in VC"""
chat = await self.get_chat(m)
if not chat:
return
self._call(m, chat)
self.group_calls[str(chat)].pause_playout()
await utils.answer(m, self.strings('pause'))
async def vresumecmd(self, m: types.Message):
""".vresume
Resume player in VC"""
chat = await self.get_chat(m)
if not chat:
return
self._call(m, chat)
self.group_calls[str(chat)].resume_playout()
await utils.answer(m, self.strings('resume'))
async def vdebugcmd(self, m: types.Message):
""".vdebug
debug"""
await utils.answer(m, f'DEBUG : {str(self.group_calls)}')
async def smcmd(self, message):
""".sm
to find music."""
args = utils.get_args_raw(message)
reply = await message.get_reply_message()
if not args:
return await message.edit("<b>No args.</b>")
try:
await message.edit("<b>Loading...</b>")
music = await message.client.inline_query('lybot', args)
await message.delete()
await message.client.send_file(message.to_id, music[0].result.document, reply_to=reply.id if reply else None)
except: return await message.client.send_message(message.chat_id, f"<b> Music named <code> {args} </code> not found. </b>")
async def shazamcmd(self, message):
""".shazam <reply to audio> - recognize track"""
s = await get_audio_shazam(message)
if not s: return
try:
shazam = Shazam(s.track.read())
recog = shazam.recognizeSong()
track = next(recog)[1]['track']
await message.client.send_file(message.to_id, file=track['images']['background'],
caption=self.tag + "recognized track: " + track['share']['subject'],
reply_to=s.reply.id)
await message.delete()
except: await message.edit(self.tag + "Could not recognize...")
async def get_audio_shazam(message):
class rct():
track = io.BytesIO()
reply = None
reply = await message.get_reply_message()
if reply and reply.file and reply.file.mime_type.split("/")[0] == "audio":
ae = rct()
await utils.answer(message, "<b>Downloading...</b>")
ae.track = io.BytesIO(await reply.download_media(bytes))
ae.reply = reply
await message.edit("<b>Recognizing...</b>")
return ae
else:
await utils.answer(message, "<b>reply to audio...</b>")
return None

View File

@@ -0,0 +1,27 @@
from telethon import events
from telethon.errors.rpcerrorlist import YouBlockedUserError
from .. import loader, utils
import asyncio
def register(cb):
cb(ValuteMod())
class ValuteMod(loader.Module):
"""Конвертер Валют"""
strings = {'name': 'Конвертер Валют'}
async def valcmd(self, message):
""".val + количество + валюта"""
state = utils.get_args_raw(message)
await message.edit("<b>Данные получены</b>")
chat = '@exchange_rates_vsk_bot'
async with message.client.conversation(chat) as conv:
try:
await message.edit("<b>Конвертирую...</b>")
response = conv.wait_event(events.NewMessage(incoming=True, from_users=1210425892))
bot_send_message = await message.client.send_message(chat, format(state))
bot_response = response = await response
except YouBlockedUserError:
await message.edit('<b>Убери из ЧС:</b> ' + chat)
return
await bot_send_message.delete()
await message.edit(response.text)
await bot_response.delete()

View File

@@ -0,0 +1,54 @@
from .. import loader, utils
from telethon import events
from telethon.errors.rpcerrorlist import YouBlockedUserError
from asyncio.exceptions import TimeoutError
def register(cb):
cb(ErrorMod())
class ErrorMod(loader.Module):
"""Модуль для проверки слов на наличие ошибок """
strings = {'name': 'Пиши грамотно'}
async def errcmd(self, message):
"""Пиши .err + слово, можно реплай."""
try:
text = utils.get_args_raw(message)
reply = await message.get_reply_message()
chat = "@SpellingMasterBot"
if not text and not reply:
await message.edit("<b>А аргументы кто указывать будет</b>")
return
if text:
await message.edit("<b>уну моменто</b>")
async with message.client.conversation(chat) as conv:
try:
response = conv.wait_event(events.NewMessage(incoming=True, from_users=1037534015))
await message.client.send_message(chat, text)
response = await response
except YouBlockedUserError:
await message.reply("<b>Удали из ЧС: @SpellingMasterBot</b>")
return
if not response.text:
await message.edit("<Ещё раз пробуй</b>")
return
await message.delete()
await message.client.send_message(message.to_id, response.text)
if reply:
await message.edit("<b>Секундочку</b>")
async with message.client.conversation(chat) as conv:
try:
response = conv.wait_event(events.NewMessage(incoming=True, from_users=1037534015))
await message.client.send_message(chat, reply)
response = await response
except YouBlockedUserError:
await message.reply("<b>Удали из ЧС: @SpellingMasterBot</b>")
return
if not response.text:
await message.edit("<Пробуй еще раз </b>")
return
await message.delete()
await message.client.send_message(message.to_id, response.text)
except TimeoutError:
return await message.edit("<b>Неизвестная ошибка</b>")

View File

@@ -0,0 +1,57 @@
from telethon import events
from .. import loader, utils
import asyncio, re
chat = 707693258
@loader.tds
class AsserMod(loader.Module):
"""easy as lists and as in PM."""
strings={"name": "as"}
async def ascmd(self, message):
"""use: .аs to fast add in as list."""
reply = await message.get_reply_message()
send_mes = True
sms = ""
check_work = "⏳processing..."
ids = []
txt = reply.raw_text
args = utils.get_args_raw(message)
await utils.answer(message, check_work)
while send_mes:
send_mes = re.search(r"(?P<link>@[0-9a-z_]+|(?:https?://)?t\.me/[0-9a-z_]+|tg://openmessage\?user_id=(?P<id>[0-9]+))", txt, flags=re.I)
if send_mes:
txt = txt[send_mes.end():]
send_mes = send_mes.groupdict()
send_mes['link'], send_mes['id'] = '@'+send_mes['id'] if send_mes['id'] else send_mes['link'], ''
mes = ''.join(send_mes.values())
ids.append(mes)
async with message.client.conversation(chat) as conv:
for i in ids:
sms += await self.yapedik(message, sms, i, check_work, conv, args)
check_work = "checked!⌛️"
await utils.answer(message, check_work+sms)
async def yapedik(self, message, sms, i, check_work, conv, args):
try:
response = conv.wait_event(events.NewMessage(incoming=True, from_users=chat, chats=chat))
await message.client.send_message(chat, 'баны ' + i)
response = await response
if response.raw_text.lower().find('он в списке «ирис-антиспам»') != -1:
sms += '\n' + f"<code>{i}</code>"
if message.chat_id != chat:
await response.forward_to(message.to_id)
elif response.raw_text.lower().find('пользователь не найден') != -1:
sms += '\n⚠️ ' + f"<code>{i}</code>"
else:
await asyncio.sleep(4)
await message.client.send_message(chat, f"+ас {i}\n{args}")
sms += '\n' + f"<code>{i}</code>"
await utils.answer(message, check_work + sms)
await asyncio.sleep(4)
return sms
except:
return await self.yapedik(message, sms, i, check_work, conv, args)