Pyrofork: add async helper

Signed-off-by: wulan17 <wulan17@nusantararom.org>
This commit is contained in:
wulan17 2023-08-18 03:41:24 +07:00
parent b43b20351f
commit c2a506fca0
No known key found for this signature in database
GPG key ID: 318CD6CD3A6AC0A5
4 changed files with 49 additions and 1 deletions

View file

@ -139,6 +139,7 @@ def pyrogram_api():
start
stop
run
run_sync
restart
add_handler
remove_handler

View file

@ -21,6 +21,7 @@ from .export_session_string import ExportSessionString
from .remove_handler import RemoveHandler
from .restart import Restart
from .run import Run
from .run_sync import RunSync
from .start import Start
from .stop import Stop
from .stop_transmission import StopTransmission
@ -32,6 +33,7 @@ class Utilities(
RemoveHandler,
Restart,
Run,
RunSync,
Start,
Stop,
StopTransmission

View file

@ -0,0 +1,41 @@
"""PyroFork async utils"""
# Copyright (C) 2020 - 2023 UserbotIndo Team, <https://github.com/userbotindo.git>
# Copyright (C) 2022-present Mayuri-Chan, <https://github.com/Mayuri-Chan.git>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from pyrogram import utils
from typing import Any, Callable, TypeVar
class RunSync:
Result = TypeVar("Result")
async def run_sync(self, func: Callable[..., Result], *args: Any, **kwargs: Any) -> Result:
"""Runs the given sync function (optionally with arguments) on a separate thread.
Parameters:
func (``Callable``):
Sync function to run.
\\*args (``any``, *optional*):
Function argument.
\\*\\*kwargs (``any``, *optional*):
Function extras arguments.
Returns:
``any``: The function result.
"""
return await utils.run_sync(func, *args, **kwargs)

View file

@ -26,7 +26,7 @@ import struct
from concurrent.futures.thread import ThreadPoolExecutor
from datetime import datetime, timezone
from getpass import getpass
from typing import Union, List, Dict, Optional
from typing import Union, List, Dict, Optional, Any, Callable, TypeVar
import pyrogram
from pyrogram import raw, enums
@ -374,3 +374,7 @@ def timestamp_to_datetime(ts: Optional[int]) -> Optional[datetime]:
def datetime_to_timestamp(dt: Optional[datetime]) -> Optional[int]:
return int(dt.timestamp()) if dt else None
async def run_sync(func: Callable[..., TypeVar("Result")], *args: Any, **kwargs: Any) -> TypeVar("Result"):
loop = asyncio.get_event_loop()
return await loop.run_in_executor(None, functools.partial(func, *args, **kwargs))