From 8e95ffcd6c0827b2b6bd770f6705892b69a55137 Mon Sep 17 00:00:00 2001 From: Zaid _ <162994967+zaid5o5@users.noreply.github.com> Date: Sun, 9 Jun 2024 21:46:09 +0300 Subject: [PATCH] Pyrofork: Add translate methods Signed-off-by: Yasir Aris M --- compiler/docs/compiler.py | 4 +- pyrogram/methods/messages/__init__.py | 5 +- pyrogram/methods/messages/translate_text.py | 105 ++++++++++++++++++ pyrogram/types/messages_and_media/__init__.py | 4 +- pyrogram/types/messages_and_media/message.py | 30 +++++ .../messages_and_media/translated_text.py | 62 +++++++++++ 6 files changed, 206 insertions(+), 4 deletions(-) create mode 100644 pyrogram/methods/messages/translate_text.py create mode 100644 pyrogram/types/messages_and_media/translated_text.py diff --git a/compiler/docs/compiler.py b/compiler/docs/compiler.py index 67c8d6ab..c9bd8b8d 100644 --- a/compiler/docs/compiler.py +++ b/compiler/docs/compiler.py @@ -219,6 +219,7 @@ def pyrogram_api(): get_discussion_replies get_discussion_replies_count get_custom_emoji_stickers + translate_message_text """, chats=""" Chats @@ -510,6 +511,7 @@ def pyrogram_api(): WebPage WebPageEmpty WebPagePreview + TranslatedText Poll PollOption Dice @@ -887,4 +889,4 @@ if "__main__" == __name__: DESTINATION = "../../docs/source/telegram" PYROGRAM_API_DEST = "../../docs/source/api" - start() + start() \ No newline at end of file diff --git a/pyrogram/methods/messages/__init__.py b/pyrogram/methods/messages/__init__.py index 677e282d..b4303b7b 100644 --- a/pyrogram/methods/messages/__init__.py +++ b/pyrogram/methods/messages/__init__.py @@ -72,7 +72,7 @@ from .send_web_page import SendWebPage from .stop_poll import StopPoll from .stream_media import StreamMedia from .vote_poll import VotePoll - +from .translate_text import TranslateText class Messages( DeleteMessages, @@ -129,6 +129,7 @@ class Messages( GetDiscussionReplies, GetDiscussionRepliesCount, StreamMedia, - GetCustomEmojiStickers + GetCustomEmojiStickers, + TranslateText ): pass diff --git a/pyrogram/methods/messages/translate_text.py b/pyrogram/methods/messages/translate_text.py new file mode 100644 index 00000000..781a5879 --- /dev/null +++ b/pyrogram/methods/messages/translate_text.py @@ -0,0 +1,105 @@ +# Pyrofork - Telegram MTProto API Client Library for Python +# Copyright (C) 2017-present Dan +# Copyright (C) 2022-present Mayuri-Chan +# +# This file is part of Pyrofork. +# +# Pyrofork is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License as published +# by the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Pyrofork is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with Pyrofork. If not, see . + +from typing import List, Optional, Union + +import pyrogram +from pyrogram import enums, raw, types, utils + + +class TranslateText: + async def translate_message_text( + self: "pyrogram.Client", + to_language_code: str, + chat_id: Optional[Union[int, str]] = None, + message_ids: Optional[Union[int, List[int]]] = None, + text: Optional[str] = None, + parse_mode: Optional["enums.ParseMode"] = None, + entities: Optional[List["types.MessageEntity"]] = None + ) -> Union["types.TranslatedText", List["types.TranslatedText"]]: + """Translates a text or message(s) to the given language. If the current user is a Telegram Premium user, then text formatting is preserved. + + Parameters: + to_language_code (``str``): + Language code of the language to which the message/text is translated. + Must be one of the supported language codes. + + chat_id (``Optional[int | str]``): + Unique identifier (int) or username (str) of the target chat. + + message_ids (``Optional[int | List[int]]``): + Identifier or list of message identifiers of the target message(s). + + text (``Optional[str]``): + Text to translate. + + parse_mode (:obj:`~pyrogram.enums.ParseMode`, *optional*): + By default, texts are parsed using both Markdown and HTML styles. + You can combine both syntaxes together. + + entities (List of :obj:`~pyrogram.types.MessageEntity`): + List of special entities that appear in message text, which can be specified instead of *parse_mode*. + + Returns: + :obj:`~pyrogram.types.TranslatedText` | List of :obj:`~pyrogram.types.TranslatedText`: In case *message_ids* was not + a list, a single result is returned, otherwise a list of results is returned. + """ + if text is not None: + message, entities = ( + await utils.parse_text_entities( + self, + text, + parse_mode, + entities + ) + ).values() + + r = await self.invoke( + raw.functions.messages.TranslateText( + to_lang=to_language_code, + text=[ + raw.types.TextWithEntities( + text=message, + entities=entities or [] + ) + ] + ) + ) + + elif chat_id is not None and message_ids is not None: + ids = [message_ids] if not isinstance(message_ids, list) else message_ids + + r = await self.invoke( + raw.functions.messages.TranslateText( + to_lang=to_language_code, + peer=await self.resolve_peer(chat_id), + id=ids + ) + ) + else: + raise ValueError("Either 'text' or both 'chat_id' and 'message_ids' must be provided.") + + return ( + types.TranslatedText._parse(self, r.result[0]) + if len(r.result) == 1 + else [ + types.TranslatedText._parse(self, i) + for i in r.result + ] + ) \ No newline at end of file diff --git a/pyrogram/types/messages_and_media/__init__.py b/pyrogram/types/messages_and_media/__init__.py index 9cf9d3e5..79558d90 100644 --- a/pyrogram/types/messages_and_media/__init__.py +++ b/pyrogram/types/messages_and_media/__init__.py @@ -70,6 +70,7 @@ from .story_views import StoryViews from .exported_story_link import ExportedStoryLink from .wallpaper import Wallpaper from .wallpaper_settings import WallpaperSettings +from .translated_text import TranslatedText __all__ = [ "Animation", @@ -124,5 +125,6 @@ __all__ = [ "StoriesPrivacyRules", "ExportedStoryLink", "Wallpaper", - "WallpaperSettings" + "WallpaperSettings", + "TranslatedText" ] diff --git a/pyrogram/types/messages_and_media/message.py b/pyrogram/types/messages_and_media/message.py index 8a2ff1ea..a104abb6 100644 --- a/pyrogram/types/messages_and_media/message.py +++ b/pyrogram/types/messages_and_media/message.py @@ -5277,3 +5277,33 @@ class Message(Object, Update): reply_message.request = request return reply_message + + async def translate( + self, + to_language_code: str + ) -> "types.TranslatedText": + """Bound method *translate* of :obj:`~pyrogram.types.Message`. + Use as a shortcut for: + .. code-block:: python + await client.translate_message_text( + chat_id=message.chat.id, + message_ids=message_id, + to_language_code="en" + ) + Example: + .. code-block:: python + await message.translate("en") + Parameters: + to_language_code (``str``): + Language code of the language to which the message is translated. + Must be one of "af", "sq", "am", "ar", "hy", "az", "eu", "be", "bn", "bs", "bg", "ca", "ceb", "zh-CN", "zh", "zh-Hans", "zh-TW", "zh-Hant", "co", "hr", "cs", "da", "nl", "en", "eo", "et", "fi", "fr", "fy", "gl", "ka", "de", "el", "gu", "ht", "ha", "haw", "he", "iw", "hi", "hmn", "hu", "is", "ig", "id", "in", "ga", "it", "ja", "jv", "kn", "kk", "km", "rw", "ko", "ku", "ky", "lo", "la", "lv", "lt", "lb", "mk", "mg", "ms", "ml", "mt", "mi", "mr", "mn", "my", "ne", "no", "ny", "or", "ps", "fa", "pl", "pt", "pa", "ro", "ru", "sm", "gd", "sr", "st", "sn", "sd", "si", "sk", "sl", "so", "es", "su", "sw", "sv", "tl", "tg", "ta", "tt", "te", "th", "tr", "tk", "uk", "ur", "ug", "uz", "vi", "cy", "xh", "yi", "ji", "yo", "zu". + Returns: + :obj:`~pyrogram.types.TranslatedText`: The translated result is returned. + Raises: + RPCError: In case of a Telegram RPC error. + """ + return await self._client.translate_message_text( + chat_id=self.chat.id, + message_ids=self.id, + to_language_code=to_language_code + ) \ No newline at end of file diff --git a/pyrogram/types/messages_and_media/translated_text.py b/pyrogram/types/messages_and_media/translated_text.py new file mode 100644 index 00000000..7215463d --- /dev/null +++ b/pyrogram/types/messages_and_media/translated_text.py @@ -0,0 +1,62 @@ +# Pyrofork - Telegram MTProto API Client Library for Python +# Copyright (C) 2017-present Dan +# Copyright (C) 2022-present Mayuri-Chan +# +# This file is part of Pyrofork. +# +# Pyrofork is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License as published +# by the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Pyrofork is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with Pyrofork. If not, see . + +from typing import List + +import pyrogram +from pyrogram import raw, types + +from ..object import Object +from .message import Str + + +class TranslatedText(Object): + """A translated text with entities. + + Parameters: + text (``str``): + Translated text. + + entities (``str``, *optional*): + Entities of the text. + """ + + def __init__( + self, + *, + text: str, + entities: List["types.MessageEntity"] = None + ): + self.text = text + self.entities = entities + + @staticmethod + def _parse( + client, + translate_result: "raw.types.TextWithEntities" + ) -> "TranslatedText": + entities = [ + types.MessageEntity._parse(client, entity, {}) + for entity in translate_result.entities + ] + entities = types.List(filter(lambda x: x is not None, entities)) + + return TranslatedText( + text=Str(translate_result.text).init(entities) or None, entities=entities or None + )