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 return f"Optional[{type}] = None" if is_flag else type
else: else:
ns, name = type.split(".") if "." in type else ("", type) 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 ""}' return f'{type}{" = None" if is_flag else ""}'
@ -430,11 +430,11 @@ def start(format: bool = False):
if function_docs: if function_docs:
docstring += function_docs["desc"] + "\n" docstring += function_docs["desc"] + "\n"
else: 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"\n\n Details:\n - Layer: ``{layer}``\n - ID: ``{c.id[2:].upper()}``\n\n"
docstring += f" Parameters:\n " + \ docstring += " Parameters:\n " + \
(f"\n ".join(docstring_args) if docstring_args else "No parameters required.\n") ("\n ".join(docstring_args) if docstring_args else "No parameters required.\n")
if c.section == "functions": if c.section == "functions":
docstring += "\n Returns:\n " + get_docstring_arg_type(c.qualtype) 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") references, count = get_references(c.qualname, "constructors")
if references: 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"{count} function{'s' if count > 1 else ''}.\n\n" \
f" .. currentmodule:: pyrogram.raw.functions\n\n" \ " .. currentmodule:: pyrogram.raw.functions\n\n" \
f" .. autosummary::\n" \ " .. autosummary::\n" \
f" :nosignatures:\n\n" \ " :nosignatures:\n\n" \
f" " + references " " + references
write_types = read_types = "" if c.has_flags else "# No flags\n " write_types = read_types = "" if c.has_flags else "# No flags\n "

View file

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

View file

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

View file

@ -37,8 +37,24 @@ class ContinuePropagation(StopAsyncIteration):
pass pass
from . import raw, types, filters, handlers, emoji, enums from . import raw, types, filters, handlers, emoji, enums # pylint: disable=wrong-import-position
from .client import Client from .client import Client # pylint: disable=wrong-import-position
from .sync import idle, compose from .sync import idle, compose # pylint: disable=wrong-import-position
crypto_executor = ThreadPoolExecutor(1, thread_name_prefix="CryptoWorker") 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 io import StringIO, BytesIO
from mimetypes import MimeTypes from mimetypes import MimeTypes
from pathlib import Path 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 import pyrogram
from pyrogram import __version__, __license__ from pyrogram import __version__, __license__
@ -51,24 +51,26 @@ from pyrogram.handlers.handler import Handler
from pyrogram.methods import Methods from pyrogram.methods import Methods
from pyrogram.session import Auth, Session from pyrogram.session import Auth, Session
from pyrogram.storage import FileStorage, MemoryStorage, Storage 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: try:
import pymongo import pymongo
except Exception: except Exception:
pass pass
else: else:
from pyrogram.storage import MongoStorage from pyrogram.storage import MongoStorage
from pyrogram.types import User, TermsOfService MONGO_AVAIL = True
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__)
class Client(Methods): class Client(Methods):
@ -316,9 +318,7 @@ class Client(Methods):
elif self.in_memory: elif self.in_memory:
self.storage = MemoryStorage(self.name) self.storage = MemoryStorage(self.name)
elif self.mongodb: elif self.mongodb:
try: if not MONGO_AVAIL:
import pymongo
except Exception:
log.warning( log.warning(
"pymongo is missing! " "pymongo is missing! "
"Using MemoryStorage as session storage" "Using MemoryStorage as session storage"
@ -888,7 +888,7 @@ class Client(Methods):
count = 0 count = 0
if not include: 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("\\", ".") namespace = current_root.replace("/", ".").replace("\\", ".")
if "__pycache__" in namespace: if "__pycache__" in namespace:
continue continue
@ -953,7 +953,7 @@ class Client(Methods):
) )
count += 1 count += 1
except Exception as e: except Exception:
pass pass
else: else:
for path, handlers in include: for path, handlers in include:
@ -1042,7 +1042,7 @@ class Client(Methods):
) )
count += 1 count += 1
except Exception as e: except Exception:
pass pass
if handlers is None: if handlers is None:
@ -1106,7 +1106,7 @@ class Client(Methods):
async def handle_download(self, packet): async def handle_download(self, packet):
file_id, directory, file_name, in_memory, file_size, progress, progress_args = 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" 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") 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/>. # along with Pyrofork. If not, see <http://www.gnu.org/licenses/>.
from .connection import Connection from .connection import Connection
__all__ = [
"Connection"
]

View file

@ -52,7 +52,7 @@ class Connection:
self.protocol: Optional[TCP] = None self.protocol: Optional[TCP] = None
async def connect(self) -> 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) self.protocol = self.protocol_factory(ipv6=self.ipv6, proxy=self.proxy)
try: try:

