translate.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. # ©️ Dan Gazizullin, 2021-2023
  2. # This file is a part of Hikka Userbot
  3. # 🌐 https://github.com/hikariatama/Hikka
  4. # You can redistribute it and/or modify it under the terms of the GNU AGPLv3
  5. # 🔑 https://www.gnu.org/licenses/agpl-3.0.html
  6. import logging
  7. from hikkatl.tl.types import Message
  8. from .. import loader, utils
  9. logger = logging.getLogger(__name__)
  10. @loader.tds
  11. class Translator(loader.Module):
  12. """Translates text (obviously)"""
  13. strings = {"name": "Translator"}
  14. @loader.command()
  15. async def tr(self, message: Message):
  16. if not (args := utils.get_args_raw(message)):
  17. text = None
  18. lang = self.strings("language")
  19. else:
  20. lang = args.split(maxsplit=1)[0]
  21. if len(lang) != 2:
  22. text = args
  23. lang = self.strings("language")
  24. else:
  25. try:
  26. text = args.split(maxsplit=1)[1]
  27. except IndexError:
  28. text = None
  29. if not text:
  30. if not (reply := await message.get_reply_message()):
  31. await utils.answer(message, self.strings("no_args"))
  32. return
  33. text = reply.raw_text
  34. entities = reply.entities
  35. else:
  36. entities = []
  37. try:
  38. await utils.answer(
  39. message,
  40. await self._client.translate(
  41. message.peer_id,
  42. message,
  43. lang,
  44. raw_text=text,
  45. entities=entities,
  46. ),
  47. )
  48. except Exception:
  49. logger.exception("Unable to translate text")
  50. await utils.answer(message, self.strings("error"))