Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ repos:
- id: check-yaml

- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.4.4
rev: v0.4.5
hooks:
- id: ruff-format
- id: ruff
Expand Down
50 changes: 27 additions & 23 deletions hydrogram/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
# You should have received a copy of the GNU Lesser General Public License
# along with Hydrogram. If not, see <http://www.gnu.org/licenses/>.

from __future__ import annotations

import asyncio
import contextlib
import functools
Expand All @@ -27,15 +29,14 @@
import re
import shutil
import sys
from collections.abc import AsyncGenerator
from concurrent.futures.thread import ThreadPoolExecutor
from datetime import datetime, timedelta
from hashlib import sha256
from importlib import import_module
from io import BytesIO, StringIO
from mimetypes import MimeTypes
from pathlib import Path
from typing import Callable, Optional, Union
from typing import TYPE_CHECKING, Callable

import hydrogram
from hydrogram import __license__, __version__, enums, raw, utils
Expand All @@ -61,6 +62,9 @@
from .parser import Parser
from .session.internals import MsgId

if TYPE_CHECKING:
from collections.abc import AsyncGenerator

log = logging.getLogger(__name__)


Expand Down Expand Up @@ -211,28 +215,28 @@ class Client(Methods):
def __init__(
self,
name: str,
api_id: Optional[Union[int, str]] = None,
api_hash: Optional[str] = None,
api_id: int | str | None = None,
api_hash: str | None = None,
app_version: str = APP_VERSION,
device_model: str = DEVICE_MODEL,
system_version: str = SYSTEM_VERSION,
lang_code: str = LANG_CODE,
ipv6: bool = False,
proxy: Optional[dict] = None,
proxy: dict | None = None,
test_mode: bool = False,
bot_token: Optional[str] = None,
session_string: Optional[str] = None,
session_storage_engine: Optional[BaseStorage] = None,
in_memory: Optional[bool] = None,
phone_number: Optional[str] = None,
phone_code: Optional[str] = None,
password: Optional[str] = None,
bot_token: str | None = None,
session_string: str | None = None,
session_storage_engine: BaseStorage | None = None,
in_memory: bool | None = None,
phone_number: str | None = None,
phone_code: str | None = None,
password: str | None = None,
workers: int = WORKERS,
workdir: str = str(WORKDIR),
plugins: Optional[dict] = None,
parse_mode: "enums.ParseMode" = enums.ParseMode.DEFAULT,
no_updates: Optional[bool] = None,
takeout: Optional[bool] = None,
plugins: dict | None = None,
parse_mode: enums.ParseMode = enums.ParseMode.DEFAULT,
no_updates: bool | None = None,
takeout: bool | None = None,
sleep_threshold: int = Session.SLEEP_THRESHOLD,
hide_password: bool = False,
max_concurrent_transmissions: int = MAX_CONCURRENT_TRANSMISSIONS,
Expand Down Expand Up @@ -299,7 +303,7 @@ def __init__(

self.disconnect_handler = None

self.me: Optional[User] = None
self.me: User | None = None

self.message_cache = Cache(10000)

Expand Down Expand Up @@ -463,7 +467,7 @@ async def authorize(self) -> User:

return signed_up

def set_parse_mode(self, parse_mode: Optional["enums.ParseMode"]):
def set_parse_mode(self, parse_mode: enums.ParseMode | None):
"""Set the parse mode to be used globally by the client.

When setting the parse mode with this method, all other methods having a *parse_mode* parameter will follow the
Expand Down Expand Up @@ -502,7 +506,7 @@ def set_parse_mode(self, parse_mode: Optional["enums.ParseMode"]):
self.parse_mode = parse_mode

async def fetch_peers(
self, peers: list[Union[raw.types.User, raw.types.Chat, raw.types.Channel]]
self, peers: list[raw.types.User | raw.types.Chat | raw.types.Channel]
) -> bool:
is_min = False
parsed_peers = []
Expand Down Expand Up @@ -884,9 +888,9 @@ async def get_file(
file_size: int = 0,
limit: int = 0,
offset: int = 0,
progress: Optional[Callable] = None,
progress: Callable | None = None,
progress_args: tuple = (),
) -> Optional[AsyncGenerator[bytes, None]]:
) -> AsyncGenerator[bytes, None] | None:
async with self.get_file_semaphore:
file_type = file_id.file_type

Expand Down Expand Up @@ -1067,10 +1071,10 @@ async def get_file(
finally:
await session.stop()

def guess_mime_type(self, filename: str) -> Optional[str]:
def guess_mime_type(self, filename: str) -> str | None:
return self.mimetypes.guess_type(filename)[0]

def guess_extension(self, mime_type: str) -> Optional[str]:
def guess_extension(self, mime_type: str) -> str | None:
return self.mimetypes.guess_extension(mime_type)


Expand Down
5 changes: 3 additions & 2 deletions hydrogram/connection/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,10 @@
# You should have received a copy of the GNU Lesser General Public License
# along with Hydrogram. If not, see <http://www.gnu.org/licenses/>.

from __future__ import annotations

import asyncio
import logging
from typing import Optional

from hydrogram.session.internals import DataCenter

Expand Down Expand Up @@ -72,5 +73,5 @@ async def close(self):
async def send(self, data: bytes):
await self.protocol.send(data)

async def recv(self) -> Optional[bytes]:
async def recv(self) -> bytes | None:
return await self.protocol.recv()
5 changes: 3 additions & 2 deletions hydrogram/connection/transport/tcp/tcp_abridged.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,9 @@
# You should have received a copy of the GNU Lesser General Public License
# along with Hydrogram. If not, see <http://www.gnu.org/licenses/>.

from __future__ import annotations

import logging
from typing import Optional

from .tcp import TCP

Expand All @@ -40,7 +41,7 @@ async def send(self, data: bytes, *args):
(bytes([length]) if length <= 126 else b"\x7f" + length.to_bytes(3, "little")) + data
)

async def recv(self, length: int = 0) -> Optional[bytes]:
async def recv(self, length: int = 0) -> bytes | None:
length = await super().recv(1)

if length is None:
Expand Down
5 changes: 3 additions & 2 deletions hydrogram/connection/transport/tcp/tcp_abridged_o.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,10 @@
# You should have received a copy of the GNU Lesser General Public License
# along with Hydrogram. If not, see <http://www.gnu.org/licenses/>.

from __future__ import annotations

import logging
import os
from typing import Optional

import hydrogram
from hydrogram.crypto import aes
Expand Down Expand Up @@ -72,7 +73,7 @@ async def send(self, data: bytes, *args):

await super().send(payload)

async def recv(self, length: int = 0) -> Optional[bytes]:
async def recv(self, length: int = 0) -> bytes | None:
length = await super().recv(1)

if length is None:
Expand Down
5 changes: 3 additions & 2 deletions hydrogram/connection/transport/tcp/tcp_full.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,11 @@
# You should have received a copy of the GNU Lesser General Public License
# along with Hydrogram. If not, see <http://www.gnu.org/licenses/>.

from __future__ import annotations

import logging
from binascii import crc32
from struct import pack, unpack
from typing import Optional

from .tcp import TCP

Expand All @@ -44,7 +45,7 @@ async def send(self, data: bytes, *args):

await super().send(data)

async def recv(self, length: int = 0) -> Optional[bytes]:
async def recv(self, length: int = 0) -> bytes | None:
length = await super().recv(4)

if length is None:
Expand Down
5 changes: 3 additions & 2 deletions hydrogram/connection/transport/tcp/tcp_intermediate.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,10 @@
# You should have received a copy of the GNU Lesser General Public License
# along with Hydrogram. If not, see <http://www.gnu.org/licenses/>.

from __future__ import annotations

import logging
from struct import pack, unpack
from typing import Optional

from .tcp import TCP

Expand All @@ -37,7 +38,7 @@ async def connect(self, address: tuple):
async def send(self, data: bytes, *args):
await super().send(pack("<i", len(data)) + data)

async def recv(self, length: int = 0) -> Optional[bytes]:
async def recv(self, length: int = 0) -> bytes | None:
length = await super().recv(4)

return None if length is None else await super().recv(unpack("<i", length)[0])
5 changes: 3 additions & 2 deletions hydrogram/connection/transport/tcp/tcp_intermediate_o.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,11 @@
# You should have received a copy of the GNU Lesser General Public License
# along with Hydrogram. If not, see <http://www.gnu.org/licenses/>.

from __future__ import annotations

import logging
import os
from struct import pack, unpack
from typing import Optional

from hydrogram.crypto import aes

Expand Down Expand Up @@ -64,7 +65,7 @@ async def connect(self, address: tuple):
async def send(self, data: bytes, *args):
await super().send(aes.ctr256_encrypt(pack("<i", len(data)) + data, *self.encrypt))

async def recv(self, length: int = 0) -> Optional[bytes]:
async def recv(self, length: int = 0) -> bytes | None:
length = await super().recv(4)

if length is None:
Expand Down
11 changes: 6 additions & 5 deletions hydrogram/crypto/aes.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,9 @@
# You should have received a copy of the GNU Lesser General Public License
# along with Hydrogram. If not, see <http://www.gnu.org/licenses/>.

from __future__ import annotations

import logging
from typing import Optional

log = logging.getLogger(__name__)

Expand All @@ -34,12 +35,12 @@ def ige256_decrypt(data: bytes, key: bytes, iv: bytes) -> bytes:
return tgcrypto.ige256_decrypt(data, key, iv)

def ctr256_encrypt(
data: bytes, key: bytes, iv: bytearray, state: Optional[bytearray] = None
data: bytes, key: bytes, iv: bytearray, state: bytearray | None = None
) -> bytes:
return tgcrypto.ctr256_encrypt(data, key, iv, state or bytearray(1))

def ctr256_decrypt(
data: bytes, key: bytes, iv: bytearray, state: Optional[bytearray] = None
data: bytes, key: bytes, iv: bytearray, state: bytearray | None = None
) -> bytes:
return tgcrypto.ctr256_decrypt(data, key, iv, state or bytearray(1))

Expand All @@ -65,12 +66,12 @@ def ige256_decrypt(data: bytes, key: bytes, iv: bytes) -> bytes:
return ige(data, key, iv, False)

def ctr256_encrypt(
data: bytes, key: bytes, iv: bytearray, state: Optional[bytearray] = None
data: bytes, key: bytes, iv: bytearray, state: bytearray | None = None
) -> bytes:
return ctr(data, key, iv, state or bytearray(1))

def ctr256_decrypt(
data: bytes, key: bytes, iv: bytearray, state: Optional[bytearray] = None
data: bytes, key: bytes, iv: bytearray, state: bytearray | None = None
) -> bytes:
return ctr(data, key, iv, state or bytearray(1))

Expand Down
8 changes: 5 additions & 3 deletions hydrogram/errors/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@
# You should have received a copy of the GNU Lesser General Public License
# along with Hydrogram. If not, see <http://www.gnu.org/licenses/>.

from typing import ClassVar, Optional
from __future__ import annotations

from typing import ClassVar

from .exceptions import (
AboutTooLong,
Expand Down Expand Up @@ -531,14 +533,14 @@ def check(cls, cond: bool, msg: str):
class SecurityCheckMismatch(SecurityError): # noqa: N818
"""Raised when a security check mismatch occurs."""

def __init__(self, msg: Optional[str] = None):
def __init__(self, msg: str | None = None):
super().__init__("A security check mismatch has occurred." if msg is None else msg)


class CDNFileHashMismatch(SecurityError): # noqa: N818
"""Raised when a CDN file hash mismatch occurs."""

def __init__(self, msg: Optional[str] = None):
def __init__(self, msg: str | None = None):
super().__init__("A CDN file hash mismatch has occurred." if msg is None else msg)


Expand Down
17 changes: 10 additions & 7 deletions hydrogram/errors/rpc_error.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,20 @@
# You should have received a copy of the GNU Lesser General Public License
# along with Hydrogram. If not, see <http://www.gnu.org/licenses/>.

from __future__ import annotations

import re
from datetime import datetime
from importlib import import_module
from pathlib import Path
from typing import Optional, Union

from hydrogram import raw
from hydrogram.raw.core import TLObject
from typing import TYPE_CHECKING

from .exceptions.all import exceptions

if TYPE_CHECKING:
from hydrogram import raw
from hydrogram.raw.core import TLObject


class RPCError(Exception):
ID = None
Expand All @@ -37,8 +40,8 @@ class RPCError(Exception):

def __init__(
self,
value: Union[int, str, raw.types.RpcError] = None,
rpc_name: Optional[str] = None,
value: int | str | raw.types.RpcError = None,
rpc_name: str | None = None,
is_unknown: bool = False,
is_signed: bool = False,
):
Expand All @@ -62,7 +65,7 @@ def __init__(
f.write(f"{datetime.now()}\t{value}\t{rpc_name}\n")

@staticmethod
def raise_it(rpc_error: "raw.types.RpcError", rpc_type: type[TLObject]):
def raise_it(rpc_error: raw.types.RpcError, rpc_type: type[TLObject]):
error_code = rpc_error.error_code
is_signed = error_code < 0
error_message = rpc_error.error_message
Expand Down
Loading