Skip to content

Commit

Permalink
fixed and code refactor (UsergeTeam#164)
Browse files Browse the repository at this point in the history
* line

* API_BANS error fixed

* update

* Revert "Merge branch 'alpha' of https://github.com/UsergeTeam/Userge into alpha"

This reverts commit b714941, reversing
changes made to 31a29ce.

* Revert "Revert "Merge branch 'alpha' of https://github.com/UsergeTeam/Userge into alpha""

This reverts commit 3c5e963.

* test plugin

* edit

* edit

* merge

* log pms update

* dont handle my msg

* edit

* 'Refactored by Sourcery'

* Delete log_pms.py

* Update utube.py

Co-authored-by: Sourcery AI <>
  • Loading branch information
muhammedfurkan authored Sep 27, 2020
1 parent 9d6c00a commit 87418e9
Show file tree
Hide file tree
Showing 12 changed files with 173 additions and 180 deletions.
6 changes: 4 additions & 2 deletions userge/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,8 @@ class Config:
HEROKU_API_KEY = os.environ.get("HEROKU_API_KEY", None)
HEROKU_APP_NAME = os.environ.get("HEROKU_APP_NAME", None)
G_DRIVE_IS_TD = os.environ.get("G_DRIVE_IS_TD") == "true"
LOAD_UNOFFICIAL_PLUGINS = os.environ.get("LOAD_UNOFFICIAL_PLUGINS") == "true"
LOAD_UNOFFICIAL_PLUGINS = os.environ.get(
"LOAD_UNOFFICIAL_PLUGINS") == "true"
THUMB_PATH = DOWN_PATH + "thumb_image.jpg"
TMP_PATH = "userge/plugins/temp/"
MAX_MESSAGE_LENGTH = 4096
Expand Down Expand Up @@ -93,7 +94,8 @@ def get_version() -> str:
if diff:
return f"{ver}-patch.{len(diff)}"
else:
diff = list(_REPO.iter_commits(f'{Config.UPSTREAM_REMOTE}/master..HEAD'))
diff = list(_REPO.iter_commits(
f'{Config.UPSTREAM_REMOTE}/master..HEAD'))
if diff:
return f"{ver}-custom.{len(diff)}"
return ver
4 changes: 1 addition & 3 deletions userge/core/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,7 @@ def is_bot(self) -> bool:
""" returns client is bot or not """
if self._bot is not None:
return hasattr(self, 'ubot')
if Config.BOT_TOKEN:
return True
return False
return bool(Config.BOT_TOKEN)

@property
def uptime(self) -> str:
Expand Down
36 changes: 19 additions & 17 deletions userge/core/types/bound/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,23 +158,25 @@ def cancel_the_process(self) -> None:
_CANCEL_LIST.append(self.message_id)

def _filter(self) -> None:
if not self._filtered:
prefix = str(self._kwargs.get('prefix', '-'))
del_pre = bool(self._kwargs.get('del_pre', False))
input_str = self.input_str
for i in input_str.strip().split():
match = re.match(f"({prefix}[a-zA-Z]+)([0-9]*)$", i)
if match:
items: Sequence[str] = match.groups()
self._flags[items[0].lstrip(prefix).lower() if del_pre
else items[0].lower()] = items[1] or ''
else:
self._filtered_input_str += ' ' + i
self._filtered_input_str = self._filtered_input_str.strip()
_LOG.debug(
_LOG_STR,
f"Filtered Input String => [ {self._filtered_input_str}, {self._flags} ]")
self._filtered = True
if self._filtered:
return

prefix = str(self._kwargs.get('prefix', '-'))
del_pre = bool(self._kwargs.get('del_pre', False))
input_str = self.input_str
for i in input_str.strip().split():
match = re.match(f"({prefix}[a-zA-Z]+)([0-9]*)$", i)
if match:
items: Sequence[str] = match.groups()
self._flags[items[0].lstrip(prefix).lower() if del_pre
else items[0].lower()] = items[1] or ''
else:
self._filtered_input_str += ' ' + i
self._filtered_input_str = self._filtered_input_str.strip()
_LOG.debug(
_LOG_STR,
f"Filtered Input String => [ {self._filtered_input_str}, {self._flags} ]")
self._filtered = True

async def send_as_file(self,
text: str,
Expand Down
73 changes: 37 additions & 36 deletions userge/core/types/new/channel_logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,39 +211,40 @@ async def forward_stored(self,
Returns:
None
"""
if message_id and isinstance(message_id, int):
message = await client.get_messages(chat_id=self._id,
message_ids=message_id)
caption = ''
file_id = file_ref = None
if message.caption:
caption = message.caption.html.split('\n\n', maxsplit=1)[-1]
elif message.text:
caption = message.text.html.split('\n\n', maxsplit=1)[-1]
if caption:
u_dict = await client.get_user_dict(user_id)
chat = await client.get_chat(chat_id)
u_dict.update({
'chat': chat.title if chat.title else "this group",
'count': chat.members_count})
caption = caption.format_map(SafeDict(**u_dict))
file_id, file_ref = get_file_id_and_ref(message)
caption, buttons = parse_buttons(caption)
if message.media and file_id and file_ref:
msg = await client.send_cached_media(
chat_id=chat_id,
file_id=file_id,
file_ref=file_ref,
caption=caption,
reply_to_message_id=reply_to_message_id,
reply_markup=buttons if client.is_bot and buttons else None)
else:
msg = await client.send_message(
chat_id=chat_id,
text=caption,
reply_to_message_id=reply_to_message_id,
disable_web_page_preview=True,
reply_markup=buttons if client.is_bot and buttons else None)
if del_in and msg:
await asyncio.sleep(del_in)
await msg.delete()
if not message_id or not isinstance(message_id, int):
return
message = await client.get_messages(chat_id=self._id,
message_ids=message_id)
caption = ''
file_id = file_ref = None
if message.caption:
caption = message.caption.html.split('\n\n', maxsplit=1)[-1]
elif message.text:
caption = message.text.html.split('\n\n', maxsplit=1)[-1]
if caption:
u_dict = await client.get_user_dict(user_id)
chat = await client.get_chat(chat_id)
u_dict.update({
'chat': chat.title if chat.title else "this group",
'count': chat.members_count})
caption = caption.format_map(SafeDict(**u_dict))
file_id, file_ref = get_file_id_and_ref(message)
caption, buttons = parse_buttons(caption)
if message.media and file_id and file_ref:
msg = await client.send_cached_media(
chat_id=chat_id,
file_id=file_id,
file_ref=file_ref,
caption=caption,
reply_to_message_id=reply_to_message_id,
reply_markup=buttons if client.is_bot and buttons else None)
else:
msg = await client.send_message(
chat_id=chat_id,
text=caption,
reply_to_message_id=reply_to_message_id,
disable_web_page_preview=True,
reply_markup=buttons if client.is_bot and buttons else None)
if del_in and msg:
await asyncio.sleep(del_in)
await msg.delete()
122 changes: 61 additions & 61 deletions userge/core/types/raw/command.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,67 +72,67 @@ def parse(cls, command: str, # pylint: disable=arguments-differ


def _format_about(about: Union[str, Dict[str, Union[str, List[str], Dict[str, str]]]]) -> str:
if isinstance(about, dict):
tmp_chelp = ''
if 'header' in about and isinstance(about['header'], str):
tmp_chelp += f"<i><b>{about['header'].title()}</b><i>"
del about['header']
if 'description' in about and isinstance(about['description'], str):
tmp_chelp += ("\n\n📝 <u><b>Description</b></u> :\n\n "
f"<i>{about['description'].capitalize()}</i>")
del about['description']
if 'flags' in about:
tmp_chelp += "\n\n⛓ <u><b>Available Flags</b></u> :\n"
if isinstance(about['flags'], dict):
for f_n, f_d in about['flags'].items():
tmp_chelp += f"\n ▫ <code>{f_n}</code> : <i>{f_d.lower()}</i>"
else:
tmp_chelp += f"\n {about['flags']}"
del about['flags']
if 'options' in about:
tmp_chelp += "\n\n🕶 <u><b>Available Options</b></u> :\n"
if isinstance(about['options'], dict):
for o_n, o_d in about['options'].items():
if not isinstance(about, dict):
return about
tmp_chelp = ''
if 'header' in about and isinstance(about['header'], str):
tmp_chelp += f"<i><b>{about['header'].title()}</b><i>"
del about['header']
if 'description' in about and isinstance(about['description'], str):
tmp_chelp += ("\n\n📝 <u><b>Description</b></u> :\n\n "
f"<i>{about['description'].capitalize()}</i>")
del about['description']
if 'flags' in about:
tmp_chelp += "\n\n⛓ <u><b>Available Flags</b></u> :\n"
if isinstance(about['flags'], dict):
for f_n, f_d in about['flags'].items():
tmp_chelp += f"\n ▫ <code>{f_n}</code> : <i>{f_d.lower()}</i>"
else:
tmp_chelp += f"\n {about['flags']}"
del about['flags']
if 'options' in about:
tmp_chelp += "\n\n🕶 <u><b>Available Options</b></u> :\n"
if isinstance(about['options'], dict):
for o_n, o_d in about['options'].items():
tmp_chelp += f"\n ▫ <code>{o_n}</code> : <i>{o_d.lower()}</i>"
else:
tmp_chelp += f"\n {about['options']}"
del about['options']
if 'types' in about:
tmp_chelp += "\n\n🎨 <u><b>Supported Types</b></u> :\n\n"
if isinstance(about['types'], list):
for _opt in about['types']:
tmp_chelp += f" <code>{_opt}</code> ,"
else:
tmp_chelp += f" {about['types']}"
del about['types']
if 'usage' in about:
tmp_chelp += f"\n\n✒ <u><b>Usage</b></u> :\n\n<code>{about['usage']}</code>"
del about['usage']
if 'examples' in about:
tmp_chelp += "\n\n✏ <u><b>Examples</b></u> :"
if isinstance(about['examples'], list):
for ex_ in about['examples']:
tmp_chelp += f"\n\n <code>{ex_}</code>"
else:
tmp_chelp += f"\n\n <code>{about['examples']}</code>"
del about['examples']
if 'others' in about:
tmp_chelp += f"\n\n📎 <u><b>Others</b></u> :\n\n{about['others']}"
del about['others']
if about:
for t_n, t_d in about.items():
tmp_chelp += f"\n\n⚙ <u><b>{t_n.title()}</b></u> :\n"
if isinstance(t_d, dict):
for o_n, o_d in t_d.items():
tmp_chelp += f"\n ▫ <code>{o_n}</code> : <i>{o_d.lower()}</i>"
else:
tmp_chelp += f"\n {about['options']}"
del about['options']
if 'types' in about:
tmp_chelp += "\n\n🎨 <u><b>Supported Types</b></u> :\n\n"
if isinstance(about['types'], list):
for _opt in about['types']:
elif isinstance(t_d, list):
tmp_chelp += '\n'
for _opt in t_d:
tmp_chelp += f" <code>{_opt}</code> ,"
else:
tmp_chelp += f" {about['types']}"
del about['types']
if 'usage' in about:
tmp_chelp += f"\n\n✒ <u><b>Usage</b></u> :\n\n<code>{about['usage']}</code>"
del about['usage']
if 'examples' in about:
tmp_chelp += "\n\n✏ <u><b>Examples</b></u> :"
if isinstance(about['examples'], list):
for ex_ in about['examples']:
tmp_chelp += f"\n\n <code>{ex_}</code>"
else:
tmp_chelp += f"\n\n <code>{about['examples']}</code>"
del about['examples']
if 'others' in about:
tmp_chelp += f"\n\n📎 <u><b>Others</b></u> :\n\n{about['others']}"
del about['others']
if about:
for t_n, t_d in about.items():
tmp_chelp += f"\n\n⚙ <u><b>{t_n.title()}</b></u> :\n"
if isinstance(t_d, dict):
for o_n, o_d in t_d.items():
tmp_chelp += f"\n ▫ <code>{o_n}</code> : <i>{o_d.lower()}</i>"
elif isinstance(t_d, list):
tmp_chelp += '\n'
for _opt in t_d:
tmp_chelp += f" <code>{_opt}</code> ,"
else:
tmp_chelp += '\n'
tmp_chelp += t_d
chelp = tmp_chelp.replace('{tr}', Config.CMD_TRIGGER)
del tmp_chelp
return chelp
return about
tmp_chelp += '\n'
tmp_chelp += t_d
chelp = tmp_chelp.replace('{tr}', Config.CMD_TRIGGER)
del tmp_chelp
return chelp
3 changes: 2 additions & 1 deletion userge/plugins/admin/gban.py
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,8 @@ async def gban_at_entry(message: Message):
async with ses.get(f'https://api.cas.chat/check?user_id={user_id}') as resp:
res = json.loads(await resp.text())
if res['ok']:
reason = ' | '.join(res['result']['messages']) if 'result' in res else None
reason = ' | '.join(
res['result']['messages']) if 'result' in res else None
await asyncio.gather(
message.client.kick_chat_member(chat_id, user_id),
message.reply(
Expand Down
11 changes: 3 additions & 8 deletions userge/plugins/misc/pathlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,12 +60,11 @@ def percentage(self) -> int:
def progress(self) -> str:
""" Returns progress """
percentage = self.percentage
progress_str = "[{}{}]".format(
return "[{}{}]".format(
''.join((Config.FINISHED_PROGRESS_STR
for i in range(floor(percentage / 5)))),
''.join((Config.UNFINISHED_PROGRESS_STR
for i in range(20 - floor(percentage / 5)))))
return progress_str

@property
def canceled(self) -> bool:
Expand Down Expand Up @@ -244,12 +243,11 @@ def percentage(self) -> int:
def progress(self) -> str:
""" Returns progress """
percentage = self.percentage
progress_str = "[{}{}]".format(
return "[{}{}]".format(
''.join((Config.FINISHED_PROGRESS_STR
for i in range(floor(percentage / 5)))),
''.join((Config.UNFINISHED_PROGRESS_STR
for i in range(20 - floor(percentage / 5)))))
return progress_str

@property
def speed(self) -> float:
Expand Down Expand Up @@ -341,10 +339,7 @@ def combine(self) -> None:
'usage': "{tr}ls [path]\n{tr}ls -d : default path"}, allow_channels=False)
async def ls_dir(message: Message) -> None:
""" list dir """
if '-d' in message.flags:
path = Config.DOWN_PATH
else:
path = message.input_str or '.'
path = Config.DOWN_PATH if '-d' in message.flags else message.input_str or '.'
if not exists(path):
await message.err("path not exists!")
return
Expand Down
6 changes: 1 addition & 5 deletions userge/plugins/misc/utube.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,11 +187,7 @@ def _yt_getInfo(link):
@pool.run_in_thread
def _supported(url):
ies = ytdl.extractor.gen_extractors()
for ie in ies:
if ie.suitable(url) and ie.IE_NAME != 'generic':
# Site has dedicated extractor
return True
return False
return any(ie.suitable(url) and ie.IE_NAME != 'generic' for ie in ies)


@pool.run_in_thread
Expand Down
2 changes: 1 addition & 1 deletion userge/plugins/tools/alive.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@ async def alive(message: Message):
f"trying again... ERROR:: {set_err} ::")
_set_data(True)
markup = None
copy_ = "https://github.com/UsergeTeam/Userge/blob/master/LICENSE"
output = f"""
**⏱ uptime** : `{userge.uptime}`
**💡 version** : `{get_version()}`
Expand All @@ -58,6 +57,7 @@ async def alive(message: Message):
🎖 **{versions.__license__}** | 👥 **{versions.__copyright__}** | 🧪 **[Repo]({Config.UPSTREAM_REPO})**
"""
else:
copy_ = "https://github.com/UsergeTeam/Userge/blob/master/LICENSE"
markup = InlineKeyboardMarkup([
[
InlineKeyboardButton(text="👥 UsergeTeam", url="https://github.com/UsergeTeam"),
Expand Down
7 changes: 2 additions & 5 deletions userge/plugins/tools/executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ async def eval_(message: Message):
async def aexec(code):
head = "async def __aexec(userge, message):\n "
if '\n' in code:
rest_code = '\n '.join(line for line in code.split('\n'))
rest_code = '\n '.join(iter(code.split('\n')))
elif any(True for k_ in keyword.kwlist
if k_ not in ('True', 'False', 'None') and code.startswith(f"{k_} ")):
rest_code = f"\n {code}"
Expand Down Expand Up @@ -129,10 +129,7 @@ async def term_(message: Message):
uid = geteuid()
except ImportError:
uid = 1
if uid == 0:
output = f"{curruser}:~# {cmd}\n"
else:
output = f"{curruser}:~$ {cmd}\n"
output = f"{curruser}:~# {cmd}\n" if uid == 0 else f"{curruser}:~$ {cmd}\n"
count = 0
while not t_obj.finished:
count += 1
Expand Down
Loading

0 comments on commit 87418e9

Please sign in to comment.