Skip to content

Commit eb576d8

Browse files
Fixed a bug, made improvements in reload system
Didn't test that much, there is still some stuff to do
1 parent d3080b6 commit eb576d8

4 files changed

Lines changed: 72 additions & 43 deletions

File tree

‎telebot/__init__.py‎

Lines changed: 30 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -880,10 +880,27 @@ def __notify_update(self, new_messages):
880880
for listener in self.update_listener:
881881
self._exec_task(listener, new_messages)
882882

883+
def _setup_change_detector(self):
884+
try:
885+
from watchdog.observers import Observer
886+
from telebot.ext.reloader import EventHandler
887+
except ImportError:
888+
raise ImportError(
889+
'Please install watchdog and psutil before using restart_on_change option.'
890+
)
891+
892+
self.event_handler = EventHandler()
893+
path = path_to_watch if path_to_watch else None
894+
if path is None:
895+
path = sys.argv[1] if len(sys.argv) > 1 else '.' # current directory
896+
897+
self.observer = Observer()
898+
self.observer.schedule(self.event_handler, path, recursive=True)
899+
self.observer.start()
883900

884901
def infinity_polling(self, timeout: Optional[int]=20, skip_pending: Optional[bool]=False, long_polling_timeout: Optional[int]=20,
885902
logger_level: Optional[int]=logging.ERROR, allowed_updates: Optional[List[str]]=None,
886-
restart_on_change: Optional[bool]=False, *args, **kwargs):
903+
restart_on_change: Optional[bool]=False, path_to_watch: Optional[str]=None, *args, **kwargs):
887904
"""
888905
Wrap polling with infinite loop and exception handling to avoid bot stops polling.
889906
@@ -912,11 +929,18 @@ def infinity_polling(self, timeout: Optional[int]=20, skip_pending: Optional[boo
912929
:param restart_on_change: Restart a file on file(s) change. Defaults to False
913930
:type restart_on_change: :obj:`bool`
914931
932+
:param path_to_watch: Path to watch for changes. Defaults to current directory
933+
:type path_to_watch: :obj:`str`
934+
915935
:return:
916936
"""
917937
if skip_pending:
918938
self.__skip_updates()
919939

940+
if restart_on_change:
941+
self._setup_change_detector(path_to_watch)
942+
restart_on_change = False
943+
920944
while not self.__stop_polling.is_set():
921945
try:
922946
self.polling(non_stop=True, timeout=timeout, long_polling_timeout=long_polling_timeout,
@@ -938,7 +962,7 @@ def infinity_polling(self, timeout: Optional[int]=20, skip_pending: Optional[boo
938962
def polling(self, non_stop: Optional[bool]=False, skip_pending: Optional[bool]=False, interval: Optional[int]=0,
939963
timeout: Optional[int]=20, long_polling_timeout: Optional[int]=20,
940964
logger_level: Optional[int]=logging.ERROR, allowed_updates: Optional[List[str]]=None,
941-
none_stop: Optional[bool]=None, restart_on_change: Optional[bool]=False):
965+
none_stop: Optional[bool]=None, restart_on_change: Optional[bool]=False, path_to_watch: Optional[str]=None):
942966
"""
943967
This function creates a new Thread that calls an internal __retrieve_updates function.
944968
This allows the bot to retrieve Updates automatically and notify listeners and message handlers accordingly.
@@ -984,6 +1008,9 @@ def polling(self, non_stop: Optional[bool]=False, skip_pending: Optional[bool]=F
9841008
9851009
:param restart_on_change: Restart a file on file(s) change. Defaults to False
9861010
:type restart_on_change: :obj:`bool`
1011+
1012+
:param path_to_watch: Path to watch for changes. Defaults to None
1013+
:type path_to_watch: :obj:`str`
9871014
9881015
:return:
9891016
"""
@@ -995,19 +1022,7 @@ def polling(self, non_stop: Optional[bool]=False, skip_pending: Optional[bool]=F
9951022
self.__skip_updates()
9961023

9971024
if restart_on_change:
998-
try:
999-
from watchdog.observers import Observer
1000-
from telebot.ext.reloader import EventHandler
1001-
except ImportError:
1002-
raise ImportError(
1003-
'Please install watchdog and psutil before using restart_on_change option.'
1004-
)
1005-
1006-
event_handler = EventHandler()
1007-
path = sys.argv[1] if len(sys.argv) > 1 else '.'
1008-
observer = Observer()
1009-
observer.schedule(event_handler, path, recursive=True)
1010-
observer.start()
1025+
self._setup_change_detector(path_to_watch)
10111026

10121027
logger.info('Starting your bot with username: [@%s]', self.user.username)
10131028

‎telebot/async_telebot.py‎

Lines changed: 40 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import re
66
import traceback
77
from typing import Any, Awaitable, Callable, List, Optional, Union
8+
import sys
89

910
# this imports are used to avoid circular import error
1011
import 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

‎telebot/asyncio_helper.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ async def _process_request(token, url, method='get', params=None, files=None, **
7171

7272
else:
7373
# let's check for timeout in params
74-
request_timeout = params.pop('timeout', None)
74+
request_timeout = params.pop('timeout', None) if params else None
7575
# we will apply default request_timeout if there is no timeout in params
7676
# otherwise, we will use timeout parameter applied for payload.
7777

‎telebot/ext/reloader.py‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,9 @@
88

99
logger = logging.getLogger('TeleBot')
1010

11-
12-
1311
class EventHandler(FileSystemEventHandler):
1412
def on_any_event(self, event: FileSystemEvent):
15-
logger.info('* Detected changes in: %s , reloading', (event.src_path))
13+
logger.info('* Detected changes in: %s, reloading', (event.src_path))
1614
restart_file()
1715

1816
def restart_file():

0 commit comments

Comments
 (0)