Skip to content

Commit

Permalink
some tweaks ;)
Browse files Browse the repository at this point in the history
Signed-off-by: rking32 <[email protected]>
  • Loading branch information
rking32 committed Mar 27, 2020
1 parent 40e09a0 commit b436438
Show file tree
Hide file tree
Showing 5 changed files with 53 additions and 58 deletions.
2 changes: 1 addition & 1 deletion app.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
},
"SCREENSHOT_API": {
"description": "api key from 'https://screenshotlayer.com'",
"value": "4",
"value": "",
"required": false
}
},
Expand Down
71 changes: 35 additions & 36 deletions userge/core/_userge/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,7 @@ def __init__(self) -> None:
api_id=Config.API_ID,
api_hash=Config.API_HASH)

def getLogger(self,
name: str) -> logging.Logger:
def getLogger(self, name: str) -> logging.Logger:
"""
This will return new logger object.
"""
Expand All @@ -45,18 +44,17 @@ def getLogger(self,

return logging.getLogger(name)

async def get_user_dict(self,
user_id: int) -> Dict[str, str]:
async def get_user_dict(self, user_id: int) -> Dict[str, str]:
"""
This will return user `Dict` which contains
`fname`, `lname`, `flname` and `uname`.
"""

user_obj = await self.get_users(user_id)

fname = user_obj.first_name or ''
lname = user_obj.last_name or ''
username = user_obj.username or ''
fname = user_obj.first_name.strip() or ''
lname = user_obj.last_name.strip() or ''
username = user_obj.username.strip() or ''

if fname and lname:
full_name = fname + ' ' + lname
Expand Down Expand Up @@ -165,7 +163,7 @@ def on_cmd(self,
if found:
match = re.match(r"([\w_]+)", command)
cname = match.groups()[0] if match else ''
pattern = f"\\{trigger}{command}"
pattern = f"^\\{trigger}{command}"

else:
cname = command
Expand Down Expand Up @@ -203,8 +201,7 @@ def on_left_member(self,
filters=Filters.left_chat_member & leaving_chats,
group=group)

def get_help(self,
key: str = '') -> Tuple[Union[str, List[str]], bool]:
def get_help(self, key: str = '') -> Tuple[Union[str, List[str]], bool]:
"""
This will return help string for specific key
or all modules or commands as `List`.
Expand All @@ -213,7 +210,7 @@ def get_help(self,
if not key:
return list(self.__HELP_DICT), True # module names

if not key.startswith('.') and key in self.__HELP_DICT:
if not key.startswith('.') and key in self.__HELP_DICT and len(self.__HELP_DICT[key]) > 1:
return list(self.__HELP_DICT[key]), False # all commands for that module

dict_ = {x: y for _, i in self.__HELP_DICT.items() for x, y in i.items()}
Expand Down Expand Up @@ -248,6 +245,7 @@ def __build_decorator(self,
**kwargs) -> Callable[[PYROFUNC], PYROFUNC]:

def __decorator(func: PYROFUNC) -> PYROFUNC:

async def __template(_: Client,
message: Message) -> None:
await func(Message(self, message, **kwargs))
Expand All @@ -264,29 +262,20 @@ async def __template(_: Client,

return __decorator

async def load_plugin(self,
name: str) -> None:
def load_plugin(self, name: str) -> None:
"""
Load plugin to Userge.
"""

name = self.__PLUGINS_PATH.format(name)
self._LOG.info(
self._MAIN_STRING.format(f"Importing {name}"))

try:
imported_ = importlib.import_module(name)

except ImportError as i_e:
self._LOG.error(i_e)
raise
self.__IMPORTED.append(
importlib.import_module(self.__PLUGINS_PATH.format(name)))

else:
self.__IMPORTED.append(imported_)

self._LOG.info(
self._MAIN_STRING.format(
f"Imported {imported_.__name__} Plugin Successfully"))
self._LOG.info(
self._MAIN_STRING.format(
f"Imported {self.__IMPORTED[-1].__name__} Plugin Successfully"))

def load_plugins(self) -> None:
"""
Expand All @@ -295,26 +284,21 @@ def load_plugins(self) -> None:

self.__HELP_DICT.clear()
self.__IMPORTED.clear()
imported: List[str] = []

self._LOG.info(
self._MAIN_STRING.format("Importing All Plugins"))

for name in get_all_plugins():
try:
imported_ = importlib.import_module(
self.__PLUGINS_PATH.format(name))
self.load_plugin(name)

except ImportError as i_e:
self._LOG.error(i_e)

else:
self.__IMPORTED.append(imported_)
imported.append(imported_.__name__)

self._LOG.info(
self._MAIN_STRING.format(
f"Imported ({len(imported)}) Plugins => {imported}"))
f"Imported ({len(self.__IMPORTED)}) Plugins => " + \
str([i.__name__ for i in self.__IMPORTED])))

