Skip to content

Commit

Permalink
trying to fix floadwait when getFullUser request and fixes client checks
Browse files Browse the repository at this point in the history
  • Loading branch information
rking32 committed Jul 9, 2020
1 parent a606f37 commit c95b4dc
Show file tree
Hide file tree
Showing 9 changed files with 88 additions and 66 deletions.
1 change: 1 addition & 0 deletions userge/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,7 @@ class Config:

if Config.LOAD_UNOFFICIAL_PLUGINS:
_LOG.info("Loading UnOfficial Plugins...")
# pylint: disable=BAN-B607
os.system("git clone --depth=1 https://github.com/UsergeTeam/Userge-Plugins.git")
os.system("pip3 install -U pip")
os.system("pip3 install -r Userge-Plugins/requirements.txt")
Expand Down
24 changes: 15 additions & 9 deletions userge/core/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,13 +48,6 @@ def uptime(self) -> str:
""" returns userge uptime """
return time_formatter(time.time() - _START_TIME)

@property
def bot(self) -> '_UsergeBot':
""" returns usergebot """
if self._bot is None:
raise UsergeBotNotFound("Need BOT_TOKEN ENV!")
return self._bot

async def finalize_load(self) -> None:
""" finalize the plugins load """
await asyncio.gather(_complete_init_tasks(), self.manager.init())
Expand Down Expand Up @@ -116,9 +109,10 @@ async def restart(self, update_req: bool = False) -> None: # pylint: disable=ar
_LOG.error(_LOG_STR, c_e)
if update_req:
_LOG.info(_LOG_STR, "Installing Requirements...")
# pylint: disable=BAN-B607
os.system("pip3 install -U pip")
os.system("pip3 install -r requirements.txt")
os.execl(sys.executable, sys.executable, '-m', 'userge')
os.execl(sys.executable, sys.executable, '-m', 'userge') # pylint: disable=BAN-B606
sys.exit()


Expand All @@ -128,6 +122,11 @@ def __init__(self, **kwargs) -> None:
_LOG.info(_LOG_STR, "Setting UsergeBot Configs")
super().__init__(session_name=":memory:", **kwargs)

@property
def ubot(self) -> 'Userge':
""" returns userbot """
return self._bot


class Userge(_AbstractUserge):
""" Userge, the userbot """
Expand All @@ -148,10 +147,17 @@ def __init__(self, **kwargs) -> None:
kwargs['bot_token'] = Config.BOT_TOKEN
if Config.HU_STRING_SESSION and Config.BOT_TOKEN:
RawClient.DUAL_MODE = True
kwargs['bot'] = _UsergeBot(**kwargs)
kwargs['bot'] = _UsergeBot(bot=self, **kwargs)
kwargs['session_name'] = Config.HU_STRING_SESSION or ":memory:"
super().__init__(**kwargs)

@property
def bot(self) -> '_UsergeBot':
""" returns usergebot """
if self._bot is None:
raise UsergeBotNotFound("Need BOT_TOKEN ENV!")
return self._bot

async def start(self) -> None:
""" start client and bot """
_LOG.info(_LOG_STR, "Starting Userge")
Expand Down
60 changes: 37 additions & 23 deletions userge/core/methods/decorators/raw_decorator.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,15 @@

__all__ = ['RawDecorator']

import time
import asyncio
from traceback import format_exc
from typing import List, Union, Any, Callable, Optional

from pyrogram import (
MessageHandler, Message as RawMessage, Filters,
StopPropagation, ContinuePropagation)
from pyrogram.errors.exceptions.bad_request_400 import (
ChatAdminRequired, UserNotParticipant, PeerIdInvalid)
from pyrogram.errors.exceptions.bad_request_400 import ChatAdminRequired, PeerIdInvalid

from userge import logging, Config
from ...ext import RawClient
Expand All @@ -28,6 +28,30 @@
_LOG_STR = "<<<! ::::: %s ::::: !>>>"

_PYROFUNC = Callable[['types.bound.Message'], Any]
_B_CMN_CHT: List[int] = []
_START_TO = time.time()
_B_ID = 0


