Skip to content

Commit

Permalink
some optimizations
Browse files Browse the repository at this point in the history
  • Loading branch information
rking32 committed Sep 6, 2020
1 parent b46b214 commit 435fc03
Show file tree
Hide file tree
Showing 5 changed files with 40 additions and 34 deletions.
1 change: 1 addition & 0 deletions init/logbot/core/api.sh
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ _getResponse() {
\terror_code : [$errcode]
\tdescription : $desc"
fi
sleep 0.6
fi
}

Expand Down
6 changes: 0 additions & 6 deletions init/logbot/methods/basic.sh
Original file line number Diff line number Diff line change
Expand Up @@ -8,26 +8,20 @@
#
# All rights reserved.

_delay=0.6

sendMessage() {
test -z "$1" || rawsendMessage $LOG_CHANNEL_ID "$1"
sleep $_delay
}

replyLastMessage() {
test -z "$1" || getLastMessage reply "$1"
sleep $_delay
}

editLastMessage() {
test -z "$1" || getLastMessage edit "$1"
sleep $_delay
}

deleteLastMessage() {
getLastMessage delete
sleep $_delay
}

deleteMessages() {
Expand Down
12 changes: 11 additions & 1 deletion userge/core/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
__all__ = ['Userge']

import time
import signal
import asyncio
import importlib
from types import ModuleType
Expand All @@ -33,6 +34,13 @@
_START_TIME = time.time()


def _shutdown():
_LOG.info(_LOG_STR, 'received stop signal, cancelling tasks...')
for task in asyncio.all_tasks():
task.cancel()
_LOG.info(_LOG_STR, 'all tasks cancelled !')


async def _complete_init_tasks() -> None:
if not _INIT_TASKS:
return
Expand Down Expand Up @@ -155,16 +163,18 @@ async def start(self) -> None:

async def stop(self) -> None: # pylint: disable=arguments-differ
""" stop client and bot """
await pool._stop() # pylint: disable=protected-access
if self._bot is not None:
_LOG.info(_LOG_STR, "Stopping UsergeBot")
await self._bot.stop()
_LOG.info(_LOG_STR, "Stopping Userge")
await super().stop()
await pool._stop() # pylint: disable=protected-access

def begin(self, coro: Optional[Awaitable[Any]] = None) -> None:
""" start userge """
loop = asyncio.get_event_loop()
loop.add_signal_handler(signal.SIGHUP, _shutdown)
loop.add_signal_handler(signal.SIGTERM, _shutdown)
run = loop.run_until_complete
run(self.start())
running_tasks: List[asyncio.Task] = []
Expand Down
39 changes: 14 additions & 25 deletions userge/plugins/tools/executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,34 +23,24 @@

@userge.on_cmd("eval", about={
'header': "run python code line | lines",
'flags': {
'-d': "debug mode (increase sensitivity)",
'-s': "silent mode (hide STDIN)"},
'usage': "{tr}eval [flag(s)] [code lines]",
'flags': {'-s': "silent mode (hide STDIN)"},
'usage': "{tr}eval [flag] [code lines]",
'examples': [
"{tr}eval print('Userge')", "{tr}eval -s print('Userge')",
"{tr}eval -d 5 + 6", "{tr}eval -s -d 5 + 6"]}, allow_channels=False)
"{tr}eval 5 + 6", "{tr}eval -s 5 + 6"]}, allow_channels=False)
async def eval_(message: Message):
""" run python code """
cmd = await init_func(message)
if cmd is None:
return
flags = []
for flag in ('-s', '-d', '-s'):
if cmd.startswith(flag):
flags.append(flag)
cmd = cmd[2:].strip()
silent_mode = False
if cmd.startswith('-s'):
silent_mode = True
cmd = cmd[2:].strip()
if not cmd:
await message.err("Unable to Parse Input!")
return
silent_mode, debug_mode, mode = False, False, ""
if '-s' in flags:
silent_mode = True
mode += "<silent> "
if '-d' in flags:
debug_mode = True
mode += "<debug> "
await message.edit(f"`Executing eval in {mode or '<normal> '}mode ...`", parse_mode='md')
await message.edit(f"`Executing eval ...`", parse_mode='md')
old_stderr = sys.stderr
old_stdout = sys.stdout
redirected_output = sys.stdout = io.StringIO()
Expand All @@ -61,8 +51,10 @@ 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'))
elif any(True for k_ in ('pass', 'break', 'continue', 'return', 'raise') if k_ in code):
rest_code = f"\n {code}"
else:
rest_code = f"\n {code}" if "return " in code else f"\n return {code}"
rest_code = f"\n return {code}"
exec(head + rest_code) # nosec pylint: disable=W0122
return await locals()['__aexec'](userge, message)
try:
Expand All @@ -73,15 +65,12 @@ async def aexec(code):
stderr = redirected_error.getvalue().strip()
sys.stdout = old_stdout
sys.stderr = old_stderr
evaluation = exc or stderr or stdout
evaluation = exc or stderr or stdout or ret_val
output = ""
if debug_mode:
evaluation = ret_val or evaluation
if not silent_mode:
output += f"**>>>** ```{cmd}```\n\n"
output += f"**>** ```{cmd}```\n\n"
if evaluation:
output += f"**>>>** ```{evaluation}```"
await asyncio.sleep(1)
output += f"**>** ```{evaluation}```"
if output:
await message.edit_or_send_as_file(text=output,
parse_mode='md',
Expand Down
16 changes: 14 additions & 2 deletions userge/plugins/tools/updater.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,14 +68,26 @@ async def check_update(message: Message):
if pull_from_repo:
await message.edit(f'`New update found for [{branch}], Now pulling...`')
await asyncio.sleep(1)
repo.git.reset('--hard', f'origin/{branch}')
repo.git.checkout(branch, force=True)
repo.git.reset('--hard', branch)
await CHANNEL.log(f"**PULLED update from [{branch}]:\n\nπŸ“„ CHANGELOG πŸ“„**\n\n{out}")
elif not push_to_heroku:
changelog_str = f'**New UPDATE available for [{branch}]:\n\nπŸ“„ CHANGELOG πŸ“„**\n\n'
await message.edit_or_send_as_file(changelog_str + out, disable_web_page_preview=True)
return
elif not push_to_heroku:
await message.edit(f'**Userge is up-to-date with [{branch}]**', del_in=5)
if pull_from_repo:
active = repo.active_branch.name
await message.edit(
f'`Moving HEAD from [{active}] >>> [{branch}] ...`', parse_mode='md')
await asyncio.sleep(1)
repo.git.checkout(branch, force=True)
repo.git.reset('--hard', branch)
await CHANNEL.log(f"`Moved HEAD from [{active}] >>> [{branch}] !`")
await message.edit('`Now restarting... Wait for a while!`', del_in=3)
asyncio.get_event_loop().create_task(userge.restart())
else:
await message.edit(f'**Userge is up-to-date with [{branch}]**', del_in=5)
return
if not push_to_heroku:
await message.edit(
Expand Down

0 comments on commit 435fc03

Please sign in to comment.