View file

@ -23,3 +23,13 @@ from .tcp_abridged_o import TCPAbridgedO
from .tcp_full import TCPFull from .tcp_full import TCPFull
from .tcp_intermediate import TCPIntermediate from .tcp_intermediate import TCPIntermediate
from .tcp_intermediate_o import TCPIntermediateO 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 ipaddress
import logging import logging
import socket import socket
from concurrent.futures import ThreadPoolExecutor
from typing import Tuple, Dict, TypedDict, Optional from typing import Tuple, Dict, TypedDict, Optional
import socks import socks

View file

@ -71,7 +71,7 @@ def unpack(
message = Message.read(data) message = Message.read(data)
except KeyError as e: except KeyError as e:
if e.args[0] == 0: 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() left = data.read().hex()

View file

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

View file

@ -23,7 +23,7 @@ import logging
from collections import OrderedDict from collections import OrderedDict
import pyrogram import pyrogram
from pyrogram import errors, raw, types, utils from pyrogram import raw, types, utils
from pyrogram.handlers.handler import Handler from pyrogram.handlers.handler import Handler
from pyrogram.handlers import ( from pyrogram.handlers import (
BotBusinessConnectHandler, BotBusinessConnectHandler,
@ -266,7 +266,7 @@ class Dispatcher:
async def start(self): async def start(self):
if not self.client.no_updates: 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.locks_list.append(asyncio.Lock())
self.handler_worker_tasks.append( 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``)" "The linked chat has been changed (see ``old_linked_chat`` and ``new_linked_chat``)"
# LOCATION_CHANGED = auto() # LOCATION_CHANGED = auto()
"" # ""
PHOTO_CHANGED = auto() PHOTO_CHANGED = auto()
"The chat photo has been changed (see ``old_photo`` and ``new_photo``)" "The chat photo has been changed (see ``old_photo`` and ``new_photo``)"
# STICKER_SET_CHANGED = auto() # STICKER_SET_CHANGED = auto()
"" # ""
TITLE_CHANGED = auto() TITLE_CHANGED = auto()
"the chat title has been changed (see ``old_title`` and ``new_title``)" "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``)" "a message has been deleted (see ``deleted_message``)"
# VOICE_CHAT_DISCARDED = auto() # VOICE_CHAT_DISCARDED = auto()
"" # ""
MESSAGE_EDITED = auto() MESSAGE_EDITED = auto()
"a message has been edited (see ``old_message`` and ``new_message``)" "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``)" "a member joined by themselves. (see ``user``)"
# MEMBER_JOINED_BY_LINK = auto() # MEMBER_JOINED_BY_LINK = auto()
"" # ""
MEMBER_LEFT = auto() MEMBER_LEFT = auto()
"a member left by themselves. (see ``user``)" "a member left by themselves. (see ``user``)"
# MEMBER_MUTED = auto() # MEMBER_MUTED = auto()
"" # ""
ADMINISTRATOR_PRIVILEGES_CHANGED = 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``)" "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``)" "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_UNMUTED = auto()
"" # ""
# MEMBER_VOLUME_CHANGED = auto() # MEMBER_VOLUME_CHANGED = auto()
"" # ""
# VIDEO_CHAT_STARTED = auto() # VIDEO_CHAT_STARTED = auto()
"" # ""
POLL_STOPPED = auto() POLL_STOPPED = auto()
"a poll has been stopped (see ``stopped_poll``)" "a poll has been stopped (see ``stopped_poll``)"
# VOICE_CHAT_SETTINGS_CHANGED = auto() # VOICE_CHAT_SETTINGS_CHANGED = auto()
"" # ""
INVITES_ENABLED = auto() INVITES_ENABLED = auto()
"the chat invitation has been enabled or disabled (see ``invites_enabled``)" "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): def __init__(self, msg: str = None):
super().__init__("A CDN file hash mismatch has occurred." if msg is None else msg) 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 .inline_query_handler import InlineQueryHandler
from .message_handler import MessageHandler from .message_handler import MessageHandler
from .poll_handler import PollHandler from .poll_handler import PollHandler
from .pre_checkout_query_handler import PreCheckoutQueryHandler
from .purchased_paid_media_handler import PurchasedPaidMediaHandler from .purchased_paid_media_handler import PurchasedPaidMediaHandler
from .raw_update_handler import RawUpdateHandler from .raw_update_handler import RawUpdateHandler
from .user_status_handler import UserStatusHandler 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 .message_reaction_count_updated_handler import MessageReactionCountUpdatedHandler
from .pre_checkout_query_handler import PreCheckoutQueryHandler from .pre_checkout_query_handler import PreCheckoutQueryHandler
from .shipping_query_handler import ShippingQueryHandler 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 return True
@staticmethod @staticmethod
# pylint: disable=method-hidden
async def callback(_, __): async def callback(_, __):
pass pass

View file

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

View file

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

View file

@ -13,4 +13,15 @@ GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with pyromod. If not, see <https://www.gnu.org/licenses/>. along with pyromod. If not, see <https://www.gnu.org/licenses/>.
""" """
from .helpers import ikb, bki, ntb, btn, kb, kbtn, array_chunk, force_reply 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 = [] line = []
for button in row: for button in row:
button_type = type(button) button_type = type(button)
if button_type == str: if isinstance(button_type, str):
button = KeyboardButton(button) button = KeyboardButton(button)
elif button_type == dict: elif isinstance(button_type, dict):
button = KeyboardButton(**button) button = KeyboardButton(**button)
line.append(button) line.append(button)

View file

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

View file

@ -35,6 +35,7 @@ class Connect:
Raises: Raises:
ConnectionError: In case you try to connect an already connected client. ConnectionError: In case you try to connect an already connected client.
""" """
# pylint: disable=access-member-before-definition
if self.is_connected: if self.is_connected:
raise ConnectionError("Client is already 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 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. disconnect a client that needs to be terminated first.
""" """
# pylint: disable=access-member-before-definition
if not self.is_connected: if not self.is_connected:
raise ConnectionError("Client is already disconnected") 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 # You should have received a copy of the GNU Lesser General Public License
# along with Pyrogram. If not, see <http://www.gnu.org/licenses/>. # along with Pyrogram. If not, see <http://www.gnu.org/licenses/>.
from typing import List
import pyrogram import pyrogram
from pyrogram import raw, types from pyrogram import raw, types

View file

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

View file

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

View file

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

View file

@ -37,6 +37,7 @@ class Terminate:
Raises: Raises:
ConnectionError: In case you try to terminate a client that is already terminated. ConnectionError: In case you try to terminate a client that is already terminated.
""" """
# pylint: disable=access-member-before-definition
if not self.is_initialized: if not self.is_initialized:
raise ConnectionError("Client is already terminated") 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 # You should have received a copy of the GNU Lesser General Public License
# along with Pyrogram. If not, see <http://www.gnu.org/licenses/>. # along with Pyrogram. If not, see <http://www.gnu.org/licenses/>.
from datetime import datetime
from typing import Union, List
import pyrogram import pyrogram
from pyrogram import types, utils, raw from pyrogram import types, raw
class GetBusinessConnection: 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.users},
{i.id: i for i in r.chats} {i.id: i for i in r.chats}
) )
else: return True
return True

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -15,9 +15,9 @@
# #
# You should have received a copy of the GNU Lesser General Public License # You should have received a copy of the GNU Lesser General Public License
# along with Pyrofork. If not, see <http://www.gnu.org/licenses/>. # along with Pyrofork. If not, see <http://www.gnu.org/licenses/>.
import pyrogram import pyrogram
from pyrogram import raw from pyrogram import raw
from pyrogram import types
from typing import Union 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.users},
{i.id: i for i in r.chats} {i.id: i for i in r.chats}
) )
else: return True
return True

