Skip to content

Commit

Permalink
this closes #83, closes #110, closes #125
Browse files Browse the repository at this point in the history
  • Loading branch information
rking32 authored and pull[bot] committed Aug 26, 2020
1 parent 661be96 commit 83cec9e
Show file tree
Hide file tree
Showing 7 changed files with 66 additions and 28 deletions.
1 change: 1 addition & 0 deletions userge/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion userge/core/types/raw/command.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 4 additions & 4 deletions userge/plugins/fun/autopic.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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())
Expand Down
1 change: 1 addition & 0 deletions userge/plugins/misc/gdrive.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
9 changes: 4 additions & 5 deletions userge/plugins/misc/upload.py
Original file line number Diff line number Diff line change
Expand Up @@ -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={
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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"):
Expand All @@ -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)


Expand Down
39 changes: 30 additions & 9 deletions userge/plugins/utils/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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 """
Expand Down Expand Up @@ -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': "<code>[name][buttonurl:link]</code> - <b>add a url button</b>\n"
"<code>[name][buttonurl:link:same]</code> - "
"<b>add a url button to same row</b>"},
Expand All @@ -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)
Expand All @@ -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,
Expand Down
34 changes: 25 additions & 9 deletions userge/plugins/utils/thumbnail.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]"})
Expand All @@ -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)
Expand All @@ -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')
Expand All @@ -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)
Expand Down

0 comments on commit 83cec9e

Please sign in to comment.