Skip to content
This repository was archived by the owner on Dec 23, 2024. It is now read-only.
Open
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
10 changes: 5 additions & 5 deletions compiler/api/compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,13 +84,13 @@ class Combinator(NamedTuple):
type: str


def snake(s: str):
def snake(s: str) -> str:
# https://stackoverflow.com/q/1175208
s = re.sub(r"(.)([A-Z][a-z]+)", r"\1_\2", s)
return re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", s).lower()


def camel(s: str):
def camel(s: str) -> str:
return "".join([i[0].upper() + i[1:] for i in s.split("_")])


Expand Down Expand Up @@ -134,7 +134,7 @@ def get_type_hint(type: str) -> str:
return f'{type}{" = None" if is_flag else ""}'


def sort_args(args):
def sort_args(args) -> str:
"""Put flags at the end"""
args = args.copy()
flags = [i for i in args if FLAGS_RE.match(i[1])]
Expand All @@ -160,7 +160,7 @@ def remove_whitespaces(source: str) -> str:
return "\n".join(lines)


def get_docstring_arg_type(t: str):
def get_docstring_arg_type(t: str) -> str:
if t in CORE_TYPES:
if t == "long":
return "``int`` ``64-bit``"
Expand All @@ -185,7 +185,7 @@ def get_docstring_arg_type(t: str):
return f":obj:`{t} <pyrogram.raw.base.{t}>`"


def get_references(t: str, kind: str):
def get_references(t: str, kind: str) -> tuple:
if kind == "constructors":
t = constructors_to_functions.get(t)
elif kind == "types":
Expand Down
4 changes: 2 additions & 2 deletions pyrogram/errors/rpc_error.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ def __init__(
rpc_name: str = None,
is_unknown: bool = False,
is_signed: bool = False
):
) -> None:
super().__init__("Telegram says: [{}{} {}] - {} {}".format(
"-" if is_signed else "",
self.CODE,
Expand All @@ -57,7 +57,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]) -> None:
error_code = rpc_error.error_code
is_signed = error_code < 0
error_message = rpc_error.error_message
Expand Down
2 changes: 1 addition & 1 deletion pyrogram/handlers/callback_query_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,5 +45,5 @@ class CallbackQueryHandler(Handler):
The received callback query.
"""

def __init__(self, callback: Callable, filters=None):
def __init__(self, callback: Callable, filters=None) -> None:
super().__init__(callback, filters)
2 changes: 1 addition & 1 deletion pyrogram/handlers/chat_join_request_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,5 +45,5 @@ class ChatJoinRequestHandler(Handler):
The received chat join request.
"""

def __init__(self, callback: Callable, filters=None):
def __init__(self, callback: Callable, filters=None) -> None:
super().__init__(callback, filters)
2 changes: 1 addition & 1 deletion pyrogram/handlers/chat_member_updated_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,5 +45,5 @@ class ChatMemberUpdatedHandler(Handler):
The received chat member update.
"""

def __init__(self, callback: Callable, filters=None):
def __init__(self, callback: Callable, filters=None) -> None:
super().__init__(callback, filters)
2 changes: 1 addition & 1 deletion pyrogram/handlers/chosen_inline_result_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,5 +46,5 @@ class ChosenInlineResultHandler(Handler):
The received chosen inline result.
"""

def __init__(self, callback: Callable, filters=None):
def __init__(self, callback: Callable, filters=None) -> None:
super().__init__(callback, filters)
4 changes: 2 additions & 2 deletions pyrogram/handlers/deleted_messages_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,10 @@ class DeletedMessagesHandler(Handler):
The deleted messages, as list.
"""

def __init__(self, callback: Callable, filters: Filter = None):
def __init__(self, callback: Callable, filters: Filter = None) -> None:
super().__init__(callback, filters)

async def check(self, client: "pyrogram.Client", messages: List[Message]):
async def check(self, client: "pyrogram.Client", messages: List[Message]) -> bool:
# Every message should be checked, if at least one matches the filter True is returned
# otherwise, or if the list is empty, False is returned
for message in messages:
Expand Down
2 changes: 1 addition & 1 deletion pyrogram/handlers/disconnect_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,5 +39,5 @@ class DisconnectHandler(Handler):
is established.
"""

