Skip to content

Commit d9cb9c5

Browse files
committed
Allow start/restart being used inside handlers with block=False
1 parent 51f88ef commit d9cb9c5

1 file changed

Lines changed: 30 additions & 6 deletions

File tree

pyrogram/client/client.py

Lines changed: 30 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -840,11 +840,17 @@ def start(self):
840840
self.initialize()
841841
return self
842842

843-
def stop(self):
843+
def stop(self, block: bool = True):
844844
"""Stop the Client.
845845
846846
This method disconnects the client from Telegram and stops the underlying tasks.
847847
848+
Parameters:
849+
block (``bool``, *optional*):
850+
Blocks the code execution until the client has been restarted. It is useful with ``block=False`` in case
851+
you want to stop the own client *within* an handler in order not to cause a deadlock.
852+
Defaults to True.
853+
848854
Returns:
849855
:obj:`Client`: The stopped client itself.
850856
@@ -864,17 +870,29 @@ def stop(self):
864870
865871
app.stop()
866872
"""
867-
self.terminate()
868-
self.disconnect()
873+
def do_it():
874+
self.terminate()
875+
self.disconnect()
876+
877+
if block:
878+
do_it()
879+
else:
880+
Thread(target=do_it).start()
869881

870882
return self
871883

872-
def restart(self):
884+
def restart(self, block: bool = True):
873885
"""Restart the Client.
874886
875887
This method will first call :meth:`~Client.stop` and then :meth:`~Client.start` in a row in order to restart
876888
a client using a single method.
877889
890+
Parameters:
891+
block (``bool``, *optional*):
892+
Blocks the code execution until the client has been restarted. It is useful with ``block=False`` in case
893+
you want to restart the own client *within* an handler in order not to cause a deadlock.
894+
Defaults to True.
895+
878896
Returns:
879897
:obj:`Client`: The restarted client itself.
880898
@@ -898,8 +916,14 @@ def restart(self):
898916
899917
app.stop()
900918
"""
901-
self.stop()
902-
self.start()
919+
def do_it():
920+
self.stop()
921+
self.start()
922+
923+
if block:
924+
do_it()
925+
else:
926+
Thread(target=do_it).start()
903927

904928
return self
905929

0 commit comments

Comments
 (0)