From dcfc13e8a23226ac6bec0796ba0878c4ca9206a8 Mon Sep 17 00:00:00 2001 From: rking32 Date: Sun, 23 Aug 2020 13:57:16 +0530 Subject: [PATCH] this closes #83, closes #110, closes #125 --- userge/config.py | 1 + userge/core/types/raw/command.py | 2 +- userge/plugins/fun/autopic.py | 8 +++---- userge/plugins/misc/gdrive.py | 1 + userge/plugins/misc/upload.py | 9 ++++--- userge/plugins/utils/filters.py | 39 ++++++++++++++++++++++++------- userge/plugins/utils/thumbnail.py | 34 ++++++++++++++++++++------- 7 files changed, 66 insertions(+), 28 deletions(-) diff --git a/userge/config.py b/userge/config.py index ba3cf67f7..4f0e1e559 100644 --- a/userge/config.py +++ b/userge/config.py @@ -64,6 +64,7 @@ class Config: HEROKU_GIT_URL = os.environ.get("HEROKU_GIT_URL", None) G_DRIVE_IS_TD = os.environ.get("G_DRIVE_IS_TD") == "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 MSG_DELETE_TIMEOUT = 120 diff --git a/userge/core/types/raw/command.py b/userge/core/types/raw/command.py index ddd6da925..d0357341b 100644 --- a/userge/core/types/raw/command.py +++ b/userge/core/types/raw/command.py @@ -60,7 +60,7 @@ def parse(cls, command: str, # pylint: disable=arguments-differ not (m.from_user and m.from_user.is_bot) and (m.outgoing or (m.from_user and m.from_user.is_self)) and not (m.chat and m.chat.type == "channel" and m.edit_date) - and (m.text.startswith(trigger) if trigger else True)) + and (m.text and m.text.startswith(trigger) if trigger else True)) incoming_flt = Filters.create( lambda _, m: not m.outgoing diff --git a/userge/plugins/fun/autopic.py b/userge/plugins/fun/autopic.py index 518af270a..3b4a53b19 100644 --- a/userge/plugins/fun/autopic.py +++ b/userge/plugins/fun/autopic.py @@ -47,8 +47,8 @@ async def autopic(message: Message): if isinstance(UPDATE_PIC, asyncio.Task): UPDATE_PIC.cancel() UPDATE_PIC = False - SAVED_SETTINGS.update_one({'_id': 'UPDATE_PIC'}, - {"$set": {'on': False}}, upsert=True) + await SAVED_SETTINGS.update_one({'_id': 'UPDATE_PIC'}, + {"$set": {'on': False}}, upsert=True) await asyncio.sleep(1) await message.edit('`setting old photo...`') await userge.set_profile_photo(photo=BASE_PIC) @@ -79,8 +79,8 @@ async def autopic(message: Message): async with aiofiles.open(BASE_PIC, "rb") as media_file: media = base64.b64encode(await media_file.read()) data_dict['media'] = media - SAVED_SETTINGS.update_one({'_id': 'UPDATE_PIC'}, - {"$set": data_dict}, upsert=True) + await SAVED_SETTINGS.update_one({'_id': 'UPDATE_PIC'}, + {"$set": data_dict}, upsert=True) await message.edit( 'auto profile picture updation has been **started**', del_in=3, log=__name__) UPDATE_PIC = asyncio.get_event_loop().create_task(apic_worker()) diff --git a/userge/plugins/misc/gdrive.py b/userge/plugins/misc/gdrive.py index ff6886f10..3c703af97 100644 --- a/userge/plugins/misc/gdrive.py +++ b/userge/plugins/misc/gdrive.py @@ -465,6 +465,7 @@ def _copy_dir(self, file_id: str, parent_id: str) -> str: new_id = self._copy_dir(file_['id'], dir_id) else: self._copy_file(file_['id'], parent_id) + time.sleep(0.5) # due to user rate limits new_id = parent_id return new_id diff --git a/userge/plugins/misc/upload.py b/userge/plugins/misc/upload.py index d581bfec1..20835d362 100644 --- a/userge/plugins/misc/upload.py +++ b/userge/plugins/misc/upload.py @@ -32,7 +32,6 @@ CHANNEL = userge.getCLogger(__name__) LOGO_PATH = 'resources/userge.png' -THUMB_PATH = Config.DOWN_PATH + "thumb_image.jpg" @userge.on_cmd("rename", about={ @@ -276,7 +275,7 @@ async def audio_upload(message: Message, path, del_path: bool = False, extra: st file_size = humanbytes(os.stat(strpath).st_size) try: album_art = stagger.read_tag(strpath) - if (album_art.picture and not os.path.lexists(THUMB_PATH)): + if (album_art.picture and not os.path.lexists(Config.THUMB_PATH)): bytes_pic_data = album_art[stagger.id3.APIC][0].data bytes_io = io.BytesIO(bytes_pic_data) image_file = Image.open(bytes_io) @@ -350,8 +349,8 @@ async def photo_upload(message: Message, path, del_path: bool = False, extra: st async def get_thumb(path: str = ''): - if os.path.exists(THUMB_PATH): - return THUMB_PATH + if os.path.exists(Config.THUMB_PATH): + return Config.THUMB_PATH if path: metadata = extractMetadata(createParser(path)) if metadata and metadata.has("duration"): @@ -364,7 +363,7 @@ async def get_thumb(path: str = ''): async def remove_thumb(thumb: str) -> None: if (thumb and os.path.exists(thumb) - and thumb != LOGO_PATH and thumb != THUMB_PATH): + and thumb != LOGO_PATH and thumb != Config.THUMB_PATH): os.remove(thumb) diff --git a/userge/plugins/utils/filters.py b/userge/plugins/utils/filters.py index 66e5addd1..6cd1cac26 100644 --- a/userge/plugins/utils/filters.py +++ b/userge/plugins/utils/filters.py @@ -19,6 +19,14 @@ FILTERS_DATA: Dict[int, Dict[str, int]] = {} FILTERS_CHATS = Filters.create(lambda _, query: query.chat.id in FILTERS_DATA) +_SUPPORTED_TYPES = (":audio:", ":video:", ":photo:", ":document:", + ":sticker:", ":animation:", ":game:", ":voice:", + ":video_note:", ":media:", ":contact:", ":media_group:", + ":location:", ":venue:", ":web_page:", ":poll:", + ":game_high_score:", ":via_bot:", ":service:", + ":mentioned:", ":edited:", ":new_chat_title:", + ":new_chat_photo:", ":delete_chat_photo:", ":pinned_message:") + def _filter_updater(chat_id: int, name: str, message_id: int) -> None: if chat_id in FILTERS_DATA: @@ -83,7 +91,7 @@ async def filters_active(message: Message) -> None: 'flags': { '-all': "remove all filters in this chat", '-every': "remove all filters in every chats"}, - 'usage': "{tr}delfilter [filter name]\n{tr}delfilter -all"}, + 'usage': "{tr}delfilter [filter name | filter type]\n{tr}delfilter -all"}, allow_channels=False, allow_bots=False) async def delete_filters(message: Message) -> None: """ delete filter in current chat """ @@ -125,7 +133,8 @@ async def delete_filters(message: Message) -> None: '{chat}': "chat name", '{count}': "chat members count", '{mention}': "mention user"}, - 'usage': "{tr}addfilter [filter name] | [content | reply to msg]", + 'usage': "{tr}addfilter [filter name | filter type] | [content | reply to msg]", + 'types': list(_SUPPORTED_TYPES), 'buttons': "[name][buttonurl:link] - add a url button\n" "[name][buttonurl:link:same] - " "add a url button to same row"}, @@ -138,7 +147,11 @@ async def add_filter(message: Message) -> None: if replied and replied.text: content = replied.text.html if not (content or (replied and replied.media)): - await message.err(text="No Content Found!") + await message.err("No Content Found !") + return + if (filter_.startswith(':') and filter_.endswith(':') + and filter_ not in _SUPPORTED_TYPES): + await message.err(f"invalid media type [ {filter_} ] !") return await message.edit("`adding filter ...`") message_id = await CHANNEL.store(replied, content) @@ -154,18 +167,26 @@ async def add_filter(message: Message) -> None: await message.edit(text=out, del_in=3, log=__name__) -@userge.on_filters(~Filters.me & ~Filters.edited & Filters.text & FILTERS_CHATS, group=1) +@userge.on_filters(~Filters.me & ~Filters.edited & FILTERS_CHATS, group=1) async def chat_filter(message: Message) -> None: """ filter handler """ if not message.from_user: return - input_text = message.text.strip() try: + reply = False for name in FILTERS_DATA[message.chat.id]: - if (input_text == name - or input_text.startswith(f"{name} ") - or input_text.endswith(f" {name}") - or f" {name} " in input_text): + if name.startswith(':') and name.endswith(':'): + media_type = name.strip(':') + if getattr(message, media_type, None): + reply = True + elif message.text: + input_text = message.text.strip() + if (input_text == name + or input_text.startswith(f"{name} ") + or input_text.endswith(f" {name}") + or f" {name} " in input_text): + reply = True + if reply: await CHANNEL.forward_stored(client=message.client, message_id=FILTERS_DATA[message.chat.id][name], chat_id=message.chat.id, diff --git a/userge/plugins/utils/thumbnail.py b/userge/plugins/utils/thumbnail.py index 548d443c0..61d43e3be 100644 --- a/userge/plugins/utils/thumbnail.py +++ b/userge/plugins/utils/thumbnail.py @@ -9,14 +9,25 @@ # All rights reserved. import os +import base64 from datetime import datetime -from userge import userge, Config, Message + +import aiofiles + +from userge import userge, Config, Message, get_collection from userge.utils import progress -THUMB_PATH = Config.DOWN_PATH + "thumb_image.jpg" +SAVED_SETTINGS = get_collection("CONFIGS") CHANNEL = userge.getCLogger(__name__) +async def _init() -> None: + data = await SAVED_SETTINGS.find_one({'_id': 'CUSTOM_THUMB'}) + if data and not os.path.exists(Config.THUMB_PATH): + with open(Config.THUMB_PATH, "wb") as thumb_file: + thumb_file.write(base64.b64decode(data['data'])) + + @userge.on_cmd('sthumb', about={ 'header': "Save thumbnail", 'usage': "{tr}sthumb [reply to any photo]"}) @@ -28,12 +39,16 @@ async def save_thumb_nail(message: Message): and (replied.photo or (replied.document and "image" in replied.document.mime_type))): start_t = datetime.now() - if os.path.exists(THUMB_PATH): - os.remove(THUMB_PATH) + if os.path.exists(Config.THUMB_PATH): + os.remove(Config.THUMB_PATH) await message.client.download_media(message=replied, - file_name=THUMB_PATH, + file_name=Config.THUMB_PATH, progress=progress, progress_args=(message, "trying to download")) + async with aiofiles.open(Config.THUMB_PATH, "rb") as thumb_file: + media = base64.b64encode(await thumb_file.read()) + await SAVED_SETTINGS.update_one({'_id': 'CUSTOM_THUMB'}, + {"$set": {'data': media}}, upsert=True) end_t = datetime.now() m_s = (end_t - start_t).seconds await message.edit(f"thumbnail saved in {m_s} seconds.", del_in=3) @@ -45,8 +60,9 @@ async def save_thumb_nail(message: Message): async def clear_thumb_nail(message: Message): """ delete thumbnail """ await message.edit("`processing ...`") - if os.path.exists(THUMB_PATH): - os.remove(THUMB_PATH) + if os.path.exists(Config.THUMB_PATH): + os.remove(Config.THUMB_PATH) + await SAVED_SETTINGS.find_one_and_delete({'_id': 'CUSTOM_THUMB'}) await message.edit("✅ Custom thumbnail deleted succesfully.", del_in=3) elif os.path.exists('resources/userge.png'): os.remove('resources/userge.png') @@ -59,9 +75,9 @@ async def clear_thumb_nail(message: Message): async def get_thumb_nail(message: Message): """ view current thumbnail """ await message.edit("processing ...") - if os.path.exists(THUMB_PATH): + if os.path.exists(Config.THUMB_PATH): msg = await message.client.send_document(chat_id=message.chat.id, - document=THUMB_PATH, + document=Config.THUMB_PATH, disable_notification=True, reply_to_message_id=message.message_id) await CHANNEL.fwd_msg(msg)