pyrofork: Cleanup codes

Signed-off-by: wulan17 <wulan17@komodos.id>
This commit is contained in:
wulan17 2025-03-26 22:05:05 +07:00
parent f5296145cd
commit 3e24f006e0
No known key found for this signature in database
GPG key ID: 737814D4B5FF0420
99 changed files with 347 additions and 194 deletions

View file

@ -130,7 +130,7 @@ def get_type_hint(type: str) -> str:
return f"Optional[{type}] = None" if is_flag else type
else:
ns, name = type.split(".") if "." in type else ("", type)
type = f'"raw.base.' + ".".join([ns, name]).strip(".") + '"'
type = '"raw.base.' + ".".join([ns, name]).strip(".") + '"'
return f'{type}{" = None" if is_flag else ""}'
@ -430,11 +430,11 @@ def start(format: bool = False):
if function_docs:
docstring += function_docs["desc"] + "\n"
else:
docstring += f"Telegram API function."
docstring += "Telegram API function."
docstring += f"\n\n Details:\n - Layer: ``{layer}``\n - ID: ``{c.id[2:].upper()}``\n\n"
docstring += f" Parameters:\n " + \
(f"\n ".join(docstring_args) if docstring_args else "No parameters required.\n")
docstring += " Parameters:\n " + \
("\n ".join(docstring_args) if docstring_args else "No parameters required.\n")
if c.section == "functions":
docstring += "\n Returns:\n " + get_docstring_arg_type(c.qualtype)
@ -442,12 +442,12 @@ def start(format: bool = False):
references, count = get_references(c.qualname, "constructors")
if references:
docstring += f"\n Functions:\n This object can be returned by " \
docstring += "\n Functions:\n This object can be returned by " \
f"{count} function{'s' if count > 1 else ''}.\n\n" \
f" .. currentmodule:: pyrogram.raw.functions\n\n" \
f" .. autosummary::\n" \
f" :nosignatures:\n\n" \
f" " + references
" .. currentmodule:: pyrogram.raw.functions\n\n" \
" .. autosummary::\n" \
" :nosignatures:\n\n" \
" " + references
write_types = read_types = "" if c.has_flags else "# No flags\n "

View file

@ -449,7 +449,7 @@ def pyrogram_api():
fmt_keys = {}
for k, v in categories.items():
name, *methods = get_title_list(v)
_, *methods = get_title_list(v)
fmt_keys.update({k: "\n ".join("{0} <{0}>".format(m) for m in methods)})
for method in methods:
@ -740,7 +740,7 @@ def pyrogram_api():
fmt_keys = {}
for k, v in categories.items():
name, *types = get_title_list(v)
_, *types = get_title_list(v)
fmt_keys.update({k: "\n ".join(types)})

View file

@ -29,7 +29,7 @@ from pygments.styles.friendly import FriendlyStyle
FriendlyStyle.background_color = "#f3f2f1"
project = "Pyrofork"
copyright = f"2022-present, Mayuri-Chan"
copyright = "2022-present, Mayuri-Chan"
author = "Mayuri-Chan"
version = ".".join(__version__.split(".")[:-1])

View file

@ -37,8 +37,24 @@ class ContinuePropagation(StopAsyncIteration):
pass
from . import raw, types, filters, handlers, emoji, enums
from .client import Client
from .sync import idle, compose
from . import raw, types, filters, handlers, emoji, enums # pylint: disable=wrong-import-position
from .client import Client # pylint: disable=wrong-import-position
from .sync import idle, compose # pylint: disable=wrong-import-position
crypto_executor = ThreadPoolExecutor(1, thread_name_prefix="CryptoWorker")
__all__ = [
"Client",
"idle",
"compose",
"crypto_executor",
"StopTransmission",
"StopPropagation",
"ContinuePropagation",
"raw",
"types",
"filters",
"handlers",
"emoji",
"enums",
]

View file

@ -33,7 +33,7 @@ from importlib import import_module
from io import StringIO, BytesIO
from mimetypes import MimeTypes
from pathlib import Path
from typing import Union, List, Optional, Callable, AsyncGenerator, Type, Tuple
from typing import Union, List, Optional, Callable, AsyncGenerator, Tuple
import pyrogram
from pyrogram import __version__, __license__
@ -51,24 +51,26 @@ from pyrogram.handlers.handler import Handler
from pyrogram.methods import Methods
from pyrogram.session import Auth, Session
from pyrogram.storage import FileStorage, MemoryStorage, Storage
from pyrogram.types import User, TermsOfService
from pyrogram.utils import ainput
from .connection import Connection
from .connection.transport import TCPAbridged
from .dispatcher import Dispatcher
from .file_id import FileId, FileType, ThumbnailSource
from .mime_types import mime_types
from .parser import Parser
from .session.internals import MsgId
log = logging.getLogger(__name__)
MONGO_AVAIL = False
try:
import pymongo
except Exception:
pass
else:
from pyrogram.storage import MongoStorage
from pyrogram.types import User, TermsOfService
from pyrogram.utils import ainput
from .connection import Connection
from .connection.transport import TCP, TCPAbridged
from .dispatcher import Dispatcher
from .file_id import FileId, FileType, ThumbnailSource
from .filters import Filter
from .mime_types import mime_types
from .parser import Parser
from .session.internals import MsgId
log = logging.getLogger(__name__)
MONGO_AVAIL = True
class Client(Methods):
@ -316,9 +318,7 @@ class Client(Methods):
elif self.in_memory:
self.storage = MemoryStorage(self.name)
elif self.mongodb:
try:
import pymongo
except Exception:
if not MONGO_AVAIL:
log.warning(
"pymongo is missing! "
"Using MemoryStorage as session storage"
@ -888,7 +888,7 @@ class Client(Methods):
count = 0
if not include:
for current_root, dirnames, filenames in os.walk(root.replace(".", "/")):
for current_root, _, filenames in os.walk(root.replace(".", "/")):
namespace = current_root.replace("/", ".").replace("\\", ".")
if "__pycache__" in namespace:
continue
@ -953,7 +953,7 @@ class Client(Methods):
)
count += 1
except Exception as e:
except Exception:
pass
else:
for path, handlers in include:
@ -1042,7 +1042,7 @@ class Client(Methods):
)
count += 1
except Exception as e:
except Exception:
pass
if handlers is None:
@ -1106,7 +1106,7 @@ class Client(Methods):
async def handle_download(self, packet):
file_id, directory, file_name, in_memory, file_size, progress, progress_args = packet
os.makedirs(directory, exist_ok=True) if not in_memory else None
_ = os.makedirs(directory, exist_ok=True) if not in_memory else None
temp_file_path = os.path.abspath(re.sub("\\\\", "/", os.path.join(directory, file_name))) + ".temp"
file = BytesIO() if in_memory else open(temp_file_path, "wb")