def __init__(self, callback: Callable):
def __init__(self, callback: Callable) -> None:
super().__init__(callback)
2 changes: 1 addition & 1 deletion pyrogram/handlers/edited_message_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,5 +45,5 @@ class EditedMessageHandler(Handler):
The received edited message.
"""

def __init__(self, callback: Callable, filters=None):
def __init__(self, callback: Callable, filters=None) -> None:
super().__init__(callback, filters)
4 changes: 2 additions & 2 deletions pyrogram/handlers/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,11 @@


class Handler:
def __init__(self, callback: Callable, filters: Filter = None):
def __init__(self, callback: Callable, filters: Filter = None) -> None:
self.callback = callback
self.filters = filters

async def check(self, client: "pyrogram.Client", update: Update):
async def check(self, client: "pyrogram.Client", update: Update) -> bool:
if callable(self.filters):
if inspect.iscoroutinefunction(self.filters.__call__):
return await self.filters(client, update)
Expand Down
2 changes: 1 addition & 1 deletion pyrogram/handlers/inline_query_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,5 +45,5 @@ class InlineQueryHandler(Handler):
The received inline query.
"""

def __init__(self, callback: Callable, filters=None):
def __init__(self, callback: Callable, filters=None) -> None:
super().__init__(callback, filters)
2 changes: 1 addition & 1 deletion pyrogram/handlers/message_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,5 +45,5 @@ class MessageHandler(Handler):
The received message.
"""

def __init__(self, callback: Callable, filters=None):
def __init__(self, callback: Callable, filters=None) -> None:
super().__init__(callback, filters)
2 changes: 1 addition & 1 deletion pyrogram/handlers/poll_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,5 +46,5 @@ class PollHandler(Handler):
The received poll.
"""

def __init__(self, callback: Callable, filters=None):
def __init__(self, callback: Callable, filters=None) -> None:
super().__init__(callback, filters)
2 changes: 1 addition & 1 deletion pyrogram/handlers/raw_update_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,5 +63,5 @@ class RawUpdateHandler(Handler):
- :obj:`~pyrogram.raw.types.ChannelForbidden`
"""

def __init__(self, callback: Callable):
def __init__(self, callback: Callable) -> None:
super().__init__(callback)
2 changes: 1 addition & 1 deletion pyrogram/handlers/user_status_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,5 +43,5 @@ class UserStatusHandler(Handler):
The user containing the updated status.
"""

def __init__(self, callback: Callable, filters=None):
def __init__(self, callback: Callable, filters=None) -> None:
super().__init__(callback, filters)
18 changes: 9 additions & 9 deletions pyrogram/parser/html.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
import logging
import re
from html.parser import HTMLParser
from typing import Optional
from typing import Optional, Union

import pyrogram
from pyrogram import raw
Expand All @@ -34,7 +34,7 @@
class Parser(HTMLParser):
MENTION_RE = re.compile(r"tg://user\?id=(\d+)")

def __init__(self, client: "pyrogram.Client"):
def __init__(self, client: "pyrogram.Client") -> None:
super().__init__()

self.client = client
Expand All @@ -43,7 +43,7 @@ def __init__(self, client: "pyrogram.Client"):
self.entities = []
self.tag_entities = {}

def handle_starttag(self, tag, attrs):
def handle_starttag(self, tag: str, attrs: list) -> None:
attrs = dict(attrs)
extra = {}

Expand Down Expand Up @@ -87,7 +87,7 @@ def handle_starttag(self, tag, attrs):

self.tag_entities[tag].append(entity(offset=len(self.text), length=0, **extra))

def handle_data(self, data):
def handle_data(self, data: str) -> None:
data = html.unescape(data)

for entities in self.tag_entities.values():
Expand All @@ -96,7 +96,7 @@ def handle_data(self, data):

self.text += data

def handle_endtag(self, tag):
def handle_endtag(self, tag: str) -> None:
try:
self.entities.append(self.tag_entities[tag].pop())
except (KeyError, IndexError):
Expand All @@ -113,10 +113,10 @@ def error(self, message):


class HTML:
def __init__(self, client: Optional["pyrogram.Client"]):
def __init__(self, client: Optional["pyrogram.Client"]) -> None:
self.client = client

async def parse(self, text: str):
async def parse(self, text: str) -> dict:
# Strip whitespaces from the beginning and the end, but preserve closing tags
text = re.sub(r"^\s*(<[\w<>=\s\"]*>)\s*", r"\1", text)
text = re.sub(r"\s*(</[\w</>]*>)\s*$", r"\1", text)
Expand Down Expand Up @@ -154,8 +154,8 @@ async def parse(self, text: str):
}

@staticmethod
def unparse(text: str, entities: list):
def parse_one(entity):
def unparse(text: str, entities: list) -> str:
def parse_one(entity) -> Union[tuple, None]:
"""
Parses a single entity and returns (start_tag, start), (end_tag, end)
"""
Expand Down
6 changes: 3 additions & 3 deletions pyrogram/parser/markdown.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,10 @@


class Markdown:
def __init__(self, client: Optional["pyrogram.Client"]):
def __init__(self, client: Optional["pyrogram.Client"]) -> None:
self.html = HTML(client)

