Skip to content

Commit

Permalink
fix rmdir + add hash , base64 , telegraph
Browse files Browse the repository at this point in the history
  • Loading branch information
rking32 committed May 11, 2020
1 parent c770e4e commit d7f3c04
Show file tree
Hide file tree
Showing 11 changed files with 153 additions and 14 deletions.
2 changes: 2 additions & 0 deletions Aptfile
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
tree
wget
wget2
pv
jq
2 changes: 2 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ nest_asyncio
oauth2client
Pillow
psutil
pybase64
pymongo
pySmartDL
python-dotenv
Expand All @@ -25,6 +26,7 @@ search-engine-parser
selenium
setuptools>=40.3.0
speedtest-cli
telegraph
tgcrypto
urbandict==0.5
wget
Expand Down
4 changes: 2 additions & 2 deletions userge/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,8 +136,8 @@ class Config:
os.mkdir('bin')

_BINS = {
#"https://raw.githubusercontent.com/yshalsager/megadown/master/megadown":
#"bin/megadown", removed temporary
"https://raw.githubusercontent.com/yshalsager/megadown/master/megadown":
"bin/megadown",
"https://raw.githubusercontent.com/yshalsager/cmrudl.py/master/cmrudl.py":
"bin/cmrudl"}

Expand Down
16 changes: 14 additions & 2 deletions userge/core/ext/conv.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,9 @@

_CONV_DICT: Dict[int, asyncio.Queue] = {}


class _MsgLimitReached(Exception):
pass


