Skip to content

Commit

Permalink
fixed logs + missing things
Browse files Browse the repository at this point in the history
  • Loading branch information
rking32 committed Jul 3, 2020
1 parent 514cf5e commit 6c48e6e
Show file tree
Hide file tree
Showing 7 changed files with 102 additions and 31 deletions.
34 changes: 30 additions & 4 deletions userge/core/types/bound/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -42,23 +44,23 @@ 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))
self.message_id: int
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 = ''
self._flags: Dict[str, str] = {}
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

Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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
4 changes: 2 additions & 2 deletions userge/core/types/new/channel_logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)

Expand Down
5 changes: 2 additions & 3 deletions userge/plugins/admin/gban.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
15 changes: 10 additions & 5 deletions userge/plugins/fun/memes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = ["/", "\\"]
Expand All @@ -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 = "-_ "
Expand All @@ -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 = ";_ "
Expand All @@ -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 "
Expand All @@ -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 "
Expand Down
2 changes: 1 addition & 1 deletion userge/plugins/fun/quote.py
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand Down
44 changes: 30 additions & 14 deletions userge/plugins/tools/alive.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,26 +7,18 @@
# 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

LOGO_STICKER_ID, LOGO_STICKER_REF = None, None


@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**
Expand All @@ -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():
Expand All @@ -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)
29 changes: 27 additions & 2 deletions userge/plugins/tools/logs.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

0 comments on commit 6c48e6e

Please sign in to comment.