async def parse(self, text: str, strict: bool = False):
async def parse(self, text: str, strict: bool = False) -> dict:
if strict:
text = html.escape(text)

Expand Down Expand Up @@ -116,7 +116,7 @@ async def parse(self, text: str, strict: bool = False):
return await self.html.parse(text)

@staticmethod
def unparse(text: str, entities: list):
def unparse(text: str, entities: list) -> str:
text = utils.add_surrogates(text)

entities_offsets = []
Expand Down
9 changes: 4 additions & 5 deletions pyrogram/parser/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 Optional
from typing import Optional, Union

import pyrogram
from pyrogram import enums
Expand All @@ -30,7 +30,7 @@ def __init__(self, client: Optional["pyrogram.Client"]):
self.html = HTML(client)
self.markdown = Markdown(client)

async def parse(self, text: str, mode: Optional[enums.ParseMode] = None):
async def parse(self, text: str, mode: Optional[enums.ParseMode] = None) -> Union[str, dict]:
text = str(text if text else "").strip()

if mode is None:
Expand All @@ -54,8 +54,7 @@ async def parse(self, text: str, mode: Optional[enums.ParseMode] = None):
raise ValueError(f'Invalid parse mode "{mode}"')

@staticmethod
def unparse(text: str, entities: list, is_html: bool):
def unparse(text: str, entities: list, is_html: bool) -> str:
if is_html:
return HTML.unparse(text, entities)
else:
return Markdown.unparse(text, entities)
return Markdown.unparse(text, entities)
4 changes: 2 additions & 2 deletions pyrogram/parser/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,10 @@ def add_surrogates(text):
)


def remove_surrogates(text):
def remove_surrogates(text: str) -> str:
# Replace each surrogate pair with a SMP code point
return text.encode("utf-16", "surrogatepass").decode("utf-16")


def replace_once(source: str, old: str, new: str, start: int):
def replace_once(source: str, old: str, new: str, start: int) -> str:
return source[:start] + source[start:].replace(old, new, 1)
2 changes: 1 addition & 1 deletion pyrogram/raw/core/future_salt.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ class FutureSalt(TLObject):

QUALNAME = "FutureSalt"

def __init__(self, valid_since: int, valid_until: int, salt: int):
def __init__(self, valid_since: int, valid_until: int, salt: int) -> None:
self.valid_since = valid_since
self.valid_until = valid_until
self.salt = salt
Expand Down
2 changes: 1 addition & 1 deletion pyrogram/raw/core/future_salts.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ class FutureSalts(TLObject):

QUALNAME = "FutureSalts"

def __init__(self, req_msg_id: int, now: int, salts: List[FutureSalt]):
def __init__(self, req_msg_id: int, now: int, salts: List[FutureSalt]) -> None:
self.req_msg_id = req_msg_id
self.now = now
self.salts = salts
Expand Down
2 changes: 1 addition & 1 deletion pyrogram/raw/core/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ class Message(TLObject):

QUALNAME = "Message"

def __init__(self, body: TLObject, msg_id: int, seq_no: int, length: int):
def __init__(self, body: TLObject, msg_id: int, seq_no: int, length: int) -> None:
self.msg_id = msg_id
self.seq_no = seq_no
self.length = length
Expand Down
8 changes: 4 additions & 4 deletions pyrogram/storage/file_storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,12 @@
class FileStorage(SQLiteStorage):
FILE_EXTENSION = ".session"

def __init__(self, name: str, workdir: Path):
def __init__(self, name: str, workdir: Path) -> None:
super().__init__(name)

self.database = workdir / (self.name + self.FILE_EXTENSION)

def update(self):
def update(self) -> None:
version = self.version()

if version == 1:
Expand All @@ -51,7 +51,7 @@ def update(self):

self.version(version)

async def open(self):
async def open(self) -> None:
path = self.database
file_exists = path.is_file()

Expand All @@ -65,5 +65,5 @@ async def open(self):
with self.conn:
self.conn.execute("VACUUM")

async def delete(self):
async def delete(self) -> None:
os.remove(self.database)
6 changes: 3 additions & 3 deletions pyrogram/storage/memory_storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,12 @@


class MemoryStorage(SQLiteStorage):
def __init__(self, name: str, session_string: str = None):
def __init__(self, name: str, session_string: str = None) -> None:
super().__init__(name)

self.session_string = session_string

async def open(self):
async def open(self) -> None:
self.conn = sqlite3.connect(":memory:", check_same_thread=False)
self.create()

Expand Down Expand Up @@ -69,5 +69,5 @@ async def open(self):
await self.is_bot(is_bot)
await self.date(0)

async def delete(self):
async def delete(self) -> None:
pass
Loading