From 3f656108345da35e278eea64245b547cd8286539 Mon Sep 17 00:00:00 2001 From: rking32 Date: Mon, 13 Apr 2020 19:25:13 +0530 Subject: [PATCH] added userge updater (beta) fixed .ub fix welcome fixed memes fixed .type fixed thumb add .repo command updated requirements updated config vars added userge updater ;P Signed-off-by: rking32 --- README.md | 2 +- app.json | 8 ++ config.env.sample | 13 ++- requirements.txt | 78 ++++++---------- userge/core/_userge/client.py | 3 - userge/core/_userge/message.py | 5 +- userge/plugins/fun/memes.py | 22 +++-- userge/plugins/fun/type.py | 12 ++- userge/plugins/misc/thumbnail.py | 18 ++-- userge/plugins/misc/welcome.py | 4 +- userge/plugins/tools/repo.py | 15 ++++ userge/plugins/utils/restart.py | 6 +- userge/plugins/utils/ub.py | 7 +- userge/plugins/utils/updater.py | 150 +++++++++++++++++++++++++++++++ userge/utils/config.py | 6 ++ 15 files changed, 254 insertions(+), 95 deletions(-) create mode 100644 userge/plugins/tools/repo.py create mode 100644 userge/plugins/utils/updater.py diff --git a/README.md b/README.md index a36faed47..7211a7151 100644 --- a/README.md +++ b/README.md @@ -63,7 +63,7 @@ async def testing(message: Message): await message.edit("testing...", del_in=5) # this will be automatically deleted after 5 sec - CHANNEL.log("testing completed!") # log to channel + await CHANNEL.log("testing completed!") # log to channel ``` ## Requirements diff --git a/app.json b/app.json index 985192409..5a25633c6 100644 --- a/app.json +++ b/app.json @@ -47,6 +47,14 @@ "LOG_CHANNEL_ID": { "description": "Telegram Log Channel ID", "required": false + }, + "HEROKU_APP_NAME": { + "description": "given app name to the heroku app", + "required": false + }, + "HEROKU_API_KEY": { + "description": "get a Heroku API key from http://dashboard.heroku.com/account", + "required": false } }, "addons": [ diff --git a/config.env.sample b/config.env.sample index d1d5ea800..c102da509 100644 --- a/config.env.sample +++ b/config.env.sample @@ -49,4 +49,15 @@ G_DRIVE_PARENT_ID = "" # Telegram Log Channel ID -LOG_CHANNEL_ID = "" \ No newline at end of file +LOG_CHANNEL_ID = "" + + +# ----------- Only If Using Heroku ----------- # + + +# get a Heroku API key from http://dashboard.heroku.com/account +HEROKU_API_KEY = "" + + +# given app name to the heroku app +HEROKU_APP_NAME = "" \ No newline at end of file diff --git a/requirements.txt b/requirements.txt index a0de597e7..f87b25832 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,53 +1,25 @@ -aiohttp==3.6.2 -async-generator==1.10 -async-lru==1.0.1 -async-timeout==3.0.1 -attrs==19.3.0 -beautifulsoup4==4.8.2 -cachetools==4.0.0 -certifi==2019.11.28 -chardet==3.0.4 -coverage==5.0.4 -dnspython==1.16.0 -emoji==0.5.4 -google-api-core==1.16.0 -google-api-python-client==1.8.0 -google-auth==1.12.0 -google-auth-httplib2==0.0.3 -google-auth-oauthlib==0.4.1 -googleapis-common-protos==1.51.0 -googletrans==2.4.0 -hachoir==3.1.1 -httplib2==0.17.0 -idna==2.9 -lxml==4.5.0 -multidict==4.7.5 -nest-asyncio==1.3.0 -oauth2client==4.1.3 -oauthlib==3.1.0 -Pillow==7.0.0 -protobuf==3.11.3 -pyaes==1.6.1 -pyasn1==0.4.8 -pyasn1-modules==0.2.8 -pymongo==3.10.1 -Pyrogram===0.17.0-asyncio -pySmartDL==1.3.3 -PySocks==1.7.1 -python-dotenv==0.12.0 -pytz==2019.3 -requests==2.23.0 -requests-oauthlib==1.3.0 -rsa==4.0 -search-engine-parser==0.5.4 -selenium==3.141.0 -six==1.14.0 -soupsieve==2.0 -speedtest-cli==2.1.2 -TgCrypto==1.2.0 -urbandict==0.6.1 -uritemplate==3.0.1 -urllib3==1.25.8 -wget==3.2 -wikipedia==1.4.0 -yarl==1.4.2 +https://github.com/pyrogram/pyrogram/archive/asyncio.zip +python-dotenv +tgcrypto +pymongo +dnspython +hachoir +Pillow +urbandict +googletrans +search-engine-parser +wikipedia +speedtest-cli +emoji +wget +nest_asyncio +requests +pySmartDL +selenium +google-api-python-client +google-auth-httplib2 +google-auth-oauthlib +oauth2client +cowpy +gitpython +heroku3 diff --git a/userge/core/_userge/client.py b/userge/core/_userge/client.py index f07d8fb5c..916326e0f 100644 --- a/userge/core/_userge/client.py +++ b/userge/core/_userge/client.py @@ -66,9 +66,6 @@ def getCLogger(self, name: str) -> CLogger: This will return new channel logger object. """ - LOG.info( - LOG_STR.format(f"Creating CLogger => {name}")) - return CLogger(self, name) @staticmethod diff --git a/userge/core/_userge/message.py b/userge/core/_userge/message.py index aafbebf7c..fe2793391 100644 --- a/userge/core/_userge/message.py +++ b/userge/core/_userge/message.py @@ -29,7 +29,7 @@ class Message(BaseMessage): """ - Moded Message Class For Userge + Modded Message Class For Userge """ def __init__(self, @@ -119,9 +119,6 @@ def cancel_the_process(self) -> None: def __msg_to_dict(self, message: BaseMessage) -> Dict[str, object]: - LOG.info( - LOG_STR.format("Creating moded message object")) - kwargs_ = vars(message) del message diff --git a/userge/plugins/fun/memes.py b/userge/plugins/fun/memes.py index 4ad3dd161..5d62aad6c 100644 --- a/userge/plugins/fun/memes.py +++ b/userge/plugins/fun/memes.py @@ -258,7 +258,7 @@ "(ノಠ ∩ಠ)ノ彡( \\o°o)\\", "“ヽ(´▽`)ノ”",) -@userge.on_cmd(":/$", about="__Check yourself ;)__", name="kek", trigger='') +@userge.on_cmd(":/$", about="__Check yourself, hint: `:/`__", name="kek", trigger='') async def kek_(message: Message): """kek""" kek = ["/", "\\"] @@ -267,20 +267,24 @@ async def kek_(message: Message): await message.edit(":" + kek[i % 2]) -@userge.on_cmd("-_-$", about="__Ok...__", name="lol", trigger='') +@userge.on_cmd("-_-$", about="__Check yourself, hint: `-_-`__", name="lol", trigger='') async def lol_(message: Message): """lol""" lol = "-_ " - for _ in range(10): + for i in range(15): + if i % 3 == 0: + lol = "-_ " lol = lol[:-1] + "_-" await message.edit(lol, parse_mode="html") -@userge.on_cmd(";_;$", about="__Like `-_-` but crying__", name="fun", trigger='') +@userge.on_cmd(";_;$", about="__Like `-_-` but crying, hint: `;_;`__", name="fun", trigger='') async def fun_(message: Message): """fun""" fun = ";_ " - for _ in range(10): + for i in range(15): + if i % 3 == 0: + fun = ";_ " fun = fun[:-1] + "_;" await message.edit(fun, parse_mode="html") @@ -400,7 +404,7 @@ async def moon_(message: Message): deq.rotate(1) except Exception: - return + await message.delete() @userge.on_cmd("clock$", about="__kensar clock animation__") @@ -415,7 +419,7 @@ async def clock_(message: Message): deq.rotate(1) except Exception: - return + await message.delete() @userge.on_cmd("bt$", about="""\ @@ -478,7 +482,7 @@ async def clap_(message: Message): `.[any cowacter]say [text]` - __cowacters:__ {['`' + x + '`' for x in cow.COWACTERS]}""", name="cowsay") + __cowacters:__ `{'`, `'.join(cow.COWACTERS)}`""", name="cowsay") async def cowsay_(message: Message): """cowsay""" arg = message.matches[0].group(1).lower() @@ -869,4 +873,4 @@ async def scam_(message: Message): count += 5 except Exception: - return + await message.delete() diff --git a/userge/plugins/fun/type.py b/userge/plugins/fun/type.py index 0586e6d77..82ae4afe5 100644 --- a/userge/plugins/fun/type.py +++ b/userge/plugins/fun/type.py @@ -20,9 +20,7 @@ `.type [text | reply to msg]`""") async def type_(message: Message): - text = message.input_str - if message.reply_to_message: - text = message.reply_to_message.text + text = message.input_or_reply_str if not text: await message.err("input not found") @@ -41,11 +39,11 @@ async def type_(message: Message): typing_text = old_text + typing_symbol try: - await message.edit(typing_text) + await message.try_to_edit(typing_text) time.sleep(s_t) - await message.edit(old_text) + await message.try_to_edit(old_text) time.sleep(s_t) - except FloodWait as x: - time.sleep(x.x) \ No newline at end of file + except FloodWait as x_e: + time.sleep(x_e.x) \ No newline at end of file diff --git a/userge/plugins/misc/thumbnail.py b/userge/plugins/misc/thumbnail.py index 8284fdfad..8632870a6 100644 --- a/userge/plugins/misc/thumbnail.py +++ b/userge/plugins/misc/thumbnail.py @@ -10,7 +10,6 @@ import os import time from datetime import datetime -from PIL import Image from userge import userge, Config, Message from userge.utils import progress @@ -29,18 +28,16 @@ async def save_thumb_nail(message: Message): start_t = datetime.now() c_time = time.time() - d_f_name = await userge.download_media(message=message.reply_to_message, - file_name=Config.DOWN_PATH, - progress=progress, - progress_args=( - "trying to download", message, c_time)) + await userge.download_media(message=message.reply_to_message, + file_name=Config.DOWN_PATH, + progress=progress, + progress_args=( + "trying to download", userge, message, c_time)) - Image.open(d_f_name).convert("RGB").save(THUMB_PATH, 'JPEG') - os.remove(d_f_name) end_t = datetime.now() - ms = (end_t - start_t).seconds + m_s = (end_t - start_t).seconds - await message.edit(f"thumbnail saved in {ms} seconds.", del_in=3) + await message.edit(f"thumbnail saved in {m_s} seconds.", del_in=3) else: await message.edit("Reply to a photo to save custom thumbnail", del_in=3) @@ -49,6 +46,7 @@ async def save_thumb_nail(message: Message): @userge.on_cmd('dthumb', about="__Delete thumbnail__") async def clear_thumb_nail(message: Message): await message.edit("`processing ...`") + if os.path.exists(THUMB_PATH): os.remove(THUMB_PATH) diff --git a/userge/plugins/misc/welcome.py b/userge/plugins/misc/welcome.py index 47b1a7f12..ea75ef74a 100644 --- a/userge/plugins/misc/welcome.py +++ b/userge/plugins/misc/welcome.py @@ -219,8 +219,8 @@ async def raw_say(message: Message, name, collection): kwargs = { **user_dict, 'chat': message.chat.title if message.chat.title else "this group", - 'mention': f"\ - {user_dict['uname'] or user_dict['flname']}", + 'mention': f"" + \ + f"{user_dict['uname'] or user_dict['flname']}", } await message.reply( diff --git a/userge/plugins/tools/repo.py b/userge/plugins/tools/repo.py new file mode 100644 index 000000000..0cac87ef0 --- /dev/null +++ b/userge/plugins/tools/repo.py @@ -0,0 +1,15 @@ +# Copyright (C) 2020 by UsergeTeam@Github, < https://github.com/UsergeTeam >. +# +# This file is part of < https://github.com/UsergeTeam/Userge > project, +# and is released under the "GNU v3.0 License Agreement". +# Please see < https://github.com/uaudith/Userge/blob/master/LICENSE > +# +# All rights reserved. + + +from userge import userge, Message, Config + + +@userge.on_cmd("repo", about="__get repo link__") +async def getplugins(message: Message): + await message.edit(f"**Hey**, __I am using__ 🥳 [Userge]({Config.OFFICIAL_REPO_LINK}) 😎") diff --git a/userge/plugins/utils/restart.py b/userge/plugins/utils/restart.py index fc65044c2..e0991f398 100644 --- a/userge/plugins/utils/restart.py +++ b/userge/plugins/utils/restart.py @@ -16,11 +16,11 @@ @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") + LOG.info("USERGE Services - Restart initiated") asyncio.create_task(restart(userge, m)) async def restart(c: userge, m: Message): await c.restart() - await m.edit(f"USERGE Services have been Restarted!") - LOG.info(f"USERGE - Restarted") + await m.edit("USERGE Services have been Restarted!") + LOG.info("USERGE - Restarted") diff --git a/userge/plugins/utils/ub.py b/userge/plugins/utils/ub.py index 0bfb9e47f..984e7a29d 100644 --- a/userge/plugins/utils/ub.py +++ b/userge/plugins/utils/ub.py @@ -43,8 +43,11 @@ async def urban_dict(message: Message): await message.err(text=f"No result found for **{query}**") return + meaning = '\n'.join([i['def'] for i in mean]) + example = '\n'.join([i['example'] for i in mean]) + output = f"**Query:** `{query}`\n\n\ -**Meaning:** __{mean[0]['def']}__\n\n\ -**Example:**\n__{mean[0]['example']}__" +**Meaning:**\n__{meaning}__\n\n\ +**Example:**\n__{example}__" await message.edit_or_send_as_file(text=output, caption=query) diff --git a/userge/plugins/utils/updater.py b/userge/plugins/utils/updater.py new file mode 100644 index 000000000..ecc582125 --- /dev/null +++ b/userge/plugins/utils/updater.py @@ -0,0 +1,150 @@ +# Copyright (C) 2020 by UsergeTeam@Github, < https://github.com/UsergeTeam >. +# +# This file is part of < https://github.com/UsergeTeam/Userge > project, +# and is released under the "GNU v3.0 License Agreement". +# Please see < https://github.com/uaudith/Userge/blob/master/LICENSE > +# +# All rights reserved. + + +import asyncio + +import heroku3 +from git import Repo +from git.exc import GitCommandError, InvalidGitRepositoryError, NoSuchPathError + +from userge import userge, Message, Config + +LOG = userge.getLogger(__name__) +CHANNEL = userge.getCLogger(__name__) + +ERROR_TEXT = "`Oops.. Updater cannot continue due to some problems occured`\n\n**LOGTRACE:**\n" + + +@userge.on_cmd("update", about="""\ +__Check Updates or Update Userge__ + +**Usage:** + + `.update` : check updates from default branch + `.update -dev` : check updates from dev branch + `.update -run` : run updater from default branch + `.update -run -dev` : run updater from dev branch""", del_pre=True) +async def check_update(message: Message): + """check or do updates""" + + await message.edit("`Checking for updates, please wait....`") + + try: + repo = Repo() + + except NoSuchPathError as error: + await CHANNEL.log(f'{ERROR_TEXT}\n`directory {error} is not found`') + await message.edit(f'{ERROR_TEXT}\n`directory {error} is not found`', del_in=5) + return + + except InvalidGitRepositoryError as error: + LOG.warn( + f'{ERROR_TEXT}\n`directory {error} does not seems to be a git repository`') + + repo = Repo.init() + + except GitCommandError as error: + await CHANNEL.log(f'{ERROR_TEXT}\n`Early failure! {error}`') + await message.edit(f'{ERROR_TEXT}\n`Early failure! {error}`', del_in=5) + return + + try: + repo.create_remote('upstream', Config.OFFICIAL_REPO_LINK) + except GitCommandError: + pass + + ups_rem = repo.remote('upstream') + flags = list(message.flags) + + if "run" in flags: + run_updater = True + flags.remove("run") + + else: + run_updater = False + + if len(flags) == 1: + branch = flags[0] + + else: + branch = repo.active_branch.name + + try: + ups_rem.fetch(branch) + except GitCommandError as error: + await CHANNEL.log(f'{ERROR_TEXT}\n`{error}`') + await message.edit(f'{ERROR_TEXT}\n`{error}`', del_in=5) + return + + repo.create_head(branch, getattr(ups_rem.refs, branch)) + getattr(repo.heads, branch).checkout(True) + + out = '' + for i in repo.iter_commits(f'HEAD..upstream/{branch}'): + out += f'•[{i.committed_datetime.strftime("%d/%m/%y")}]: {i.summary} <{i.author}>\n' + + if not out: + await CHANNEL.log(f'**Userge is up-to-date with [{branch}]**') + await message.edit(f'**Userge is up-to-date with [{branch}]**', del_in=5) + return + + if not run_updater: + changelog_str = f'**New UPDATE available for [{branch}]:\n\nCHANGELOG:**\n\n`{out}`' + await CHANNEL.log(changelog_str) + await message.edit_or_send_as_file(changelog_str) + + else: + await message.edit(f'`New update found for [{branch}], trying to update...`') + repo.git.reset('--hard', 'FETCH_HEAD') + + if Config.HEROKU_API_KEY: + heroku = heroku3.from_key(Config.HEROKU_API_KEY) + heroku_app = None + + for heroku_app in heroku.apps(): + if heroku_app and Config.HEROKU_APP_NAME and \ + heroku_app.name == Config.HEROKU_APP_NAME: + break + + if heroku_app: + await message.edit('`Heroku app found, trying to push update...`') + + heroku_git_url = heroku_app.git_url.replace( + "https://", + "https://api:" + Config.HEROKU_API_KEY + "@") + + if "heroku" in repo.remotes: + remote = repo.remote("heroku") + remote.set_url(heroku_git_url) + + else: + remote = repo.create_remote("heroku", heroku_git_url) + + remote.push(refspec=f"HEAD:refs/heads/{branch}") + + else: + await CHANNEL.log("please check your heroku app name") + await message.reply( + "no heroku application found for given name, but a key is given? 😕", del_in=3) + + await CHANNEL.log(f"**UPDATED Userge from [{branch}]:\n\nCHANGELOG:**\n\n`{out}`") + + await message.edit( + '**Userge Successfully Updated!**\n __Now restarting... Wait for a while!__`', del_in=3) + + asyncio.create_task(restart(userge)) + + +async def restart(client: userge): + """restart the client""" + + await client.restart() + + LOG.info("USERGE - Restarted") + await CHANNEL.log("Userge Restarted!") diff --git a/userge/utils/config.py b/userge/utils/config.py index 1d11d1222..a7f45f3f8 100644 --- a/userge/utils/config.py +++ b/userge/utils/config.py @@ -55,6 +55,12 @@ class Config: LOG_CHANNEL_ID = int(os.environ.get("LOG_CHANNEL_ID", 0)) + OFFICIAL_REPO_LINK = "https://github.com/UsergeTeam/Userge" + + HEROKU_API_KEY = os.environ.get("HEROKU_API_KEY", None) + + HEROKU_APP_NAME = os.environ.get("HEROKU_APP_NAME", None) + if not os.path.isdir(Config.DOWN_PATH): os.makedirs(Config.DOWN_PATH)