class Conv:
"""Conversation class for userge"""
def __init__(self,
Expand Down Expand Up @@ -115,6 +113,20 @@ async def send_document(self, document: str) -> Optional[RawMessage]:
"""
return await self._client.send_document(chat_id=self._chat_id, document=document)

async def forward_message(self, message: RawMessage) -> RawMessage:
"""\nForward message to the conversation.
Parameters:
message (:obj: `Message`):
single message.
Returns:
On success, forwarded message is returned.
"""
return await self._client.forward_messages(chat_id=self._chat_id,
from_chat_id=message.chat.id,
message_ids=message.message_id)

@staticmethod
def init(client: '_client.Userge') -> None:
"""initialize the conversation method"""
Expand Down
4 changes: 1 addition & 3 deletions userge/plugins/fun/quote.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,7 @@ async def quotecmd(message: Message):
async with userge.conversation('QuotLyBot') as conv:
try:
if replied:
await userge.forward_messages(chat_id=conv.chat_id,
from_chat_id=message.chat.id,
message_ids=replied.message_id)
await conv.forward_message(replied)
else:
if not args:
await message.err('input not found!')
Expand Down
19 changes: 16 additions & 3 deletions userge/plugins/misc/pathlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -362,11 +362,21 @@ async def ls_dir(message: Message) -> None:
files = ''
for p_s in path_.iterdir():
if p_s.is_file():
if str(p_s).endswith((".mp3", ".flac", ".wav", ".m4a")):
files += '🎵'
elif str(p_s).endswith((".mkv", ".mp4", ".webm", ".avi", ".mov", ".flv")):
files += '📹'
elif str(p_s).endswith((".zip", ".tar", ".tar.gz", ".rar")):
files += '🗜'
elif str(p_s).endswith((".jpg", ".jpeg", ".png", ".gif", ".bmp", ".ico")):
files += '🖼'
else:
files += '📄'
size = os.stat(str(p_s)).st_size
files += f"📄 <code>{p_s.name}</code> <i>({humanbytes(size)})</i>\n"
files += f" <code>{p_s.name}</code> <i>({humanbytes(size)})</i>\n"
else:
folders += f"📁 <code>{p_s.name}</code>\n"
out += folders + files
out += (folders + files) or "<code>empty path!</code>"
else:
size = os.stat(str(path_)).st_size
out += f"📄 <code>{path_.name}</code> <i>({humanbytes(size)})</i>\n"
Expand Down Expand Up @@ -416,7 +426,10 @@ async def rmdir_(message: Message) -> None:
if not exists(path):
await message.err("file path not exists!")
return
rmtree(path)
if isfile(path):
os.remove(path)
else:
rmtree(path)
await message.edit(f"path : `{path}` **deleted** successfully!", del_in=5)


Expand Down
4 changes: 2 additions & 2 deletions userge/plugins/utils/direct_links.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,8 @@ async def direct_(message: Message):
# elif 'zippyshare.com' in link:
# reply += f" 👉 {zippy_share(link)}\n"

# elif 'mega.' in link:
# reply += f" 👉 {mega_dl(link)}\n"
elif 'mega.' in link:
reply += f" 👉 {mega_dl(link)}\n"

elif 'yadi.sk' in link:
reply += f" 👉 {yandex_disk(link)}\n"
Expand Down
54 changes: 54 additions & 0 deletions userge/plugins/utils/hash.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# 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 pybase64

from userge import userge, Message
from userge.utils import runcmd


@userge.on_cmd("hash", about={
'header': "find hash of text",
'description': "Find the md5, sha1, sha256, sha512 of the string when written into a txt file",
'usage': "{tr}hash [text or reply to msg]"})
async def gethash(message: Message):
input_ = message.input_or_reply_str
if not input_:
await message.err("input not found!")
return
with open("hash.txt", "w+") as hashtxt:
hashtxt.write(input_)
md5 = (await runcmd("md5sum hash.txt"))[0].split()[0]
sha1 = (await runcmd("sha1sum hash.txt"))[0].split()[0]
sha256 = (await runcmd("sha256sum hash.txt"))[0].split()[0]
sha512 = (await runcmd("sha512sum hash.txt"))[0].split()[0]
await runcmd("rm hash.txt")
ans = (f"**Text** : `{input_}`\n**MD5** : `{md5}`\n**SHA1** : `{sha1}`\n"
f"**SHA256** : `{sha256}`\n**SHA512** : `{sha512}`")
await message.edit_or_send_as_file(ans, filename="hash.txt", caption="hash.txt")


@userge.on_cmd("base64", about={
'header': "Find the base64 encoding of the given string",
'usage': "{tr}base64 [text or reply to msg] : encode\n"
"{tr}base64 -d [text or reply to msg] : decode"}, del_pre=True)
async def endecrypt(message: Message):
if message.reply_to_message:
input_ = message.reply_to_message.text
else:
input_ = message.filtered_input_str
if not input_:
await message.err("input not found!")
return
if 'd' in message.flags:
out = str(pybase64.b64decode(bytes(input_, "utf-8"), validate=True))[2:-1]
await message.edit(f"**Decoded** : `{out}`")
else:
out = str(pybase64.b64encode(bytes(input_, "utf-8")))[2:-1]
await message.edit(f"**Encoded** : `{out}`")
58 changes: 58 additions & 0 deletions userge/plugins/utils/telegraph.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# 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 os
import time

from telegraph import upload_file

from userge import userge, Message, Config
from userge.utils import progress

_T_LIMIT = 5242880


@userge.on_cmd("telegraph", about={
'header': "Upload file to Telegra.ph's servers",
'types': ['.jpg', '.jpeg', '.png', '.gif', '.mp4'],
'usage': "reply {tr}telegraph to supported media : limit 5MB"})
async def telegraph_(message: Message):
replied = message.reply_to_message
if not replied:
await message.err("reply to supported media")
return
if not ((replied.photo and replied.photo.file_size <= _T_LIMIT)
or (replied.animation and replied.animation.file_size <= _T_LIMIT)
or (replied.video and replied.video.file_name.endswith('.mp4')
and replied.video.file_size <= _T_LIMIT)
or (replied.document
and replied.document.file_name.endswith(
('.jpg', '.jpeg', '.png', '.gif', '.mp4'))
and replied.document.file_size <= _T_LIMIT)):
await message.err("not supported!")
return
await message.edit("`processing...`")
c_time = time.time()
dl_loc = 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
)
)
await message.edit("`uploading to telegraph...`")
try:
response = upload_file(dl_loc)
except Exception as t_e:
await message.err(t_e)
else:
await message.edit(f"**[Here Your Telegra.ph Link!](https://telegra.ph{response[0]})**")
finally:
os.remove(dl_loc)
2 changes: 1 addition & 1 deletion userge/utils/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ async def take_screen_shot(video_file: str, duration: int) -> Optional[str]:
ttl = duration // 2
thumb_image_path = f"{video_file}.jpg"
command = f"ffmpeg -ss {ttl} -i '{video_file}' -vframes 1 '{thumb_image_path}'"
_, err, _, _ = await runcmd(command)
err = (await runcmd(command))[1]
if err:
_LOG.error(err)
return thumb_image_path if os.path.exists(thumb_image_path) else None
Expand Down
2 changes: 1 addition & 1 deletion userge/versions.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
__version_mjaor__ = 0
__version_minor__ = 1
__version_micro__ = 4
__version_beta__ = 8
__version_beta__ = 9

__version__ = "{}.{}.{}".format(__version_mjaor__,
__version_minor__,
Expand Down

0 comments on commit d7f3c04

Please sign in to comment.