2020-06-10 16:04:54 +00:00
|
|
|
"""
|
|
|
|
Sends updates to a Telegram bot.
|
2021-12-01 20:47:00 +00:00
|
|
|
|
|
|
|
Usage:
|
|
|
|
>>> from tqdm.contrib.telegram import tqdm, trange
|
|
|
|
>>> for i in trange(10, token='{token}', chat_id='{chat_id}'):
|
|
|
|
... ...
|
|
|
|
|
|
|
|
![screenshot](https://img.tqdm.ml/screenshot-telegram.gif)
|
2020-06-10 16:04:54 +00:00
|
|
|
"""
|
|
|
|
from __future__ import absolute_import
|
|
|
|
|
2021-12-01 20:47:00 +00:00
|
|
|
from os import getenv
|
|
|
|
from warnings import warn
|
|
|
|
|
2020-06-10 16:04:54 +00:00
|
|
|
from requests import Session
|
|
|
|
|
2021-12-01 20:47:00 +00:00
|
|
|
from ..auto import tqdm as tqdm_auto
|
|
|
|
from ..std import TqdmWarning
|
|
|
|
from ..utils import _range
|
|
|
|
from .utils_worker import MonoWorker
|
|
|
|
|
2020-06-10 16:04:54 +00:00
|
|
|
__author__ = {"github.com/": ["casperdcl"]}
|
|
|
|
__all__ = ['TelegramIO', 'tqdm_telegram', 'ttgrange', 'tqdm', 'trange']
|
|
|
|
|
|
|
|
|
2021-12-01 20:47:00 +00:00
|
|
|
class TelegramIO(MonoWorker):
|
|
|
|
"""Non-blocking file-like IO using a Telegram Bot."""
|
2020-06-10 16:04:54 +00:00
|
|
|
API = 'https://api.telegram.org/bot'
|
|
|
|
|
|
|
|
def __init__(self, token, chat_id):
|
|
|
|
"""Creates a new message in the given `chat_id`."""
|
2021-12-01 20:47:00 +00:00
|
|
|
super(TelegramIO, self).__init__()
|
2020-06-10 16:04:54 +00:00
|
|
|
self.token = token
|
|
|
|
self.chat_id = chat_id
|
2021-12-01 20:47:00 +00:00
|
|
|
self.session = Session()
|
2020-06-10 16:04:54 +00:00
|
|
|
self.text = self.__class__.__name__
|
2021-12-01 20:47:00 +00:00
|
|
|
self.message_id
|
|
|
|
|
|
|
|
@property
|
|
|
|
def message_id(self):
|
|
|
|
if hasattr(self, '_message_id'):
|
|
|
|
return self._message_id
|
2020-06-10 16:04:54 +00:00
|
|
|
try:
|
2021-12-01 20:47:00 +00:00
|
|
|
res = self.session.post(
|
2020-06-10 16:04:54 +00:00
|
|
|
self.API + '%s/sendMessage' % self.token,
|
2021-12-01 20:47:00 +00:00
|
|
|
data={'text': '`' + self.text + '`', 'chat_id': self.chat_id,
|
|
|
|
'parse_mode': 'MarkdownV2'}).json()
|
2020-06-10 16:04:54 +00:00
|
|
|
except Exception as e:
|
|
|
|
tqdm_auto.write(str(e))
|
|
|
|
else:
|
2021-12-01 20:47:00 +00:00
|
|
|
if res.get('error_code') == 429:
|
|
|
|
warn("Creation rate limit: try increasing `mininterval`.",
|
|
|
|
TqdmWarning, stacklevel=2)
|
|
|
|
else:
|
|
|
|
self._message_id = res['result']['message_id']
|
|
|
|
return self._message_id
|
2020-06-10 16:04:54 +00:00
|
|
|
|
|
|
|
def write(self, s):
|
|
|
|
"""Replaces internal `message_id`'s text with `s`."""
|
|
|
|
if not s:
|
2021-12-01 20:47:00 +00:00
|
|
|
s = "..."
|
|
|
|
s = s.replace('\r', '').strip()
|
2020-06-10 16:04:54 +00:00
|
|
|
if s == self.text:
|
|
|
|
return # avoid duplicate message Bot error
|
2021-12-01 20:47:00 +00:00
|
|
|
message_id = self.message_id
|
|
|
|
if message_id is None:
|
|
|
|
return
|
2020-06-10 16:04:54 +00:00
|
|
|
self.text = s
|
|
|
|
try:
|
2021-12-01 20:47:00 +00:00
|
|
|
future = self.submit(
|
|
|
|
self.session.post, self.API + '%s/editMessageText' % self.token,
|
|
|
|
data={'text': '`' + s + '`', 'chat_id': self.chat_id,
|
|
|
|
'message_id': message_id, 'parse_mode': 'MarkdownV2'})
|
2020-06-10 16:04:54 +00:00
|
|
|
except Exception as e:
|
|
|
|
tqdm_auto.write(str(e))
|
|
|
|
else:
|
2021-12-01 20:47:00 +00:00
|
|
|
return future
|
2020-06-10 16:04:54 +00:00
|
|
|
|
2021-12-01 20:47:00 +00:00
|
|
|
def delete(self):
|
|
|
|
"""Deletes internal `message_id`."""
|
2020-06-10 16:04:54 +00:00
|
|
|
try:
|
2021-12-01 20:47:00 +00:00
|
|
|
future = self.submit(
|
|
|
|
self.session.post, self.API + '%s/deleteMessage' % self.token,
|
|
|
|
data={'chat_id': self.chat_id, 'message_id': self.message_id})
|
|
|
|
except Exception as e:
|
|
|
|
tqdm_auto.write(str(e))
|
|
|
|
else:
|
|
|
|
return future
|
2020-06-10 16:04:54 +00:00
|
|
|
|
|
|
|
|
|
|
|
class tqdm_telegram(tqdm_auto):
|
|
|
|
"""
|
2021-12-01 20:47:00 +00:00
|
|
|
Standard `tqdm.auto.tqdm` but also sends updates to a Telegram Bot.
|
|
|
|
May take a few seconds to create (`__init__`).
|
|
|
|
|
|
|
|
- create a bot <https://core.telegram.org/bots#6-botfather>
|
|
|
|
- copy its `{token}`
|
|
|
|
- add the bot to a chat and send it a message such as `/start`
|
|
|
|
- go to <https://api.telegram.org/bot`{token}`/getUpdates> to find out
|
|
|
|
the `{chat_id}`
|
|
|
|
- paste the `{token}` & `{chat_id}` below
|
2020-06-10 16:04:54 +00:00
|
|
|
|
|
|
|
>>> from tqdm.contrib.telegram import tqdm, trange
|
2021-12-01 20:47:00 +00:00
|
|
|
>>> for i in tqdm(iterable, token='{token}', chat_id='{chat_id}'):
|
|
|
|
... ...
|
2020-06-10 16:04:54 +00:00
|
|
|
"""
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
"""
|
|
|
|
Parameters
|
|
|
|
----------
|
2021-12-01 20:47:00 +00:00
|
|
|
token : str, required. Telegram token
|
|
|
|
[default: ${TQDM_TELEGRAM_TOKEN}].
|
|
|
|
chat_id : str, required. Telegram chat ID
|
|
|
|
[default: ${TQDM_TELEGRAM_CHAT_ID}].
|
2020-06-10 16:04:54 +00:00
|
|
|
|
|
|
|
See `tqdm.auto.tqdm.__init__` for other parameters.
|
|
|
|
"""
|
2021-12-01 20:47:00 +00:00
|
|
|
if not kwargs.get('disable'):
|
|
|
|
kwargs = kwargs.copy()
|
|
|
|
self.tgio = TelegramIO(
|
|
|
|
kwargs.pop('token', getenv('TQDM_TELEGRAM_TOKEN')),
|
|
|
|
kwargs.pop('chat_id', getenv('TQDM_TELEGRAM_CHAT_ID')))
|
2020-06-10 16:04:54 +00:00
|
|
|
super(tqdm_telegram, self).__init__(*args, **kwargs)
|
|
|
|
|
|
|
|
def display(self, **kwargs):
|
|
|
|
super(tqdm_telegram, self).display(**kwargs)
|
|
|
|
fmt = self.format_dict
|
2021-12-01 20:47:00 +00:00
|
|
|
if fmt.get('bar_format', None):
|
|
|
|
fmt['bar_format'] = fmt['bar_format'].replace(
|
|
|
|
'<bar/>', '{bar:10u}').replace('{bar}', '{bar:10u}')
|
2020-06-10 16:04:54 +00:00
|
|
|
else:
|
2021-12-01 20:47:00 +00:00
|
|
|
fmt['bar_format'] = '{l_bar}{bar:10u}{r_bar}'
|
2020-06-10 16:04:54 +00:00
|
|
|
self.tgio.write(self.format_meter(**fmt))
|
|
|
|
|
2021-12-01 20:47:00 +00:00
|
|
|
def clear(self, *args, **kwargs):
|
|
|
|
super(tqdm_telegram, self).clear(*args, **kwargs)
|
|
|
|
if not self.disable:
|
|
|
|
self.tgio.write("")
|
|
|
|
|
|
|
|
def close(self):
|
|
|
|
if self.disable:
|
|
|
|
return
|
|
|
|
super(tqdm_telegram, self).close()
|
|
|
|
if not (self.leave or (self.leave is None and self.pos == 0)):
|
|
|
|
self.tgio.delete()
|
2020-06-10 16:04:54 +00:00
|
|
|
|
|
|
|
|
|
|
|
def ttgrange(*args, **kwargs):
|
|
|
|
"""
|
|
|
|
A shortcut for `tqdm.contrib.telegram.tqdm(xrange(*args), **kwargs)`.
|
|
|
|
On Python3+, `range` is used instead of `xrange`.
|
|
|
|
"""
|
|
|
|
return tqdm_telegram(_range(*args), **kwargs)
|
|
|
|
|
|
|
|
|
|
|
|
# Aliases
|
|
|
|
tqdm = tqdm_telegram
|
|
|
|
trange = ttgrange
|