telegram_tqdm.py 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import telepot
  2. from tqdm import tqdm
  3. from datetime import datetime
  4. class _TelegramIO():
  5. def __init__(self, token, chat_id, #chat_id_list,
  6. show_last_update=True):
  7. self.bot = telepot.Bot(token)
  8. self.text = self.prev_text = '<< Init tg_tqdm bar >>'
  9. # self.chat_id_list = chat_id_list
  10. # for chat_id in chat_id_list:
  11. self.chat_id = chat_id
  12. self.message_id = self.bot.sendMessage(chat_id, self.text)['message_id']
  13. self.show_last_update = show_last_update
  14. def write(self, s):
  15. new_text = s.strip().replace('\r', '')
  16. if len(new_text) != 0:
  17. self.text = new_text
  18. def flush(self):
  19. if self.prev_text != self.text:
  20. if '%' in self.text:
  21. # for chat_id in self.chat_id_list:
  22. self.bot.editMessageText((self.chat_id, self.message_id), self.text +
  23. '\nLast update: {}'.format(datetime.now()) if self.show_last_update else '')
  24. self.prev_text = self.text
  25. def tg_tqdm(token, chat_id, #chat_id_list,
  26. iterable=None, show_last_update=True,
  27. desc=None, total=None, leave=True, ncols=None, mininterval=1.0, maxinterval=10.0,
  28. miniters=None, ascii=False, disable=False, unit='it',
  29. unit_scale=False, dynamic_ncols=False, smoothing=0.3,
  30. bar_format=None, initial=0, position=None, postfix=None,
  31. unit_divisor=1000, gui=False, **kwargs):
  32. """
  33. Decorate an iterable object, returning an iterator which acts exactly
  34. like the original iterable, but send to Telegram a dynamically updating
  35. progressbar every time a value is requested.
  36. Parameters
  37. ----------
  38. iterable : iterable, required
  39. Iterable to decorate with a progressbar.
  40. Leave blank to manually manage the updates.
  41. token : string, required
  42. Token of your telegram bot
  43. chat_id : int, required
  44. Chat ID where information will be sent about the progress
  45. show_last_update : bool, optional [default: True]
  46. Should I show the time-date of the last change in the progress bar?
  47. desc, total, leave, ncols, ... :
  48. Like in tqdm
  49. """
  50. tg_io = _TelegramIO(token, chat_id, #chat_id_list,
  51. show_last_update)
  52. return tqdm(iterable=iterable,
  53. desc=desc,
  54. total=total,
  55. leave=leave,
  56. file=tg_io,
  57. ncols=ncols,
  58. mininterval=mininterval,
  59. maxinterval=maxinterval,
  60. miniters=miniters,
  61. ascii=ascii,
  62. disable=disable,
  63. unit=unit,
  64. unit_scale=unit_scale,
  65. dynamic_ncols=dynamic_ncols,
  66. smoothing=smoothing,
  67. bar_format=bar_format,
  68. initial=initial,
  69. position=position,
  70. postfix=postfix,
  71. unit_divisor=unit_divisor,
  72. gui=gui,
  73. **kwargs)