heroku_waker.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. # █ █ ▀ █▄▀ ▄▀█ █▀█ ▀
  2. # █▀█ █ █ █ █▀█ █▀▄ █
  3. # © Copyright 2022
  4. # https://t.me/hikariatama
  5. #
  6. # 🔒 Licensed under the GNU AGPLv3
  7. # 🌐 https://www.gnu.org/licenses/agpl-3.0.html
  8. import logging
  9. import os
  10. try:
  11. import redis
  12. except ImportError as e:
  13. if "DYNO" in os.environ:
  14. raise e
  15. from telethon.tl.types import Message
  16. from .. import loader, main, utils, heroku
  17. from telethon.errors.rpcerrorlist import YouBlockedUserError
  18. from telethon.tl.functions.contacts import UnblockRequest
  19. logger = logging.getLogger(__name__)
  20. @loader.tds
  21. class HerokuMod(loader.Module):
  22. """Stuff related to Hikka Heroku installation"""
  23. strings = {
  24. "name": "Heroku",
  25. "redisdocs": (
  26. "<emoji document_id='5458675903028535170'>🛍</emoji> <b>Redis"
  27. " Database</b>\n\n🇷🇺 <b>If you are from Russia, or just want to use"
  28. " external service:</b>\n1. Go to https://redis.com\n2. Register"
  29. " account\n3. Create database instance\n4. Enter your Redis Database URL"
  30. " via <code>.setredis &lt;redis_url&gt;</code>\n<i><emoji"
  31. " document_id='6318918617891080008'>💡</emoji> Hint: URL structure is"
  32. " <code>redis://:PASSWORD@ENDPOINT</code></i>\n\n♓️ <b>If you are not from"
  33. " Russia, just enable </b><code>heroku-redis</code><b> plugin for your app."
  34. " For this action Heroku account verification is required!</b>"
  35. ),
  36. "url_invalid": (
  37. "<emoji document_id='5379568936218009290'>👎</emoji> <b>Invalid URL"
  38. " specified</b>"
  39. ),
  40. "url_saved": (
  41. "<emoji document_id='5368324170671202286'>👍</emoji> <b>URL saved</b>"
  42. ),
  43. }
  44. strings_ru = {
  45. "redisdocs": (
  46. "<emoji document_id='5458675903028535170'>🛍</emoji> <b>База данных"
  47. " Redis</b>\n\n🇷🇺 <b>Если ты из России, или просто хочешь использовать"
  48. " внешний сервис:</b>\n1. Перейди на https://redis.com\n2."
  49. " Зарегистрируйся\n3. Создай базу данных\n4. Введи Database URL в"
  50. " <code>.setredis &lt;redis_url&gt;</code>\n<i><emoji"
  51. " document_id='6318918617891080008'>💡</emoji> Подсказка: URL выглядит так:"
  52. " <code>redis://:PASSWORD@ENDPOINT</code></i>\n\n♓️ <b>Если ты не из"
  53. " России, можешь просто активировать плагин"
  54. " </b><code>heroku-redis</code><b> в Hikka app Heroku. Для этого тебе нужно"
  55. " будет верифицировать аккаунт</b>"
  56. ),
  57. "url_invalid": (
  58. "<emoji document_id='5379568936218009290'>👎</emoji> <b>Указан неверный"
  59. " URL</b>"
  60. ),
  61. "url_saved": (
  62. "<emoji document_id='5368324170671202286'>👍</emoji> <b>URL сохранен</b>"
  63. ),
  64. }
  65. _bot = "@WebpageBot"
  66. async def client_ready(self):
  67. if "DYNO" not in os.environ:
  68. raise loader.SelfUnload
  69. await utils.dnd(self._client, self._bot, True)
  70. self._heroku_url = heroku.get_app(api_token=main.hikka.api_token)[0].web_url
  71. self._heroku_pinger.start()
  72. @loader.command(ru_doc="<ссылка Redis> - Установить базу данных Redis")
  73. async def setredis(self, message: Message):
  74. """<redis_url> - Set Redis Database URL"""
  75. args = utils.get_args_raw(message)
  76. if not args:
  77. await utils.answer(message, self.strings("redisdocs"))
  78. return
  79. try:
  80. redis.from_url(args)
  81. except Exception:
  82. await utils.answer(message, self.strings("url_invalid"))
  83. return
  84. main.save_config_key("redis_uri", args)
  85. await self._db.redis_init()
  86. await self._db.remote_force_save()
  87. await utils.answer(message, self.strings("url_saved"))
  88. @loader.loop(interval=20 * 60, wait_before=True)
  89. async def _heroku_pinger(self):
  90. """Sends request to Heroku webapp through WebpageBot"""
  91. async with self._client.conversation(self._bot) as conv:
  92. try:
  93. m = await conv.send_message(self._heroku_url)
  94. except YouBlockedUserError:
  95. await self._client(UnblockRequest(self._bot))
  96. m = await conv.send_message(self._heroku_url)
  97. r = await conv.get_response()
  98. await m.delete()
  99. await r.delete()