From c95b4dc50a3ada103a2f8b19622e3a0cfae8ea2c Mon Sep 17 00:00:00 2001 From: rking32 Date: Wed, 8 Jul 2020 23:54:57 +0530 Subject: [PATCH] trying to fix floadwait when getFullUser request and fixes client checks --- userge/config.py | 1 + userge/core/client.py | 24 +++++--- .../core/methods/decorators/raw_decorator.py | 60 ++++++++++++------- userge/plugins/fun/autopic.py | 4 +- userge/plugins/fun/carbon.py | 2 +- userge/plugins/misc/gdrive.py | 47 ++++++++------- userge/plugins/tools/alive.py | 2 +- userge/plugins/utils/afk.py | 6 +- userge/plugins/utils/pmpermit.py | 8 +-- 9 files changed, 88 insertions(+), 66 deletions(-) diff --git a/userge/config.py b/userge/config.py index 6f278f942..ef7c77345 100644 --- a/userge/config.py +++ b/userge/config.py @@ -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") diff --git a/userge/core/client.py b/userge/core/client.py index dc814bb43..6e2f8aa98 100644 --- a/userge/core/client.py +++ b/userge/core/client.py @@ -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()) @@ -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() @@ -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 """ @@ -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") diff --git a/userge/core/methods/decorators/raw_decorator.py b/userge/core/methods/decorators/raw_decorator.py index 483082702..5b31690bf 100644 --- a/userge/core/methods/decorators/raw_decorator.py +++ b/userge/core/methods/decorators/raw_decorator.py @@ -10,6 +10,7 @@ __all__ = ['RawDecorator'] +import time import asyncio from traceback import format_exc from typing import List, Union, Any, Callable, Optional @@ -17,8 +18,7 @@ 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 @@ -28,6 +28,30 @@ _LOG_STR = "<<>>" _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): @@ -56,31 +80,21 @@ 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: @@ -88,7 +102,7 @@ async def template(r_c: Union['_client.Userge', '_client._UsergeBot'], 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) diff --git a/userge/plugins/fun/autopic.py b/userge/plugins/fun/autopic.py index 6a84e362c..29de5b171 100644 --- a/userge/plugins/fun/autopic.py +++ b/userge/plugins/fun/autopic.py @@ -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'] @@ -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): diff --git a/userge/plugins/fun/carbon.py b/userge/plugins/fun/carbon.py index 4053cfdbf..9a2f97205 100644 --- a/userge/plugins/fun/carbon.py +++ b/userge/plugins/fun/carbon.py @@ -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', diff --git a/userge/plugins/misc/gdrive.py b/userge/plugins/misc/gdrive.py index a68ada2c7..76eed0878 100644 --- a/userge/plugins/misc/gdrive.py +++ b/userge/plugins/misc/gdrive.py @@ -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 @@ -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( @@ -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'}): @@ -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 @@ -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: @@ -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 @@ -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") @@ -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) @@ -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__) @@ -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, @@ -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__) @@ -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}`") @@ -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: @@ -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: @@ -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: @@ -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__) @@ -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__) @@ -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__) @@ -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( @@ -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( @@ -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) @@ -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( diff --git a/userge/plugins/tools/alive.py b/userge/plugins/tools/alive.py index 31183514e..b473adccd 100644 --- a/userge/plugins/tools/alive.py +++ b/userge/plugins/tools/alive.py @@ -36,7 +36,7 @@ async def alive(message: Message): async def refresh_id(): - global LOGO_STICKER_ID, LOGO_STICKER_REF + global LOGO_STICKER_ID, LOGO_STICKER_REF # pylint: disable=global-statement sticker = (await userge.get_messages('theUserge', 8)).sticker LOGO_STICKER_ID = sticker.file_id LOGO_STICKER_REF = sticker.file_ref diff --git a/userge/plugins/utils/afk.py b/userge/plugins/utils/afk.py index 218c0b5ee..b2ca799ae 100644 --- a/userge/plugins/utils/afk.py +++ b/userge/plugins/utils/afk.py @@ -27,7 +27,7 @@ async def _init() -> None: - global IS_AFK, REASON, TIME + global IS_AFK, REASON, TIME # pylint: disable=global-statement data = await SAVED_SETTINGS.find_one({'_id': 'AFK'}) if data: IS_AFK = data['on'] @@ -44,7 +44,7 @@ async def _init() -> None: 'usage': "{tr}afk or {tr}afk [reason]"}, allow_channels=False) async def active_afk(message: Message) -> None: """ turn on or off afk mode """ - global REASON, IS_AFK, TIME + global REASON, IS_AFK, TIME # pylint: disable=global-statement IS_AFK = True TIME = time.time() REASON = message.input_str @@ -110,7 +110,7 @@ async def handle_afk_incomming(message: Message) -> None: @userge.on_filters(IS_AFK_FILTER & Filters.outgoing, group=-1, allow_via_bot=False) async def handle_afk_outgoing(message: Message) -> None: """ handle outgoing messages when you afk """ - global IS_AFK + global IS_AFK # pylint: disable=global-statement IS_AFK = False afk_time = time_formatter(round(time.time() - TIME)) replied: Message = await message.reply("`I'm no longer AFK!`", log=__name__) diff --git a/userge/plugins/utils/pmpermit.py b/userge/plugins/utils/pmpermit.py index 2b9e0fc50..54494731e 100644 --- a/userge/plugins/utils/pmpermit.py +++ b/userge/plugins/utils/pmpermit.py @@ -27,7 +27,7 @@ async def _init() -> None: - global noPmMessage, blocked_message + global noPmMessage, blocked_message # pylint: disable=global-statement async for chat in ALLOWED_COLLECTION.find({"status": 'allowed'}): Config.ALLOWED_CHATS.add(chat.get("_id")) _pm = await SAVED_SETTINGS.find_one({'_id': 'PM GUARD STATUS'}) @@ -115,7 +115,7 @@ async def get_id(message: Message): allow_channels=False) async def pmguard(message: Message): """ enable or disable auto pm handler """ - global pmCounter + global pmCounter # pylint: disable=global-statement if Config.ALLOW_ALL_PMS: Config.ALLOW_ALL_PMS = False await message.edit("`PM_guard activated`", del_in=3, log=__name__) @@ -139,7 +139,7 @@ async def pmguard(message: Message): '{mention}': "mention user"}}, allow_channels=False) async def set_custom_nopm_message(message: Message): """ setup custom pm message """ - global noPmMessage + global noPmMessage # pylint: disable=global-statement await message.edit('`Custom NOpm message saved`', del_in=3, log=__name__) if message.reply_to_message: string = message.reply_to_message.text @@ -164,7 +164,7 @@ async def set_custom_nopm_message(message: Message): '{mention}': "mention user"}}, allow_channels=False) async def set_custom_blockpm_message(message: Message): """ setup custom blockpm message """ - global blocked_message + global blocked_message # pylint: disable=global-statement await message.edit('`Custom BLOCKpm message saved`', del_in=3, log=__name__) if message.reply_to_message: string = message.reply_to_message.text