Skip to content

Commit

Permalink
fix kang [ 512 x 512 ] issue , gban via bot + minor fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
rking32 committed Aug 2, 2020
1 parent 01b6355 commit f8f9d18
Show file tree
Hide file tree
Showing 33 changed files with 180 additions and 174 deletions.
2 changes: 1 addition & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@ install:
before_script:
- mkdir -p logs
script:
- python test.py
- python -m tests
1 change: 0 additions & 1 deletion Aptfile
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,3 @@ wget2
pv
jq
p7zip-full
p7zip-rar
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ async def testing(message: Message):

## Requirements 🥴

* Python 3.7 or Higher 👻
* Python 3.8 or Higher 👻
* Telegram [API Keys](https://my.telegram.org/apps)
* Google Drive [API Keys](https://console.developers.google.com/)
* MongoDB [Database URL](https://cloud.mongodb.com/)
Expand Down
2 changes: 1 addition & 1 deletion genStr
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@
#
# All rights reserved.

python3 genStrSession.py
python3 tools/genStrSession.py
8 changes: 3 additions & 5 deletions init/checks.sh
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@ _checkBashReq() {

_checkPythonVersion() {
log "Checking Python Version ..."
test $(sed 's/\.//g' <<< $pVer) -lt 370 \
&& quit "You MUST have a python version of at least 3.7.0 !"
test $(sed 's/\.//g' <<< $pVer) -lt 380 \
&& quit "You MUST have a python version of at least 3.8.0 !"
log "\tFound PYTHON - v$pVer ..."
}

Expand Down Expand Up @@ -78,12 +78,10 @@ _checkDatabase() {
editLastMessage "Checking DATABASE_URL ..."
local err=$(runPythonCode '
import pymongo
try:
pymongo.MongoClient("'$DATABASE_URL'").list_database_names()
except Exception as e:
print(e)
')
print(e)')
[[ $err ]] && quit "pymongo response > $err" || log "\tpymongo response > {status : 200}"
}

Expand Down
3 changes: 2 additions & 1 deletion init/logbot/methods/methods.sh
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ printMessages() {
}

startLogBotPolling() {
_polling &
test -z $BOT_TOKEN || _polling &
}

_polling() {
Expand All @@ -63,6 +63,7 @@ _polling() {
log "unknown : < $cmd >"
test -z $cmd && break;;
esac
sleep 1
done
log "LogBot Polling Ended with SIGTERM !"
exit 0
Expand Down
2 changes: 1 addition & 1 deletion init/utils.sh
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
#
# All rights reserved.

declare -r pVer=$(sed -E 's/\w+ ([2-3])\.([0-9]+)\.([0-9]+)/\1.\2.\3/g' < <(python3 -V))
declare -r pVer=$(sed -E 's/\w+ ([2-3])\.([0-9]+)\.([0-9]+)/\1.\2.\3/g' < <(python3.8 -V))

log() {
local text="$*"
Expand Down
2 changes: 1 addition & 1 deletion runtime.txt
Original file line number Diff line number Diff line change
@@ -1 +1 @@
python-3.8.4
python-3.8.5
9 changes: 9 additions & 0 deletions tests/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# pylint: disable=missing-module-docstring
#
# 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.
File renamed without changes.
File renamed without changes.
2 changes: 1 addition & 1 deletion userge/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ class Config:
for heroku_app in heroku3.from_key(Config.HEROKU_API_KEY).apps():
if (heroku_app and Config.HEROKU_APP_NAME
and heroku_app.name == Config.HEROKU_APP_NAME):
LogBot.edit_last_msg("Heroku App : %s Found..." % heroku_app.name, _LOG.info)
_LOG.info("Heroku App : %s Found...", heroku_app.name)
Config.HEROKU_APP = heroku_app
break
LogBot.del_last_msg()
Expand Down
6 changes: 2 additions & 4 deletions userge/core/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,9 @@
_RUN = asyncio.get_event_loop().run_until_complete

if "Userge" in _RUN(_MGCLIENT.list_database_names()):
LogBot.reply_last_msg(
"Userge Database Found :) => Now Logging to it...", _LOG.info, _LOG_STR)
_LOG.info(_LOG_STR, "Userge Database Found :) => Now Logging to it...")
else:
LogBot.reply_last_msg(
"Userge Database Not Found :( => Creating New Database...", _LOG.info, _LOG_STR)
_LOG.info(_LOG_STR, "Userge Database Not Found :( => Creating New Database...")

_DATABASE: AgnosticDatabase = _MGCLIENT["Userge"]
_COL_LIST: List[str] = _RUN(_DATABASE.list_collection_names())
Expand Down
8 changes: 6 additions & 2 deletions userge/core/methods/decorators/on_cmd.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ def on_cmd(self,
allow_channels: bool = True,
allow_via_bot: bool = True,
check_client: bool = False,
check_downpath: bool = False,
**kwargs: Union[str, bool]
) -> RawDecorator._PYRORETTYPE:
"""\nDecorator for handling messages.
Expand Down Expand Up @@ -93,6 +94,9 @@ def on_cmd(self,
check_client (``bool``, *optional*):
If ``True``, check client is bot or not before execute, defaults to False.
check_downpath (``bool``, *optional*):
If ``True``, check downpath and make if not exist, defaults to False.
kwargs:
prefix (``str``, *optional*):
set prefix for flags, defaults to '-'.
Expand Down Expand Up @@ -143,5 +147,5 @@ def on_cmd(self,
and (m.text.startswith(Config.SUDO_TRIGGER) if trigger else True))
filters_ = filters_ & (outgoing_flt | incoming_flt)
return self._build_decorator(log=f"On {pattern}", filters=filters_, flt=cmd,
check_client=check_client and allow_via_bot,
scope=scope, **kwargs)
check_client=allow_via_bot and check_client,
check_downpath=check_downpath, scope=scope, **kwargs)
9 changes: 7 additions & 2 deletions userge/core/methods/decorators/on_filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ def on_filters(self,
filters: Filters,
group: int = 0,
allow_via_bot: bool = True,
check_client: bool = True) -> RawDecorator._PYRORETTYPE:
check_client: bool = True,
check_downpath: bool = False) -> RawDecorator._PYRORETTYPE:
"""\nDecorator for handling filters
Parameters:
Expand All @@ -37,8 +38,12 @@ def on_filters(self,
check_client (``bool``, *optional*):
If ``True``, check client is bot or not before execute, defaults to True.
check_downpath (``bool``, *optional*):
If ``True``, check downpath and make if not exist, defaults to False.
"""
flt = types.raw.Filter(self, group, allow_via_bot)
filters = Filters.create(lambda _, __: flt.is_enabled) & filters
return self._build_decorator(log=f"On Filters {filters}", filters=filters,
flt=flt, check_client=check_client and allow_via_bot)
flt=flt, check_client=allow_via_bot and check_client,
check_downpath=check_downpath)
9 changes: 7 additions & 2 deletions userge/core/methods/decorators/on_left_member.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ def on_left_member(self,
leaving_chats: Filters.chat,
group: int = -2,
allow_via_bot: bool = True,
check_client: bool = True) -> RawDecorator._PYRORETTYPE:
check_client: bool = True,
check_downpath: bool = False) -> RawDecorator._PYRORETTYPE:
"""\nDecorator for handling left members
Parameters:
Expand All @@ -36,7 +37,11 @@ def on_left_member(self,
check_client (``bool``, *optional*):
If ``True``, check client is bot or not before execute, defaults to True.
check_downpath (``bool``, *optional*):
If ``True``, check downpath and make if not exist, defaults to False.
"""
return self.on_filters(
filters=Filters.group & Filters.left_chat_member & leaving_chats,
group=group, allow_via_bot=allow_via_bot, check_client=check_client)
group=group, allow_via_bot=allow_via_bot,
check_client=check_client, check_downpath=check_downpath)
9 changes: 7 additions & 2 deletions userge/core/methods/decorators/on_new_member.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ def on_new_member(self,
welcome_chats: Filters.chat,
group: int = -2,
allow_via_bot: bool = True,
check_client: bool = True) -> RawDecorator._PYRORETTYPE:
check_client: bool = True,
check_downpath: bool = False) -> RawDecorator._PYRORETTYPE:
"""\nDecorator for handling new members
Parameters:
Expand All @@ -36,7 +37,11 @@ def on_new_member(self,
check_client (``bool``, *optional*):
If ``True``, check client is bot or not before execute, defaults to True.
check_downpath (``bool``, *optional*):
If ``True``, check downpath and make if not exist, defaults to False.
"""
return self.on_filters(
filters=Filters.group & Filters.new_chat_members & welcome_chats,
group=group, allow_via_bot=allow_via_bot, check_client=check_client)
group=group, allow_via_bot=allow_via_bot,
check_client=check_client, check_downpath=check_downpath)
8 changes: 7 additions & 1 deletion userge/core/methods/decorators/raw_decorator.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

__all__ = ['RawDecorator']

import os
import time
import asyncio
from traceback import format_exc
Expand Down Expand Up @@ -111,14 +112,16 @@ def __init__(self, **kwargs) -> None:
super().__init__(**kwargs)

def on_filters(self, filters: Filters, group: int = 0, allow_via_bot: bool = True,
check_client: bool = False) -> 'RawDecorator._PYRORETTYPE':
check_client: bool = False, check_downpath: bool = False
) -> 'RawDecorator._PYRORETTYPE':
""" abstract on filter method """

def _build_decorator(self,
log: str,
filters: Filters,
flt: Union['types.raw.Command', 'types.raw.Filter'],
check_client: bool,
check_downpath: bool,
scope: Optional[List[str]] = None,
**kwargs: Union[str, bool]
) -> 'RawDecorator._PYRORETTYPE':
Expand All @@ -142,6 +145,9 @@ async def template(r_c: Union['_client.Userge', '_client._UsergeBot'],
and 'admin' in scope and not await _is_admin(r_c, r_m)):
await _raise("`chat admin required`")
else:
if check_downpath:
if not os.path.isdir(Config.DOWN_PATH):
os.makedirs(Config.DOWN_PATH)
try:
await func(types.bound.Message(r_c, r_m, **kwargs))
except (StopPropagation, ContinuePropagation): # pylint: disable=W0706
Expand Down
20 changes: 18 additions & 2 deletions userge/core/types/bound/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,20 +62,36 @@ def client(self) -> Union['_client.Userge', '_client._UsergeBot']:
""" returns client """
return self._client

@property
def input_raw(self) -> str:
""" Returns the input string without command as raw """
input_ = self.text.html if hasattr(self.text, 'html') else self.text
if ' ' in input_ or '\n' in input_:
return str(input_.split(maxsplit=1)[1].strip())
return ''

@property
def input_str(self) -> str:
""" Returns the input string without command """
input_ = self.text.html if hasattr(self.text, 'html') else self.text
input_ = self.text
if ' ' in input_ or '\n' in input_:
return str(input_.split(maxsplit=1)[1].strip())
return ''

@property
def input_or_reply_raw(self) -> str:
""" Returns the input string or replied msg text without command as raw """
input_ = self.input_raw
if not input_ and self.reply_to_message:
input_ = (self.reply_to_message.text.html if self.reply_to_message.text else '').strip()
return input_

@property
def input_or_reply_str(self) -> str:
""" Returns the input string or replied msg text without command """
input_ = self.input_str
if not input_ and self.reply_to_message:
input_ = (self.reply_to_message.text.html if self.reply_to_message.text else '').strip()
input_ = (self.reply_to_message.text or '').strip()
return input_

@property
Expand Down
23 changes: 16 additions & 7 deletions userge/plugins/admin/gban.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,11 @@
WHITELIST = get_collection("WHITELIST_USER")
CHANNEL = userge.getCLogger(__name__)
LOG = userge.getLogger(__name__)
ADMEME_CHATS = []
PATHETIC_CHATS = []

U_ADMEME_CHATS = []
U_PATHETIC_CHATS = []
B_ADMEME_CHATS = []
B_PATHETIC_CHATS = []


async def me_can_restrict_members(message: Message, chat_id: int):
Expand Down Expand Up @@ -261,14 +264,20 @@ async def list_white(message: Message):
@userge.on_filters(Filters.group & Filters.new_chat_members & ~Filters.me, group=1)
async def gban_at_entry(message: Message):
""" handle gbans """
if message.client.is_bot:
admin_chats = B_ADMEME_CHATS
pathetic_chats = B_PATHETIC_CHATS
else:
admin_chats = U_ADMEME_CHATS
pathetic_chats = U_PATHETIC_CHATS
chat_id = message.chat.id
# Trying To Avoid Flood Waits
if chat_id not in ADMEME_CHATS + PATHETIC_CHATS:
if chat_id not in admin_chats + pathetic_chats:
if await me_can_restrict_members(message, chat_id):
ADMEME_CHATS.append(chat_id)
admin_chats.append(chat_id)
else:
PATHETIC_CHATS.append(chat_id)
if chat_id in PATHETIC_CHATS:
pathetic_chats.append(chat_id)
if chat_id in pathetic_chats:
return
for user in message.new_chat_members:
user_id = user.id
Expand All @@ -295,7 +304,7 @@ async def gban_at_entry(message: Message):
elif Config.ANTISPAM_SENTRY:
res = requests.get(f'https://api.cas.chat/check?user_id={user_id}').json()
if res['ok']:
reason = res['description'] if 'description' in res else None
reason = res['result']['messages'][0] if 'result' in res else None
await asyncio.gather(
message.client.kick_chat_member(chat_id, user_id),
message.reply(
Expand Down
10 changes: 3 additions & 7 deletions userge/plugins/fun/kang.py
Original file line number Diff line number Diff line change
Expand Up @@ -207,13 +207,9 @@ async def sticker_pack_info_(message: Message):
def resize_photo(photo: str) -> str:
""" Resize the given photo to 512x512 """
image = Image.open(photo)
maxsize = (512, 512)
if max(image.width, image.height) < 512:
scale = 512 / max(image.width, image.height)
new_size = (int(image.width * scale), int(image.height * scale))
image = image.resize(new_size, Image.ANTIALIAS)
else:
image.thumbnail(maxsize)
scale = 512 / max(image.width, image.height)
new_size = (int(image.width*scale), int(image.height*scale))
image = image.resize(new_size, Image.ANTIALIAS)
os.remove(photo)
photo = os.path.join(Config.DOWN_PATH, "sticker.png")
if os.path.exists(photo):
Expand Down
13 changes: 4 additions & 9 deletions userge/plugins/misc/download.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
# All rights reserved.

import os
import time
import math
import asyncio
from datetime import datetime
Expand All @@ -24,21 +23,17 @@
@userge.on_cmd("download", about={
'header': "Download files to server",
'usage': "{tr}download [url | reply to telegram media]",
'examples': "{tr}download https://speed.hetzner.de/100MB.bin | testing upload.bin"})
'examples': "{tr}download https://speed.hetzner.de/100MB.bin | testing upload.bin"},
check_downpath=True)
async def down_load_media(message: Message):
await message.edit("Trying to Download...")
if not os.path.isdir(Config.DOWN_PATH):
os.mkdir(Config.DOWN_PATH)
await message.edit("`Trying to Download...`")
if message.reply_to_message and message.reply_to_message.media:
start_t = datetime.now()
c_time = time.time()
dl_loc = await message.client.download_media(
message=message.reply_to_message,
file_name=Config.DOWN_PATH,
progress=progress,
progress_args=(
"trying to download", userge, message, c_time
)
progress_args=(message, "trying to download")
)
if message.process_is_canceled:
await message.edit("`Process Canceled!`", del_in=5)
Expand Down
Loading

0 comments on commit f8f9d18

Please sign in to comment.