PagerMaid-Pyro/pagermaid/listener.py

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

395 lines
16 KiB
Python
Raw Permalink Normal View History

2023-01-14 05:49:08 +00:00
import asyncio
2022-06-20 13:55:14 +00:00
import contextlib
2022-05-23 12:40:30 +00:00
import sys
from time import strftime, gmtime, time
from traceback import format_exc
from pyrogram import ContinuePropagation, StopPropagation, filters, Client
2022-08-01 16:04:45 +00:00
from pyrogram.errors import Flood, Forbidden
2022-05-23 12:40:30 +00:00
from pyrogram.errors.exceptions.bad_request_400 import (
MessageIdInvalid,
MessageNotModified,
MessageEmpty,
2023-03-12 03:56:01 +00:00
UserNotParticipant,
PeerIdInvalid,
2022-05-23 12:40:30 +00:00
)
from pyrogram.handlers import MessageHandler, EditedMessageHandler
2023-01-31 16:24:56 +00:00
from pagermaid.common.ignore import ignore_groups_manager
from pagermaid.config import Config
from pagermaid.enums import Message
from pagermaid.enums.command import CommandHandler, CommandHandlerDecorator
2022-05-23 12:40:30 +00:00
from pagermaid.group_manager import Permission
from pagermaid.hook import Hook
from pagermaid.services import bot
from pagermaid.static import help_messages, read_context, all_permissions
2023-03-12 03:56:01 +00:00
from pagermaid.utils import (
lang,
alias_command,
logs,
)
from pagermaid.utils.bot_utils import attach_report
from pagermaid.utils.listener import (
sudo_filter,
2023-03-12 03:56:01 +00:00
get_permission_name,
process_exit,
2024-02-05 13:16:25 +00:00
format_exc as format_exc_text,
2023-03-12 03:56:01 +00:00
)
from pagermaid.web import web
from pyromod.utils import mod_filters
from pyromod.utils.errors import (
AlreadyInConversationError,
ListenerCanceled,
TimeoutConversationError,
)
2022-05-23 12:40:30 +00:00
2023-01-14 05:49:08 +00:00
_lock = asyncio.Lock()
2022-05-23 12:40:30 +00:00
def listener(**args) -> CommandHandlerDecorator:
2023-03-12 03:56:01 +00:00
"""Register an event listener."""
parent_command = args.get("__parent_command")
2022-06-07 12:44:45 +00:00
command = args.get("command")
allow_parent = args.get("allow_parent", False)
2022-06-07 12:44:45 +00:00
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)
ignore_reacted = args.get("ignore_reacted", True)
ignore_forwarded = args.get("ignore_forwarded", True)
2022-06-07 12:44:45 +00:00
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:
2023-03-12 03:56:01 +00:00
"""Priority 0 is reserved for modules."""
2022-07-04 09:53:43 +00:00
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 parent_command is None and command in help_messages:
2022-07-04 09:53:43 +00:00
if help_messages[alias_command(command)]["priority"] <= priority:
2023-03-12 03:56:01 +00:00
raise ValueError(
f"{lang('error_prefix')} {lang('command')} \"{command}\" {lang('has_reg')}"
)
2022-07-04 09:53:43 +00:00
else:
block_process = True
real_command = (
alias_command(command, disallow_alias)
if parent_command is None
else f"{parent_command} {command}"
)
pattern = rf"^(,|){real_command}(?: |$)([\s\S]*)"
sudo_pattern = rf"^(/){real_command}(?: |$)([\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
2022-05-23 12:40:30 +00:00
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.me
if ignore_forwarded:
base_filters &= ~filters.forwarded
sudo_filters &= ~filters.forwarded
if ignore_reacted:
base_filters &= ~mod_filters.reacted
sudo_filters &= ~mod_filters.reacted
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 "ignore_reacted" in args:
del args["ignore_reacted"]
if "ignore_forwarded" in args:
del args["ignore_forwarded"]
2022-06-07 12:44:45 +00:00
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) -> CommandHandler:
func = CommandHandler(
function,
2024-08-13 10:38:13 +00:00
(
alias_command(command, disallow_alias)
if command and parent_command is None
else None
),
)
2022-05-23 12:40:30 +00:00
async def handler(client: Client, message: Message):
try:
2023-01-31 16:24:56 +00:00
# ignore
try:
if ignore_groups_manager.check_id(message.chat.id):
raise ContinuePropagation
except ContinuePropagation:
raise ContinuePropagation
except BaseException:
pass
2022-05-23 12:40:30 +00:00
try:
arguments = message.matches[0].group(2)
parameter = arguments.split(" ")
2022-06-07 12:44:45 +00:00
if parameter == [""]:
2022-05-23 12:40:30 +00:00
parameter = []
if parent_command is not None and command is not None:
parameter.insert(0, command)
arguments = f"{command} {arguments}".strip()
2022-05-23 12:40:30 +00:00
message.parameter = parameter
message.arguments = arguments
2022-05-23 12:40:30 +00:00
except BaseException:
message.parameter = None
message.arguments = None
# solve same process
2023-01-14 05:49:08 +00:00
async with _lock:
2022-05-23 12:40:30 +00:00
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,
parent_command or command,
command if parent_command else None,
)
await func.handler(client, message)
if command:
await Hook.command_post(
message,
parent_command or command,
command if parent_command else None,
)
2022-06-20 13:55:14 +00:00
except StopPropagation as e:
raise StopPropagation from e
except KeyboardInterrupt as e:
raise KeyboardInterrupt from e
2023-03-12 03:56:01 +00:00
except (
UserNotParticipant,
MessageNotModified,
MessageEmpty,
Flood,
Forbidden,
PeerIdInvalid,
):
2023-01-02 04:16:31 +00:00
logs.warning(
"An unknown chat error occurred while processing a command.",
)
2022-05-23 12:40:30 +00:00
except MessageIdInvalid:
2023-03-12 03:56:01 +00:00
logs.warning("Please Don't Delete Commands While it's Processing..")
2022-06-26 12:59:36 +00:00
except AlreadyInConversationError:
2023-03-12 03:56:01 +00:00
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:
2023-03-12 03:56:01 +00:00
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:
2023-03-12 03:56:01 +00:00
logs.warning("Listener Canceled While Processing Commands..")
2022-06-30 06:49:03 +00:00
with contextlib.suppress(BaseException):
await message.edit(lang("reload_des"))
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()
web.stop()
2024-02-05 13:16:25 +00:00
except BaseException as exc:
2022-05-23 12:40:30 +00:00
exc_info = sys.exc_info()[1]
exc_format = format_exc()
2022-06-20 13:55:14 +00:00
with contextlib.suppress(BaseException):
2024-02-05 13:16:25 +00:00
exc_text = format_exc_text(exc)
text = f'{lang("run_error")}\n\n{exc_text}'
await message.edit(text, no_reply=True) # noqa
2022-05-23 12:40:30 +00:00
if not diagnostics:
return
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-06-20 13:55:14 +00:00
logs.error(report)
if Config.ERROR_REPORT:
2023-03-12 03:56:01 +00:00
await attach_report(
report,
f"exception.{time()}.pgp.txt",
None,
"PGP Error report generated.",
)
2024-02-05 13:16:25 +00:00
await Hook.process_error_exec(message, command, exc_info, exc_format)
2022-05-23 12:40:30 +00:00
if (message.chat.id, message.id) in read_context:
del read_context[(message.chat.id, message.id)]
if block_process or (parent_command and not allow_parent):
2022-07-04 09:53:43 +00:00
message.stop_propagation()
2022-05-23 12:40:30 +00:00
message.continue_propagation()
bot.dispatcher.add_handler(
MessageHandler(handler, filters=base_filters),
group=0 + priority,
first=parent_command and not allow_parent,
2023-03-12 03:56:01 +00:00
)
2023-01-14 05:49:08 +00:00
if command:
bot.dispatcher.add_handler(
MessageHandler(handler, filters=sudo_filters),
group=50 + priority,
first=parent_command and not allow_parent,
2023-03-12 03:56:01 +00:00
)
2022-05-23 12:40:30 +00:00
if not ignore_edited:
bot.dispatcher.add_handler(
EditedMessageHandler(handler, filters=base_filters),
group=1 + priority,
first=parent_command and not allow_parent,
2023-03-12 03:56:01 +00:00
)
2023-01-14 05:49:08 +00:00
if command:
bot.dispatcher.add_handler(
2023-03-12 03:56:01 +00:00
EditedMessageHandler(handler, filters=sudo_filters),
group=51 + priority,
first=parent_command and not allow_parent,
2023-03-12 03:56:01 +00:00
)
2022-05-23 12:40:30 +00:00
func.set_handler(handler)
return func
2022-05-23 12:40:30 +00:00
if description is not None and command is not None and parent_command is None:
2022-05-23 12:40:30 +00:00
if parameters is None:
parameters = ""
2023-03-12 03:56:01 +00:00
help_messages.update(
{
f"{alias_command(command)}": {
"permission": permission_name,
"use": f"**{lang('use_method')}:** `,{command} {parameters}`\n"
f"**{lang('need_permission')}:** `{permission_name}`\n"
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):
2023-01-31 16:24:56 +00:00
# ignore
try:
if ignore_groups_manager.check_id(message.chat.id):
raise ContinuePropagation
except ContinuePropagation:
raise ContinuePropagation
except BaseException:
pass
2023-01-14 05:49:08 +00:00
# solve same process
async with _lock:
if (message.chat.id, message.id) in read_context:
raise ContinuePropagation
read_context[(message.chat.id, message.id)] = True
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:
2023-03-12 03:56:01 +00:00
logs.warning("Please Don't Delete Commands While it's Processing..")
2022-06-26 12:59:36 +00:00
except AlreadyInConversationError:
2023-03-12 03:56:01 +00:00
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:
2023-03-12 03:56:01 +00:00
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:
2023-03-12 03:56:01 +00:00
logs.warning("Listener Canceled While Processing Commands..")
2022-06-30 06:49:03 +00:00
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)
2023-03-12 03:56:01 +00:00
except (
UserNotParticipant,
MessageNotModified,
MessageEmpty,
Flood,
Forbidden,
):
2022-05-23 12:40:30 +00:00
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):
2023-03-12 03:56:01 +00:00
await message.edit(lang("run_error"), no_reply=True)
2022-05-23 12:40:30 +00:00
if Config.ERROR_REPORT:
2023-03-12 03:56:01 +00:00
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.",
)
2022-05-23 12:40:30 +00:00
message.continue_propagation()
bot.add_handler(MessageHandler(handler, filters=filter_s), group=2)
return handler
return decorator