Major Shit's Fixes

This commit is contained in:
allinoneallinone00
2024-04-30 00:35:34 +00:00
parent 5d34fbdcad
commit 3715eafe69
31 changed files with 394 additions and 451 deletions

View File

@@ -16,7 +16,7 @@
from contextlib import suppress
from pyrogram import Client, ContinuePropagation, filters, enums
from pyrogram import Client, ContinuePropagation, filters
from pyrogram.errors import (
UserAdminInvalid,
ChatAdminRequired,
@@ -93,7 +93,6 @@ async def admintool_handler(_, message: Message):
await message.reply(
db_cache.get(f"welcome_text{message.chat.id}"),
disable_web_page_preview=True,
parse_mode=enums.ParseMode.HTML,
)
raise ContinuePropagation

View File

@@ -17,11 +17,10 @@
# import json
# from html import escape as t
from time import perf_counter
from typing import AsyncGenerator, Optional, List, Union
from typing import AsyncGenerator, List, Optional, Union
from pyrogram import Client, filters
# from pyrogram.errors.exceptions.flood_420 import FloodWait
from pyrogram import types, raw, utils, enums
from pyrogram import Client, enums, filters, raw, types, utils
from pyrogram.types.object import Object
from utils.misc import modules_help, prefix
@@ -112,9 +111,7 @@ class Chat(Object):
username=user.username,
first_name=user.first_name,
last_name=user.last_name,
photo=types.ChatPhoto._parse(
client, user.photo, peer_id, user.access_hash
),
photo=types.ChatPhoto._parse(client, user.photo, peer_id, user.access_hash),
restrictions=types.List(
[types.Restriction._parse(r) for r in user.restriction_reason]
)
@@ -142,7 +139,7 @@ class Chat(Object):
has_protected_content=getattr(chat, "noforwards", None),
client=client,
is_admin=True if getattr(chat, "admin_rights", False) else False,
deactivated=getattr(chat, "deactivated"),
deactivated=chat.deactivated,
)
@staticmethod
@@ -152,9 +149,11 @@ class Chat(Object):
return Chat(
id=peer_id,
type=enums.ChatType.SUPERGROUP
if getattr(channel, "megagroup", None)
else enums.ChatType.CHANNEL,
type=(
enums.ChatType.SUPERGROUP
if getattr(channel, "megagroup", None)
else enums.ChatType.CHANNEL
),
is_verified=getattr(channel, "verified", None),
is_restricted=getattr(channel, "restricted", None),
is_creator=getattr(channel, "creator", None),
@@ -234,9 +233,7 @@ class Dialog(Object):
self.is_pinned = is_pinned
@staticmethod
def _parse(
client, dialog: "raw.types.Dialog", messages, users, chats
) -> "Dialog":
def _parse(client, dialog: "raw.types.Dialog", messages, users, chats) -> "Dialog":
return Dialog(
chat=Chat._parse_dialog(client, dialog.peer, users, chats),
top_message=messages.get(utils.get_peer_id(dialog.peer)),
@@ -275,9 +272,7 @@ async def get_dialogs(
if isinstance(message, raw.types.MessageEmpty):
continue
chat_id = utils.get_peer_id(message.peer_id)
messages[chat_id] = await types.Message._parse(
self, message, users, chats
)
messages[chat_id] = await types.Message._parse(self, message, users, chats)
dialogs = []
for dialog in r.dialogs:
if not isinstance(dialog, raw.types.Dialog):
@@ -298,9 +293,7 @@ async def get_dialogs(
@Client.on_message(filters.command("admlist", prefix) & filters.me)
async def admlist(client: Client, message: types.Message):
await message.edit(
"<b>Retrieving information... (it'll take some time)</b>", parse_mode=enums.ParseMode.HTML
)
await message.edit("<b>Retrieving information... (it'll take some time)</b>")
start = perf_counter()
try:
@@ -311,9 +304,7 @@ async def admlist(client: Client, message: types.Message):
chat = dialog.chat
if getattr(chat, "deactivated", False):
continue
if getattr(chat, "is_creator", False) and getattr(
chat, "username", None
):
if getattr(chat, "is_creator", False) and getattr(chat, "username", None):
owned_usernamed_chats.append(chat)
elif getattr(chat, "is_creator", False):
owned_chats.append(chat)
@@ -333,9 +324,7 @@ async def admlist(client: Client, message: types.Message):
text += "\n<b>Owned chats with username:</b>\n"
for index, chat in enumerate(owned_usernamed_chats):
cid = str(chat.id).replace("-100", "")
text += (
f"{index + 1}. <a href=https://t.me/{cid}>{chat.title}</a>\n"
)
text += f"{index + 1}. <a href=https://t.me/c/{cid}/1>{chat.title}</a>\n"
stop = perf_counter()
total_count = (
@@ -347,20 +336,16 @@ async def admlist(client: Client, message: types.Message):
f"\n<b><u>Adminned chats:</u></b> {len(adminned_chats)}\n"
f"<b><u>Owned chats:</u></b> {len(owned_chats)}\n"
f"<b><u>Owned chats with username:</u></b> {len(owned_usernamed_chats)}\n\n"
f"Done at {round(stop - start, 3)} seconds.",
parse_mode=enums.ParseMode.HTML
f"Done in {round(stop - start, 3)} seconds.",
)
except Exception as e:
await message.edit(format_exc(e), parse_mode=enums.ParseMode.HTML)
await message.edit(format_exc(e))
return
@Client.on_message(filters.command("admcount", prefix) & filters.me)
async def admcount(client: Client, message: types.Message):
await message.edit(
"<b>Retrieving information... (it'll take some time)</b>",
parse_mode=enums.ParseMode.HTML
)
await message.edit("<b>Retrieving information... (it'll take some time)</b>")
start = perf_counter()
try:
@@ -371,9 +356,7 @@ async def admcount(client: Client, message: types.Message):
chat = dialog.chat
if getattr(chat, "deactivated", False):
continue
if getattr(chat, "is_creator", False) and getattr(
chat, "username", None
):
if getattr(chat, "is_creator", False) and getattr(chat, "username", None):
owned_usernamed_chats += 1
elif getattr(chat, "is_creator", False):
owned_chats += 1
@@ -383,16 +366,15 @@ async def admcount(client: Client, message: types.Message):
stop = perf_counter()
total_count = adminned_chats + owned_chats + owned_usernamed_chats
await message.edit(
f"<b><u>Total:</u></b> {adminned_chats + owned_chats + owned_usernamed_chats}"
f"<b><u>Total:</u></b> {total_count}"
f"\n<b><u>Adminned chats:</u></b> {adminned_chats}\n"
f"<b><u>Owned chats:</u></b> {owned_chats}\n"
f"<b><u>Owned chats with username:</u></b> {owned_usernamed_chats}\n\n"
f"Done at {round(stop - start, 3)} seconds.\n\n"
f"Done in {round(stop - start, 3)} seconds.\n\n"
f"<b>Get full list: </b><code>{prefix}admlist</code>",
parse_mode=enums.ParseMode.HTML
)
except Exception as e:
await message.edit(format_exc(e), parse_mode=enums.ParseMode.HTML)
await message.edit(format_exc(e))
return

View File

@@ -18,36 +18,22 @@
import asyncio
from datetime import datetime
import humanize
from pyrogram import Client, enums, filters
from pyrogram.types import Message
from utils.misc import modules_help, prefix
from utils.scripts import import_library
from utils.scripts import import_library, ReplyCheck
humanize = import_library("humanize")
import humanize
import_library("humanize")
# Variables
AFK = False
AFK_REASON = ""
AFK_TIME = ""
USERS = {}
GROUPS = {}
# Helpers
def ReplyCheck(message: Message):
reply_id = None
if message.reply_to_message:
reply_id = message.reply_to_message.id
elif not message.from_user.is_self:
reply_id = message.id
return reply_id
def GetChatID(message: Message):
"""Get the group id of the incoming message"""
@@ -87,7 +73,6 @@ async def collect_afk_messages(bot: Client, message: Message):
chat_id=GetChatID(message),
text=text,
reply_to_message_id=ReplyCheck(message),
parse_mode=enums.ParseMode.HTML,
)
CHAT_TYPE[GetChatID(message)] = 1
return
@@ -104,7 +89,6 @@ async def collect_afk_messages(bot: Client, message: Message):
chat_id=GetChatID(message),
text=text,
reply_to_message_id=ReplyCheck(message),
parse_mode=enums.ParseMode.HTML,
)
elif CHAT_TYPE[GetChatID(message)] > 50:
return
@@ -119,7 +103,6 @@ async def collect_afk_messages(bot: Client, message: Message):
chat_id=GetChatID(message),
text=text,
reply_to_message_id=ReplyCheck(message),
parse_mode=enums.ParseMode.HTML,
)
CHAT_TYPE[GetChatID(message)] += 1
@@ -153,8 +136,7 @@ async def afk_unset(bot: Client, message: Message):
await message.edit(
f"<code>While you were away (for {last_seen}), you received {sum(USERS.values()) + sum(GROUPS.values())} "
f"messages from {len(USERS) + len(GROUPS)} chats</code>",
parse_mode=enums.ParseMode.HTML
)
)
AFK = False
AFK_TIME = ""
AFK_REASON = ""
@@ -173,8 +155,7 @@ async def auto_afk_unset(bot: Client, message: Message):
last_seen = subtract_time(datetime.now(), AFK_TIME).replace("ago", "").strip()
reply = await message.reply(
f"<code>While you were away (for {last_seen}), you received {sum(USERS.values()) + sum(GROUPS.values())} "
f"messages from {len(USERS) + len(GROUPS)} chats</code>",
parse_mode=enums.ParseMode.HTML,
f"messages from {len(USERS) + len(GROUPS)} chats</code>"
)
AFK = False
AFK_TIME = ""
@@ -189,3 +170,5 @@ modules_help["afk"] = {
"afk [reason]": "Go to AFK mode with reason as anything after .afk\nUsage: <code>.afk <reason></code>",
"unafk": "Get out of AFK",
}

View File

