hikka_info.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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. # scope: inline
  9. import logging
  10. import git
  11. from telethon.tl.types import Message
  12. from telethon.utils import get_display_name
  13. from .. import loader, utils, version
  14. from ..inline.types import InlineQuery
  15. logger = logging.getLogger(__name__)
  16. @loader.tds
  17. class HikkaInfoMod(loader.Module):
  18. """Show userbot info"""
  19. strings = {
  20. "name": "HikkaInfo",
  21. "owner": "Owner",
  22. "version": "Version",
  23. "build": "Build",
  24. "prefix": "Prefix",
  25. "uptime": "Uptime",
  26. "branch": "Branch",
  27. "send_info": "Send userbot info",
  28. "description": "ℹ This will not compromise any sensitive info",
  29. "up-to-date": "<b>😌 Up-to-date</b>",
  30. "update_required": "<b>😕 Update required </b><code>.update</code>",
  31. "_cfg_cst_msg": (
  32. "Custom message for info. May contain {me}, {version}, {build}, {prefix},"
  33. " {platform}, {upd}, {uptime}, {branch} keywords"
  34. ),
  35. "_cfg_cst_btn": "Custom button for info. Leave empty to remove button",
  36. "_cfg_banner": "URL to image banner",
  37. }
  38. strings_ru = {
  39. "owner": "Владелец",
  40. "version": "Версия",
  41. "build": "Сборка",
  42. "prefix": "Префикс",
  43. "uptime": "Аптайм",
  44. "branch": "Ветка",
  45. "send_info": "Отправить информацию о юзерботе",
  46. "description": "ℹ Это не раскроет никакой личной информации",
  47. "_ihandle_doc_info": "Отправить информацию о юзерботе",
  48. "up-to-date": "<b>😌 Актуальная версия</b>",
  49. "update_required": "<b>😕 Требуется обновление </b><code>.update</code>",
  50. "_cfg_cst_msg": (
  51. "Кастомный текст сообщения в info. Может содержать ключевые слова {me},"
  52. " {version}, {build}, {prefix}, {platform}, {upd}, {uptime}, {branch}"
  53. ),
  54. "_cfg_cst_btn": (
  55. "Кастомная кнопка в сообщении в info. Оставь пустым, чтобы убрать кнопку"
  56. ),
  57. "_cfg_banner": "Ссылка на баннер-картинку",
  58. }
  59. def __init__(self):
  60. self.config = loader.ModuleConfig(
  61. loader.ConfigValue(
  62. "custom_message",
  63. doc=lambda: self.strings("_cfg_cst_msg"),
  64. ),
  65. loader.ConfigValue(
  66. "custom_button",
  67. ["🌘 Support chat", "https://t.me/hikka_talks"],
  68. lambda: self.strings("_cfg_cst_btn"),
  69. validator=loader.validators.Union(
  70. loader.validators.Series(fixed_len=2),
  71. loader.validators.NoneType(),
  72. ),
  73. ),
  74. loader.ConfigValue(
  75. "banner_url",
  76. "https://github.com/hikariatama/assets/raw/master/hikka_banner.png",
  77. lambda: self.strings("_cfg_banner"),
  78. validator=loader.validators.Link(),
  79. ),
  80. )
  81. async def client_ready(self):
  82. self._me = await self._client.get_me()
  83. def _render_info(self) -> str:
  84. try:
  85. repo = git.Repo(search_parent_directories=True)
  86. diff = repo.git.log([f"HEAD..origin/{version.branch}", "--oneline"])
  87. upd = (
  88. self.strings("update_required") if diff else self.strings("up-to-date")
  89. )
  90. except Exception:
  91. upd = ""
  92. me = (
  93. "<b><a"
  94. f' href="tg://user?id={self._me.id}">{utils.escape_html(get_display_name(self._me))}</a></b>'
  95. )
  96. build = utils.get_commit_url()
  97. _version = f'<i>{".".join(list(map(str, list(version.__version__))))}</i>'
  98. prefix = f"«<code>{utils.escape_html(self.get_prefix())}</code>»"
  99. platform = utils.get_named_platform()
  100. return (
  101. (
  102. "<b>🌘 Hikka</b>\n"
  103. if "hikka" not in self.config["custom_message"].lower()
  104. else ""
  105. )
  106. + self.config["custom_message"].format(
  107. me=me,
  108. version=_version,
  109. build=build,
  110. prefix=prefix,
  111. platform=platform,
  112. upd=upd,
  113. uptime=utils.formatted_uptime(),
  114. branch=version.branch,
  115. )
  116. if self.config["custom_message"]
  117. else (
  118. "<b>🌘 Hikka</b>\n"
  119. f'<b>🤴 {self.strings("owner")}: </b>{me}\n\n'
  120. f"<b>🔮 {self.strings('version')}: </b>{_version} {build}\n"
  121. f"<b>🌳 {self.strings('branch')}: </b><code>{version.branch}</code>\n"
  122. f"{upd}\n\n"
  123. f"<b>📼 {self.strings('prefix')}: </b>{prefix}\n"
  124. f"<b>⌚️ {self.strings('uptime')}: </b>{utils.formatted_uptime()}\n"
  125. f"<b>{platform}</b>\n"
  126. )
  127. )
  128. def _get_mark(self):
  129. return (
  130. {
  131. "text": self.config["custom_button"][0],
  132. "url": self.config["custom_button"][1],
  133. }
  134. if self.config["custom_button"]
  135. else None
  136. )
  137. @loader.inline_everyone
  138. async def info_inline_handler(self, _: InlineQuery) -> dict:
  139. """Send userbot info"""
  140. return {
  141. "title": self.strings("send_info"),
  142. "description": self.strings("description"),
  143. "message": self._render_info(),
  144. "thumb": (
  145. "https://github.com/hikariatama/Hikka/raw/master/assets/hikka_pfp.png"
  146. ),
  147. "reply_markup": self._get_mark(),
  148. }
  149. @loader.unrestricted
  150. async def infocmd(self, message: Message):
  151. """Send userbot info"""
  152. await self.inline.form(
  153. message=message,
  154. text=self._render_info(),
  155. reply_markup=self._get_mark(),
  156. **(
  157. {"photo": self.config["banner_url"]}
  158. if self.config["banner_url"]
  159. else {}
  160. ),
  161. )
  162. @loader.unrestricted
  163. async def hikkainfocmd(self, message: Message):
  164. """[en/ru - default en] - Send info aka 'What is Hikka?'"""
  165. args = utils.get_args_raw(message)
  166. args = args if args in {"en", "ru"} else "en"
  167. await utils.answer(
  168. message,
  169. "<emoji document_id=6318565919471699564>🌌</emoji>"
  170. " <b>Hikka</b>\n\nTelegram userbot with a lot of features, like inline"
  171. " galleries, forms, lists and animated emojis support. Userbot - software,"
  172. " running on your Telegram account. If you write a command to any chat, it"
  173. " will get executed right there. Check out live examples at <a"
  174. ' href="https://github.com/hikariatama/Hikka">GitHub</a>'
  175. if args == "en"
  176. else (
  177. "<emoji document_id=6318565919471699564>🌌</emoji>"
  178. " <b>Hikka</b>\n\nTelegram юзербот с огромным количеством функций, из"
  179. " которых: инлайн галереи, формы, списки, а также поддержка"
  180. " анимированных эмодзи. Юзербот - программа, которая запускается на"
  181. " твоем Telegram-аккаунте. Когда ты пишешь команду в любом чате, она"
  182. " сразу же выполняется. Обрати внимание на живые примеры на <a"
  183. ' href="https://github.com/hikariatama/Hikka">GitHub</a>'
  184. ),
  185. )