View file

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

View file

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

View file

@ -180,8 +180,12 @@ class CopyMediaGroup:
**await self.parser.parse( **await self.parser.parse(
captions[i] if isinstance(captions, list) and i < len(captions) and captions[i] else captions[i] if isinstance(captions, list) and i < len(captions) and captions[i] else
captions if isinstance(captions, str) and i == 0 else captions if isinstance(captions, str) and i == 0 else
message.caption if message.caption and message.caption != "None" and not type( message.caption if (
captions) is str else "") 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) is_iterable = not isinstance(ids, int)
ids = list(ids) if is_iterable else [ids] 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: if replies < 0:
replies = (1 << 31) - 1 replies = (1 << 31) - 1

View file

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

View file

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

View file

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

View file

@ -17,4 +17,8 @@
# You should have received a copy of the GNU Lesser General Public License # You should have received a copy of the GNU Lesser General Public License
# along with Pyrofork. If not, see <http://www.gnu.org/licenses/>. # along with Pyrofork. If not, see <http://www.gnu.org/licenses/>.
from .pagination import Pagination from .pagination import Pagination
__all__ = [
"Pagination"
]

View file

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

View file

@ -18,7 +18,6 @@
# along with Pyrofork. If not, see <http://www.gnu.org/licenses/>. # along with Pyrofork. If not, see <http://www.gnu.org/licenses/>.
import html import html
import logging
import re import re
from typing import Optional from typing import Optional
@ -251,7 +250,7 @@ class Markdown:
# Handle multiline blockquotes # Handle multiline blockquotes
text_subset = text[s:e] text_subset = text[s:e]
lines = text_subset.splitlines() 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]) line_start = s + sum(len(l) + 1 for l in lines[:line_num])
if entity.collapsed: if entity.collapsed:
insert_at.append((line_start, i, BLOCKQUOTE_EXPANDABLE_DELIM)) 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(): for k, v in objects.items():
path, name = v.rsplit(".", 1) path, name = v.rsplit(".", 1)
objects[k] = getattr(import_module(path), name) 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.string import String
from .primitives.vector import Vector from .primitives.vector import Vector
from .tl_object import TLObject 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 .int import Int, Long, Int128, Int256
from .string import String from .string import String
from .vector import Vector 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 .auth import Auth
from .session import Session from .session import Session
__all__ = [
"Auth",
"Session"
]

