PagerMaid-Pyro/pagermaid/listener.py

304 lines
13 KiB
Python
Raw Normal View History

2022-06-20 13:55:14 +00:00
import contextlib
2022-05-23 12:40:30 +00:00
import sys
import secrets
from asyncio import sleep
from time import strftime, gmtime, time
from traceback import format_exc
from pyrogram import ContinuePropagation, StopPropagation, filters, Client
from pyrogram.errors.exceptions.bad_request_400 import (
MessageIdInvalid,
MessageNotModified,
MessageEmpty,
UserNotParticipant
)
from pyrogram.handlers import MessageHandler, EditedMessageHandler
from pagermaid import help_messages, logs, Config, bot, read_context, all_permissions
from pagermaid.group_manager import Permission
from pagermaid.inject import inject
2022-06-30 06:49:03 +00:00
from pagermaid.single_utils import Message, AlreadyInConversationError, TimeoutConversationError, ListenerCanceled
2022-06-07 12:44:45 +00:00
from pagermaid.utils import lang, attach_report, sudo_filter, alias_command, get_permission_name, process_exit
2022-06-20 13:55:14 +00:00
from pagermaid.utils import client as httpx_client
2022-06-27 13:42:24 +00:00
from pagermaid.hook import Hook
2022-05-23 12:40:30 +00:00
secret_generator = secrets.SystemRandom()
def noop(*args, **kw):
pass
def listener(**args):
""" Register an event listener. """
2022-06-07 12:44:45 +00:00
command = args.get("command")
disallow_alias = args.get("disallow_alias", False)
need_admin = args.get("need_admin", False)
description = args.get("description")
parameters = args.get("parameters")
pattern = sudo_pattern = args.get("pattern")
diagnostics = args.get("diagnostics", True)
ignore_edited = args.get("ignore_edited", False)
is_plugin = args.get("is_plugin", True)
incoming = args.get("incoming", False)
outgoing = args.get("outgoing", True)
2022-05-23 12:40:30 +00:00
groups_only = args.get("groups_only", False)
privates_only = args.get("privates_only", False)
2022-07-04 09:53:43 +00:00
priority = args.get("priority", 50)
block_process = args.get("block_process", False)
if priority < 0 or priority > 100:
raise ValueError("Priority must be between 0 and 100.")
elif priority == 0 and is_plugin:
""" Priority 0 is reserved for modules. """
priority = 1
elif (not is_plugin) and need_admin:
priority = 0
2022-05-23 12:40:30 +00:00
if command is not None:
if command in help_messages:
2022-07-04 09:53:43 +00:00
if help_messages[alias_command(command)]["priority"] <= priority:
raise ValueError(f"{lang('error_prefix')} {lang('command')} \"{command}\" {lang('has_reg')}")
else:
block_process = True
pattern = fr"^(,|){alias_command(command, disallow_alias)}(?: |$)([\s\S]*)"
2022-07-05 15:13:39 +00:00
sudo_pattern = fr"^(/){alias_command(command, disallow_alias)}(?: |$)([\s\S]*)"
2022-06-07 12:44:45 +00:00
if pattern is not None and not pattern.startswith("(?i)"):
args["pattern"] = f"(?i){pattern}"
2022-05-23 12:40:30 +00:00
else:
2022-06-07 12:44:45 +00:00
args["pattern"] = pattern
if sudo_pattern is not None and not sudo_pattern.startswith("(?i)"):
2022-05-23 12:40:30 +00:00
sudo_pattern = f"(?i){sudo_pattern}"
if outgoing and not incoming:
base_filters = filters.me & ~filters.via_bot & ~filters.forwarded
elif incoming and not outgoing:
2022-06-07 14:33:33 +00:00
base_filters = filters.incoming & ~filters.me
2022-05-23 12:40:30 +00:00
else:
base_filters = filters.all
permission_name = get_permission_name(is_plugin, need_admin, command)
sudo_filters = (
sudo_filter(permission_name)
& ~filters.via_bot
& ~filters.forwarded
)
2022-06-07 12:44:45 +00:00
if args["pattern"]:
base_filters &= filters.regex(args["pattern"])
2022-05-23 12:40:30 +00:00
sudo_filters &= filters.regex(sudo_pattern)
if groups_only:
base_filters &= filters.group
sudo_filters &= filters.group
if privates_only:
base_filters &= filters.private
sudo_filters &= filters.private
2022-06-07 12:44:45 +00:00
if "ignore_edited" in args:
del args["ignore_edited"]
if "command" in args:
del args["command"]
if "diagnostics" in args:
del args["diagnostics"]
if "description" in args:
del args["description"]
if "parameters" in args:
del args["parameters"]
if "is_plugin" in args:
del args["is_plugin"]
if "owners_only" in args:
del args["owners_only"]
if "admins_only" in args:
del args["admins_only"]
if "groups_only" in args:
del args["groups_only"]
if "need_admin" in args:
del args["need_admin"]
2022-07-04 09:53:43 +00:00
if "priority" in args:
del args["priority"]
if "block_process" in args:
del args["block_process"]
2022-05-23 12:40:30 +00:00
def decorator(function):
async def handler(client: Client, message: Message):
2022-06-20 13:55:14 +00:00
message.bot = client
message.request = httpx_client
2022-05-23 12:40:30 +00:00
try:
try:
2022-07-05 15:13:39 +00:00
parameter = message.matches[0].group(2).split(" ")
2022-06-07 12:44:45 +00:00
if parameter == [""]:
2022-05-23 12:40:30 +00:00
parameter = []
message.parameter = parameter
2022-07-05 15:13:39 +00:00
message.arguments = message.matches[0].group(2)
2022-05-23 12:40:30 +00:00
except BaseException:
message.parameter = None
message.arguments = None
# solve same process
if not message.outgoing:
await sleep(secret_generator.randint(1, 100) / 1000)
if (message.chat.id, message.id) in read_context:
raise ContinuePropagation
read_context[(message.chat.id, message.id)] = True
if command:
await Hook.command_pre(message)
if data := inject(message, function):
await function(**data)
else:
if function.__code__.co_argcount == 0:
await function()
if function.__code__.co_argcount == 1:
await function(message)
elif function.__code__.co_argcount == 2:
await function(client, message)
if command:
await Hook.command_post(message)
2022-06-20 13:55:14 +00:00
except StopPropagation as e:
raise StopPropagation from e
except KeyboardInterrupt as e:
raise KeyboardInterrupt from e
2022-05-23 12:40:30 +00:00
except MessageNotModified:
pass
except MessageIdInvalid:
logs.warning(
"Please Don't Delete Commands While it's Processing.."
)
2022-06-26 12:59:36 +00:00
except AlreadyInConversationError:
logs.warning(
"Please Don't Send Commands In The Same Conversation.."
)
2022-06-27 13:42:24 +00:00
with contextlib.suppress(BaseException):
await message.edit(lang("conversation_already_in_error"))
2022-06-26 12:59:36 +00:00
except TimeoutConversationError:
logs.warning(
"Conversation Timed out while processing commands.."
)
2022-06-27 13:42:24 +00:00
with contextlib.suppress(BaseException):
await message.edit(lang("conversation_timed_out_error"))
2022-06-30 06:49:03 +00:00
except ListenerCanceled:
logs.warning(
"Listener Canceled While Processing Commands.."
)
with contextlib.suppress(BaseException):
await message.edit(lang("reload_des"))
2022-05-23 12:40:30 +00:00
except UserNotParticipant:
pass
2022-06-20 13:55:14 +00:00
except ContinuePropagation as e:
2022-07-04 09:53:43 +00:00
if block_process:
raise StopPropagation from e
2022-06-20 13:55:14 +00:00
raise ContinuePropagation from e
2022-05-23 12:40:30 +00:00
except SystemExit:
2022-06-07 12:44:45 +00:00
await process_exit(start=False, _client=client, message=message)
2022-06-27 13:42:24 +00:00
await Hook.shutdown()
2022-05-25 04:19:25 +00:00
sys.exit(0)
2022-05-23 12:40:30 +00:00
except BaseException:
exc_info = sys.exc_info()[1]
exc_format = format_exc()
2022-06-20 13:55:14 +00:00
with contextlib.suppress(BaseException):
2022-06-07 12:44:45 +00:00
await message.edit(lang("run_error"), no_reply=True) # noqa
2022-05-23 12:40:30 +00:00
if not diagnostics:
return
2022-07-08 14:26:36 +00:00
await Hook.process_error_exec(message, exc_info, exc_format)
2022-05-23 12:40:30 +00:00
if Config.ERROR_REPORT:
2022-06-20 13:55:14 +00:00
report = f"""# Generated: {strftime('%H:%M %d/%m/%Y', gmtime())}. \n# ChatID: {message.chat.id}. \n# UserID: {message.from_user.id if message.from_user else message.sender_chat.id}. \n# Message: \n-----BEGIN TARGET MESSAGE-----\n{message.text or message.caption}\n-----END TARGET MESSAGE-----\n# Traceback: \n-----BEGIN TRACEBACK-----\n{str(exc_format)}\n-----END TRACEBACK-----\n# Error: "{str(exc_info)}". \n"""
2022-05-23 12:40:30 +00:00
await attach_report(report, f"exception.{time()}.pagermaid", None,
"Error report generated.")
if (message.chat.id, message.id) in read_context:
del read_context[(message.chat.id, message.id)]
2022-07-04 09:53:43 +00:00
if block_process:
message.stop_propagation()
2022-05-23 12:40:30 +00:00
message.continue_propagation()
2022-07-04 09:53:43 +00:00
bot.add_handler(MessageHandler(handler, filters=base_filters), group=0 + priority)
bot.add_handler(MessageHandler(handler, filters=sudo_filters), group=50 + priority)
2022-05-23 12:40:30 +00:00
if not ignore_edited:
2022-07-04 09:53:43 +00:00
bot.add_handler(EditedMessageHandler(handler, filters=base_filters), group=1 + priority)
bot.add_handler(EditedMessageHandler(handler, filters=sudo_filters), group=51 + priority)
2022-05-23 12:40:30 +00:00
return handler
if description is not None and command is not None:
if parameters is None:
parameters = ""
help_messages.update({
2022-06-22 03:50:39 +00:00
f"{alias_command(command)}": {"permission": permission_name,
"use": f"**{lang('use_method')}:** `,{command} {parameters}`\n"
f"**{lang('need_permission')}:** `{permission_name}`\n"
2022-07-04 09:53:43 +00:00
f"{description}",
"priority": priority, }
2022-05-23 12:40:30 +00:00
})
all_permissions.append(Permission(permission_name))
return decorator
def raw_listener(filter_s):
"""Simple Decorator To Handel Custom Filters"""
def decorator(function):
async def handler(client, message):
2022-06-20 13:55:14 +00:00
message.bot = client
message.request = httpx_client
2022-05-23 12:40:30 +00:00
try:
2022-06-20 13:55:14 +00:00
if function.__code__.co_argcount == 1:
await function(message)
elif function.__code__.co_argcount == 2:
await function(client, message)
except StopPropagation as e:
raise StopPropagation from e
except ContinuePropagation as e:
raise ContinuePropagation from e
2022-06-26 12:59:36 +00:00
except MessageIdInvalid:
logs.warning(
"Please Don't Delete Commands While it's Processing.."
)
except AlreadyInConversationError:
logs.warning(
"Please Don't Send Commands In The Same Conversation.."
)
2022-06-27 13:42:24 +00:00
with contextlib.suppress(BaseException):
await message.edit(lang("conversation_already_in_error"))
2022-06-26 12:59:36 +00:00
except TimeoutConversationError:
logs.warning(
"Conversation Timed out while processing commands.."
)
2022-06-27 13:42:24 +00:00
with contextlib.suppress(BaseException):
await message.edit(lang("conversation_timed_out_error"))
2022-06-30 06:49:03 +00:00
except ListenerCanceled:
logs.warning(
"Listener Canceled While Processing Commands.."
)
with contextlib.suppress(BaseException):
await message.edit(lang("reload_des"))
2022-05-23 12:40:30 +00:00
except SystemExit:
2022-06-07 12:44:45 +00:00
await process_exit(start=False, _client=client, message=message)
2022-06-27 13:42:24 +00:00
await Hook.shutdown()
2022-05-25 04:19:25 +00:00
sys.exit(0)
2022-05-23 12:40:30 +00:00
except UserNotParticipant:
pass
except MessageEmpty:
pass
except BaseException:
exc_info = sys.exc_info()[1]
exc_format = format_exc()
2022-06-20 13:55:14 +00:00
with contextlib.suppress(BaseException):
2022-05-23 12:40:30 +00:00
await message.edit(lang('run_error'), no_reply=True)
if Config.ERROR_REPORT:
report = f"# Generated: {strftime('%H:%M %d/%m/%Y', gmtime())}. \n" \
f"# ChatID: {message.chat.id}. \n" \
f"# UserID: {message.from_user.id if message.from_user else message.sender_chat.id}. \n" \
f"# Message: \n-----BEGIN TARGET MESSAGE-----\n" \
f"{message.text}\n-----END TARGET MESSAGE-----\n" \
f"# Traceback: \n-----BEGIN TRACEBACK-----\n" \
f"{str(exc_format)}\n-----END TRACEBACK-----\n" \
f"# Error: \"{str(exc_info)}\". \n"
await attach_report(report, f"exception.{time()}.pagermaid", None,
"Error report generated.")
message.continue_propagation()
bot.add_handler(MessageHandler(handler, filters=filter_s), group=2)
return handler
return decorator