async def _get_bot_chats(r_c: Union['_client.Userge', '_client._UsergeBot'],
r_m: RawMessage) -> List[int]:
global _START_TO, _B_ID # pylint: disable=global-statement
if isinstance(r_c, _client.Userge):
if round(time.time() - _START_TO) > 20:
if not _B_ID:
_B_ID = (await r_c.bot.get_me()).id
try:
chats = await r_c.get_common_chats(_B_ID)
_B_CMN_CHT.clear()
for chat in chats:
_B_CMN_CHT.append(chat.id)
except PeerIdInvalid:
pass
_START_TO = time.time()
else:
if r_m.chat.id not in _B_CMN_CHT:
_B_CMN_CHT.append(r_m.chat.id)
return _B_CMN_CHT


class RawDecorator(RawClient):
Expand Down Expand Up @@ -56,39 +80,29 @@ async def template(r_c: Union['_client.Userge', '_client._UsergeBot'],
r_m: RawMessage) -> None:
if RawClient.DUAL_MODE:
if check_client or (r_m.from_user and r_m.from_user.id in Config.SUDO_USERS):
try:
if Config.USE_USER_FOR_CLIENT_CHECKS:
# pylint: disable=protected-access
if Config.USE_USER_FOR_CLIENT_CHECKS:
assert isinstance(r_c, _client.Userge)
else:
bot_available = False
if isinstance(r_c, _client._UsergeBot):
return
else:
if r_m.chat.id in await _get_bot_chats(r_c, r_m):
if isinstance(r_c, _client.Userge):
try:
await r_m.chat.get_member((await r_c.bot.get_me()).id)
bot_available = True
except (UserNotParticipant, PeerIdInvalid):
pass
else:
bot_available = True
if bot_available:
assert isinstance(r_c, _client._UsergeBot)
else:
assert isinstance(r_c, _client.Userge)
except AssertionError:
return
return
if isinstance(flt, types.raw.Command) and r_m.chat and (r_m.chat.type not in scope):
try:
_sent = await r_m.reply(
_sent = await r_c.send_message(
r_m.chat.id,
"**ERROR** : `Sorry!, this command not supported "
f"in this chat type [{r_m.chat.type}] !`")
f"in this chat type [{r_m.chat.type}] !`",
reply_to_message_id=r_m.message_id)
await asyncio.sleep(5)
await _sent.delete()
except ChatAdminRequired:
pass
else:
try:
await func(types.bound.Message(r_c, r_m, **kwargs))
except (StopPropagation, ContinuePropagation):
except (StopPropagation, ContinuePropagation): # pylint: disable=PYL-W0706
raise
except Exception as f_e: # pylint: disable=broad-except
_LOG.exception(_LOG_STR, f_e)
Expand Down
4 changes: 2 additions & 2 deletions userge/plugins/fun/autopic.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@