View file

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

View file

@ -19,10 +19,20 @@
from .file_storage import FileStorage from .file_storage import FileStorage
from .memory_storage import MemoryStorage from .memory_storage import MemoryStorage
MONGO_AVAIL = False
try: try:
import pymongo import pymongo
except Exception: except Exception:
pass pass
else: else:
MONGO_AVAIL = True
from .mongo_storage import MongoStorage from .mongo_storage import MongoStorage
from .storage import Storage 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 .user_and_chats import *
from .payments import * from .payments import *
from .pyromod import * from .pyromod import *
__all__ = [
"List",
"Object"
]

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -19,6 +19,7 @@
import pyrogram import pyrogram
from pyrogram import raw, types from pyrogram import raw, types
from typing import Dict
from ..object import Object from ..object import Object
from ..update import Update from ..update import Update
@ -62,7 +63,7 @@ class ShippingQuery(Object, Update):
async def _parse( async def _parse(
client: "pyrogram.Client", client: "pyrogram.Client",
shipping_query: "raw.types.UpdateBotShippingQuery", shipping_query: "raw.types.UpdateBotShippingQuery",
users: dict users: Dict[int, "raw.types.User"]
) -> "types.PreCheckoutQuery": ) -> "types.PreCheckoutQuery":
# Try to decode pre-checkout query payload into string. If that fails, fallback to bytes instead of decoding by # 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. # 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 # You should have received a copy of the GNU Lesser General Public License
# along with Pyrofork. If not, see <http://www.gnu.org/licenses/>. # along with Pyrofork. If not, see <http://www.gnu.org/licenses/>.
from typing import List, Match from typing import List, Match, Dict
import pyrogram import pyrogram
from pyrogram import raw from pyrogram import raw
@ -78,7 +78,11 @@ class InlineQuery(Object, Update):
self.matches = matches self.matches = matches
@staticmethod @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 peer_type = inline_query.peer_type
chat_type = None chat_type = None

View file

@ -22,7 +22,7 @@ from typing import List
import pyrogram import pyrogram
from pyrogram import raw, utils from pyrogram import raw, utils
from pyrogram import types 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 from ..object import Object

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -193,6 +193,7 @@ class Story(Object, Update):
animation = None animation = None
photo = None photo = None
video = None video = None
media_type = None
chat = None chat = None
from_user = None from_user = None
sender_chat = None sender_chat = None
@ -268,14 +269,13 @@ class Story(Object, Update):
elif isinstance(priv, raw.types.PrivacyValueDisallowContacts): elif isinstance(priv, raw.types.PrivacyValueDisallowContacts):
privacy = enums.StoryPrivacy.NO_CONTACTS privacy = enums.StoryPrivacy.NO_CONTACTS
''' #if allowed_chats and len(allowed_chats) > 0:
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]
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))
privacy_rules.append(raw.types.InputPrivacyValueAllowChatParticipants(chats=chats)) #if denied_chats and len(denied_chats) > 0:
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]
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))
privacy_rules.append(raw.types.InputPrivacyValueDisallowChatParticipants(chats=chats))
'''
if isinstance(priv, raw.types.PrivacyValueAllowUsers): if isinstance(priv, raw.types.PrivacyValueAllowUsers):
allowed_users = priv.users allowed_users = priv.users
if isinstance(priv, raw.types.PrivacyValueDisallowUsers): if isinstance(priv, raw.types.PrivacyValueDisallowUsers):

View file

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

View file

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

View file