@@ -14,27 +14,26 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
from pyrogram import Client, filters, enums
from pyrogram import Client, filters
from pyrogram.raw import functions
from pyrogram.types import Message
from utils.config import pm_limit
from utils.db import db
from utils.misc import modules_help, prefix
from utils.config import pm_limit
anti_pm_enabled = filters.create(
lambda _, __, ___: db.get("core.antipm", "status", False)
)
in_contact_list = filters.create(
lambda _, __, message: message.from_user.is_contact
)
in_contact_list = filters.create(lambda _, __, message: message.from_user.is_contact)
is_support = filters.create(lambda _, __, message: message.chat.is_support)
message_counts = {}
@Client.on_message(
filters.private
& ~filters.me
@@ -66,7 +65,11 @@ Do not spam further messages else I may have to block you!</i>
if db.get("core.antipm", "block", False):
await client.block_user(user_info)
if db.get("core.antipm", f"disallowusers{id}") == user_id != db.get("core.antipm", f"allowusers{id}") or db.get("core.antipm", f"disallowusers{id}") != user_id != db.get("core.antipm", f"allowusers{id}") :
if db.get("core.antipm", f"disallowusers{id}") == user_id != db.get(
"core.antipm", f"allowusers{id}"
) or db.get("core.antipm", f"disallowusers{id}") != user_id != db.get(
"core.antipm", f"allowusers{id}"
):
await client.send_message(message.chat.id, f"{default_text}")
if user_id in message_counts:
@@ -80,7 +83,10 @@ Do not spam further messages else I may have to block you!</i>
db.set("core.antipm", "warns", m_n_n)
if message_counts[user_id] > pm_limit:
await client.send_message(message.chat.id, f"<b>Ehm...! That was your Last warn, Bye Bye see you L0L</b>")
await client.send_message(
message.chat.id,
"<b>Ehm...! That was your Last warn, Bye Bye see you L0L</b>",
)
await client.block_user(user_id)
del message_counts[user_id]
db.set("core.antipm", "warns", 0)
@@ -92,21 +98,21 @@ async def anti_pm(_, message: Message):
if db.get("core.antipm", "status", False):
await message.edit(
"<b>Anti-PM status: enabled\n"
f"Disable with: </b><code>{prefix}antipm disable</code>", parse_mode=enums.ParseMode.HTML
f"Disable with: </b><code>{prefix}antipm disable</code>"
)
else:
await message.edit(
"<b>Anti-PM status: disabled\n"
f"Enable with: </b><code>{prefix}antipm enable</code>", parse_mode=enums.ParseMode.HTML
f"Enable with: </b><code>{prefix}antipm enable</code>"
)
elif message.command[1] in ["enable", "on", "1", "yes", "true"]:
db.set("core.antipm", "status", True)
await message.edit("<b>Anti-PM enabled!</b>", parse_mode=enums.ParseMode.HTML)
await message.edit("<b>Anti-PM enabled!</b>")
elif message.command[1] in ["disable", "off", "0", "no", "false"]:
db.set("core.antipm", "status", False)
await message.edit("<b>Anti-PM disabled!</b>", parse_mode=enums.ParseMode.HTML)
await message.edit("<b>Anti-PM disabled!</b>")
else:
await message.edit(f"<b>Usage: {prefix}antipm [enable|disable]</b>", parse_mode=enums.ParseMode.HTML)
await message.edit(f"<b>Usage: {prefix}antipm [enable|disable]</b>")
@Client.on_message(filters.command(["antipm_report"], prefix) & filters.me)
@@ -115,23 +121,21 @@ async def antipm_report(_, message: Message):
if db.get("core.antipm", "spamrep", False):
await message.edit(
"<b>Spam-reporting enabled.\n"
f"Disable with: </b><code>{prefix}antipm_report disable</code>", parse_mode=enums.ParseMode.HTML
f"Disable with: </b><code>{prefix}antipm_report disable</code>"
)
else:
await message.edit(
"<b>Spam-reporting disabled.\n"
f"Enable with: </b><code>{prefix}antipm_report enable</code>", parse_mode=enums.ParseMode.HTML
f"Enable with: </b><code>{prefix}antipm_report enable</code>"
)
elif message.command[1] in ["enable", "on", "1", "yes", "true"]:
db.set("core.antipm", "spamrep", True)
await message.edit("<b>Spam-reporting enabled!</b>", parse_mode=enums.ParseMode.HTML)
await message.edit("<b>Spam-reporting enabled!</b>")
elif message.command[1] in ["disable", "off", "0", "no", "false"]:
db.set("core.antipm", "spamrep", False)
await message.edit("<b>Spam-reporting disabled!</b>", parse_mode=enums.ParseMode.HTML)
await message.edit("<b>Spam-reporting disabled!</b>")
else:
await message.edit(
f"<b>Usage: {prefix}antipm_report [enable|disable]</b>", parse_mode=enums.ParseMode.HTML
)
await message.edit(f"<b>Usage: {prefix}antipm_report [enable|disable]</b>")
@Client.on_message(filters.command(["antipm_block"], prefix) & filters.me)
@@ -140,47 +144,49 @@ async def antipm_block(_, message: Message):
if db.get("core.antipm", "block", False):
await message.edit(
"<b>Blocking users enabled.\n"
f"Disable with: </b><code>{prefix}antipm_block disable</code>", parse_mode=enums.ParseMode.HTML
f"Disable with: </b><code>{prefix}antipm_block disable</code>"
)
else:
await message.edit(
"<b>Blocking users disabled.\n"
f"Enable with: </b><code>{prefix}antipm_block enable</code>", parse_mode=enums.ParseMode.HTML
f"Enable with: </b><code>{prefix}antipm_block enable</code>"
)
elif message.command[1] in ["enable", "on", "1", "yes", "true"]:
db.set("core.antipm", "block", True)
await message.edit("<b>Blocking users enabled!</b>", parse_mode=enums.ParseMode.HTML)
await message.edit("<b>Blocking users enabled!</b>")
elif message.command[1] in ["disable", "off", "0", "no", "false"]:
db.set("core.antipm", "block", False)
await message.edit("<b>Blocking users disabled!</b>", parse_mode=enums.ParseMode.HTML)
await message.edit("<b>Blocking users disabled!</b>")
else:
await message.edit(
f"<b>Usage: {prefix}antipm_block [enable|disable]</b>", parse_mode=enums.ParseMode.HTML
)
await message.edit(f"<b>Usage: {prefix}antipm_block [enable|disable]</b>")
@Client.on_message(filters.command(["a"], prefix) & filters.me)
async def add_contact(client: Client, message: Message):
id = message.chat.id
id = message.chat.id
user = await client.get_users(id)
db.set("core.antipm", f"allowusers{id}", id)
db.set("core.antipm", "warns", 0)
await message.edit("User Approved!")
user = await client.get_users(id)
db.set("core.antipm", f"allowusers{id}", id)
db.set("core.antipm", "warns", 0)
await message.edit("User Approved!")
@Client.on_message(filters.command(["d"], prefix) & filters.me)
async def del_contact(client: Client, message: Message):
id = message.chat.id
id = message.chat.id
user = await client.get_users(id)
db.set("core.antipm", f"disallowusers{id}", id)
db.remove("core.antipm", f"allowusers{id}")
await message.edit("User DisApproved!")
user = await client.get_users(id)
db.set("core.antipm", f"disallowusers{id}", id)
db.remove("core.antipm", f"allowusers{id}")
await message.edit("User DisApproved!")
modules_help["antipm"] = {
"antipm [enable|disable]*": "Enable Pm permit",
"antipm_report [enable|disable]*": "Enable spam reporting",
"antipm_block [enable|disable]*": "Enable user blocking",
"a": "Approve User",
"d": "DisApprove User"
"d": "DisApprove User",
}

View File

@@ -14,7 +14,7 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
from pyrogram import Client, filters, enums
from pyrogram import Client, filters
from pyrogram.errors import FloodWait
from pyrogram.raw import functions, types
from pyrogram.types import Message
@@ -37,7 +37,7 @@ async def global_mention_clear(client: Client, message: Message):
result = await client.invoke(request)
except FloodWait as e:
await message.edit_text(
f"<b>FloodWait received. Wait {e.x} seconds before trying again</b>", parse_mode=enums.ParseMode.HTML
f"<b>FloodWait received. Wait {e.x} seconds before trying again</b>"
)
return
await message.delete()
@@ -66,7 +66,7 @@ async def global_reaction_clear(client: Client, message: Message):
result = await client.invoke(request)
except FloodWait as e:
await message.edit_text(
f"<b>FloodWait received. Wait {e.x} seconds before trying again</b>", parse_mode=enums.ParseMode.HTML
f"<b>FloodWait received. Wait {e.x} seconds before trying again</b>"
)
return
await message.delete()

View File

@@ -52,7 +52,7 @@ async def direct_link_generator(_, m: Message):
elif m.reply_to_message:
message = m.reply_to_message.text
else:
await m.edit(f"<b>Usage: </b><code>{prefix}direct [url]</code>", parse_mode=enums.ParseMode.HTML)
await m.edit(f"<b>Usage: </b><code>{prefix}direct [url]</code>")
return
reply = ""
links = re.findall(r"\bhttps?://.*\.\S+", message)

View File

@@ -18,18 +18,18 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
from pyrogram import Client, filters, ContinuePropagation, errors, enums
from pyrogram import Client, ContinuePropagation, enums, errors, filters
from pyrogram.types import (
Message,
InputMediaAudio,
InputMediaDocument,
InputMediaPhoto,
InputMediaVideo,
InputMediaAudio,
Message,
)
from utils.db import db
from utils.misc import modules_help, prefix
from utils.scripts import format_exc
from utils.db import db
def get_filters_chat(chat_id):
@@ -52,11 +52,9 @@ contains = filters.create(contains_filter)
async def filters_main_handler(client: Client, message: Message):
value = get_filters_chat(message.chat.id)[message.text.lower()]
try:
await client.get_messages(
int(value["CHAT_ID"]), int(value["MESSAGE_ID"])
)
except errors.RPCError:
raise ContinuePropagation
await client.get_messages(int(value["CHAT_ID"]), int(value["MESSAGE_ID"]))
except errors.RPCError as exc:
raise ContinuePropagation from exc
if value.get("MEDIA_GROUP"):
messages_grouped = await client.get_media_group(
@@ -87,9 +85,7 @@ async def filters_main_handler(client: Client, message: Message):
)
elif _.video.thumbs:
media_grouped_list.append(
InputMediaVideo(
_.video.file_id, _.video.thumbs[0].file_id
)
InputMediaVideo(_.video.file_id, _.video.thumbs[0].file_id)
)
else:
media_grouped_list.append(InputMediaVideo(_.video.file_id))
@@ -112,9 +108,7 @@ async def filters_main_handler(client: Client, message: Message):
)
else:
media_grouped_list.append(
InputMediaDocument(
_.document.file_id, _.caption.HTML
)
InputMediaDocument(_.document.file_id, _.caption.HTML)
)
elif _.document.thumbs:
media_grouped_list.append(
@@ -123,14 +117,9 @@ async def filters_main_handler(client: Client, message: Message):
)
)
else:
media_grouped_list.append(
InputMediaDocument(_.document.file_id)
)
media_grouped_list.append(InputMediaDocument(_.document.file_id))
await client.send_media_group(
message.chat.id,
media_grouped_list,
reply_to_message_id=message.id,
parse_mode=enums.ParseMode.HTML,
message.chat.id, media_grouped_list, reply_to_message_id=message.id
)
else:
await client.copy_message(
@@ -147,16 +136,16 @@ async def filter_handler(client: Client, message: Message):
try:
if len(message.text.split()) < 2:
return await message.edit(
f"<b>Usage</b>: <code>{prefix}filter [name] (Reply required)</code>", parse_mode=enums.ParseMode.HTML
f"<b>Usage</b>: <code>{prefix}filter [name] (Reply required)</code>"
)
name = message.text.split(maxsplit=1)[1].lower()
chat_filters = get_filters_chat(message.chat.id)
if name in chat_filters.keys():
return await message.edit(
f"<b>Filter</b> <code>{name}</code> already exists.", parse_mode=enums.ParseMode.HTML
f"<b>Filter</b> <code>{name}</code> already exists."
)
if not message.reply_to_message:
return await message.edit("<b>Reply to message</b> please.", parse_mode=enums.ParseMode.HTML)
return await message.edit("<b>Reply to message</b> please.")
try:
chat = await client.get_chat(db.get("core.notes", "chat_id", 0))
@@ -182,7 +171,7 @@ async def filter_handler(client: Client, message: Message):
)
except errors.ChatForwardsRestricted:
await message.edit(
"<b>Forwarding messages is restricted by chat admins</b>", parse_mode=enums.ParseMode.HTML
"<b>Forwarding messages is restricted by chat admins</b>"
)
return
filter_ = {
@@ -206,27 +195,24 @@ async def filter_handler(client: Client, message: Message):
set_filters_chat(message.chat.id, chat_filters)
return await message.edit(
f"<b>Filter</b> <code>{name}</code> has been added.",
parse_mode=enums.ParseMode.HTML
)
except Exception as e:
return await message.edit(format_exc(e), parse_mode=enums.ParseMode.HTML)
return await message.edit(format_exc(e))
@Client.on_message(filters.command(["filters"], prefix) & filters.me)
async def filters_handler(client: Client, message: Message):
try:
text = ""
for index, a in enumerate(
get_filters_chat(message.chat.id).items(), start=1
):
for index, a in enumerate(get_filters_chat(message.chat.id).items(), start=1):
key, item = a
key = key.replace("<", "").replace(">", "")
text += f"{index}. <code>{key}</code>\n"
text = f"<b>Your filters in current chat</b>:\n\n" f"{text}"
text = text[:4096]
return await message.edit(text, parse_mode=enums.ParseMode.HTML)
return await message.edit(text)
except Exception as e:
return await message.edit(format_exc(e), parse_mode=enums.ParseMode.HTML)
return await message.edit(format_exc(e))
@Client.on_message(
@@ -237,23 +223,20 @@ async def filter_del_handler(client: Client, message: Message):
if len(message.text.split()) < 2:
return await message.edit(
f"<b>Usage</b>: <code>{prefix}fdel [name]</code>",
parse_mode=enums.ParseMode.HTML
)
name = message.text.split(maxsplit=1)[1].lower()
chat_filters = get_filters_chat(message.chat.id)
if name not in chat_filters.keys():
return await message.edit(
f"<b>Filter</b> <code>{name}</code> doesn't exists.",
parse_mode=enums.ParseMode.HTML
)
del chat_filters[name]
set_filters_chat(message.chat.id, chat_filters)
return await message.edit(
f"<b>Filter</b> <code>{name}</code> has been deleted.",
parse_mode=enums.ParseMode.HTML
)
except Exception as e:
return await message.edit(format_exc(e), parse_mode=enums.ParseMode.HTML)
return await message.edit(format_exc(e))
@Client.on_message(filters.command(["fsearch"], prefix) & filters.me)
@@ -262,22 +245,19 @@ async def filter_search_handler(client: Client, message: Message):
if len(message.text.split()) < 2:
return await message.edit(
f"<b>Usage</b>: <code>{prefix}fsearch [name]</code>",
parse_mode=enums.ParseMode.HTML
)
name = message.text.split(maxsplit=1)[1].lower()
chat_filters = get_filters_chat(message.chat.id)
if name not in chat_filters.keys():
return await message.edit(
f"<b>Filter</b> <code>{name}</code> doesn't exists.",
parse_mode=enums.ParseMode.HTML
)
return await message.edit(
f"<b>Trigger</b>:\n<code>{name}</code"
f">\n<b>Answer</b>:\n{chat_filters[name]}",
parse_mode=enums.ParseMode.HTML,
f">\n<b>Answer</b>:\n{chat_filters[name]}"
)
except Exception as e:
return await message.edit(format_exc(e), parse_mode=enums.ParseMode.HTML)
return await message.edit(format_exc(e))
modules_help["filters"] = {

View File

@@ -38,13 +38,11 @@ async def help_cmd(_, message: Message):
await message.reply(
text,
disable_web_page_preview=True,
parse_mode=enums.ParseMode.HTML,
)
else:
await message.edit(
text,
disable_web_page_preview=True,
parse_mode=enums.ParseMode.HTML,
)
msg_edited = True
text = "<b>"
@@ -53,16 +51,15 @@ async def help_cmd(_, message: Message):
if msg_edited:
await message.reply(
text, disable_web_page_preview=True, parse_mode=enums.ParseMode.HTML
text, disable_web_page_preview=True
)
else:
await message.edit(
text, disable_web_page_preview=True, parse_mode=enums.ParseMode.HTML
text, disable_web_page_preview=True
)
elif message.command[1].lower() in modules_help:
await message.edit(
format_module_help(message.command[1].lower(), prefix),
parse_mode=enums.ParseMode.HTML,
format_module_help(message.command[1].lower(), prefix)
)
else:
command_name = message.command[1].lower()
@@ -77,10 +74,9 @@ async def help_cmd(_, message: Message):
f"<code>{prefix}{cmd[0]}</code>"
f"{' <code>' + cmd[1] + '</code>' if len(cmd) > 1 else ''}"
f" — <i>{cmd_desc}</i>",
parse_mode=enums.ParseMode.HTML,
)
await message.edit(
f"<b>Module {command_name} not found</b>", parse_mode=enums.ParseMode.HTML
f"<b>Module {command_name} not found</b>"
)
# TODO: refactor this cringe
command_name = message.command[1].lower()
@@ -95,10 +91,9 @@ async def help_cmd(_, message: Message):
f"<code>{prefix}{cmd[0]}</code>"
f"{' <code>' + cmd[1] + '</code>' if len(cmd) > 1 else ''}"
f" — <i>{cmd_desc}</i>",
parse_mode=enums.ParseMode.HTML,
)
await message.edit(
f"<b>Module {command_name} not found</b>", parse_mode=enums.ParseMode.HTML
f"<b>Module {command_name} not found</b>"
)

View File

@@ -35,15 +35,13 @@ async def get_mod_hash(_, message: Message):
resp = requests.get(url)
if not resp.ok:
await message.edit(
f"<b>Troubleshooting with downloading module <code>{url}</code></b>",
parse_mode=enums.ParseMode.HTML,
f"<b>Troubleshooting with downloading module <code>{url}</code></b>"
)
return
await message.edit(
f"<b>Module hash: <code>{hashlib.sha256(resp.content).hexdigest()}</code>\n"
f"Link: <code>{url}</code>\nFile: <code>{url.split('/')[-1]}</code></b>",
parse_mode=enums.ParseMode.HTML,
)
@@ -57,9 +55,7 @@ async def loadmod(_, message: Message):
)
and len(message.command) == 1
):
await message.edit(
"<b>Specify module to download</b>", parse_mode=enums.ParseMode.HTML
)
await message.edit("<b>Specify module to download</b>")
return
if len(message.command) > 1:
@@ -81,7 +77,6 @@ async def loadmod(_, message: Message):
if not resp.ok:
await message.edit(
f"<b>Troubleshooting with downloading module <code>{url}</code></b>",
parse_mode=enums.ParseMode.HTML,
)
return
@@ -92,17 +87,13 @@ async def loadmod(_, message: Message):
"<a href=https://github.com/The-MoonTg-project/custom_modules>"
"custom_modules</a> repository are supported!</b>",
disable_web_page_preview=True,
parse_mode=enums.ParseMode.HTML,
)
module_name = url.split("/")[-1].split(".")[0]
resp = requests.get(url)
if not resp.ok:
await message.edit(
f"<b>Module <code>{module_name}</code> is not found</b>",
parse_mode=enums.ParseMode.HTML,
)
await message.edit(f"<b>Module <code>{module_name}</code> is not found</b>")
return
if not os.path.exists(f"{BASE_PATH}/modules/custom_modules"):
@@ -129,15 +120,11 @@ async def loadmod(_, message: Message):
"<a href=https://github.com/The-MoonTg-project/custom_modules>"
"custom_modules</a> repository are supported!</b>",
disable_web_page_preview=True,
parse_mode=enums.ParseMode.HTML
)
else:
os.rename(file_name, f"./modules/custom_modules/{module_name}.py")
await message.edit(
f"<b>The module <code>{module_name}</code> is loaded!</b>",
parse_mode=enums.ParseMode.HTML,
)
await message.edit(f"<b>The module <code>{module_name}</code> is loaded!</b>")
restart()
@@ -155,26 +142,19 @@ async def unload_mods(_, message: Message):
if os.path.exists(f"{BASE_PATH}/modules/custom_modules/{module_name}.py"):
os.remove(f"{BASE_PATH}/modules/custom_modules/{module_name}.py")
await message.edit(
f"<b>The module <code>{module_name}</code> removed!</b>",
parse_mode=enums.ParseMode.HTML,
)
await message.edit(f"<b>The module <code>{module_name}</code> removed!</b>")
restart()
elif os.path.exists(f"{BASE_PATH}/modules/{module_name}.py"):
await message.edit(
"<b>It is forbidden to remove built-in modules, it will disrupt the updater</b>",
parse_mode=enums.ParseMode.HTML,
"<b>It is forbidden to remove built-in modules, it will disrupt the updater</b>"
)
else:
await message.edit(
f"<b>Module <code>{module_name}</code> is not found</b>",
parse_mode=enums.ParseMode.HTML,
)
await message.edit(f"<b>Module <code>{module_name}</code> is not found</b>")
@Client.on_message(filters.command(["loadallmods"], prefix) & filters.me)
async def load_all_mods(_, message: Message):
await message.edit("<b>Fetching info...</b>", parse_mode=enums.ParseMode.HTML)
await message.edit("<b>Fetching info...</b>")
if not os.path.exists(f"{BASE_PATH}/modules/custom_modules"):
os.mkdir(f"{BASE_PATH}/modules/custom_modules")
@@ -191,23 +171,22 @@ async def load_all_mods(_, message: Message):
continue
new_modules[module_info["name"][:-3]] = module_info["download_url"]
if not new_modules:
return await message.edit("<b>All modules already loaded</b>", parse_mode=enums.ParseMode.HTML)
return await message.edit("<b>All modules already loaded</b>")
await message.edit(f'<b>Loading new modules: {" ".join(new_modules.keys())}</b>', parse_mode=enums.ParseMode.HTML)
await message.edit(f'<b>Loading new modules: {" ".join(new_modules.keys())}</b>')
for name, url in new_modules.items():
with open(f"./modules/custom_modules/{name}.py", "wb") as f:
f.write(requests.get(url).content)
await message.edit(
f'<b>Successfully loaded new modules: {" ".join(new_modules.keys())}</b>',
parse_mode=enums.ParseMode.HTML
)
restart()
@Client.on_message(filters.command(["updateallmods"], prefix) & filters.me)
async def updateallmods(_, message: Message):
await message.edit("<b>Updating modules...</b>", parse_mode=enums.ParseMode.HTML)
await message.edit("<b>Updating modules...</b>")
if not os.path.exists(f"{BASE_PATH}/modules/custom_modules"):
os.mkdir(f"{BASE_PATH}/modules/custom_modules")
@@ -215,7 +194,7 @@ async def updateallmods(_, message: Message):
modules_installed = list(os.walk("modules/custom_modules"))[0][2]
if not modules_installed:
return await message.edit("<b>You don't have any modules installed</b>", parse_mode=enums.ParseMode.HTML)
return await message.edit("<b>You don't have any modules installed</b>")
for module_name in modules_installed:
if not module_name.endswith(".py"):
@@ -231,7 +210,7 @@ async def updateallmods(_, message: Message):
with open(f"./modules/custom_modules/{module_name}", "wb") as f:
f.write(resp.content)
await message.edit(f"<b>Successfully updated {len(modules_installed)} modules</b>", parse_mode=enums.ParseMode.HTML)
await message.edit(f"<b>Successfully updated {len(modules_installed)} modules</b>")
modules_help["loader"] = {
@@ -243,3 +222,4 @@ modules_help["loader"] = {
"loadallmods": "Load all custom modules (use it at your own risk)",
"updateallmods": "Update all custom modules",
}

View File

@@ -14,17 +14,17 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
from pyrogram import Client, filters, errors, enums
from pyrogram import Client, enums, errors, filters
from pyrogram.types import Message
from utils.db import db
from utils.misc import modules_help, prefix
from utils.handlers import NoteSendHandler
from utils.misc import modules_help, prefix
@Client.on_message(filters.command(["save"], prefix) & filters.me)
async def save_note(client: Client, message: Message):
await message.edit("<b>Loading...</b>", parse_mode=enums.ParseMode.HTML)
await message.edit("<b>Loading...</b>")
try:
chat = await client.get_chat(db.get("core.notes", "chat_id", 0))
@@ -55,7 +55,6 @@ async def save_note(client: Client, message: Message):
except errors.ChatForwardsRestricted:
await message.edit(
"<b>Forwarding messages is restricted by chat admins</b>",
parse_mode=enums.ParseMode.HTML
)
return
note = {
@@ -64,9 +63,9 @@ async def save_note(client: Client, message: Message):
"CHAT_ID": str(chat_id),
}
db.set("core.notes", f"note{note_name}", note)
await message.edit(f"<b>Note {note_name} saved</b>", parse_mode=enums.ParseMode.HTML)
await message.edit(f"<b>Note {note_name} saved</b>")
else:
await message.edit("<b>This note already exists</b>", parse_mode=enums.ParseMode.HTML)
await message.edit("<b>This note already exists</b>")
else:
checking_note = db.get("core.notes", f"note{note_name}", False)
if not checking_note:
@@ -80,9 +79,9 @@ async def save_note(client: Client, message: Message):
"CHAT_ID": str(chat_id),
}
db.set("core.notes", f"note{note_name}", note)
await message.edit(f"<b>Note {note_name} saved</b>", parse_mode=enums.ParseMode.HTML)
await message.edit(f"<b>Note {note_name} saved</b>")
else:
await message.edit("<b>This note already exists</b>", parse_mode=enums.ParseMode.HTML)
await message.edit("<b>This note already exists</b>")
elif len(message.text.split()) >= 3:
note_name = message.text.split(maxsplit=1)[1].split()[0]
checking_note = db.get("core.notes", f"note{note_name}", False)
@@ -96,31 +95,30 @@ async def save_note(client: Client, message: Message):
"CHAT_ID": str(chat_id),
}
db.set("core.notes", f"note{note_name}", note)
await message.edit(f"<b>Note {note_name} saved</b>", parse_mode=enums.ParseMode.HTML)
await message.edit(f"<b>Note {note_name} saved</b>")
else:
await message.edit("<b>This note already exists</b>", parse_mode=enums.ParseMode.HTML)
await message.edit("<b>This note already exists</b>")
else:
await message.edit(
f"<b>Example: <code>{prefix}save note_name</code></b>",
parse_mode=enums.ParseMode.HTML
)
@Client.on_message(filters.command("note", prefix) & filters.me)
async def note_send(client: Client, message: Message):
handler = NoteSendHandler(client, message)
await handler.handle_note_send()
@Client.on_message(filters.command(["notes"], prefix) & filters.me)
async def notes(_, message: Message):
await message.edit("<b>Loading...</b>", parse_mode=enums.ParseMode.HTML)
await message.edit("<b>Loading...</b>")
text = "Available notes:\n\n"
collection = db.get_collection("core.notes")
for note in collection.keys():
if note[:4] == "note":
text += f"<code>{note[4:]}</code>\n"
await message.edit(text, parse_mode=enums.ParseMode.HTML)
await message.edit(text)
@Client.on_message(filters.command(["clear"], prefix) & filters.me)
@@ -130,14 +128,11 @@ async def clear_note(_, message: Message):
find_note = db.get("core.notes", f"note{note_name}", False)
if find_note:
db.remove("core.notes", f"note{note_name}")
await message.edit(f"<b>Note {note_name} deleted</b>", parse_mode=enums.ParseMode.HTML)
await message.edit(f"<b>Note {note_name} deleted</b>")
else:
await message.edit("<b>There is no such note</b>", parse_mode=enums.ParseMode.HTML)
await message.edit("<b>There is no such note</b>")
else:
await message.edit(
f"<b>Example: <code>{prefix}clear note_name</code></b>",
parse_mode=enums.ParseMode.HTML
)
await message.edit(f"<b>Example: <code>{prefix}clear note_name</code></b>")
modules_help["notes"] = {

View File

@@ -13,7 +13,7 @@ from time import perf_counter
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
from pyrogram import Client, enums, filters
from pyrogram import Client, filters
from pyrogram.types import Message
from utils.misc import modules_help, prefix
@@ -27,10 +27,10 @@ from utils.misc import modules_help, prefix
@Client.on_message(filters.command(["ping", "p"], prefix) & filters.me)
async def ping(_, message: Message):
start = perf_counter()
await message.edit("<b>Pong!</b>", parse_mode=enums.ParseMode.HTML)
await message.edit("<b>Pong!</b>")
end = perf_counter()
await message.edit(
f"<b>Pong! {round(end - start, 3)}s</b>", parse_mode=enums.ParseMode.HTML
f"<b>Pong! {round(end - start, 3)}s</b>"
)

View File

@@ -14,7 +14,7 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
from pyrogram import Client, enums, filters
from pyrogram import Client, filters
from pyrogram.types import Message
from utils.db import db
@@ -30,13 +30,12 @@ async def setprefix(_, message: Message):
pref = message.command[1]
db.set("core.main", "prefix", pref)
await message.edit(
f"<b>Prefix [ <code>{pref}</code> ] is set!</b>",
parse_mode=enums.ParseMode.HTML,
f"<b>Prefix [ <code>{pref}</code> ] is set!</b>"
)
restart()
else:
await message.edit(
"<b>The prefix must not be empty!</b>", parse_mode=enums.ParseMode.HTML
"<b>The prefix must not be empty!</b>"
)

View File

@@ -15,7 +15,7 @@
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import asyncio
from pyrogram import Client, filters, enums
from pyrogram import Client, filters
from pyrogram.types import Message
from utils.misc import modules_help, prefix

View File

@@ -21,7 +21,7 @@
from contextlib import redirect_stdout
from io import StringIO
from pyrogram import Client, enums, filters
from pyrogram import Client, filters
from pyrogram.types import Message
# noinspection PyUnresolvedReferences
@@ -38,7 +38,7 @@ from utils.scripts import format_exc
async def user_exec(client: Client, message: Message):
if len(message.command) == 1:
await message.edit(
"<b>Code to execute isn't provided</b>", parse_mode=enums.ParseMode.HTML
"<b>Code to execute isn't provided</b>"
)
return
@@ -47,7 +47,7 @@ async def user_exec(client: Client, message: Message):
code = message.text.split(maxsplit=1)[1]
stdout = StringIO()
await message.edit("<b>Executing...</b>", parse_mode=enums.ParseMode.HTML)
await message.edit("<b>Executing...</b>")
try:
with redirect_stdout(stdout):
@@ -59,18 +59,18 @@ async def user_exec(client: Client, message: Message):
f"<code>{stdout.getvalue()}</code>"
)
if message.command[0] == "exnoedit":
await message.reply(text, parse_mode=enums.ParseMode.HTML)
await message.reply(text)
else:
await message.edit(text, parse_mode=enums.ParseMode.HTML)
await message.edit(text)
except Exception as e:
await message.edit(format_exc(e), parse_mode=enums.ParseMode.HTML)
await message.edit(format_exc(e))
# noinspection PyUnusedLocal
@Client.on_message(filters.command(["ev", "eval"], prefix) & filters.me)
async def user_eval(client: Client, message: Message):
if len(message.command) == 1:
await message.edit("<b>Code to eval isn't provided</b>", parse_mode=enums.ParseMode.HTML)
await message.edit("<b>Code to eval isn't provided</b>")
return
reply = message.reply_to_message
@@ -83,11 +83,10 @@ async def user_eval(client: Client, message: Message):
"<b>Expression:</b>\n"
f"<code>{code}</code>\n\n"
"<b>Result</b>:\n"
f"<code>{result}</code>",
parse_mode=enums.ParseMode.HTML,
f"<code>{result}</code>"
)
except Exception as e:
await message.edit(format_exc(e), parse_mode=enums.ParseMode.HTML)
await message.edit(format_exc(e))
modules_help["python"] = {

View File

@@ -152,7 +152,7 @@ async def rmbg(client: Client, message: Message):
@Client.on_message(filters.command("rebg", prefix) & filters.me)
async def rembg(client: Client, message: Message):
await message.edit("<code>Processing...</code>", parse_mode=enums.ParseMode.HTML)
await message.edit("<code>Processing...</code>")
chat_id = message.chat.id
try:
try:
@@ -162,7 +162,7 @@ async def rembg(client: Client, message: Message):
photo_data = await message.reply_to_message.download()
except ValueError:
await message.edit(
"<b>File not found</b>", parse_mode=enums.ParseMode.HTML
"<b>File not found</b>"
)
return
background_removed_data = remove_background(photo_data)

View File

@@ -3,7 +3,7 @@ import requests
import aiofiles
import base64
from pyrogram import Client, filters, enums
from pyrogram import Client, filters
from pyrogram.types import Message, InputMediaPhoto
from pyrogram.errors import MediaCaptionTooLong, MessageTooLong
@@ -156,7 +156,7 @@ async def tsearch(client: Client, message: Message):
link_results = await telegraph(title="Search Results", user_name=message.from_user.first_name, content=all_results_content)
if coverImage_url != None:
if coverImage_url is not None:
coverImage = requests.get(url=coverImage_url).content
async with aiofiles.open('coverImage.jpg', mode='wb') as f:
await f.write(coverImage)
@@ -177,12 +177,12 @@ async def tsearch(client: Client, message: Message):
await client.send_media_group(
chat_id,
[
InputMediaPhoto('coverImage.jpg', caption=f"<b>Title:</b> <code>{title}</code>\n<b>Category:</b> <code>{category}</code>\n<b>Language:</b> <code>{Language}</code>\n<b>Size:</b> <code>{size}</code>\n<b>Genres:</b> <code>{genre}</code>\n<b>Description:</b> {description}\n<b>Magnet Link:</b> <a href='{link_result}'>Click Here</a>")
InputMediaPhoto('coverImage.jpg', caption=f"<b>Title:</b> <code>{title}</code>\n<b>Category:</b> <code>{category}</code>\n<b>Language:</b> <code>{language}</code>\n<b>Size:</b> <code>{size}</code>\n<b>Genres:</b> <code>{genre}</code>\n<b>Description:</b> {description}\n<b>Magnet Link:</b> <a href='{link_result}'>Click Here</a>")
])
except MessageTooLong:
description = description[:150]
await message.edit_text(f"<b>Title:</b> <code>{title}</code>\n<b>Category:</b> <code>{category}</code>\n<b>Language:</b> <code>{Language}</code>\n<b>Size:</b> <code>{size}</code>\n<b>Genres:</b> <code>{genre}</code>\n<b>Description:</b> {description}\n<b>Magnet Link:</b> <a href='{link_result}'>Click Here</a>", disable_web_page_preview=True)
await message.edit_text(f"<b>Title:</b> <code>{title}</code>\n<b>Category:</b> <code>{category}</code>\n<b>Language:</b> <code>{language}</code>\n<b>Size:</b> <code>{size}</code>\n<b>Genres:</b> <code>{genre}</code>\n<b>Description:</b> {description}\n<b>Magnet Link:</b> <a href='{link_result}'>Click Here</a>", disable_web_page_preview=True)
except Exception as e:
await message.edit_text(format_exc(e))

View File

@@ -18,7 +18,7 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
from pyrogram import Client, enums, filters
from pyrogram import Client, filters
from pyrogram.types import Message
from utils.misc import modules_help, prefix
@@ -29,7 +29,7 @@ async def say(_, message: Message):
if len(message.command) == 1:
return
command = " ".join(message.command[1:])
await message.edit(f"<code>{command}</code>", parse_mode=enums.ParseMode.HTML)
await message.edit(f"<code>{command}</code>")
modules_help["say"] = {

View File

@@ -7,7 +7,7 @@
# (at your option) any later version.
import os
from pyrogram import Client, enums, filters
from pyrogram import Client, filters
from pyrogram.types import Message
from utils.misc import modules_help, prefix
@@ -26,12 +26,11 @@ from utils.scripts import format_exc, format_module_help, format_small_module_he
async def sendmod(client: Client, message: Message):
if len(message.command) == 1:
await message.edit(
"<b>Module name to send is not provided</b>",
parse_mode=enums.ParseMode.HTML,
"<b>Module name to send is not provided</b>"
)
return
await message.edit("<b>Dispatching...</b>", parse_mode=enums.ParseMode.HTML)
await message.edit("<b>Dispatching...</b>")
try:
module_name = message.command[1].lower()
if module_name in modules_help:
@@ -50,12 +49,9 @@ async def sendmod(client: Client, message: Message):
)
await message.delete()
else:
await message.edit(
f"<b>Module {module_name} not found!</b>",
parse_mode=enums.ParseMode.HTML,
)
await message.edit(f"<b>Module {module_name} not found!</b>")
except Exception as e:
await message.edit(format_exc(e), parse_mode=enums.ParseMode.HTML)
await message.edit(format_exc(e))
modules_help["sendmod"] = {

View File

@@ -20,7 +20,7 @@ import time
from datetime import datetime
from html import escape
from pyrogram import Client, filters, enums
from pyrogram import Client, filters
from pyrogram import ContinuePropagation
from pyrogram.errors import RPCError
from pyrogram.raw.functions.account import GetAuthorizations, ResetAuthorization
@@ -30,7 +30,6 @@ from pyrogram.types import Message
from utils.db import db
from utils.misc import modules_help, prefix
from textwrap import dedent
from datetime import datetime
auth_hashes = db.get("core.sessionkiller", "auths_hashes", [])
@@ -91,7 +90,7 @@ async def sessions_list(client: Client, message: Message):
answer = ""
chunk.clear()
if len(chunk):
await message.reply("\n\n".join(chunk), parse_mode=enums.ParseMode.HTML)
await message.reply("\n\n".join(chunk))
await message.delete()
@@ -103,16 +102,16 @@ async def sessionkiller(client: Client, message: Message):
if db.get("core.sessionkiller", "enabled", False):
await message.edit(
"<b>Sessionkiller status: enabled\n"
f"You can disable it with <code>{prefix}sessionkiller disable</code></b>", parse_mode=enums.ParseMode.HTML
f"You can disable it with <code>{prefix}sessionkiller disable</code></b>"
)
else:
await message.edit(
"<b>Sessionkiller status: disabled\n"
f"You can enable it with <code>{prefix}sessionkiller enable</code></b>", parse_mode=enums.ParseMode.HTML
f"You can enable it with <code>{prefix}sessionkiller enable</code></b>"
)
elif message.command[1] in ["enable", "on", "1", "yes", "true"]:
db.set("core.sessionkiller", "enabled", True)
await message.edit("<b>Sessionkiller enabled!</b>", parse_mode=enums.ParseMode.HTML)
await message.edit("<b>Sessionkiller enabled!</b>")
db.set(
"core.sessionkiller",
"auths_hashes",
@@ -126,10 +125,10 @@ async def sessionkiller(client: Client, message: Message):
elif message.command[1] in ["disable", "off", "0", "no", "false"]:
db.set("core.sessionkiller", "enabled", False)
await message.edit("<b>Sessionkiller disabled!</b>", parse_mode=enums.ParseMode.HTML)
await message.edit("<b>Sessionkiller disabled!</b>")
else:
await message.edit(
f"<b>Usage: {prefix}sessionkiller [enable|disable]</b>", parse_mode=enums.ParseMode.HTML
f"<b>Usage: {prefix}sessionkiller [enable|disable]</b>"
)
@@ -189,7 +188,7 @@ async def check_new_login(
# schedule sending report message so user will get notification
schedule_date = int(time.time() + 15)
await client.send_message(
"me", full_report, schedule_date=schedule_date, parse_mode=enums.ParseMode.HTML
"me", full_report, schedule_date=schedule_date
)
return

View File

@@ -13,7 +13,7 @@ async def sg(client: Client, message: Message):
if message.reply_to_message and message.reply_to_message.from_user:
user_id = message.reply_to_message.from_user.id
else:
await message.edit(f"<b>Usage: </b><code>{prefix}sgb [id]</code>", parse_mode=enums.ParseMode.HTML)
await message.edit(f"<b>Usage: </b><code>{prefix}sgb [id]</code>")
return
try:
await client.send_message("@SangMata_beta_bot","/start", parse_mode=enums.ParseMode.MARKDOWN)

View File

@@ -18,7 +18,7 @@ from subprocess import Popen, PIPE, TimeoutExpired
import os
from time import perf_counter
from pyrogram import Client, filters, enums
from pyrogram import Client, filters
from pyrogram.types import Message
from utils.misc import modules_help, prefix
@@ -27,7 +27,7 @@ from utils.misc import modules_help, prefix
@Client.on_message(filters.command(["shell", "sh"], prefix) & filters.me)
async def shell(_, message: Message):
if len(message.command) < 2:
return await message.edit("<b>Specify the command in message text</b>", parse_mode=enums.ParseMode.HTML)
return await message.edit("<b>Specify the command in message text</b>")
cmd_text = message.text.split(maxsplit=1)[1]
cmd_obj = Popen(
cmd_text,
@@ -40,7 +40,7 @@ async def shell(_, message: Message):
char = "#" if os.getuid() == 0 else "$"
text = f"<b>{char}</b> <code>{cmd_text}</code>\n\n"
await message.edit(text + "<b>Running...</b>", parse_mode=enums.ParseMode.HTML)
await message.edit(text + "<b>Running...</b>")
try:
start_time = perf_counter()
stdout, stderr = cmd_obj.communicate(timeout=60)
@@ -53,7 +53,7 @@ async def shell(_, message: Message):
if stderr:
text += f"<b>Error:</b>\n<code>{stderr}</code>\n\n"
text += f"<b>Completed in {round(stop_time - start_time, 5)} seconds with code {cmd_obj.returncode}</b>"
await message.edit(text, parse_mode=enums.ParseMode.HTML)
await message.edit(text)
cmd_obj.kill()

View File

@@ -16,7 +16,7 @@
import asyncio
from pyrogram import Client, filters, enums
from pyrogram import Client, filters
from pyrogram.types import Message
from utils.misc import modules_help, prefix
@@ -33,11 +33,11 @@ async def spam(client: Client, message: Message):
await message.delete()
for msg in range(amount):
for _msg in range(amount):
if message.reply_to_message:
sent = await message.reply_to_message.reply(text, parse_mode=enums.ParseMode.HTML)
sent = await message.reply_to_message.reply(text)
else:
sent = await client.send_message(message.chat.id, text, parse_mode=enums.ParseMode.HTML)
sent = await client.send_message(message.chat.id, text)
if message.command[0] == "statspam":
await asyncio.sleep(0.1)

View File

@@ -19,7 +19,7 @@ import os
from io import BytesIO
import requests
from pyrogram import Client, filters, errors, types, enums
from pyrogram import Client, filters, errors, types
from pyrogram.types import Message
from utils.misc import modules_help, prefix
@@ -65,9 +65,9 @@ async def quote_cmd(client: Client, message: Message):
if send_for_me:
await message.delete()
message = await client.send_message("me", "<b>Generating...</b>", parse_mode=enums.ParseMode.HTML)
message = await client.send_message("me", "<b>Generating...</b>")
else:
await message.edit("<b>Generating...</b>", parse_mode=enums.ParseMode.HTML)
await message.edit("<b>Generating...</b>")
url = "https://quotes.fl1yd.su/generate"
params = {
@@ -83,20 +83,20 @@ async def quote_cmd(client: Client, message: Message):
response = requests.post(url, json=params)
if not response.ok:
return await message.edit(
f"<b>Quotes API error!</b>\n" f"<code>{response.text}</code>", parse_mode=enums.ParseMode.HTML
f"<b>Quotes API error!</b>\n" f"<code>{response.text}</code>"
)
resized = resize_image(
BytesIO(response.content), img_type="PNG" if is_png else "WEBP"
)
await message.edit("<b>Sending...</b>", parse_mode=enums.ParseMode.HTML)
await message.edit("<b>Sending...</b>")
try:
func = client.send_document if is_png else client.send_sticker
chat_id = "me" if send_for_me else message.chat.id
await func(chat_id, resized)
except errors.RPCError as e: # no rights to send stickers, etc
await message.edit(format_exc(e), parse_mode=enums.ParseMode.HTML)
await message.edit(format_exc(e))
else:
await message.delete()
@@ -117,7 +117,7 @@ async def fake_quote_cmd(client: Client, message: types.Message):
)
if not fake_quote_text:
return await message.edit("<b>Fake quote text is empty</b>", parse_mode=enums.ParseMode.HTML)
return await message.edit("<b>Fake quote text is empty</b>")
q_message = await client.get_messages(
message.chat.id, message.reply_to_message.id
@@ -129,9 +129,9 @@ async def fake_quote_cmd(client: Client, message: types.Message):
if send_for_me:
await message.delete()
message = await client.send_message("me", "<b>Generating...</b>", parse_mode=enums.ParseMode.HTML)
message = await client.send_message("me", "<b>Generating...</b>")
else:
await message.edit("<b>Generating...</b>", parse_mode=enums.ParseMode.HTML)
await message.edit("<b>Generating...</b>")
url = "https://quotes.fl1yd.su/generate"
params = {
@@ -143,20 +143,20 @@ async def fake_quote_cmd(client: Client, message: types.Message):
response = requests.post(url, json=params)
if not response.ok:
return await message.edit(
f"<b>Quotes API error!</b>\n<code>{response.text}</code>", parse_mode=enums.ParseMode.HTML
f"<b>Quotes API error!</b>\n<code>{response.text}</code>"
)
resized = resize_image(
BytesIO(response.content), img_type="PNG" if is_png else "WEBP"
)
await message.edit("<b>Sending...</b>", parse_mode=enums.ParseMode.HTML)
await message.edit("<b>Sending...</b>")
try:
func = client.send_document if is_png else client.send_sticker
chat_id = "me" if send_for_me else message.chat.id
await func(chat_id, resized)
except errors.RPCError as e: # no rights to send stickers, etc
await message.edit(format_exc(e), parse_mode=enums.ParseMode.HTML)
await message.edit(format_exc(e))
else:
await message.delete()

View File

@@ -32,13 +32,13 @@ from utils.scripts import (
@Client.on_message(filters.command("kang", prefix) & filters.me)
@with_reply
async def kang(client: Client, message: types.Message):
await message.edit("<b>Please wait...</b>", parse_mode=enums.ParseMode.HTML)
await message.edit("<b>Please wait...</b>")
if len(message.command) < 2:
await message.edit(
"<b>No arguments provided\n"
f"Usage: <code>{prefix}kang [pack]* [emoji]</code></b>",
parse_mode=enums.ParseMode.HTML
)
return
@@ -54,12 +54,12 @@ async def kang(client: Client, message: types.Message):
result = await interact_with(await client.send_message("@stickers", pack, parse_mode=enums.ParseMode.MARKDOWN))
if ".TGS" in result.text:
await message.edit("<b>Animated packs aren't supported</b>", parse_mode=enums.ParseMode.HTML)
await message.edit("<b>Animated packs aren't supported</b>")
return
if "StickerExample.psd" not in result.text:
await message.edit(
"<b>Stickerpack doesn't exitst. Create it using @Stickers bot (via /newpack command)</b>",
parse_mode=enums.ParseMode.HTML
)
return
@@ -68,7 +68,7 @@ async def kang(client: Client, message: types.Message):
except ValueError:
await message.edit(
"<b>Replied message doesn't contain any downloadable media</b>",
parse_mode=enums.ParseMode.HTML
)
return
@@ -84,10 +84,10 @@ async def kang(client: Client, message: types.Message):
await client.delete_messages("@stickers", interact_with_to_delete)
await message.edit(
f"<b>Sticker added to <a href=https://t.me/addstickers/{pack}>pack</a></b>",
parse_mode=enums.ParseMode.HTML
)
else:
await message.edit("<b>Something went wrong. Check history with @stickers</b>", parse_mode=enums.ParseMode.HTML)
await message.edit("<b>Something went wrong. Check history with @stickers</b>")
interact_with_to_delete.clear()
@@ -95,7 +95,7 @@ async def kang(client: Client, message: types.Message):
@with_reply
async def stick2png(client: Client, message: types.Message):
try:
await message.edit("<b>Downloading...</b>", parse_mode=enums.ParseMode.HTML)
await message.edit("<b>Downloading...</b>")
path = await message.reply_to_message.download()
with open(path, "rb") as f:
@@ -108,7 +108,7 @@ async def stick2png(client: Client, message: types.Message):
await client.send_document(message.chat.id, file_io, parse_mode=enums.ParseMode.MARKDOWN)
except Exception as e:
await message.edit(format_exc(e), parse_mode=enums.ParseMode.HTML)
await message.edit(format_exc(e))
else:
await message.delete()
@@ -117,7 +117,7 @@ async def stick2png(client: Client, message: types.Message):
@with_reply
async def resize_cmd(client: Client, message: types.Message):
try:
await message.edit("<b>Downloading...</b>", parse_mode=enums.ParseMode.HTML)
await message.edit("<b>Downloading...</b>")
path = await message.reply_to_message.download()
resized = resize_image(path)
@@ -127,7 +127,7 @@ async def resize_cmd(client: Client, message: types.Message):
await client.send_document(message.chat.id, resized, parse_mode=enums.ParseMode.MARKDOWN)
except Exception as e:
await message.edit(format_exc(e), parse_mode=enums.ParseMode.HTML)
await message.edit(format_exc(e))
else:
await message.delete()

View File

@@ -13,7 +13,7 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
from pyrogram import Client, filters, enums
from pyrogram import Client, filters
from pyrogram.types import Message
import random
import datetime
@@ -28,7 +28,7 @@ async def support(_, message: Message):
commands_count = 0.0
for module in modules_help:
for cmd in module:
for _cmd in module:
commands_count += 1
await message.edit(
@@ -45,7 +45,6 @@ async def support(_, message: Message):
f"Modules count: {len(modules_help) / 1}\n"
f"Commands count: {commands_count}</b>",
disable_web_page_preview=True,
parse_mode=enums.ParseMode.HTML,
)
@@ -81,7 +80,6 @@ async def version(client: Client, message: Message):
+ f"Commit: <a href={remote_url}/commit/{gitrepo.head.commit.hexsha}>"
f"{gitrepo.head.commit.hexsha[:7]}</a> by {gitrepo.head.commit.author.name}\n"
f"Commit time: {commit_time}</b>",
parse_mode=enums.ParseMode.HTML,
)

View File

@@ -18,7 +18,7 @@ import os
import sys
import subprocess
from pyrogram import Client, filters, enums
from pyrogram import Client, filters
from pyrogram.types import Message
from utils.misc import modules_help, prefix, requirements_list
@@ -39,11 +39,11 @@ async def restart_cmd(_, message: Message):
)
if "LAVHOST" in os.environ:
await message.edit("<b>Your lavHost is restarting...</b>", parse_mode=enums.ParseMode.HTML)
await message.edit("<b>Your lavHost is restarting...</b>")
os.system("lavhost restart")
return
await message.edit("<b>Restarting...</b>", parse_mode=enums.ParseMode.HTML)
await message.edit("<b>Restarting...</b>")
restart()
@@ -60,11 +60,11 @@ async def update(_, message: Message):
)
if "LAVHOST" in os.environ:
await message.edit("<b>Your lavHost is updating...</b>", parse_mode=enums.ParseMode.HTML)
await message.edit("<b>Your lavHost is updating...</b>")
os.system("lavhost update")
return
await message.edit("<b>Updating...</b>", parse_mode=enums.ParseMode.HTML)
await message.edit("<b>Updating...</b>")
try:
subprocess.run([sys.executable, "-m", "pip", "install", "-U", "pip"])
subprocess.run(["git", "pull"])
@@ -84,10 +84,10 @@ async def update(_, message: Message):
[sys.executable, "-m", "pip", "install", "-U", *requirements_list]
)
except Exception as e:
await message.edit(format_exc(e), parse_mode=enums.ParseMode.HTML)
await message.edit(format_exc(e))
db.remove("core.updater", "restart_info")
else:
await message.edit("<b>Updating: done! Restarting...</b>", parse_mode=enums.ParseMode.HTML)
await message.edit("<b>Updating: done! Restarting...</b>")
restart()

View File

@@ -1,6 +1,6 @@
import os
from pyrogram import Client, enums, filters
from pyrogram import Client, filters
from pyrogram.types import Message
from utils.misc import modules_help, prefix
@@ -15,27 +15,25 @@ async def upl(client: Client, message: Message):
link = message.reply_to_message.text
else:
await message.edit(
f"<b>Usage: </b><code>{prefix}upl [filepath to upload]</code>",
parse_mode=enums.ParseMode.HTML,
f"<b>Usage: </b><code>{prefix}upl [filepath to upload]</code>"
)
return
# Ensure that the link is an absolute path to a file on your local machine
if not os.path.isfile(link):
await message.edit(
f"<b>Error: </b><code>{link}</code> is not a valid file path.",
parse_mode=enums.ParseMode.HTML,
f"<b>Error: </b><code>{link}</code> is not a valid file path."
)
return
try:
await message.edit("<b>Uploading Now...</b>", parse_mode=enums.ParseMode.HTML)
await message.edit("<b>Uploading Now...</b>")
await client.send_document(
message.chat.id, link, parse_mode=enums.ParseMode.HTML
message.chat.id, link
)
await message.delete()
except Exception as e:
await message.edit(format_exc(e), parse_mode=enums.ParseMode.HTML)
await message.edit(format_exc(e))
@Client.on_message(filters.command("uplr", prefix) & filters.me)
@@ -46,27 +44,25 @@ async def uplr(client: Client, message: Message):
link = message.reply_to_message.text
else:
await message.edit(
f"<b>Usage: </b><code>{prefix}upl [filepath to upload]</code>",
parse_mode=enums.ParseMode.HTML,
f"<b>Usage: </b><code>{prefix}upl [filepath to upload]</code>"
)
return
# Ensure that the link is an absolute path to a file on your local machine
if not os.path.isfile(link):
await message.edit(
f"<b>Error: </b><code>{link}</code> is not a valid file path.",
parse_mode=enums.ParseMode.HTML,
f"<b>Error: </b><code>{link}</code> is not a valid file path."
)
return
try:
await message.edit("<b>Uploading Now...</b>", parse_mode=enums.ParseMode.HTML)
await message.edit("<b>Uploading Now...</b>")
await client.send_document(
message.chat.id, link, parse_mode=enums.ParseMode.HTML
message.chat.id, link
)
await message.delete()
except Exception as e:
await message.edit(format_exc(e), parse_mode=enums.ParseMode.HTML)
await message.edit(format_exc(e))
finally:
if os.path.exists(link):
os.remove(link)

View File

@@ -55,15 +55,13 @@ async def short(_, message: Message):
link = message.reply_to_message.text
else:
await message.edit(
f"<b>Usage: </b><code>{prefix}short [url to short]</code>",
parse_mode=enums.ParseMode.HTML,
f"<b>Usage: </b><code>{prefix}short [url to short]</code>"
)
return
r = http.request("GET", "https://clck.ru/--?url=" + link)
await message.edit(
r.data.decode().replace("https://", "<b>Shortened Url:</b>"),
disable_web_page_preview=True,
parse_mode=enums.ParseMode.HTML,
)
@@ -77,8 +75,7 @@ async def urldl(client: Client, message: Message):
link = message.reply_to_message.text
else:
await message.edit(
f"<b>Usage: </b><code>{prefix}urldl [url to download]</code>",
parse_mode=enums.ParseMode.HTML,
f"<b>Usage: </b><code>{prefix}urldl [url to download]</code>"
)
return
@@ -187,20 +184,19 @@ async def upload_cmd(_, message: Message):
)
except ValueError:
await message.edit(
"<b>File to upload not found</b>", parse_mode=enums.ParseMode.HTML
"<b>File to upload not found</b>"
)
return
if os.path.getsize(file_name) > max_size:
await message.edit(
f"<b>Files longer than {max_size_mb}MB isn't supported</b>",
parse_mode=enums.ParseMode.HTML,
f"<b>Files longer than {max_size_mb}MB isn't supported</b>"
)
if os.path.exists(file_name):
os.remove(file_name)
return
await message.edit("<b>Uploading...</b>", parse_mode=enums.ParseMode.HTML)
await message.edit("<b>Uploading...</b>")
with open(file_name, "rb") as f:
response = requests.post(
"https://x0.at",
@@ -216,13 +212,11 @@ async def upload_cmd(_, message: Message):
url = response.text.replace("https://", "")
await message.edit(
f"<b>Your URL: {url}\nYour file will remain live for {file_age} days</b>",
disable_web_page_preview=True,
parse_mode=enums.ParseMode.HTML,
disable_web_page_preview=True
)
else:
await message.edit(
f"<b>API returned an error!\n" f"{response.text}\n Not allowed</b>",
parse_mode=enums.ParseMode.HTML,
f"<b>API returned an error!\n" f"{response.text}\n Not allowed</b>"
)
print(response.text)
if os.path.exists(file_name):
@@ -241,8 +235,7 @@ async def webshot(client: Client, message: Message):
url = "https://" + message.text.split(maxsplit=1)[1]
else:
await message.edit_text(
f"<b>Usage: </b><code>{prefix}webshot/{prefix}ws [url/reply to url]</code>",
parse_mode=enums.ParseMode.HTML,
f"<b>Usage: </b><code>{prefix}webshot/{prefix}ws [url/reply to url]</code>"
)
return

View File

@@ -14,7 +14,7 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
from pyrogram import Client, filters, enums
from pyrogram import Client, filters
from pyrogram.raw import functions
from pyrogram.types import Message
@@ -50,12 +50,12 @@ async def get_user_inf(client: Client, message: Message):
|-Deleted: <code>{user.deleted}</code>
|-BIO: <code>{about}</code>
</b>"""
await message.edit(user_info, parse_mode=enums.ParseMode.HTML)
await message.edit(user_info)
@Client.on_message(filters.command("inffull", prefix) & filters.me)
async def get_full_user_inf(client: Client, message: Message):
await message.edit("<b>Receiving the information...</b>", parse_mode=enums.ParseMode.HTML)
await message.edit("<b>Receiving the information...</b>")
try:
if len(message.command) >= 2:
@@ -73,7 +73,7 @@ async def get_full_user_inf(client: Client, message: Message):
await client.unblock_user("@creationdatebot")
try:
response = await interact_with(
await client.send_message("creationdatebot", f"/id {user.id}", parse_mode=enums.ParseMode.HTML)
await client.send_message("creationdatebot", f"/id {user.id}")
)
except RuntimeError:
creation_date = "None"
@@ -104,9 +104,9 @@ async def get_full_user_inf(client: Client, message: Message):
|-Phone calls available: <code>{full_user.phone_calls_available}</code>
|-Phone calls private: <code>{full_user.phone_calls_private}</code>
|-Blocked: <code>{full_user.blocked}</code></b>"""
await message.edit(user_info, parse_mode=enums.ParseMode.HTML)
await message.edit(user_info)
except Exception as e:
await message.edit(format_exc(e), parse_mode=enums.ParseMode.HTML)
await message.edit(format_exc(e))
modules_help["user_info"] = {
"inf [reply|id|username]": "Get brief information about user",

View File

@@ -1,35 +1,37 @@
import re
from datetime import timedelta, datetime
from datetime import datetime, timedelta
from typing import Dict, Union
from pyrogram import Client, enums
from pyrogram.errors import (
UserAdminInvalid,
ChatAdminRequired,
PeerIdInvalid,
RPCError,
UserAdminInvalid,
UsernameInvalid,
)
from pyrogram.raw import functions, types
from pyrogram.types import (
Message,
ChatPermissions,
ChatPrivileges,
InputMediaPhoto,
InputMediaVideo,
InputMediaAudio,
InputMediaDocument,
InputMediaPhoto,
InputMediaVideo,
Message,
)
from pyrogram.utils import (
get_channel_id,
MAX_USER_ID,
MIN_CHAT_ID,
MAX_CHANNEL_ID,
MAX_USER_ID,
MIN_CHANNEL_ID,
MIN_CHAT_ID,
get_channel_id,
)
from utils.db import db
from utils.scripts import text, format_exc
from utils.misc import prefix
from utils.scripts import format_exc, text
async def check_username_or_id(data: Union[str, int]) -> str:
data = str(data)
@@ -54,6 +56,7 @@ async def check_username_or_id(data: Union[str, int]) -> str:
raise ValueError(f"Peer id invalid: {peer_id}")
async def get_user_and_name(message):
if message.reply_to_message.from_user:
return (
@@ -66,6 +69,7 @@ async def get_user_and_name(message):
message.reply_to_message.sender_chat.title,
)
class BanHandler:
def __init__(self, client: Client, message: Message):
self.client = client
@@ -93,7 +97,11 @@ class BanHandler:
if len(self.cause.split()) > 1:
user_to_ban = await self.get_user_to_ban()
if user_to_ban:
self.name = user_to_ban.first_name if getattr(user_to_ban, "first_name", None) else user_to_ban.title
self.name = (
user_to_ban.first_name
if getattr(user_to_ban, "first_name", None)
else user_to_ban.title
)
await self.ban_user(user_to_ban.id)
async def get_user_to_ban(self):
@@ -144,10 +152,10 @@ class BanHandler:
)
await self.message.edit(
f"<b>{self.name}</b> <code>banned!</code>"
+ f"\n{'<b>Cause:</b> <i>' + text_c.split(maxsplit=1)[1] + '</i>' if len(text_c.split()) > 1 else ''}",
parse_mode=enums.ParseMode.HTML,
+ f"\n{'<b>Cause:</b> <i>' + text_c.split(maxsplit=1)[1] + '</i>' if len(text_c.split()) > 1 else ''}"
)
class UnbanHandler:
def __init__(self, client: Client, message: Message):
self.client = client
@@ -175,7 +183,11 @@ class UnbanHandler:
if len(self.cause.split()) > 1:
user_to_unban = await self.get_user_to_unban()
if user_to_unban:
self.name = user_to_unban.first_name if getattr(user_to_unban, "first_name", None) else user_to_unban.title
self.name = (
user_to_unban.first_name
if getattr(user_to_unban, "first_name", None)
else user_to_unban.title
)
await self.unban_user(user_to_unban.id)
async def get_user_to_unban(self):
@@ -209,10 +221,10 @@ class UnbanHandler:
)
await self.message.edit(
f"<b>{self.name}</b> <code>unbanned!</code>"
+ f"\n{'<b>Cause:</b> <i>' + text_c.split(maxsplit=1)[1] + '</i>' if len(text_c.split()) > 1 else ''}",
parse_mode=enums.ParseMode.HTML,
+ f"\n{'<b>Cause:</b> <i>' + text_c.split(maxsplit=1)[1] + '</i>' if len(text_c.split()) > 1 else ''}"
)
class KickHandler:
def __init__(self, client: Client, message: Message):
self.client = client
@@ -242,7 +254,11 @@ class KickHandler:
if len(self.cause.split()) > 1:
user_to_kick = await self.get_user_to_kick()
if user_to_kick:
self.name = user_to_kick.first_name if getattr(user_to_kick, "first_name", None) else user_to_kick.title
self.name = (
user_to_kick.first_name
if getattr(user_to_kick, "first_name", None)
else user_to_kick.title
)
await self.kick_user(user_to_kick.id)
else:
await self.message.edit("<b>user_id or username</b>")
@@ -304,10 +320,10 @@ class KickHandler:
)
await self.message.edit(
f"<b>{self.name}</b> <code>kicked!</code>"
+ f"\n{'<b>Cause:</b> <i>' + text_c.split(maxsplit=1)[1] + '</i>' if len(text_c.split()) > 1 else ''}",
parse_mode=enums.ParseMode.HTML,
+ f"\n{'<b>Cause:</b> <i>' + text_c.split(maxsplit=1)[1] + '</i>' if len(text_c.split()) > 1 else ''}"
)
class KickDeletedAccountsHandler:
def __init__(self, client: Client, message: Message):
self.client = client
@@ -326,19 +342,17 @@ class KickDeletedAccountsHandler:
return await self.message.edit(format_exc(e))
await self.message.edit(
f"<b>Successfully kicked {self.kicked_count} deleted account(s)</b>",
parse_mode=enums.ParseMode.HTML
)
async def kick_member(self, user_id):
try:
await self.client.ban_chat_member(
self.chat_id,
user_id,
datetime.now() + timedelta(seconds=31)
self.chat_id, user_id, datetime.now() + timedelta(seconds=31)
)
except Exception as e:
await self.message.edit(f"Failed to kick user {user_id}: {format_exc(e)}")
class TimeMuteHandler:
def __init__(self, client: Client, message: Message):
self.client = client
@@ -366,7 +380,6 @@ class TimeMuteHandler:
await self.message.edit(
f"<b>{name}</b> <code>in tmute</code>"
+ f"\n{'<b>Cause:</b> <i>' + self.cause.split(maxsplit=1)[1] + '</i>' if len(self.cause.split()) > 1 else ''}",
parse_mode=enums.ParseMode.HTML
)
async def handle_non_reply_tmute(self):
@@ -374,19 +387,21 @@ class TimeMuteHandler:
if len(self.cause.split()) > 1:
user_to_tmute = await self.get_user_to_tmute()
if user_to_tmute:
name = user_to_tmute.first_name if getattr(user_to_tmute, "first_name", None) else user_to_tmute.title
name = (
user_to_tmute.first_name
if getattr(user_to_tmute, "first_name", None)
else user_to_tmute.title
)
if user_to_tmute.id not in self.tmuted_users:
self.tmuted_users.append(user_to_tmute.id)
db.set("core.ats", f"c{self.chat_id}", self.tmuted_users)
await self.message.edit(
f"<b>{name}</b> <code>in tmute</code>"
+ f"\n{'<b>Cause:</b> <i>' + self.cause.split(maxsplit=2)[2] + '</i>' if len(self.cause.split()) > 2 else ''}",
parse_mode=enums.ParseMode.HTML
)
else:
await self.message.edit(
f"<b>{name}</b> <code>already in tmute</code>",
parse_mode=enums.ParseMode.HTML
)
else:
await self.message.edit("<b>user_id or username</b>")
@@ -401,6 +416,7 @@ class TimeMuteHandler:
await self.message.edit("<b>Invalid user type</b>")
return None
class TimeUnmuteHandler:
def __init__(self, client: Client, message: Message):
self.client = client
@@ -428,7 +444,6 @@ class TimeUnmuteHandler:
await self.message.edit(
f"<b>{name}</b> <code>tunmuted</code>"
+ f"\n{'<b>Cause:</b> <i>' + self.cause.split(maxsplit=1)[1] + '</i>' if len(self.cause.split()) > 1 else ''}",
parse_mode=enums.ParseMode.HTML
)
async def handle_non_reply_tunmute(self):
@@ -436,11 +451,14 @@ class TimeUnmuteHandler:
if len(self.cause.split()) > 1:
user_to_tunmute = await self.get_user_to_tunmute()
if user_to_tunmute:
name = user_to_tunmute.first_name if getattr(user_to_tunmute, "first_name", None) else user_to_tunmute.title
name = (
user_to_tunmute.first_name
if getattr(user_to_tunmute, "first_name", None)
else user_to_tunmute.title
)
if user_to_tunmute.id not in self.tmuted_users:
await self.message.edit(
f"<b>{name}</b> <code>not in tmute</code>",
parse_mode=enums.ParseMode.HTML
)
else:
self.tmuted_users.remove(user_to_tunmute.id)
@@ -448,7 +466,6 @@ class TimeUnmuteHandler:
await self.message.edit(
f"<b>{name}</b> <code>tunmuted</code>"
+ f"\n{'<b>Cause:</b> <i>' + self.cause.split(maxsplit=2)[2] + '</i>' if len(self.cause.split()) > 2 else ''}",
parse_mode=enums.ParseMode.HTML
)
else:
await self.message.edit("<b>user_id or username</b>")
@@ -463,6 +480,7 @@ class TimeUnmuteHandler:
await self.message.edit("<b>Invalid user type</b>")
return None
class TimeMuteUsersHandler:
def __init__(self, client: Client, message: Message):
self.client = client
@@ -486,7 +504,7 @@ class TimeMuteUsersHandler:
await self.message.edit("<b>No users in tmute</b>")
else:
text += f"\n<b>Total users in tmute</b> {count}"
await self.message.edit(text, parse_mode=enums.ParseMode.HTML)
await self.message.edit(text)
else:
await self.message.edit("<b>Unsupported</b>")
@@ -511,6 +529,7 @@ class TimeMuteUsersHandler:
except PeerIdInvalid:
return None
class UnmuteHandler:
def __init__(self, client: Client, message: Message):
self.client = client
@@ -589,6 +608,7 @@ class UnmuteHandler:
except Exception as e:
await self.message.edit(format_exc(e))
class MuteHandler:
def __init__(self, client: Client, message: Message):
self.client = client
@@ -611,7 +631,9 @@ class MuteHandler:
mute_seconds = self.calculate_mute_seconds()
try:
await self.mute_user(user_for_mute.id, mute_seconds)
await self.message.edit(self.construct_mute_message(user_for_mute, mute_seconds))
await self.message.edit(
self.construct_mute_message(user_for_mute, mute_seconds)
)
except UserAdminInvalid:
await self.message.edit("<b>No rights</b>")
except ChatAdminRequired:
@@ -629,7 +651,9 @@ class MuteHandler:
mute_seconds = self.calculate_mute_seconds()
try:
await self.mute_user(user_to_mute.id, mute_seconds)
await self.message.edit(self.construct_mute_message(user_to_mute, mute_seconds))
await self.message.edit(
self.construct_mute_message(user_to_mute, mute_seconds)
)
except UserAdminInvalid:
await self.message.edit("<b>No rights</b>")
except ChatAdminRequired:
@@ -702,6 +726,7 @@ class MuteHandler:
message_text = message_text.replace(" ", " ")
return message_text
class DemoteHandler:
def __init__(self, client: Client, message: Message):
self.client = client
@@ -736,7 +761,9 @@ class DemoteHandler:
if user_for_demote:
try:
await self.demote_user(user_for_demote.id)
await self.message.edit(self.construct_demote_message(user_for_demote))
await self.message.edit(
self.construct_demote_message(user_for_demote)
)
except UserAdminInvalid:
await self.message.edit("<b>No rights</b>")
except ChatAdminRequired:
@@ -753,7 +780,9 @@ class DemoteHandler:
if user_to_demote:
try:
await self.demote_user(user_to_demote.id)
await self.message.edit(self.construct_demote_message(user_to_demote))
await self.message.edit(
self.construct_demote_message(user_to_demote)
)
except UserAdminInvalid:
await self.message.edit("<b>No rights</b>")
except ChatAdminRequired:
@@ -791,6 +820,7 @@ class DemoteHandler:
+ f"\n{'<b>Cause:</b> <i>' + self.cause.split(' ', maxsplit=2)[2] + '</i>' if len(self.cause.split()) > 2 else ''}"
)
class PromoteHandler:
def __init__(self, client: Client, message: Message):
self.client = client
@@ -818,7 +848,9 @@ class PromoteHandler:
if user_for_promote:
try:
await self.promote_user(user_for_promote.id)
await self.message.edit(self.construct_promote_message(user_for_promote))
await self.message.edit(
self.construct_promote_message(user_for_promote)
)
except UserAdminInvalid:
await self.message.edit("<b>No rights</b>")
except ChatAdminRequired:
@@ -835,7 +867,9 @@ class PromoteHandler:
if user_to_promote:
try:
await self.promote_user(user_to_promote.id)
await self.message.edit(self.construct_promote_message(user_to_promote))
await self.message.edit(
self.construct_promote_message(user_to_promote)
)
except UserAdminInvalid:
await self.message.edit("<b>No rights</b>")
except ChatAdminRequired:
@@ -880,6 +914,7 @@ class PromoteHandler:
+ f"\n{'<b>Prefix:</b> <i>' + self.cause.split(' ', maxsplit=1)[1] + '</i>' if len(self.cause.split()) > 1 else ''}"
)
class AntiChannelsHandler:
def __init__(self, client: Client, message: Message):
self.client = client
@@ -900,7 +935,9 @@ class AntiChannelsHandler:
elif command[1] in ["disable", "off", "0", "no", "false"]:
await self.disable_anti_channels()
else:
await self.message.edit(f"<b>Usage: {self.prefix}antich [enable|disable]</b>")
await self.message.edit(
f"<b>Usage: {self.prefix}antich [enable|disable]</b>"
)
async def toggle_anti_channels_status(self):
current_status = db.get("core.ats", f"antich{self.chat_id}", False)
@@ -924,6 +961,7 @@ class AntiChannelsHandler:
db.set("core.ats", f"antich{self.chat_id}", False)
await self.message.edit("<b>Blocking channels in this chat disabled.</b>")
class DeleteHistoryHandler:
def __init__(self, client: Client, message: Message):
self.client = client
@@ -960,7 +998,11 @@ class DeleteHistoryHandler:
try:
user_to_delete = await self.get_user_to_delete()
if user_to_delete:
name = user_to_delete.first_name if getattr(user_to_delete, "first_name", None) else user_to_delete.title
name = (
user_to_delete.first_name
if getattr(user_to_delete, "first_name", None)
else user_to_delete.title
)
await self.delete_user_history(user_to_delete.id, name)
else:
await self.message.edit("<b>User is not found</b>")
@@ -1003,6 +1045,7 @@ class DeleteHistoryHandler:
except Exception as e:
await self.message.edit(format_exc(e))
class AntiRaidHandler:
def __init__(self, client: Client, message: Message):
self.client = client
@@ -1053,6 +1096,7 @@ class AntiRaidHandler:
else:
await self.message.edit("<b>Anti-raid mode disabled</b>")
class NoteSendHandler:
def __init__(self, client: Client, message: Message):
self.client = client
@@ -1062,26 +1106,24 @@ class NoteSendHandler:
async def handle_note_send(self):
if len(self.message.text.split()) >= 2:
await self.message.edit("<b>Loading...</b>", parse_mode=enums.ParseMode.HTML)
await self.message.edit("<b>Loading...</b>")
note_name = self.message.text.split(maxsplit=1)[1]
find_note = db.get("core.notes", f"note{note_name}", False)
if find_note:
try:
await self.send_note(find_note)
except errors.RPCError:
except RPCError:
await self.message.edit(
"<b>Sorry, but this note is unavailable.\n\n"
f"You can delete this note with "
f"<code>{self.prefix}clear {note_name}</code></b>",
parse_mode=enums.ParseMode.HTML
f"<code>{self.prefix}clear {note_name}</code></b>"
)
else:
await self.message.edit("<b>There is no such note</b>", parse_mode=enums.ParseMode.HTML)
await self.message.edit("<b>There is no such note</b>")
else:
await self.message.edit(
f"<b>Example: <code>{self.prefix}note note_name</code></b>",
parse_mode=enums.ParseMode.HTML
)
async def send_note(self, find_note):
@@ -1102,12 +1144,9 @@ class NoteSendHandler:
self.message.chat.id,
media_grouped_list,
reply_to_message_id=self.message.reply_to_message.id,
parse_mode=enums.ParseMode.HTML,
)
else:
await self.client.send_media_group(
self.message.chat.id, media_grouped_list
)
await self.client.send_media_group(self.message.chat.id, media_grouped_list)
async def copy_message(self, find_note):
if self.message.reply_to_message:
@@ -1154,7 +1193,9 @@ class NoteSendHandler:
else:
return InputMediaVideo(message.video.file_id, message.caption.markdown)
elif message.video.thumbs:
return InputMediaVideo(message.video.file_id, message.video.thumbs[0].file_id)
return InputMediaVideo(
message.video.file_id, message.video.thumbs[0].file_id
)
else:
return InputMediaVideo(message.video.file_id)
@@ -1173,8 +1214,12 @@ class NoteSendHandler:
message.caption.markdown,
)
else:
return InputMediaDocument(message.document.file_id, message.caption.markdown)
return InputMediaDocument(
message.document.file_id, message.caption.markdown
)
elif message.document.thumbs:
return InputMediaDocument(message.document.file_id, message.document.thumbs[0].file_id)
return InputMediaDocument(
message.document.file_id, message.document.thumbs[0].file_id
)
else:
return InputMediaDocument(message.document.file_id)

