diff --git a/userge/core/types/bound/message.py b/userge/core/types/bound/message.py index 562f456e1..2ba8fedbb 100644 --- a/userge/core/types/bound/message.py +++ b/userge/core/types/bound/message.py @@ -17,9 +17,11 @@ from pyrogram import InlineKeyboardMarkup, Message as RawMessage from pyrogram.errors.exceptions import MessageAuthorRequired, MessageTooLong from pyrogram.errors.exceptions.bad_request_400 import MessageNotModified, MessageIdInvalid +from pyrogram.errors.exceptions.forbidden_403 import MessageDeleteForbidden from userge import logging from ... import client as _client # pylint: disable=unused-import +from ..new import ChannelLogger _CANCEL_LIST: List[int] = [] _ERROR_MSG_DELETE_TIMEOUT = 5 @@ -42,7 +44,7 @@ def _msg_to_dict(message: RawMessage) -> Dict[str, object]: class Message(RawMessage): """ Modded Message Class For Userge """ def __init__(self, - client: Union['_client.Userge', '_client.UsergeBot'], + client: Union['_client.Userge', '_client._UsergeBot'], message: RawMessage, **kwargs: Union[str, bool]) -> None: super().__init__(client=client, **_msg_to_dict(message)) @@ -50,7 +52,7 @@ def __init__(self, self.reply_to_message: Optional[RawMessage] if self.reply_to_message: self.reply_to_message = self.__class__(self._client, self.reply_to_message) - self._channel = client._channel + self._channel = ChannelLogger(client, "CORE") self._filtered = False self._process_canceled = False self._filtered_input_str: str = '' @@ -58,7 +60,7 @@ def __init__(self, self._kwargs = kwargs @property - def client(self) -> Union['_client.Userge', '_client.UsergeBot']: + def client(self) -> Union['_client.Userge', '_client._UsergeBot']: """ returns client """ return self._client @@ -163,7 +165,6 @@ async def send_as_file(self, filename=filename, caption=caption, log=log, - delete_message=delete_message, reply_to_message_id=reply_to_id) async def reply(self, @@ -783,3 +784,28 @@ async def force_edit_or_send_as_file(self, disable_web_page_preview=disable_web_page_preview, reply_markup=reply_markup, **kwargs) + + # pylint: disable=arguments-differ + async def delete(self, revoke: bool = True, sudo: bool = True,) -> bool: + """\nThis will first try to delete and ignore + it if it raises MessageDeleteForbidden + + Parameters: + revoke (``bool``, *optional*): + Deletes messages on both parts. + This is only for private cloud chats and normal groups, messages on + channels and supergroups are always revoked (i.e.: deleted for everyone). + Defaults to True. + + sudo (``bool``, *optional*): + If ``True``, sudo users supported. + + Returns: + True on success, False otherwise. + """ + try: + return bool(await super().delete(revoke=revoke)) + except MessageDeleteForbidden as m_e: + if not sudo: + raise m_e + return True diff --git a/userge/core/types/new/channel_logger.py b/userge/core/types/new/channel_logger.py index 049a9a628..74acc09af 100644 --- a/userge/core/types/new/channel_logger.py +++ b/userge/core/types/new/channel_logger.py @@ -11,7 +11,7 @@ __all__ = ['ChannelLogger'] import asyncio -from typing import Optional, Tuple +from typing import Optional, Tuple, Union from pyrogram import Message as RawMessage from pyrogram.errors.exceptions.bad_request_400 import ChannelInvalid @@ -51,7 +51,7 @@ def _get_file_id_and_ref(message: '_message.Message') -> Tuple[str, str]: class ChannelLogger: """ Channel logger for Userge """ - def __init__(self, client: '_client.Userge', name: str) -> None: + def __init__(self, client: Union['_client.Userge', '_client._UsergeBot'], name: str) -> None: self._client = client self._string = _gen_string(name) diff --git a/userge/plugins/admin/gban.py b/userge/plugins/admin/gban.py index d151dc6ec..822445685 100644 --- a/userge/plugins/admin/gban.py +++ b/userge/plugins/admin/gban.py @@ -256,7 +256,8 @@ async def list_white(message: Message): f"**--Whitelisted Users List--**\n\n{msg}" if msg else "`whitelist empty!`") -@userge.on_filters(Filters.group & Filters.new_chat_members & ~Filters.me, group=1) +@userge.on_filters(Filters.group & Filters.new_chat_members & ~Filters.me, + group=1, allow_via_bot=False) async def gban_at_entry(message: Message): """ handle gbans """ chat_id = message.chat.id @@ -266,10 +267,8 @@ async def gban_at_entry(message: Message): ADMEME_CHATS.append(chat_id) else: PATHETIC_CHATS.append(chat_id) - if chat_id in PATHETIC_CHATS: return - for user in message.new_chat_members: user_id = user.id first_name = user.first_name diff --git a/userge/plugins/fun/memes.py b/userge/plugins/fun/memes.py index cb8ce18c4..a1e12f85e 100644 --- a/userge/plugins/fun/memes.py +++ b/userge/plugins/fun/memes.py @@ -23,7 +23,8 @@ @userge.on_cmd(r"(?:Kek|:/)$", - about={'header': "Check yourself, hint: `:/`"}, name='Kek', trigger='') + about={'header': "Check yourself, hint: `:/`"}, name='Kek', + trigger='', allow_via_bot=False) async def kek_(message: Message): """kek""" kek = ["/", "\\"] @@ -33,7 +34,8 @@ async def kek_(message: Message): @userge.on_cmd(r"(?:Lol|-_-)$", - about={'header': "Check yourself, hint: `-_-`"}, name='Lol', trigger='') + about={'header': "Check yourself, hint: `-_-`"}, name='Lol', + trigger='', allow_via_bot=False) async def lol_(message: Message): """lol""" lol = "-_ " @@ -45,7 +47,8 @@ async def lol_(message: Message): @userge.on_cmd(r"(?:Fun|;_;)$", - about={'header': "Check yourself, hint: `;_;`"}, name="Fun", trigger='') + about={'header': "Check yourself, hint: `;_;`"}, name="Fun", + trigger='', allow_via_bot=False) async def fun_(message: Message): """fun""" fun = ";_ " @@ -56,7 +59,8 @@ async def fun_(message: Message): await message.edit(fun, parse_mode="html") -@userge.on_cmd("Oof$", about={'header': "Ooooof"}, trigger='') +@userge.on_cmd("Oof$", about={'header': "Ooooof"}, + trigger='', allow_via_bot=False) async def Oof_(message: Message): """Oof""" Oof = "Oo " @@ -65,7 +69,8 @@ async def Oof_(message: Message): await message.edit(Oof) -@userge.on_cmd("Hmm$", about={'header': "Hmmmmm"}, trigger='') +@userge.on_cmd("Hmm$", about={'header': "Hmmmmm"}, + trigger='', allow_via_bot=False) async def Hmm_(message: Message): """Hmm""" Hmm = "Hm " diff --git a/userge/plugins/fun/quote.py b/userge/plugins/fun/quote.py index 1c2e032dc..bc2531c76 100644 --- a/userge/plugins/fun/quote.py +++ b/userge/plugins/fun/quote.py @@ -15,7 +15,7 @@ @userge.on_cmd("quote", about={ 'header': "Quote a message", - 'usage': "{tr}quote [text or reply to msg]"}) + 'usage': "{tr}quote [text or reply to msg]"}, allow_via_bot=False) async def quotecmd(message: Message): """quotecmd""" asyncio.get_event_loop().create_task(message.delete()) diff --git a/userge/plugins/tools/alive.py b/userge/plugins/tools/alive.py index 25eb8bb75..31183514e 100644 --- a/userge/plugins/tools/alive.py +++ b/userge/plugins/tools/alive.py @@ -7,7 +7,7 @@ # All rights reserved. from pyrogram.errors.exceptions import FileIdInvalid, FileReferenceEmpty -from pyrogram.errors.exceptions.bad_request_400 import BadRequest +from pyrogram.errors.exceptions.bad_request_400 import BadRequest, ChannelInvalid, MediaEmpty from userge import userge, Message, Config, versions, get_version @@ -15,18 +15,10 @@ @userge.on_cmd("alive", about={ - 'header': "This command is just for fun"}, allow_channels=False, allow_via_bot=False) + 'header': "This command is just for fun"}, allow_channels=False) async def alive(message: Message): await message.delete() - try: - if LOGO_STICKER_ID: - await sendit(LOGO_STICKER_ID, message) - else: - await refresh_id() - await sendit(LOGO_STICKER_ID, message) - except (FileIdInvalid, FileReferenceEmpty, BadRequest): - await refresh_id() - await sendit(LOGO_STICKER_ID, message) + await sendit(message) output = f""" **USERGE is Up and Running** @@ -40,7 +32,7 @@ async def alive(message: Message): • **copyright** : {versions.__copyright__} • **repo** : [Userge]({Config.UPSTREAM_REPO}) """ - await userge.send_message(message.chat.id, output, disable_web_page_preview=True) + await message.client.send_message(message.chat.id, output, disable_web_page_preview=True) async def refresh_id(): @@ -50,5 +42,29 @@ async def refresh_id(): LOGO_STICKER_REF = sticker.file_ref -async def sendit(fileid, message): - await userge.send_sticker(message.chat.id, fileid, file_ref=LOGO_STICKER_REF) +async def send_sticker(message): + try: + await message.client.send_sticker( + message.chat.id, LOGO_STICKER_ID, file_ref=LOGO_STICKER_REF) + except MediaEmpty: + pass + + +async def sendit(message): + if LOGO_STICKER_ID: + try: + await send_sticker(message) + except (FileIdInvalid, FileReferenceEmpty, BadRequest): + try: + await refresh_id() + except ChannelInvalid: + pass + else: + await send_sticker(message) + else: + try: + await refresh_id() + except ChannelInvalid: + pass + else: + await send_sticker(message) diff --git a/userge/plugins/tools/logs.py b/userge/plugins/tools/logs.py index 2527eae9a..39db7ee43 100644 --- a/userge/plugins/tools/logs.py +++ b/userge/plugins/tools/logs.py @@ -8,14 +8,39 @@ import aiofiles -from userge import userge, Message +from userge import userge, Message, logging @userge.on_cmd("logs", about={'header': "check userge logs"}, allow_channels=False) async def check_logs(message: Message): - """check logs""" + """ check logs """ await message.edit("`checking logs ...`") async with aiofiles.open("logs/userge.log", "r") as l_f: await message.edit_or_send_as_file(f"**USERGE LOGS** :\n\n`{await l_f.read()}`", filename='userge.log', caption='userge.log') + +_LEVELS = { + 'debug': logging.DEBUG, + 'info': logging.INFO, + 'warning': logging.WARNING, + 'error': logging.ERROR, + 'critical': logging.CRITICAL +} + + +@userge.on_cmd("setlvl", about={ + 'header': "set logger level, default to info", + 'types': ['debug', 'info', 'warning', 'error', 'critical'], + 'usage': "{tr}setlvl [level]", + 'examples': ["{tr}setlvl info", "{tr}setlvl debug"]}) +async def set_level(message: Message): + """ set logger level """ + await message.edit("`setting logger level ...`") + level = message.input_str.lower() + if level not in _LEVELS: + await message.err("unknown level !") + return + for logger in (logging.getLogger(name) for name in logging.root.manager.loggerDict): + logger.setLevel(_LEVELS[level]) + await message.edit(f"`successfully set logger level as **{level.upper()}**`", del_in=3)