@ -22,7 +22,7 @@ from typing import List
import pyrogram import pyrogram
from pyrogram import raw, types, utils 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 from ..object import Object

View file

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

View file

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

View file

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

View file

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

View file

@ -19,7 +19,8 @@
import pyrogram import pyrogram
from ..object import Object from ..object import Object
from pyrogram import types, utils from pyrogram import raw, types, utils
from typing import Dict
class GiftCode(Object): class GiftCode(Object):
@ -78,7 +79,11 @@ class GiftCode(Object):
self.crypto_amount = crypto_amount self.crypto_amount = crypto_amount
@staticmethod @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 = None
boosted_chat_raw = chats.get(utils.get_raw_peer_id(gift_code.boost_peer), None) boosted_chat_raw = chats.get(utils.get_raw_peer_id(gift_code.boost_peer), None)
if boosted_chat_raw: if boosted_chat_raw:

View file

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

View file

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

View file

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

View file

@ -107,7 +107,7 @@ class PaymentForm(Object):
bot=types.User._parse(client, users.get(payment_form.bot_id)), bot=types.User._parse(client, users.get(payment_form.bot_id)),
title=payment_form.title, title=payment_form.title,
description=payment_form.description, 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))), provider=types.User._parse(client, users.get(getattr(payment_form, "provider_id", None))),
url=getattr(payment_form, "url", None), url=getattr(payment_form, "url", None),
can_save_credentials=getattr(payment_form, "can_save_credentials", 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 # You should have received a copy of the GNU Lesser General Public License
# along with Pyrofork. If not, see <http://www.gnu.org/licenses/>. # along with Pyrofork. If not, see <http://www.gnu.org/licenses/>.
from pyrogram import types
from ..object import Object from ..object import Object

View file

@ -18,6 +18,7 @@
from datetime import datetime from datetime import datetime
from pyrogram import raw, types, utils from pyrogram import raw, types, utils
from typing import Dict
from ..object import Object from ..object import Object
class StarsTransaction(Object): class StarsTransaction(Object):
@ -100,7 +101,7 @@ class StarsTransaction(Object):
def _parse( def _parse(
client, client,
transaction: "raw.types.StarsTransaction", transaction: "raw.types.StarsTransaction",
users: dict users: Dict[int, "raw.types.User"]
) -> "StarsTransaction": ) -> "StarsTransaction":
chat_id = utils.get_raw_peer_id(transaction.peer.peer) chat_id = utils.get_raw_peer_id(transaction.peer.peer)
chat = types.User._parse(client, users.get(chat_id, None)) 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 # You should have received a copy of the GNU Lesser General Public License
# along with Pyrofork. If not, see <http://www.gnu.org/licenses/>. # along with Pyrofork. If not, see <http://www.gnu.org/licenses/>.
import pyrogram
from pyrogram import raw from pyrogram import raw
from pyrogram import types from pyrogram import types
from ..object import Object from ..object import Object

View file

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

View file

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

View file

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

View file

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

View file

@ -18,7 +18,7 @@
# along with Pyrofork. If not, see <http://www.gnu.org/licenses/>. # along with Pyrofork. If not, see <http://www.gnu.org/licenses/>.
from datetime import datetime from datetime import datetime
from typing import Union, List, Optional, AsyncGenerator, BinaryIO from typing import Union, List, Optional, AsyncGenerator, BinaryIO, Dict
import pyrogram import pyrogram
from pyrogram import raw, enums from pyrogram import raw, enums
@ -434,8 +434,8 @@ class Chat(Object):
def _parse( def _parse(
client, client,
message: Union[raw.types.Message, raw.types.MessageService], message: Union[raw.types.Message, raw.types.MessageService],
users: dict, users: Dict[int, "raw.types.User"],
chats: dict, chats: Dict[int, "raw.types.Chat"],
is_chat: bool is_chat: bool
) -> "Chat": ) -> "Chat":
from_id = utils.get_raw_peer_id(message.from_id) 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]) return Chat._parse_channel_chat(client, chats[chat_id])
@staticmethod @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): if isinstance(peer, raw.types.PeerUser):
return Chat._parse_user_chat(client, users[peer.user_id]) return Chat._parse_user_chat(client, users[peer.user_id])
elif isinstance(peer, raw.types.PeerChat): 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 # You should have received a copy of the GNU Lesser General Public License
# along with Pyrofork. If not, see <http://www.gnu.org/licenses/>. # along with Pyrofork. If not, see <http://www.gnu.org/licenses/>.
from pyrogram import raw, types from pyrogram import raw
from typing import Union
from ..object import Object from ..object import Object