async def _init() -> None:
global UPDATE_PIC
global UPDATE_PIC # pylint: disable=global-statement
data = await SAVED_SETTINGS.find_one({'_id': 'UPDATE_PIC'})
if data:
UPDATE_PIC = data['on']
Expand All @@ -41,7 +41,7 @@ async def _init() -> None:
'usage': "{tr}autopic\n{tr}autopic [image path]\nset timeout using {tr}sapicto"},
allow_channels=False, allow_via_bot=False)
async def autopic(message: Message):
global UPDATE_PIC
global UPDATE_PIC # pylint: disable=global-statement
await message.edit('`processing...`')
if UPDATE_PIC:
if isinstance(UPDATE_PIC, asyncio.Task):
Expand Down
2 changes: 1 addition & 1 deletion userge/plugins/fun/carbon.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ async def carbon_(message: Message):
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get(url)
await message.edit("`Processing... 40%`")
driver.command_executor._commands["send_command"] = (
driver.command_executor._commands["send_command"] = ( # pylint: disable=protected-access
"POST", '/session/$sessionId/chromium/send_command')
params = {
'cmd': 'Page.setDownloadBehavior',
Expand Down
47 changes: 24 additions & 23 deletions userge/plugins/misc/gdrive.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
import re
import time
import math
import pickle
import pickle # pylint: disable=BAN-B403
import asyncio
from json import dumps
from functools import wraps
Expand Down Expand Up @@ -49,14 +49,14 @@


async def _init() -> None:
global _CREDS
global _CREDS # pylint: disable=global-statement
_LOG.debug("Setting GDrive DBase...")
result = await _SAVED_SETTINGS.find_one({'_id': 'GDRIVE'}, {'creds': 1})
_CREDS = pickle.loads(result['creds']) if result else None
_CREDS = pickle.loads(result['creds']) if result else None # pylint: disable=BAN-B301


async def _set_creds(creds: object) -> str:
global _CREDS
global _CREDS # pylint: disable=global-statement
_LOG.info("Setting Creds...")
_CREDS = creds
result = await _SAVED_SETTINGS.update_one(
Expand All @@ -67,7 +67,7 @@ async def _set_creds(creds: object) -> str:


async def _clear_creds() -> str:
global _CREDS
global _CREDS # pylint: disable=global-statement
_CREDS = None
_LOG.info("Clearing Creds...")
if await _SAVED_SETTINGS.find_one_and_delete({'_id': 'GDRIVE'}):
Expand All @@ -92,6 +92,7 @@ async def wrapper(self):
await _refresh_creds()
await func(self)
else:
# pylint: disable=protected-access
await self._message.edit("Please run `.gsetup` first", del_in=5)
return wrapper

Expand Down Expand Up @@ -603,7 +604,7 @@ def _get_file_id(self, filter_str: bool = False) -> tuple:

async def setup(self) -> None:
""" Setup GDrive """
global _AUTH_FLOW
global _AUTH_FLOW # pylint: disable=global-statement
if _CREDS:
await self._message.edit("`Already Setup!`", del_in=5)
else:
Expand All @@ -619,7 +620,7 @@ async def setup(self) -> None:

async def confirm_setup(self) -> None:
""" Finalize GDrive setup """
global _AUTH_FLOW
global _AUTH_FLOW # pylint: disable=global-statement
if _AUTH_FLOW is None:
await self._message.edit("Please run `.gsetup` first", del_in=5)
return
Expand All @@ -641,7 +642,7 @@ async def clear(self) -> None:

async def set_parent(self) -> None:
""" Set Parent id """
global _PARENT_ID
global _PARENT_ID # pylint: disable=global-statement
file_id, file_type = self._get_file_id()
if file_type != "folder":
await self._message.err("Please send me a folder link")
Expand All @@ -652,7 +653,7 @@ async def set_parent(self) -> None:

async def reset_parent(self) -> None:
""" Reset parent id """
global _PARENT_ID
global _PARENT_ID # pylint: disable=global-statement
_PARENT_ID = ""
await self._message.edit("`Parents Reset successfully`", del_in=5)

Expand All @@ -665,7 +666,7 @@ async def share(self) -> None:
out = await pool.run_in_thread(self._get_output)(file_id)
except HttpError as h_e:
_LOG.exception(h_e)
await self._message.err(h_e._get_reason())
await self._message.err(h_e._get_reason()) # pylint: disable=protected-access
return
await self._message.edit(f"**Shareable Links**\n\n{out}",
disable_web_page_preview=True, log=__name__)
Expand All @@ -679,7 +680,7 @@ async def search(self) -> None:
self._message.filtered_input_str, self._message.flags)
except HttpError as h_e:
_LOG.exception(h_e)
await self._message.err(h_e._get_reason())
await self._message.err(h_e._get_reason()) # pylint: disable=protected-access
return
await self._message.edit_or_send_as_file(
out, disable_web_page_preview=True,
Expand All @@ -698,7 +699,7 @@ async def make_folder(self) -> None:
out = await self._create_drive_folder(self._message.input_str, self._parent_id)
except HttpError as h_e:
_LOG.exception(h_e)
await self._message.err(h_e._get_reason())
await self._message.err(h_e._get_reason()) # pylint: disable=protected-access
return
await self._message.edit(f"**Folder Created Successfully**\n\n{out}",
disable_web_page_preview=True, log=__name__)
Expand All @@ -719,7 +720,7 @@ async def list_folder(self) -> None:
out = await self._search('*', self._message.flags, file_id, root)
except HttpError as h_e:
_LOG.exception(h_e)
await self._message.err(h_e._get_reason())
await self._message.err(h_e._get_reason()) # pylint: disable=protected-access
return
await self._message.edit_or_send_as_file(
out, disable_web_page_preview=True, caption=f"list results for `{file_id}`")
Expand Down Expand Up @@ -829,7 +830,7 @@ async def upload(self) -> None:
end_t = datetime.now()
m_s = (end_t - start_t).seconds
if isinstance(self._output, HttpError):
out = f"**ERROR** : `{self._output._get_reason()}`"
out = f"**ERROR** : `{self._output._get_reason()}`" # pylint: disable=protected-access
elif self._output is not None and not self._is_canceled:
out = f"**Uploaded Successfully** __in {m_s} seconds__\n\n{self._output}"
elif self._output is not None and self._is_canceled:
Expand Down Expand Up @@ -859,7 +860,7 @@ async def download(self) -> None:
end_t = datetime.now()
m_s = (end_t - start_t).seconds
if isinstance(self._output, HttpError):
out = f"**ERROR** : `{self._output._get_reason()}`"
out = f"**ERROR** : `{self._output._get_reason()}`" # pylint: disable=protected-access
elif self._output is not None and not self._is_canceled:
out = f"**Downloaded Successfully** __in {m_s} seconds__\n\n`{self._output}`"
elif self._output is not None and self._is_canceled:
Expand Down Expand Up @@ -890,7 +891,7 @@ async def copy(self) -> None:
end_t = datetime.now()
m_s = (end_t - start_t).seconds
if isinstance(self._output, HttpError):
out = f"**ERROR** : `{self._output._get_reason()}`"
out = f"**ERROR** : `{self._output._get_reason()}`" # pylint: disable=protected-access
elif self._output is not None and not self._is_canceled:
out = f"**Copied Successfully** __in {m_s} seconds__\n\n{self._output}"
elif self._output is not None and self._is_canceled:
Expand All @@ -911,7 +912,7 @@ async def move(self) -> None:
link = await self._move(file_id)
except HttpError as h_e:
_LOG.exception(h_e)
await self._message.err(h_e._get_reason())
await self._message.err(h_e._get_reason()) # pylint: disable=protected-access
else:
await self._message.edit(
f"`{file_id}` **Moved Successfully**\n\n{link}", log=__name__)
Expand All @@ -925,7 +926,7 @@ async def delete(self) -> None:
await self._delete(file_id)
except HttpError as h_e:
_LOG.exception(h_e)
await self._message.err(h_e._get_reason())
await self._message.err(h_e._get_reason()) # pylint: disable=protected-access
else:
await self._message.edit(
f"`{file_id}` **Deleted Successfully**", del_in=5, log=__name__)
Expand All @@ -938,7 +939,7 @@ async def empty(self) -> None:
await self._empty_trash()
except HttpError as h_e:
_LOG.exception(h_e)
await self._message.err(h_e._get_reason())
await self._message.err(h_e._get_reason()) # pylint: disable=protected-access
else:
await self._message.edit(
"`Empty the Trash Successfully`", del_in=5, log=__name__)
Expand All @@ -952,7 +953,7 @@ async def get(self) -> None:
meta_data = await self._get(file_id)
except HttpError as h_e:
_LOG.exception(h_e)
await self._message.err(h_e._get_reason())
await self._message.err(h_e._get_reason()) # pylint: disable=protected-access
return
out = f"**I Found these Details for** `{file_id}`\n\n{meta_data}"
await self._message.edit_or_send_as_file(
Expand All @@ -968,7 +969,7 @@ async def get_perms(self) -> None:
out = await self._get_perms(file_id)
except HttpError as h_e:
_LOG.exception(h_e)
await self._message.err(h_e._get_reason())
await self._message.err(h_e._get_reason()) # pylint: disable=protected-access
return
out = f"**I Found these Permissions for** `{file_id}`\n\n{out}"
await self._message.edit_or_send_as_file(
Expand All @@ -984,7 +985,7 @@ async def set_perms(self) -> None:
link = await self._set_perms(file_id)
except HttpError as h_e:
_LOG.exception(h_e)
await self._message.err(h_e._get_reason())
await self._message.err(h_e._get_reason()) # pylint: disable=protected-access
else:
out = f"**Set Permissions successfully for** `{file_id}`\n\n{link}"
await self._message.edit(out, disable_web_page_preview=True)
Expand All @@ -998,7 +999,7 @@ async def del_perms(self) -> None:
out = await self._del_perms(file_id)
except HttpError as h_e:
_LOG.exception(h_e)
await self._message.err(h_e._get_reason())
await self._message.err(h_e._get_reason()) # pylint: disable=protected-access
return
out = f"**Removed These Permissions successfully from** `{file_id}`\n\n{out}"
await self._message.edit_or_send_as_file(
Expand Down
Loading

0 comments on commit c95b4dc

Please sign in to comment.