restore original docs, misc linting

This commit is contained in:
Casper da Costa-Luis 2024-10-28 00:33:45 +00:00
parent 03b90e444e
commit f1129e70c9
No known key found for this signature in database
GPG Key ID: F5126E5FBD2512AD
1 changed files with 41 additions and 47 deletions

View File

@ -1,3 +1,13 @@
"""
Sends updates to a Discord bot.
Usage:
>>> from tqdm.contrib.discord import tqdm, trange
>>> for i in trange(10, token='{token}', channel_id='{channel_id}'):
... ...
![screenshot](https://tqdm.github.io/img/screenshot-discord.png)
"""
from os import getenv
from warnings import warn
@ -5,16 +15,15 @@ import requests
from ..auto import tqdm as tqdm_auto
from ..std import TqdmWarning
from .utils_worker import MonoWorker
from ..version import __version__
from .utils_worker import MonoWorker
__author__ = {"github.com/": ["casperdcl","guigoruiz1"]}
__all__ = ["DiscordIO", "tqdm_discord", "tdrange", "tqdm", "trange"]
__author__ = {"github.com/": ["casperdcl", "guigoruiz1"]}
__all__ = ['DiscordIO', 'tqdm_discord', 'tdrange', 'tqdm', 'trange']
class DiscordIO(MonoWorker):
"""Non-blocking file-like IO using a Discord Bot."""
API = "https://discord.com/api/v10"
user_agent = f"TQDM Discord progress bar (https://tqdm.github.io, {__version__})"
@ -28,31 +37,27 @@ class DiscordIO(MonoWorker):
@property
def message_id(self):
if hasattr(self, "_message_id"):
if hasattr(self, '_message_id'):
return self._message_id
try:
headers = {
"Authorization": f"Bot {self.token}",
"User-Agent": self.user_agent,
}
data = {"content": "`" + self.text + "`"}
res = requests.post(
f"{self.API}/channels/{self.channel_id}/messages",
headers=headers,
json=data,
).json()
f'{self.API}/channels/{self.channel_id}/messages',
headers={'Authorization': f'Bot {self.token}', 'User-Agent': self.UA},
json={'content': f"`{self.text}`"}).json()
except Exception as e:
tqdm_auto.write(str(e))
else:
if "id" in res:
self._message_id = res["id"]
if 'id' not in res:
warn("Message not sent", TqdmWarning, stacklevel=2)
else:
self._message_id = res['id']
return self._message_id
def write(self, s):
"""Replaces internal `message_id`'s text with `s`."""
if not s:
s = "..."
s = s.replace("\r", "").strip()
s = s.replace('\r', '').strip()
if s == self.text:
return # avoid duplicate message Bot error
message_id = self.message_id
@ -60,17 +65,11 @@ class DiscordIO(MonoWorker):
return
self.text = s
try:
headers = {
"Authorization": f"Bot {self.token}",
"User-Agent": self.user_agent,
}
data = {"content": "`" + s + "`"}
future = self.submit(
requests.patch,
f"{self.API}/channels/{self.channel_id}/messages/{message_id}",
headers=headers,
json=data,
)
f'{self.API}/channels/{self.channel_id}/messages/{message_id}',
headers={'Authorization': f'Bot {self.token}', 'User-Agent': self.UA},
json={'content': f"`{self.text}`"})
except Exception as e:
tqdm_auto.write(str(e))
else:
@ -79,15 +78,10 @@ class DiscordIO(MonoWorker):
def delete(self):
"""Deletes internal `message_id`."""
try:
headers = {
"Authorization": f"Bot {self.token}",
"User-Agent": self.user_agent,
}
future = self.submit(
requests.delete,
f"{self.API}/channels/{self.channel_id}/messages/{self.message_id}",
headers=headers,
)
f'{self.API}/channels/{self.channel_id}/messages/{self.message_id}',
headers={'Authorization': f'Bot {self.token}', 'User-Agent': self.UA})
except Exception as e:
tqdm_auto.write(str(e))
else:
@ -99,41 +93,41 @@ class tqdm_discord(tqdm_auto):
Standard `tqdm.auto.tqdm` but also sends updates to a Discord Bot.
May take a few seconds to create (`__init__`).
>>> from tqdm.contrib.discord import tqdm, drange
- create a discord bot (not public, no requirement of OAuth2 code
grant, only send message permissions) & invite it to a channel:
<https://discordpy.readthedocs.io/en/latest/discord.html>
- copy the bot `{token}` & `{channel_id}` and paste below
>>> from tqdm.contrib.discord import tqdm, trange
>>> for i in tqdm(iterable, token='{token}', channel_id='{channel_id}'):
... ...
"""
def __init__(self, *args, **kwargs):
"""
Parameters
----------
token : str, required. Discord bot token
[default: ${TQDM_DISCORD_TOKEN}].
channel_id : str, required. Discord channel ID
channel_id : int, required. Discord channel ID
[default: ${TQDM_DISCORD_CHANNEL_ID}].
See `tqdm.auto.tqdm.__init__` for other parameters.
"""
if not kwargs.get("disable"):
if not kwargs.get('disable'):
kwargs = kwargs.copy()
self.dio = DiscordIO(
kwargs.pop("token", getenv("TQDM_DISCORD_TOKEN")),
kwargs.pop("channel_id", getenv("TQDM_DISCORD_CHANNEL_ID")),
)
kwargs.pop('token', getenv('TQDM_DISCORD_TOKEN')),
kwargs.pop('channel_id', getenv('TQDM_DISCORD_CHANNEL_ID')))
super().__init__(*args, **kwargs)
def display(self, **kwargs):
super().display(**kwargs)
fmt = self.format_dict
if fmt.get("bar_format", None):
fmt["bar_format"] = (
fmt["bar_format"]
.replace("<bar/>", "{bar:10u}")
.replace("{bar}", "{bar:10u}")
)
if fmt.get('bar_format', None):
fmt['bar_format'] = fmt['bar_format'].replace(
'<bar/>', '{bar:10u}').replace('{bar}', '{bar:10u}')
else:
fmt["bar_format"] = "{l_bar}{bar:10u}{r_bar}"
fmt['bar_format'] = '{l_bar}{bar:10u}{r_bar}'
self.dio.write(self.format_meter(**fmt))
def clear(self, *args, **kwargs):