55import re
66import traceback
77from typing import Any , Awaitable , Callable , List , Optional , Union
8+ import sys
89
910# this imports are used to avoid circular import error
1011import telebot .util
@@ -213,9 +214,27 @@ async def get_updates(self, offset: Optional[int]=None, limit: Optional[int]=Non
213214 json_updates = await asyncio_helper .get_updates (self .token , offset , limit , timeout , allowed_updates , request_timeout )
214215 return [types .Update .de_json (ju ) for ju in json_updates ]
215216
217+ def _setup_change_detector (self , path_to_watch : str ) -> None :
218+ try :
219+ from watchdog .observers import Observer
220+ from telebot .ext .reloader import EventHandler
221+ except ImportError :
222+ raise ImportError (
223+ 'Please install watchdog and psutil before using restart_on_change option.'
224+ )
225+
226+ self .event_handler = EventHandler ()
227+ path = path_to_watch if path_to_watch else None
228+ if path is None :
229+ path = sys .argv [1 ] if len (sys .argv ) > 1 else '.' # current directory
230+
231+ self .observer = Observer ()
232+ self .observer .schedule (self .event_handler , path , recursive = True )
233+ self .observer .start ()
234+
216235 async def polling (self , non_stop : bool = False , skip_pending = False , interval : int = 0 , timeout : int = 20 ,
217236 request_timeout : Optional [int ]= None , allowed_updates : Optional [List [str ]]= None ,
218- none_stop : Optional [bool ]= None , restart_on_change : Optional [bool ]= False ):
237+ none_stop : Optional [bool ]= None , restart_on_change : Optional [bool ]= False , path_to_watch : Optional [ str ] = None ):
219238 """
220239 Runs bot in long-polling mode in a main loop.
221240 This allows the bot to retrieve Updates automagically and notify listeners and message handlers accordingly.
@@ -259,6 +278,9 @@ async def polling(self, non_stop: bool=False, skip_pending=False, interval: int=
259278
260279 :param restart_on_change: Restart a file on file(s) change. Defaults to False
261280 :type restart_on_change: :obj:`bool`
281+
282+ :param path_to_watch: Path to watch for changes. Defaults to current directory
283+ :type path_to_watch: :obj:`str`
262284
263285 :return:
264286 """
@@ -268,11 +290,15 @@ async def polling(self, non_stop: bool=False, skip_pending=False, interval: int=
268290
269291 if skip_pending :
270292 await self .skip_updates ()
271- await self ._process_polling (non_stop , interval , timeout , request_timeout , allowed_updates , restart_on_change )
293+
294+ if restart_on_change :
295+ self ._setup_change_detector (path_to_watch )
296+
297+ await self ._process_polling (non_stop , interval , timeout , request_timeout , allowed_updates )
272298
273299 async def infinity_polling (self , timeout : Optional [int ]= 20 , skip_pending : Optional [bool ]= False , request_timeout : Optional [int ]= None ,
274300 logger_level : Optional [int ]= logging .ERROR , allowed_updates : Optional [List [str ]]= None ,
275- restart_on_change : Optional [bool ]= False , * args , ** kwargs ):
301+ restart_on_change : Optional [bool ]= False , path_to_watch : Optional [ str ] = None , * args , ** kwargs ):
276302 """
277303 Wrap polling with infinite loop and exception handling to avoid bot stops polling.
278304
@@ -302,15 +328,24 @@ async def infinity_polling(self, timeout: Optional[int]=20, skip_pending: Option
302328 :param restart_on_change: Restart a file on file(s) change. Defaults to False
303329 :type restart_on_change: :obj:`bool`
304330
331+ :param path_to_watch: Path to watch for changes. Defaults to current directory
332+ :type path_to_watch: :obj:`str`
333+
305334 :return: None
306335 """
307336 if skip_pending :
308337 await self .skip_updates ()
309338 self ._polling = True
339+
340+ if restart_on_change :
341+ restart_on_change = False
342+
343+ self ._setup_change_detector (path_to_watch )
344+
310345 while self ._polling :
311346 try :
312347 await self ._process_polling (non_stop = False , timeout = timeout , request_timeout = request_timeout ,
313- allowed_updates = allowed_updates , restart_on_change = restart_on_change , * args , ** kwargs )
348+ allowed_updates = allowed_updates , * args , ** kwargs )
314349 except Exception as e :
315350 if logger_level and logger_level >= logging .ERROR :
316351 logger .error ("Infinity polling exception: %s" , str (e ))
@@ -324,7 +359,7 @@ async def infinity_polling(self, timeout: Optional[int]=20, skip_pending: Option
324359 logger .error ("Break infinity polling" )
325360
326361 async def _process_polling (self , non_stop : bool = False , interval : int = 0 , timeout : int = 20 ,
327- request_timeout : int = None , allowed_updates : Optional [List [str ]]= None , restart_on_change : Optional [ bool ] = False ):
362+ request_timeout : int = None , allowed_updates : Optional [List [str ]]= None ):
328363 """
329364 Function to process polling.
330365
@@ -341,30 +376,11 @@ async def _process_polling(self, non_stop: bool=False, interval: int=0, timeout:
341376 Please note that this parameter doesn't affect updates created before the call to the get_updates,
342377 so unwanted updates may be received for a short period of time.
343378
344- :param restart_on_change: Restart a file on file(s) change. Defaults to False
345- :type restart_on_change: :obj:`bool`
346-
347379 :return:
348380
349381 """
350382
351383 self ._user = await self .get_me ()
352-
353-
354- if restart_on_change :
355- try :
356- from watchdog .observers import Observer
357- from telebot .ext .reloader import EventHandler
358- except ImportError :
359- raise ImportError (
360- 'Please install watchdog and psutil before using restart_on_change option.'
361- )
362-
363- event_handler = EventHandler ()
364- path = sys .argv [1 ] if len (sys .argv ) > 1 else '.'
365- observer = Observer ()
366- observer .schedule (event_handler , path , recursive = True )
367- observer .start ()
368384
369385 logger .info ('Starting your bot with username: [@%s]' , self .user .username )
370386
0 commit comments