hikka_info.py 7.9 KB

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