heroku_waker.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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. "🥡 <b>Redis Database</b>\n\n🇷🇺 <b>If you are from Russia, or just want to"
  27. " use external service:</b>\n1. Go to https://redis.com\n2. Register"
  28. " account\n3. Create database instance\n4. Enter your Redis Database URL"
  29. " via <code>.setredis &lt;redis_url&gt;</code>\n<i>💡 Hint: URL structure is"
  30. " <code>redis://:PASSWORD@ENDPOINT</code></i>\n\n♓️ <b>If you are not from"
  31. " Russia, just enable </b><code>heroku-redis</code><b> plugin for your app."
  32. " For this action Heroku account verification is required!</b>"
  33. ),
  34. "url_invalid": "🚫 <b>Invalid URL specified</b>",
  35. "url_saved": "✅ <b>URL saved</b>",
  36. }
  37. strings_ru = {
  38. "redisdocs": (
  39. "🥡 <b>База данных Redis</b>\n\n🇷🇺 <b>Если ты из России, или просто хочешь"
  40. " использовать внешний сервис:</b>\n1. Перейди на https://redis.com\n2."
  41. " Зарегистрируйся\n3. Создай базу данных\n4. Введи Database URL в"
  42. " <code>.setredis &lt;redis_url&gt;</code>\n<i>💡 Подсказка: URL выглядит"
  43. " так: <code>redis://:PASSWORD@ENDPOINT</code></i>\n\n♓️ <b>Если ты не из"
  44. " России, можешь просто активировать плагин"
  45. " </b><code>heroku-redis</code><b> в Hikka app Heroku. Для этого тебе нужно"
  46. " будет верифицировать аккаунт</b>"
  47. ),
  48. "url_invalid": "🚫 <b>Указан неверный URL</b>",
  49. "url_saved": "✅ <b>URL сохранен</b>",
  50. }
  51. _bot = "@WebpageBot"
  52. async def client_ready(self, client, _):
  53. if "DYNO" not in os.environ:
  54. raise loader.SelfUnload
  55. await utils.dnd(client, self._bot, True)
  56. self._heroku_url = heroku.get_app(api_token=main.hikka.api_token)[0].web_url
  57. self._heroku_pinger.start()
  58. async def setrediscmd(self, message: Message):
  59. """<redis_url> - Set Redis Database URL"""
  60. args = utils.get_args_raw(message)
  61. if not args:
  62. await utils.answer(message, self.strings("redisdocs"))
  63. return
  64. try:
  65. redis.from_url(args)
  66. except Exception:
  67. await utils.answer(message, self.strings("url_invalid"))
  68. return
  69. main.save_config_key("redis_uri", args)
  70. await self._db.redis_init()
  71. await self._db.remote_force_save()
  72. await utils.answer(message, self.strings("url_saved"))
  73. @loader.loop(interval=20 * 60, wait_before=True)
  74. async def _heroku_pinger(self):
  75. """Sends request to Heroku webapp through WebpageBot"""
  76. async with self._client.conversation(self._bot) as conv:
  77. try:
  78. m = await conv.send_message(self._heroku_url)
  79. except YouBlockedUserError:
  80. await self._client(UnblockRequest(self._bot))
  81. m = await conv.send_message(self._heroku_url)
  82. r = await conv.get_response()
  83. await m.delete()
  84. await r.delete()