discord.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. """
  2. Sends updates to a Discord bot.
  3. Usage:
  4. >>> from tqdm.contrib.discord import tqdm, trange
  5. >>> for i in tqdm(iterable, token='{token}', channel_id='{channel_id}'):
  6. ... ...
  7. ![screenshot](
  8. https://raw.githubusercontent.com/tqdm/img/src/screenshot-discord.png)
  9. """
  10. from __future__ import absolute_import
  11. import logging
  12. from os import getenv
  13. try:
  14. from disco.client import Client, ClientConfig
  15. except ImportError:
  16. raise ImportError("Please `pip install disco-py`")
  17. from tqdm.auto import tqdm as tqdm_auto
  18. from tqdm.utils import _range
  19. from .utils_worker import MonoWorker
  20. __author__ = {"github.com/": ["casperdcl"]}
  21. __all__ = ['DiscordIO', 'tqdm_discord', 'tdrange', 'tqdm', 'trange']
  22. class DiscordIO(MonoWorker):
  23. """Non-blocking file-like IO using a Discord Bot."""
  24. def __init__(self, token, channel_id):
  25. """Creates a new message in the given `channel_id`."""
  26. super(DiscordIO, self).__init__()
  27. config = ClientConfig()
  28. config.token = token
  29. client = Client(config)
  30. self.text = self.__class__.__name__
  31. try:
  32. self.message = client.api.channels_messages_create(
  33. channel_id, self.text)
  34. except Exception as e:
  35. tqdm_auto.write(str(e))
  36. def write(self, s):
  37. """Replaces internal `message`'s text with `s`."""
  38. if not s:
  39. return
  40. s = s.replace('\r', '').strip()
  41. if s == self.text:
  42. return # skip duplicate message
  43. self.text = s
  44. try:
  45. future = self.submit(self.message.edit, '`' + s + '`')
  46. except Exception as e:
  47. tqdm_auto.write(str(e))
  48. else:
  49. return future
  50. class tqdm_discord(tqdm_auto):
  51. """
  52. Standard `tqdm.auto.tqdm` but also sends updates to a Discord Bot.
  53. May take a few seconds to create (`__init__`).
  54. - create a discord bot (not public, no requirement of OAuth2 code
  55. grant, only send message permissions) & invite it to a channel:
  56. <https://discordpy.readthedocs.io/en/latest/discord.html>
  57. - copy the bot `{token}` & `{channel_id}` and paste below
  58. >>> from tqdm.contrib.discord import tqdm, trange
  59. >>> for i in tqdm(iterable, token='{token}', channel_id='{channel_id}'):
  60. ... ...
  61. """
  62. def __init__(self, *args, **kwargs):
  63. """
  64. Parameters
  65. ----------
  66. token : str, required. Discord token
  67. [default: ${TQDM_DISCORD_TOKEN}].
  68. channel_id : int, required. Discord channel ID
  69. [default: ${TQDM_DISCORD_CHANNEL_ID}].
  70. mininterval : float, optional.
  71. Minimum of [default: 1.5] to avoid rate limit.
  72. See `tqdm.auto.tqdm.__init__` for other parameters.
  73. """
  74. kwargs = kwargs.copy()
  75. logging.getLogger("HTTPClient").setLevel(logging.WARNING)
  76. self.dio = DiscordIO(
  77. kwargs.pop('token', getenv("TQDM_DISCORD_TOKEN")),
  78. kwargs.pop('channel_id', getenv("TQDM_DISCORD_CHANNEL_ID")))
  79. kwargs['mininterval'] = max(1.5, kwargs.get('mininterval', 1.5))
  80. super(tqdm_discord, self).__init__(*args, **kwargs)
  81. def display(self, **kwargs):
  82. super(tqdm_discord, self).display(**kwargs)
  83. fmt = self.format_dict
  84. if 'bar_format' in fmt and fmt['bar_format']:
  85. fmt['bar_format'] = fmt['bar_format'].replace('<bar/>', '{bar}')
  86. else:
  87. fmt['bar_format'] = '{l_bar}{bar}{r_bar}'
  88. fmt['bar_format'] = fmt['bar_format'].replace('{bar}', '{bar:10u}')
  89. self.dio.write(self.format_meter(**fmt))
  90. def __new__(cls, *args, **kwargs):
  91. """
  92. Workaround for mixed-class same-stream nested progressbars.
  93. See [#509](https://github.com/tqdm/tqdm/issues/509)
  94. """
  95. with cls.get_lock():
  96. try:
  97. cls._instances = tqdm_auto._instances
  98. except AttributeError:
  99. pass
  100. instance = super(tqdm_discord, cls).__new__(cls, *args, **kwargs)
  101. with cls.get_lock():
  102. try:
  103. # `tqdm_auto` may have been changed so update
  104. cls._instances.update(tqdm_auto._instances)
  105. except AttributeError:
  106. pass
  107. tqdm_auto._instances = cls._instances
  108. return instance
  109. def tdrange(*args, **kwargs):
  110. """
  111. A shortcut for `tqdm.contrib.discord.tqdm(xrange(*args), **kwargs)`.
  112. On Python3+, `range` is used instead of `xrange`.
  113. """
  114. return tqdm_discord(_range(*args), **kwargs)
  115. # Aliases
  116. tqdm = tqdm_discord
  117. trange = tdrange