View File

@@ -14,24 +14,23 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import logging
import asyncio
import importlib
import math
import time
import os
import re
import sys
import asyncio
import traceback
import importlib
import shlex
import subprocess
import sys
import time
import traceback
from io import BytesIO
from types import ModuleType
from typing import Dict, Tuple
import shlex
from PIL import Image
from pyrogram import Client, errors, types
from pyrogram.errors import FloodWait, MessageNotModified
from pyrogram import Client, errors, types, enums
from pyrogram.types import Message
from .misc import modules_help, prefix, requirements_list
@@ -39,6 +38,7 @@ from .misc import modules_help, prefix, requirements_list
META_COMMENTS = re.compile(r"^ *# *meta +(\S+) *: *(.*?)\s*$", re.MULTILINE)
interact_with_to_delete = []
def time_formatter(milliseconds: int) -> str:
"""Time Formatter"""
seconds, milliseconds = divmod(int(milliseconds), 1000)
@@ -54,11 +54,12 @@ def time_formatter(milliseconds: int) -> str:
)
return tmp[:-2]
def humanbytes(size):
"""Convert Bytes To Bytes So That Human Can Read It"""
if not size:
return ""
power = 2 ** 10
power = 2**10
raised_to_pow = 0
dict_power_n = {0: "", 1: "Ki", 2: "Mi", 3: "Gi", 4: "Ti"}
while size > power:
@@ -66,20 +67,20 @@ def humanbytes(size):
raised_to_pow += 1
return str(round(size, 2)) + " " + dict_power_n[raised_to_pow] + "B"
async def edit_or_send_as_file(
text: str,
message: Message,
client: Client,
caption: str = "`Result!`",
caption: str = "<code>Result!</code>",
file_name: str = "result",
parse_mode=enums.ParseMode.MARKDOWN,
):
"""Send As File If Len Of Text Exceeds Tg Limit Else Edit Message"""
if not text:
await message.edit("`Wait, What?`", parse_mode=enums.ParseMode.MARKDOWN)
await message.edit("<code>Wait, What?</code>")
return
if len(text) > 1024:
await message.edit("`OutPut is Too Large, Sending As File!`", parse_mode=enums.ParseMode.MARKDOWN)
await message.edit("<code>OutPut is Too Large, Sending As File!</code>")
file_names = f"{file_name}.text"
open(file_names, "w").write(text)
await client.send_document(message.chat.id, file_names, caption=caption)
@@ -88,7 +89,8 @@ async def edit_or_send_as_file(
os.remove(file_names)
return
else:
return await message.edit(text, parse_mode=parse_mode)
return await message.edit(text)
def get_text(message: Message) -> [None, str]:
"""Extract Text From Commands"""
@@ -103,6 +105,7 @@ def get_text(message: Message) -> [None, str]:
else:
return None
async def progress(current, total, message, start, type_of_ps, file_name=None):
"""Progress Bar For Showing Progress While Uploading / Downloading File - Normal"""
now = time.time()
@@ -126,7 +129,7 @@ async def progress(current, total, message, start, type_of_ps, file_name=None):
if file_name:
try:
await message.edit(
"{}\n**File Name:** `{}`\n{}".format(type_of_ps, file_name, tmp, parse_mode=enums.ParseMode.MARKDOWN)
"{}\n<b>File Name:</b> <code>{}</code>\n{}".format(type_of_ps, file_name, tmp)
)
except FloodWait as e:
await asyncio.sleep(e.x)
@@ -134,12 +137,13 @@ async def progress(current, total, message, start, type_of_ps, file_name=None):
pass
else:
try:
await message.edit("{}\n{}".format(type_of_ps, tmp), parse_mode=enums.ParseMode.MARKDOWN)
await message.edit("{}\n{}".format(type_of_ps, tmp))
except FloodWait as e:
await asyncio.sleep(e.x)
except MessageNotModified:
pass
async def run_cmd(prefix: str) -> Tuple[str, str, int, int]:
"""Run Commands"""
args = shlex.split(prefix)
@@ -154,6 +158,7 @@ async def run_cmd(prefix: str) -> Tuple[str, str, int, int]:
process.pid,
)
def mediainfo(media):
xx = str((str(media)).split("(", maxsplit=1)[0])
m = ""
@@ -188,13 +193,15 @@ def mediainfo(media):
m = "web"
return m
async def edit_or_reply(message, text, parse_mode=enums.ParseMode.MARKDOWN):
async def edit_or_reply(message, text):
"""Edit Message If Its From Self, Else Reply To Message"""
if not message:
return await message.edit(text, parse_mode=parse_mode)
return await message.edit(text)
if not message.from_user:
return await message.edit(text, parse_mode=parse_mode)
return await message.edit(text, parse_mode=parse_mode)
return await message.edit(text)
return await message.edit(text)
def text(message: types.Message) -> str:
"""Find text in `types.Message` object"""
@@ -213,16 +220,13 @@ def format_exc(e: Exception, suffix="") -> str:
f"<b>Telegram API error!</b>\n"
f"<code>[{e.CODE} {e.ID or e.NAME}] — {e.MESSAGE.format(value=e.value)}</code>\n\n<b>{suffix}</b>"
)
return (
f"<b>Error!</b>\n"
f"<code>{err}</code>"
)
return f"<b>Error!</b>\n" f"<code>{err}</code>"
def with_reply(func):
async def wrapped(client: Client, message: types.Message):
if not message.reply_to_message:
await message.edit("<b>Reply to message is required</b>", parse_mode=enums.ParseMode.HTML)
await message.edit("<b>Reply to message is required</b>")
else:
return await func(client, message)
@@ -243,10 +247,7 @@ async def interact_with(message: types.Message) -> types.Message:
await asyncio.sleep(1)
# noinspection PyProtectedMember
response = [
msg
async for msg in message._client.get_chat_history(
message.chat.id, limit=1
)
msg async for msg in message._client.get_chat_history(message.chat.id, limit=1)
]
seconds_waiting = 0
@@ -259,9 +260,7 @@ async def interact_with(message: types.Message) -> types.Message:
# noinspection PyProtectedMember
response = [
msg
async for msg in message._client.get_chat_history(
message.chat.id, limit=1
)
async for msg in message._client.get_chat_history(message.chat.id, limit=1)
]
interact_with_to_delete.append(message.id)
@@ -274,9 +273,7 @@ def format_module_help(module_name: str, full=True):
commands = modules_help[module_name]
help_text = (
f"<b>Help for |{module_name}|\n\nUsage:</b>\n"
if full
else "<b>Usage:</b>\n"
f"<b>Help for |{module_name}|\n\nUsage:</b>\n" if full else "<b>Usage:</b>\n"
)
for command, desc in commands.items():
@@ -295,13 +292,11 @@ def format_small_module_help(module_name: str, full=True):
if full
else "<b>Commands list:\n"
)
for command, desc in commands.items():
for command, _desc in commands.items():
cmd = command.split(maxsplit=1)
args = " <code>" + cmd[1] + "</code>" if len(cmd) > 1 else ""
help_text += f"<code>{prefix}{cmd[0]}</code>{args}\n"
help_text += (
f"\nGet full usage: <code>{prefix}help {module_name}</code></b>"
)
help_text += f"\nGet full usage: <code>{prefix}help {module_name}</code></b>"
return help_text
@@ -319,15 +314,14 @@ def import_library(library_name: str, package_name: str = None):
try:
return importlib.import_module(library_name)
except ImportError:
except ImportError as exc:
completed = subprocess.run(
[sys.executable, "-m", "pip", "install", package_name]
)
if completed.returncode != 0:
raise AssertionError(
f"Failed to install library {package_name} (pip exited with code {completed.returncode})",
parse_mode=enums.ParseMode.HTML
)
f"Failed to install library {package_name} (pip exited with code {completed.returncode})"
) from exc
return importlib.import_module(library_name)
@@ -384,10 +378,7 @@ async def load_module(
raise
if message:
await message.edit(
f"<b>Installing requirements: {' '.join(packages)}</b>",
parse_mode=enums.ParseMode.HTML
)
await message.edit(f"<b>Installing requirements: {' '.join(packages)}</b>")
proc = await asyncio.create_subprocess_exec(
sys.executable,
@@ -401,10 +392,7 @@ async def load_module(
await asyncio.wait_for(proc.wait(), timeout=120)
except asyncio.TimeoutError:
if message:
await message.edit(
"<b>Timeout while installed requirements. Try to install them manually</b>",
parse_mode=enums.ParseMode.HTML
)
await message.edit("<b>Timeout while installed requirements. Try to install them manually</b>")
raise TimeoutError("timeout while installing requirements") from e
if proc.returncode != 0:
@@ -412,14 +400,13 @@ async def load_module(
await message.edit(
f"<b>Failed to install requirements (pip exited with code {proc.returncode}). "
f"Check logs for futher info</b>",
parse_mode=enums.ParseMode.HTML
)
raise RuntimeError("failed to install requirements") from e
module = importlib.import_module(path)
for name, obj in vars(module).items():
if type(getattr(obj, "handlers", [])) == list:
for _name, obj in vars(module).items():
if isinstance(getattr(obj, "handlers", []), list):
for handler, group in getattr(obj, "handlers", []):
client.add_handler(handler, group)
@@ -435,7 +422,7 @@ async def unload_module(module_name: str, client: Client) -> bool:
module = importlib.import_module(path)
for name, obj in vars(module).items():
for _name, obj in vars(module).items():
for handler, group in getattr(obj, "handlers", []):
client.remove_handler(handler, group)
@@ -452,3 +439,14 @@ def parse_meta_comments(code: str) -> Dict[str, str]:
return {}
return {groups[i]: groups[i + 1] for i in range(0, len(groups), 2)}
def ReplyCheck(message: Message):
reply_id = None
if message.reply_to_message:
reply_id = message.reply_to_message.id
elif not message.from_user.is_self:
reply_id = message.id
return reply_id