View file

@ -18,3 +18,7 @@
# along with Pyrofork. If not, see <http://www.gnu.org/licenses/>.
from .connection import Connection
__all__ = [
"Connection"
]

View file

@ -52,7 +52,7 @@ class Connection:
self.protocol: Optional[TCP] = None
async def connect(self) -> None:
for i in range(Connection.MAX_CONNECTION_ATTEMPTS):
for _ in range(Connection.MAX_CONNECTION_ATTEMPTS):
self.protocol = self.protocol_factory(ipv6=self.ipv6, proxy=self.proxy)
try:

View file

@ -23,3 +23,13 @@ from .tcp_abridged_o import TCPAbridgedO
from .tcp_full import TCPFull
from .tcp_intermediate import TCPIntermediate
from .tcp_intermediate_o import TCPIntermediateO
__all__ = [
"TCP",
"Proxy",
"TCPAbridged",
"TCPAbridgedO",
"TCPFull",
"TCPIntermediate",
"TCPIntermediateO"
]

View file

@ -21,7 +21,6 @@ import asyncio
import ipaddress
import logging
import socket
from concurrent.futures import ThreadPoolExecutor
from typing import Tuple, Dict, TypedDict, Optional
import socks

View file

@ -71,7 +71,7 @@ def unpack(
message = Message.read(data)
except KeyError as e:
if e.args[0] == 0:
raise ConnectionError(f"Received empty data. Check your internet connection.")
raise ConnectionError("Received empty data. Check your internet connection.")
left = data.read().hex()

View file

@ -55,7 +55,7 @@ def decompose(pq: int) -> int:
while g == 1:
x = y
for i in range(r):
for _ in range(r):
y = (pow(y, 2, pq) + c) % pq
k = 0
@ -63,7 +63,7 @@ def decompose(pq: int) -> int:
while k < r and g == 1:
ys = y
for i in range(min(m, r - k)):
for _ in range(min(m, r - k)):
y = (pow(y, 2, pq) + c) % pq
q = q * (abs(x - y)) % pq

View file

@ -23,7 +23,7 @@ import logging
from collections import OrderedDict
import pyrogram
from pyrogram import errors, raw, types, utils
from pyrogram import raw, types, utils
from pyrogram.handlers.handler import Handler
from pyrogram.handlers import (
BotBusinessConnectHandler,
@ -266,7 +266,7 @@ class Dispatcher:
async def start(self):
if not self.client.no_updates:
for i in range(self.client.workers):
for _ in range(self.client.workers):
self.locks_list.append(asyncio.Lock())
self.handler_worker_tasks.append(

View file

@ -35,13 +35,13 @@ class ChatEventAction(AutoName):
"The linked chat has been changed (see ``old_linked_chat`` and ``new_linked_chat``)"
# LOCATION_CHANGED = auto()
""
# ""
PHOTO_CHANGED = auto()
"The chat photo has been changed (see ``old_photo`` and ``new_photo``)"
# STICKER_SET_CHANGED = auto()
""
# ""
TITLE_CHANGED = auto()
"the chat title has been changed (see ``old_title`` and ``new_title``)"
@ -56,7 +56,7 @@ class ChatEventAction(AutoName):
"a message has been deleted (see ``deleted_message``)"
# VOICE_CHAT_DISCARDED = auto()
""
# ""
MESSAGE_EDITED = auto()
"a message has been edited (see ``old_message`` and ``new_message``)"
@ -77,13 +77,13 @@ class ChatEventAction(AutoName):
"a member joined by themselves. (see ``user``)"
# MEMBER_JOINED_BY_LINK = auto()
""
# ""
MEMBER_LEFT = auto()
"a member left by themselves. (see ``user``)"
# MEMBER_MUTED = auto()
""
# ""
ADMINISTRATOR_PRIVILEGES_CHANGED = auto()
"a chat member has been promoted/demoted or their administrator privileges has changed (see ``old_administrator_privileges`` and ``new_administrator_privileges``)"
@ -92,19 +92,19 @@ class ChatEventAction(AutoName):
"a chat member has been restricted/unrestricted or banned/unbanned, or their permissions has changed (see ``old_member_permissions`` and ``new_member_permissions``)"
# MEMBER_UNMUTED = auto()
""
# ""
# MEMBER_VOLUME_CHANGED = auto()
""
# ""
# VIDEO_CHAT_STARTED = auto()
""
# ""
POLL_STOPPED = auto()
"a poll has been stopped (see ``stopped_poll``)"
# VOICE_CHAT_SETTINGS_CHANGED = auto()
""
# ""
INVITES_ENABLED = auto()
"the chat invitation has been enabled or disabled (see ``invites_enabled``)"

View file

@ -65,3 +65,11 @@ class CDNFileHashMismatch(SecurityError):
def __init__(self, msg: str = None):
super().__init__("A CDN file hash mismatch has occurred." if msg is None else msg)
__all__ = [
"BadMsgNotification",
"SecurityError",
"SecurityCheckMismatch",
"CDNFileHashMismatch",
"UnknownError"
]

View file

@ -33,7 +33,6 @@ from .error_handler import ErrorHandler
from .inline_query_handler import InlineQueryHandler
from .message_handler import MessageHandler
from .poll_handler import PollHandler
from .pre_checkout_query_handler import PreCheckoutQueryHandler
from .purchased_paid_media_handler import PurchasedPaidMediaHandler
from .raw_update_handler import RawUpdateHandler
from .user_status_handler import UserStatusHandler
@ -42,3 +41,31 @@ from .message_reaction_updated_handler import MessageReactionUpdatedHandler
from .message_reaction_count_updated_handler import MessageReactionCountUpdatedHandler
from .pre_checkout_query_handler import PreCheckoutQueryHandler
from .shipping_query_handler import ShippingQueryHandler
__all__ = [
"BotBusinessConnectHandler",
"BotBusinessMessageHandler",
"CallbackQueryHandler",
"ChatJoinRequestHandler",
"ChatMemberUpdatedHandler",
"ConversationHandler",
"ChosenInlineResultHandler",
"DeletedMessagesHandler",
"DeletedBotBusinessMessagesHandler",
"DisconnectHandler",
"EditedMessageHandler",
"EditedBotBusinessMessageHandler",
"ErrorHandler",
"InlineQueryHandler",
"MessageHandler",
"PollHandler",
"PreCheckoutQueryHandler",
"PurchasedPaidMediaHandler",
"RawUpdateHandler",
"UserStatusHandler",
"StoryHandler",
"MessageReactionUpdatedHandler",
"MessageReactionCountUpdatedHandler",
"PreCheckoutQueryHandler",
"ShippingQueryHandler",
]

View file

@ -61,6 +61,7 @@ class ConversationHandler(MessageHandler, CallbackQueryHandler):
return True
@staticmethod
# pylint: disable=method-hidden
async def callback(_, __):
pass

View file

@ -58,5 +58,4 @@ class DeletedBotBusinessMessagesHandler(Handler):
for message in messages:
if await super().check(client, message):
return True
else:
return False

View file

@ -58,5 +58,4 @@ class DeletedMessagesHandler(Handler):
for message in messages:
if await super().check(client, message):
return True
else:
return False

View file

@ -14,3 +14,14 @@ You should have received a copy of the GNU General Public License
along with pyromod. If not, see <https://www.gnu.org/licenses/>.
"""
from .helpers import ikb, bki, ntb, btn, kb, kbtn, array_chunk, force_reply
__all__ = [
"ikb",
"bki",
"ntb",
"btn",
"kb",
"kbtn",
"array_chunk",
"force_reply"
]

View file

@ -101,9 +101,9 @@ def kb(rows=None, **kwargs):
line = []
for button in row:
button_type = type(button)
if button_type == str:
if isinstance(button_type, str):
button = KeyboardButton(button)
elif button_type == dict:
elif isinstance(button_type, dict):
button = KeyboardButton(**button)
line.append(button)

View file

@ -23,7 +23,6 @@ import inspect
import io
import logging
import math
import os
from hashlib import md5
from pathlib import PurePath
from typing import Union, BinaryIO, Callable

View file

@ -35,6 +35,7 @@ class Connect:
Raises:
ConnectionError: In case you try to connect an already connected client.
"""
# pylint: disable=access-member-before-definition
if self.is_connected:
raise ConnectionError("Client is already connected")

View file

@ -30,6 +30,7 @@ class Disconnect:
ConnectionError: In case you try to disconnect an already disconnected client or in case you try to
disconnect a client that needs to be terminated first.
"""
# pylint: disable=access-member-before-definition
if not self.is_connected:
raise ConnectionError("Client is already disconnected")

View file

@ -16,8 +16,6 @@
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrogram. If not, see <http://www.gnu.org/licenses/>.
from typing import List
import pyrogram
from pyrogram import raw, types

View file

@ -41,6 +41,7 @@ class Initialize:
if not self.is_connected:
raise ConnectionError("Can't initialize a disconnected client")
# pylint: disable=access-member-before-definition
if self.is_initialized:
raise ConnectionError("Client is already initialized")

View file

@ -61,6 +61,7 @@ class SendCode:
)
)
except (PhoneMigrate, NetworkMigrate) as e:
# pylint: disable=access-member-before-definition
await self.session.stop()
await self.storage.dc_id(e.value)

View file

@ -58,6 +58,7 @@ class SignInBot:
)
)
except UserMigrate as e:
# pylint: disable=access-member-before-definition
await self.session.stop()
await self.storage.dc_id(e.value)

View file

@ -37,6 +37,7 @@ class Terminate:
Raises:
ConnectionError: In case you try to terminate a client that is already terminated.
"""
# pylint: disable=access-member-before-definition
if not self.is_initialized:
raise ConnectionError("Client is already terminated")

View file

@ -16,11 +16,8 @@
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrogram. If not, see <http://www.gnu.org/licenses/>.
from datetime import datetime
from typing import Union, List
import pyrogram
from pyrogram import types, utils, raw
from pyrogram import types, raw
class GetBusinessConnection:

View file

@ -117,5 +117,4 @@ class BanChatMember:
{i.id: i for i in r.users},
{i.id: i for i in r.chats}
)
else:
return True

View file

@ -15,9 +15,9 @@
#
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrofork. If not, see <http://www.gnu.org/licenses/>.
import pyrogram
from pyrogram import raw
from pyrogram import types
from typing import Union

View file

@ -15,9 +15,9 @@
#
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrofork. If not, see <http://www.gnu.org/licenses/>.
import pyrogram
from pyrogram import raw
from pyrogram import types
from typing import Union

View file

@ -15,9 +15,9 @@
#
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrofork. If not, see <http://www.gnu.org/licenses/>.
import pyrogram
from pyrogram import raw
from pyrogram import types
from typing import Union

View file

@ -15,9 +15,9 @@
#
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrofork. If not, see <http://www.gnu.org/licenses/>.
import pyrogram
from pyrogram import raw
from pyrogram import types
from typing import Union

View file

@ -15,9 +15,9 @@
#
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrofork. If not, see <http://www.gnu.org/licenses/>.
import pyrogram
from pyrogram import raw
from pyrogram import types
from typing import Union

View file

@ -77,7 +77,6 @@ class GetChatMember:
else:
if member.user.id == user.user_id:
return member
else:
raise UserNotParticipant
elif isinstance(chat, raw.types.InputPeerChannel):
r = await self.invoke(

View file

@ -23,7 +23,6 @@ from typing import Union, Optional, AsyncGenerator
import pyrogram
from pyrogram import raw
from pyrogram import types
from pyrogram import utils
log = logging.getLogger(__name__)

View file

@ -23,7 +23,6 @@ from typing import Union, List, Iterable
import pyrogram
from pyrogram import raw
from pyrogram import types
from pyrogram import utils
log = logging.getLogger(__name__)
@ -63,7 +62,7 @@ class GetForumTopicsByID:
Raises:
ValueError: In case of invalid arguments.
"""
ids, ids_type = (
ids, _ = (
(topic_ids, int) if topic_ids
else (None, None)
)

View file

@ -17,7 +17,6 @@
# along with Pyrofork. If not, see <http://www.gnu.org/licenses/>.
import pyrogram
from pyrogram import raw
from pyrogram import types
from typing import Union

View file

@ -15,9 +15,9 @@
#
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrofork. If not, see <http://www.gnu.org/licenses/>.
import pyrogram
from pyrogram import raw
from pyrogram import types
from typing import Union

View file

@ -15,9 +15,9 @@
#
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrofork. If not, see <http://www.gnu.org/licenses/>.
import pyrogram
from pyrogram import raw
from pyrogram import types
from typing import Union

View file

@ -164,5 +164,4 @@ class SetChatPhoto:
{i.id: i for i in r.users},
{i.id: i for i in r.chats}
)
else:
return True

View file

@ -15,9 +15,9 @@
#
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrofork. If not, see <http://www.gnu.org/licenses/>.
import pyrogram
from pyrogram import raw
from pyrogram import types
from typing import Union

View file

@ -16,7 +16,7 @@
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrogram. If not, see <http://www.gnu.org/licenses/>.
from typing import Callable, Optional, Union
from typing import Callable
import pyrogram
from pyrogram.filters import Filter

View file

@ -180,8 +180,12 @@ class CopyMediaGroup:
**await self.parser.parse(
captions[i] if isinstance(captions, list) and i < len(captions) and captions[i] else
captions if isinstance(captions, str) and i == 0 else
message.caption if message.caption and message.caption != "None" and not type(
captions) is str else "")
message.caption if (
message.caption
and message.caption != "None"
and not isinstance(captions, str)
) else ""
)
)
)

View file

@ -104,7 +104,7 @@ class GetMessages:
is_iterable = not isinstance(ids, int)
ids = list(ids) if is_iterable else [ids]
ids = [ids_type(id=i) for i in ids]
ids = [ids_type(id=i) for i in ids] # pylint: disable=not-callable
if replies < 0:
replies = (1 << 31) - 1

View file

@ -16,7 +16,6 @@
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrofork. If not, see <http://www.gnu.org/licenses/>.
import re
from datetime import datetime
from typing import Union, List, Optional

View file

@ -17,9 +17,6 @@
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrofork. If not, see <http://www.gnu.org/licenses/>.
from typing import Union
import pyrogram
from pyrogram import raw

View file

@ -17,11 +17,10 @@
# along with Pyrofork. If not, see <http://www.gnu.org/licenses/>.
import logging
from typing import Union, List, Iterable
from typing import Union, Iterable
import pyrogram
from pyrogram import raw
from pyrogram import types
log = logging.getLogger(__name__)

View file

@ -222,14 +222,13 @@ class EditStory:
if caption:
text, entities = self._split(**await utils.parse_text_entities(self, caption, parse_mode, caption_entities))
'''
if allowed_chats and len(allowed_chats) > 0:
chats = [int(str(chat_id)[3:]) if str(chat_id).startswith("-100") else chat_id for chat_id in allowed_chats]
privacy_rules.append(raw.types.InputPrivacyValueAllowChatParticipants(chats=chats))
if denied_chats and len(denied_chats) > 0:
chats = [int(str(chat_id)[3:]) if str(chat_id).startswith("-100") else chat_id for chat_id in denied_chats]
privacy_rules.append(raw.types.InputPrivacyValueDisallowChatParticipants(chats=chats))
'''
#if allowed_chats and len(allowed_chats) > 0:
# chats = [int(str(chat_id)[3:]) if str(chat_id).startswith("-100") else chat_id for chat_id in allowed_chats]
# privacy_rules.append(raw.types.InputPrivacyValueAllowChatParticipants(chats=chats))
#if denied_chats and len(denied_chats) > 0:
# chats = [int(str(chat_id)[3:]) if str(chat_id).startswith("-100") else chat_id for chat_id in denied_chats]
# privacy_rules.append(raw.types.InputPrivacyValueDisallowChatParticipants(chats=chats))
if allowed_users and len(allowed_users) > 0:
users = [await self.resolve_peer(user_id) for user_id in allowed_users]
privacy_rules.append(raw.types.InputPrivacyValueAllowUsers(users=users))

View file

@ -213,14 +213,13 @@ class SendStory:
text, entities = self._split(**await utils.parse_text_entities(self, caption, parse_mode, caption_entities))
'''
if allowed_chats and len(allowed_chats) > 0:
chats = [await self.resolve_peer(chat_id) for chat_id in allowed_chats]
privacy_rules.append(raw.types.InputPrivacyValueAllowChatParticipants(chats=chats))
if denied_chats and len(denied_chats) > 0:
chats = [await self.resolve_peer(chat_id) for chat_id in denied_chats]
privacy_rules.append(raw.types.InputPrivacyValueDisallowChatParticipants(chats=chats))
'''
#if allowed_chats and len(allowed_chats) > 0:
# chats = [await self.resolve_peer(chat_id) for chat_id in allowed_chats]
# privacy_rules.append(raw.types.InputPrivacyValueAllowChatParticipants(chats=chats))
#if denied_chats and len(denied_chats) > 0:
# chats = [await self.resolve_peer(chat_id) for chat_id in denied_chats]
# privacy_rules.append(raw.types.InputPrivacyValueDisallowChatParticipants(chats=chats))
if allowed_users and len(allowed_users) > 0:
users = [await self.resolve_peer(user_id) for user_id in allowed_users]
privacy_rules.append(raw.types.InputPrivacyValueAllowUsers(users=users))

View file

@ -18,3 +18,7 @@
# along with Pyrofork. If not, see <http://www.gnu.org/licenses/>.
from .pagination import Pagination
__all__ = [
"Pagination"
]

View file

@ -18,3 +18,7 @@
# along with Pyrofork. If not, see <http://www.gnu.org/licenses/>.
from .parser import Parser
__all__ = [
"Parser"
]

View file

@ -18,7 +18,6 @@
# along with Pyrofork. If not, see <http://www.gnu.org/licenses/>.
import html
import logging
import re
from typing import Optional
@ -251,7 +250,7 @@ class Markdown:
# Handle multiline blockquotes
text_subset = text[s:e]
lines = text_subset.splitlines()
for line_num, line in enumerate(lines):
for line_num, _ in enumerate(lines):
line_start = s + sum(len(l) + 1 for l in lines[:line_num])
if entity.collapsed:
insert_at.append((line_start, i, BLOCKQUOTE_EXPANDABLE_DELIM))

View file

@ -25,3 +25,11 @@ from .all import objects
for k, v in objects.items():
path, name = v.rsplit(".", 1)
objects[k] = getattr(import_module(path), name)
__all__ = [
"types",
"functions",
"base",
"core",
"objects"
]

View file

@ -30,3 +30,24 @@ from .primitives.int import Int, Long, Int128, Int256
from .primitives.string import String
from .primitives.vector import Vector
from .tl_object import TLObject
__all__ = [
"FutureSalt",
"FutureSalts",
"GzipPacked",
"List",
"Message",
"MsgContainer",
"Bool",
"BoolFalse",
"BoolTrue",
"Bytes",
"Double",
"Int",
"Long",
"Int128",
"Int256",
"String",
"Vector",
"TLObject"
]

View file

@ -23,3 +23,17 @@ from .double import Double
from .int import Int, Long, Int128, Int256
from .string import String
from .vector import Vector
__all__ = [
"Bool",
"BoolFalse",
"BoolTrue",
"Bytes",
"Double",
"Int",
"Long",
"Int128",
"Int256",
"String",
"Vector"
]

View file

@ -19,3 +19,8 @@
from .auth import Auth
from .session import Session
__all__ = [
"Auth",
"Session"
]

View file

@ -20,3 +20,9 @@
from .data_center import DataCenter
from .msg_factory import MsgFactory
from .msg_id import MsgId
__all__ = [
"DataCenter",
"MsgFactory",
"MsgId"
]

View file

@ -19,10 +19,20 @@
from .file_storage import FileStorage
from .memory_storage import MemoryStorage
MONGO_AVAIL = False
try:
import pymongo
except Exception:
pass
else:
MONGO_AVAIL = True
from .mongo_storage import MongoStorage
from .storage import Storage
__all__ = [
"FileStorage",
"MemoryStorage",
"Storage"
]
if MONGO_AVAIL:
__all__.append("MongoStorage")

View file

@ -30,3 +30,8 @@ from .update import *
from .user_and_chats import *
from .payments import *
from .pyromod import *
__all__ = [
"List",
"Object"
]

View file

@ -18,8 +18,7 @@
from typing import List
import pyrogram
from pyrogram import raw, types, utils
from pyrogram import raw, types
from ..object import Object

View file

@ -20,6 +20,7 @@
import pyrogram
from pyrogram import raw, utils
from pyrogram import types
from typing import Dict
from ..object import Object
@ -52,7 +53,11 @@ class GameHighScore(Object):
self.position = position
@staticmethod
def _parse(client, game_high_score: raw.types.HighScore, users: dict) -> "GameHighScore":
def _parse(
client,
game_high_score: raw.types.HighScore,
users: Dict[int, "raw.types.User"]
) -> "GameHighScore":
users = {i.id: i for i in users}
return GameHighScore(
@ -63,7 +68,11 @@ class GameHighScore(Object):
)
@staticmethod
def _parse_action(client, service: raw.types.MessageService, users: dict):
def _parse_action(
client,
service: raw.types.MessageService,
users: Dict[int, "raw.types.User"]
) -> "GameHighScore":
return GameHighScore(
user=types.User._parse(client, users[utils.get_raw_peer_id(service.from_id or service.peer_id)]),
score=service.action.score,

View file

@ -17,7 +17,7 @@
# along with Pyrofork. If not, see <http://www.gnu.org/licenses/>.
from ..object import Object
from pyrogram import enums, raw, types
from pyrogram import raw, types
from typing import Union, List
class RequestedChats(Object):

View file

@ -17,7 +17,7 @@
# along with Pyrofork. If not, see <http://www.gnu.org/licenses/>.
from ..object import Object
from pyrogram import enums, raw, types
from pyrogram import raw, types
from typing import Union
class RequestedUser(Object):

View file

@ -17,9 +17,6 @@
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrogram. If not, see <http://www.gnu.org/licenses/>.
from typing import List
import pyrogram
from pyrogram import raw, types
from ..object import Object

View file

@ -19,6 +19,7 @@
import pyrogram
from pyrogram import raw, types
from typing import Dict
from ..object import Object
from ..update import Update
@ -62,7 +63,7 @@ class ShippingQuery(Object, Update):
async def _parse(
client: "pyrogram.Client",
shipping_query: "raw.types.UpdateBotShippingQuery",
users: dict
users: Dict[int, "raw.types.User"]
) -> "types.PreCheckoutQuery":
# Try to decode pre-checkout query payload into string. If that fails, fallback to bytes instead of decoding by
# ignoring/replacing errors, this way, button clicks will still work.

View file

@ -17,7 +17,7 @@
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrofork. If not, see <http://www.gnu.org/licenses/>.
from typing import List, Match
from typing import List, Match, Dict
import pyrogram
from pyrogram import raw
@ -78,7 +78,11 @@ class InlineQuery(Object, Update):
self.matches = matches
@staticmethod
def _parse(client, inline_query: raw.types.UpdateBotInlineQuery, users: dict) -> "InlineQuery":
def _parse(
client,
inline_query: raw.types.UpdateBotInlineQuery,
users: Dict[int, "raw.types.User"]
) -> "InlineQuery":
peer_type = inline_query.peer_type
chat_type = None

View file

@ -22,7 +22,7 @@ from typing import List
import pyrogram
from pyrogram import raw, utils
from pyrogram import types
from pyrogram.file_id import FileId, FileType, FileUniqueId, FileUniqueType, ThumbnailSource
from pyrogram.file_id import FileId, FileType, FileUniqueId, FileUniqueType
from ..object import Object

View file

@ -17,7 +17,6 @@
# along with Pyrofork. If not, see <http://www.gnu.org/licenses/>.
from pyrogram import raw
from typing import List
from ..object import Object
class ExportedStoryLink(Object):

View file

@ -16,12 +16,10 @@
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrofork. If not, see <http://www.gnu.org/licenses/>.
import asyncio
import pyrogram
from datetime import datetime
from pyrogram import raw, types, utils
from pyrogram.errors import FloodWait
from ..object import Object
from typing import List, Dict

View file

@ -16,7 +16,7 @@
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrofork. If not, see <http://www.gnu.org/licenses/>.
from pyrogram import types, raw
from pyrogram import raw
from ..object import Object

View file

@ -20,7 +20,7 @@
import logging
from datetime import datetime
from functools import partial
from typing import List, Match, Union, BinaryIO, Optional, Callable
from typing import List, Match, Union, BinaryIO, Optional, Callable, Dict
import pyrogram
from pyrogram import enums, raw, types, utils
@ -690,9 +690,9 @@ class Message(Object, Update):
async def _parse(
client: "pyrogram.Client",
message: raw.base.Message,
users: dict,
chats: dict,
topics: dict = None,
users: Dict[int, "raw.types.User"],
chats: Dict[int, "raw.types.Chat"],
topics: Dict[int, "raw.types.ForumTopic"] = None,
is_scheduled: bool = False,
business_connection_id: str = None,
replies: int = 1

View file

@ -17,7 +17,7 @@
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrofork. If not, see <http://www.gnu.org/licenses/>.
from typing import Optional
from typing import Optional, Dict
import pyrogram
from pyrogram import raw, enums
@ -82,7 +82,11 @@ class MessageEntity(Object):
self.collapsed = collapsed
@staticmethod
def _parse(client, entity: "raw.base.MessageEntity", users: dict) -> Optional["MessageEntity"]:
def _parse(
client,
entity: "raw.base.MessageEntity",
users: Dict[int, "raw.types.User"] = None
) -> Optional["MessageEntity"]:
# Special case for InputMessageEntityMentionName -> MessageEntityType.TEXT_MENTION
# This happens in case of UpdateShortSentMessage inside send_message() where entities are parsed from the input
if isinstance(entity, raw.types.InputMessageEntityMentionName):

View file

@ -17,7 +17,7 @@
# along with PyroFork. If not, see <http://www.gnu.org/licenses/>.
import pyrogram
from pyrogram import raw, types, utils
from pyrogram import raw, utils
from datetime import datetime
from ..object import Object

View file

@ -145,7 +145,7 @@ class Sticker(Object):
Sticker.cache[(set_id, set_access_hash)] = name
if len(Sticker.cache) > 250:
for i in range(50):
for _ in range(50):
Sticker.cache.pop(next(iter(Sticker.cache)))
return name

View file

@ -16,11 +16,8 @@
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrofork. If not, see <http://www.gnu.org/licenses/>.
from typing import List, Optional, Union
import pyrogram
from pyrogram import raw
from pyrogram.file_id import FileId, FileType, FileUniqueId, FileUniqueType, ThumbnailSource
from ..object import Object

View file

@ -193,6 +193,7 @@ class Story(Object, Update):
animation = None
photo = None
video = None
media_type = None
chat = None
from_user = None
sender_chat = None
@ -268,14 +269,13 @@ class Story(Object, Update):
elif isinstance(priv, raw.types.PrivacyValueDisallowContacts):
privacy = enums.StoryPrivacy.NO_CONTACTS
'''
if allowed_chats and len(allowed_chats) > 0:
chats = [int(str(chat_id)[3:]) if str(chat_id).startswith("-100") else chat_id for chat_id in allowed_chats]
privacy_rules.append(raw.types.InputPrivacyValueAllowChatParticipants(chats=chats))
if denied_chats and len(denied_chats) > 0:
chats = [int(str(chat_id)[3:]) if str(chat_id).startswith("-100") else chat_id for chat_id in denied_chats]
privacy_rules.append(raw.types.InputPrivacyValueDisallowChatParticipants(chats=chats))
'''
#if allowed_chats and len(allowed_chats) > 0:
# chats = [int(str(chat_id)[3:]) if str(chat_id).startswith("-100") else chat_id for chat_id in allowed_chats]
# privacy_rules.append(raw.types.InputPrivacyValueAllowChatParticipants(chats=chats))
#if denied_chats and len(denied_chats) > 0:
# chats = [int(str(chat_id)[3:]) if str(chat_id).startswith("-100") else chat_id for chat_id in denied_chats]
# privacy_rules.append(raw.types.InputPrivacyValueDisallowChatParticipants(chats=chats))
if isinstance(priv, raw.types.PrivacyValueAllowUsers):
allowed_users = priv.users
if isinstance(priv, raw.types.PrivacyValueDisallowUsers):

View file

@ -57,7 +57,7 @@ class TranscribedAudio(Object):
self.trial_remains_until_date = trial_remains_until_date
@staticmethod
def _parse(transcribe_result: "raw.types.messages.TranscribedAudio") -> "TranscribeAudio":
def _parse(transcribe_result: "raw.types.messages.TranscribedAudio") -> "TranscribedAudio":
return TranscribedAudio(
transcription_id=transcribe_result.transcription_id,
text=transcribe_result.text,

View file

@ -19,7 +19,6 @@
from typing import List
import pyrogram
from pyrogram import raw, types
from ..object import Object

View file

@ -22,7 +22,7 @@ from typing import List
import pyrogram
from pyrogram import raw, types, utils
from pyrogram.file_id import FileId, FileType, FileUniqueId, FileUniqueType, ThumbnailSource
from pyrogram.file_id import FileId, FileType, FileUniqueId, FileUniqueType
from ..object import Object

View file

@ -17,9 +17,7 @@
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrofork. If not, see <http://www.gnu.org/licenses/>.
import pyrogram
from pyrogram import raw
from pyrogram import types
from ..object import Object

View file

@ -17,7 +17,6 @@
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrofork. If not, see <http://www.gnu.org/licenses/>.
import pyrogram
from pyrogram import raw
from pyrogram import types
from ..object import Object

View file

@ -18,7 +18,7 @@
# along with Pyrofork. If not, see <http://www.gnu.org/licenses/>.
from datetime import datetime
from typing import List, Optional, Union
from typing import List, Optional, Union, Dict
import pyrogram
from pyrogram import raw, types, utils
@ -226,7 +226,7 @@ class Gift(Object):
self.raw = raw
@staticmethod
async def _parse(client, gift, users={}, chats={}):
async def _parse(client, gift, users=None, chats=None):
if isinstance(gift, raw.types.StarGift):
return await Gift._parse_regular(client, gift)
elif isinstance(gift, raw.types.StarGiftUnique):
@ -263,8 +263,8 @@ class Gift(Object):
async def _parse_unique(
client,
star_gift: "raw.types.StarGiftUnique",
users: dict = {},
chats: dict = {}
users: Dict[int, "raw.types.User"] = None,
chats: Dict[int, "raw.types.Chat"] = None
) -> "Gift":
owner_id = utils.get_raw_peer_id(getattr(star_gift, "owner_id", None))
return Gift(
@ -273,7 +273,7 @@ class Gift(Object):
title=star_gift.title,
collectible_id=star_gift.num,
attributes=types.List(
[await types.GiftAttribute._parse(client, attr, users, chats) for attr in star_gift.attributes]
[await types.GiftAttribute._parse(client, attr, users) for attr in star_gift.attributes]
) or None,
available_amount=getattr(star_gift, "availability_issued", None),
total_amount=getattr(star_gift, "availability_total", None),
@ -289,8 +289,8 @@ class Gift(Object):
async def _parse_saved(
client,
saved_gift: "raw.types.SavedStarGift",
users: dict = {},
chats: dict = {}
users: Dict[int, "raw.types.User"] = None,
chats: Dict[int, "raw.types.Chat"] = None
) -> "Gift":
caption, caption_entities = (
utils.parse_text_with_entities(
@ -324,8 +324,8 @@ class Gift(Object):
async def _parse_action(
client,
message: "raw.base.Message",
users: dict = {},
chats: dict = {}
users: Dict[int, "raw.types.User"] = None,
chats: Dict[int, "raw.types.Chat"] = None
) -> "Gift":
action = message.action # type: raw.types.MessageActionStarGift

View file

@ -18,7 +18,7 @@
# along with Pyrofork. If not, see <http://www.gnu.org/licenses/>.
from datetime import datetime
from typing import List, Optional
from typing import List, Optional, Dict
import pyrogram
from pyrogram import enums, raw, types, utils
@ -119,8 +119,7 @@ class GiftAttribute(Object):
async def _parse(
client,
attr: "raw.base.StarGiftAttribute",
users: dict,
chats: dict
users: Dict[int, "raw.types.User"]
) -> "GiftAttribute":
caption = None
caption_entities = None

View file

@ -19,7 +19,8 @@
import pyrogram
from ..object import Object
from pyrogram import types, utils
from pyrogram import raw, types, utils
from typing import Dict
class GiftCode(Object):
@ -78,7 +79,11 @@ class GiftCode(Object):
self.crypto_amount = crypto_amount
@staticmethod
def _parse(client: "pyrogram.Client", gift_code: "types.GiftCode", chats: dict,) -> "GiftCode":
def _parse(
client: "pyrogram.Client",
gift_code: "types.GiftCode",
chats: Dict[int, "raw.types.Chat"]
) -> "GiftCode":
boosted_chat = None
boosted_chat_raw = chats.get(utils.get_raw_peer_id(gift_code.boost_peer), None)
if boosted_chat_raw:

View file

@ -17,9 +17,7 @@
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrofork. If not, see <http://www.gnu.org/licenses/>.
from random import choice
from pyrogram import raw, types
from pyrogram import raw
from ..object import Object

View file

@ -16,8 +16,6 @@
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrofork. If not, see <http://www.gnu.org/licenses/>.
import pyrogram
from pyrogram import raw
from ..object import Object

View file

@ -16,9 +16,7 @@
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrofork. If not, see <http://www.gnu.org/licenses/>.
import pyrogram
from pyrogram import raw, types, utils
from pyrogram import raw
from ..object import Object

View file

@ -107,7 +107,7 @@ class PaymentForm(Object):
bot=types.User._parse(client, users.get(payment_form.bot_id)),
title=payment_form.title,
description=payment_form.description,
invoice=types.Invoice._parse(client, payment_form.invoice),
invoice=types.Invoice._parse(payment_form.invoice),
provider=types.User._parse(client, users.get(getattr(payment_form, "provider_id", None))),
url=getattr(payment_form, "url", None),
can_save_credentials=getattr(payment_form, "can_save_credentials", None),

View file

@ -17,6 +17,8 @@
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrofork. If not, see <http://www.gnu.org/licenses/>.
from pyrogram import types
from ..object import Object

View file

@ -18,6 +18,7 @@
from datetime import datetime
from pyrogram import raw, types, utils
from typing import Dict
from ..object import Object
class StarsTransaction(Object):
@ -100,7 +101,7 @@ class StarsTransaction(Object):
def _parse(
client,
transaction: "raw.types.StarsTransaction",
users: dict
users: Dict[int, "raw.types.User"]
) -> "StarsTransaction":
chat_id = utils.get_raw_peer_id(transaction.peer.peer)
chat = types.User._parse(client, users.get(chat_id, None))

View file

@ -17,6 +17,8 @@
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrofork. If not, see <http://www.gnu.org/licenses/>.
import pyrogram
from pyrogram import raw
from pyrogram import types
from ..object import Object

View file

@ -16,10 +16,7 @@
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrofork. If not, see <http://www.gnu.org/licenses/>.
from typing import Optional, Union
from pyrogram import raw
from pyrogram import enums
from ..object import Object

View file

@ -16,7 +16,7 @@
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrofork. If not, see <http://www.gnu.org/licenses/>.
from typing import Optional
from typing import Optional, Dict
from pyrogram import types, raw
from ..object import Object
@ -62,7 +62,7 @@ class BusinessInfo(Object):
def _parse(
client,
user: "raw.types.UserFull" = None,
users: dict = None
users: Dict[int, "raw.types.User"] = None
) -> Optional["BusinessInfo"]:
working_hours = getattr(user, "business_work_hours", None)
location = getattr(user, "business_location", None)

View file

@ -17,7 +17,7 @@
# along with Pyrofork. If not, see <http://www.gnu.org/licenses/>.
from datetime import datetime
from typing import Optional, Union, List
from typing import Optional, Union, List, Dict
from pyrogram import types, enums, raw, utils
from ..object import Object
@ -83,7 +83,7 @@ class BusinessMessage(Object):
def _parse(
client,
message: Union["raw.types.BusinessGreetingMessage", "raw.types.BusinessAwayMessage"] = None,
users: dict = None
users: Dict[int, "raw.types.User"] = None
) -> Optional["BusinessMessage"]:
if not message:
return None

View file

@ -16,7 +16,7 @@
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrofork. If not, see <http://www.gnu.org/licenses/>.
from typing import List
from typing import List, Dict
from pyrogram import types, raw
from ..object import Object
@ -66,7 +66,7 @@ class BusinessRecipients(Object):
def _parse(
client,
recipients: "raw.types.BusinessRecipients",
users: dict = None
users: Dict[int, "raw.types.User"] = None
) -> "BusinessRecipients":
return BusinessRecipients(
existing_chats=getattr(recipients, "existing_chats", None),

View file

@ -18,7 +18,7 @@
# along with Pyrofork. If not, see <http://www.gnu.org/licenses/>.
from datetime import datetime
from typing import Union, List, Optional, AsyncGenerator, BinaryIO
from typing import Union, List, Optional, AsyncGenerator, BinaryIO, Dict
import pyrogram
from pyrogram import raw, enums
@ -434,8 +434,8 @@ class Chat(Object):
def _parse(
client,
message: Union[raw.types.Message, raw.types.MessageService],
users: dict,
chats: dict,
users: Dict[int, "raw.types.User"],
chats: Dict[int, "raw.types.Chat"],
is_chat: bool
) -> "Chat":
from_id = utils.get_raw_peer_id(message.from_id)
@ -451,7 +451,16 @@ class Chat(Object):
return Chat._parse_channel_chat(client, chats[chat_id])
@staticmethod
def _parse_dialog(client, peer, users: dict, chats: dict):
def _parse_dialog(
client,
peer: Union[
raw.types.PeerUser,
raw.types.PeerChat,
raw.types.PeerChannel
],
users: Dict[int, "raw.types.User"],
chats: Dict[int, "raw.types.Chat"]
) -> "Chat":
if isinstance(peer, raw.types.PeerUser):
return Chat._parse_user_chat(client, users[peer.user_id])
elif isinstance(peer, raw.types.PeerChat):

View file

@ -16,8 +16,7 @@
# You should have received a copy of the GNU Lesser General Public License
# along with Pyrofork. If not, see <http://www.gnu.org/licenses/>.
from pyrogram import raw, types
from typing import Union
from pyrogram import raw
from ..object import Object