async def reload_plugins(self) -> int:
"""
Expand All @@ -337,10 +321,26 @@ async def reload_plugins(self) -> int:
reloaded.append(reloaded_.__name__)

self._LOG.info(
self._MAIN_STRING.format(f"Reloaded These Plugins => {reloaded}"))
self._MAIN_STRING.format(
f"Reloaded {len(reloaded)} Plugins => {reloaded}"))

return len(reloaded)

async def restart(self) -> None:
"""
Restart the Userge.
"""

self._LOG.info(
self._MAIN_STRING.format("Restarting Userge"))

await self.stop()
await self.reload_plugins()
await self.start()

self._LOG.info(
self._MAIN_STRING.format("Restarted Userge"))

def begin(self) -> None:
"""
This will start the Userge.
Expand All @@ -350,7 +350,6 @@ def begin(self) -> None:
self._MAIN_STRING.format("Starting Userge"))

self._NST_ASYNC.apply()

self.run()

self._LOG.info(
Expand Down
27 changes: 13 additions & 14 deletions userge/core/_userge/message.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import re
import os
import asyncio
from typing import Dict, List, Union, Optional, Sequence
from typing import Dict, Union, Optional, Sequence

from pyrogram import Client, Message as Msg, InlineKeyboardMarkup
from pyrogram.errors.exceptions import MessageAuthorRequired
Expand All @@ -24,8 +24,9 @@ def __init__(self,
super().__init__(client=client,
**self._msg_to_dict(message))

self.__filtered_input_str: Optional[str] = None
self.__flags: Optional[Dict[str, str]] = None
self.__filtered = False
self.__filtered_input_str: str = ''
self.__flags: Dict[str, str] = {}
self.__kwargs = kwargs

@property
Expand All @@ -43,7 +44,7 @@ def input_str(self) -> str:
return ''

@property
def filtered_input_str(self) -> Optional[str]:
def filtered_input_str(self) -> str:
"""
Returns the filtered input string without command and flags.
"""
Expand All @@ -53,7 +54,7 @@ def filtered_input_str(self) -> Optional[str]:
return self.__filtered_input_str

@property
def flags(self) -> Optional[Dict[str, str]]:
def flags(self) -> Dict[str, str]:
"""
Returns all flags in input string as `Dict`.
"""
Expand All @@ -64,31 +65,29 @@ def flags(self) -> Optional[Dict[str, str]]:

def __filter(self) -> None:

if self.__filtered_input_str is None or self.__flags is None:
if not self.__filtered:
prefix: str = self.__kwargs.get('prefix', '-')
del_pre: bool = self.__kwargs.get('del_pre', False)
input_str: str = self.input_str

text: List[str] = []
flags: Dict[str, str] = {}

for i in input_str.strip().split():
match = re.match(f"({prefix}[a-z]+)($|[0-9]+)?$", i)

if match:
items: Sequence[str] = match.groups()
flags[items[0].lstrip(prefix) if del_pre \
self.__flags[items[0].lstrip(prefix) if del_pre \
else items[0]] = items[1] or ''

else:
text.append(i)
self.__filtered_input_str += ' ' + i

self.__filtered_input_str = ' '.join(text)
self.__flags = flags
self.__filtered_input_str = self.__filtered_input_str.strip()

self._LOG.info(
self._SUB_STRING.format(
f"Filtered Input String => [ {self.__filtered_input_str}, {flags} ]"))
f"Filtered Input String => [ {self.__filtered_input_str}, {self.__flags} ]"))

self.__filtered = True

async def send_as_file(self,
text: str,
Expand Down
5 changes: 2 additions & 3 deletions userge/plugins/utils/loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ async def load_cmd_handler(message: Message):
plugin = get_import_path(ROOT, path)

try:
await userge.load_plugin(plugin)
userge.load_plugin(plugin)

except Exception as e:
os.remove(path)
Expand All @@ -40,5 +40,4 @@ async def load_cmd_handler(message: Message):
@userge.on_cmd('reload', about="__Reload all plugins__")
async def reload_cmd_handler(message: Message):
await message.edit("`Reloading All Plugins`")
reloaded = await userge.reload_plugins()
await message.edit(f"`Reloaded {reloaded} Plugins`", del_in=3)
await message.edit(f"`Reloaded {await userge.reload_plugins()} Plugins`", del_in=3)
6 changes: 2 additions & 4 deletions userge/plugins/utils/restart.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,14 @@
LOG = userge.getLogger(__name__)


@userge.on_cmd('restart', about="__Restarts the bot and load all plugins__")
@userge.on_cmd('restart', about="__Restarts the bot and reload all plugins__")
async def restart_cmd_handler(m: Message):
await m.edit("Restarting Userge Services")
LOG.info(f"USERGE Services - Restart initiated")
asyncio.create_task(restart(userge, m))


async def restart(c: userge, m: Message):
await c.stop()
await c.reload_plugins()
await c.start()
await c.restart()
await m.edit(f"USERGE Services have been Restarted!")
LOG.info(f"USERGE - Restarted")

0 comments on commit b436438

Please sign in to comment.