Skip to content

Commit 1078d07

Browse files
authored
Add translate (#39)
1 parent f6e3e92 commit 1078d07

File tree

7 files changed

+247
-1
lines changed

7 files changed

+247
-1
lines changed

compiler/docs/compiler.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -336,6 +336,8 @@ def get_title_list(s: str) -> list:
336336
view_messages
337337
vote_poll
338338
get_chat_sponsored_messages
339+
translate_text
340+
translate_message_text
339341
""",
340342
password="""
341343
Password
@@ -552,6 +554,7 @@ def get_title_list(s: str) -> list:
552554
ReactionTypeEmoji
553555
ReactionTypeCustomEmoji
554556
Thumbnail
557+
TranslatedText
555558
StrippedThumbnail
556559
Poll
557560
PollOption

docs/source/releases/changes-in-this-fork.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ If you found any issue or have any suggestions, feel free to make `an issue <htt
1414
| Scheme layer used: 181 |
1515
+------------------------+
1616

17+
- Added the methods :meth:`~pyrogram.Client.translate_text`, :meth:`~pyrogram.Client.translate_message_text`, :meth:`~pyrogram.types.Message.translate` and the type :obj:`~pyrogram.types.TranslatedText` (`#39 <https://github.com/TelegramPlayGround/pyrogram/pull/39>`_).
1718
- Added the methods :meth:`~pyrogram.Client.create_video_chat`, :meth:`~pyrogram.Client.discard_group_call`, :meth:`~pyrogram.Client.get_video_chat_rtmp_url` and the type :obj:`~pyrogram.types.RtmpUrl` (`#37 <https://github.com/TelegramPlayGround/pyrogram/pull/37>`_).
1819
- Added :meth:`~Client.on_story` to listen to story updates.
1920
- Ability to run in `replit` environment without creating `a deployment <https://ask.replit.com/t/pyrogram-network-issue/33679/46>`_. Set the environment variable ``PYROGRAM_REPLIT_NWTRAFIK_PORT`` value to ``5222`` if you want to connect to Production Telegram Servers, **OR** Set the environment variable ``PYROGRAM_REPLIT_WNTRAFIK_PORT`` value to ``5223`` if you want to connect to Test Telegram Servers, before starting the :obj:`~pyrogram.Client`.

pyrogram/methods/messages/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@
6969
from .get_chat_sponsored_messages import GetChatSponsoredMessages
7070
from .search_public_hashtag_messages import SearchPublicHashtagMessages
7171
from .search_public_hashtag_messages_count import SearchPublicHashtagMessagesCount
72-
72+
from .translate_text import TranslateText
7373

7474
class Messages(
7575
CopyMediaGroup,
@@ -125,5 +125,6 @@ class Messages(
125125
ViewMessages,
126126
VotePoll,
127127
GetChatSponsoredMessages,
128+
TranslateText,
128129
):
129130
pass
Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,139 @@
1+
# Pyrogram - Telegram MTProto API Client Library for Python
2+
# Copyright (C) 2017-present Dan <https://github.com/delivrance>
3+
#
4+
# This file is part of Pyrogram.
5+
#
6+
# Pyrogram is free software: you can redistribute it and/or modify
7+
# it under the terms of the GNU Lesser General Public License as published
8+
# by the Free Software Foundation, either version 3 of the License, or
9+
# (at your option) any later version.
10+
#
11+
# Pyrogram is distributed in the hope that it will be useful,
12+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
13+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14+
# GNU Lesser General Public License for more details.
15+
#
16+
# You should have received a copy of the GNU Lesser General Public License
17+
# along with Pyrogram. If not, see <http://www.gnu.org/licenses/>.
18+
19+
from typing import List, Optional, Union
20+
21+
import pyrogram
22+
from pyrogram import enums, raw, types, utils
23+
24+
25+
class TranslateText:
26+
async def translate_message_text(
27+
self: "pyrogram.Client",
28+
to_language_code: str,
29+
chat_id: Union[int, str],
30+
message_ids: Union[int, List[int]]
31+
) -> Union["types.TranslatedText", List["types.TranslatedText"]]:
32+
"""Extracts text or caption of the given message and translates it to the given language. If the current user is a Telegram Premium user, then text formatting is preserved.
33+
34+
.. include:: /_includes/usable-by/users.rst
35+
36+
Parameters:
37+
to_language_code (``str``):
38+
Language code of the language to which the message is translated.
39+
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".
40+
41+
chat_id (``int`` | ``str``):
42+
Unique identifier (int) or username (str) of the target chat.
43+
44+
message_ids (``int`` | List of ``int``):
45+
Identifier or list of message identifiers of the target message.
46+
47+
Returns:
48+
:obj:`~pyrogram.types.TranslatedText` | List of :obj:`~pyrogram.types.TranslatedText`: In case *message_ids* was not
49+
a list, a single result is returned, otherwise a list of results is returned.
50+
51+
Example:
52+
.. code-block:: python
53+
54+
await app.translate_message_text("en", chat_id, message_id)
55+
"""
56+
ids = [message_ids] if not isinstance(message_ids, list) else message_ids
57+
58+
r = await self.invoke(
59+
raw.functions.messages.TranslateText(
60+
to_lang=to_language_code,
61+
peer=await self.resolve_peer(chat_id),
62+
id=ids
63+
)
64+
)
65+
66+
return (
67+
types.TranslatedText._parse(self, r.result[0])
68+
if len(r.result) == 1
69+
else [
70+
types.TranslatedText._parse(self, i)
71+
for i in r.result
72+
]
73+
)
74+
75+
76+
async def translate_text(
77+
self: "pyrogram.Client",
78+
to_language_code: str,
79+
text: str,
80+
parse_mode: Optional["enums.ParseMode"] = None,
81+
entities: List["types.MessageEntity"] = None
82+
) -> Union["types.TranslatedText", List["types.TranslatedText"]]:
83+
"""Translates a text to the given language. If the current user is a Telegram Premium user, then text formatting is preserved.
84+
85+
.. include:: /_includes/usable-by/users.rst
86+
87+
Parameters:
88+
to_language_code (``str``):
89+
Language code of the language to which the message is translated.
90+
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".
91+
92+
text (``str``):
93+
Text to translate.
94+
95+
parse_mode (:obj:`~pyrogram.enums.ParseMode`, *optional*):
96+
By default, texts are parsed using both Markdown and HTML styles.
97+
You can combine both syntaxes together.
98+
99+
entities (List of :obj:`~pyrogram.types.MessageEntity`):
100+
List of special entities that appear in message text, which can be specified instead of *parse_mode*.
101+
102+
Returns:
103+
:obj:`~pyrogram.types.TranslatedText` | List of :obj:`~pyrogram.types.TranslatedText`: In case *message_ids* was not
104+
a list, a single result is returned, otherwise a list of results is returned.
105+
106+
Example:
107+
.. code-block:: python
108+
109+
await app.translate_text("fa", "Pyrogram")
110+
"""
111+
message, entities = (
112+
await utils.parse_text_entities(
113+
self,
114+
text,
115+
parse_mode,
116+
entities
117+
)
118+
).values()
119+
120+
r = await self.invoke(
121+
raw.functions.messages.TranslateText(
122+
to_lang=to_language_code,
123+
text=[
124+
raw.types.TextWithEntities(
125+
text=message,
126+
entities=entities or []
127+
)
128+
]
129+
)
130+
)
131+
132+
return (
133+
types.TranslatedText._parse(self, r.result[0])
134+
if len(r.result) == 1
135+
else [
136+
types.TranslatedText._parse(self, i)
137+
for i in r.result
138+
]
139+
)

pyrogram/types/messages_and_media/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@
5656
from .gift_code import GiftCode
5757
from .gifted_premium import GiftedPremium
5858
from .message_effect import MessageEffect
59+
from .translated_text import TranslatedText
5960

6061
__all__ = [
6162
"Animation",
@@ -96,4 +97,5 @@
9697
"Voice",
9798
"WebAppData",
9899
"WebPage",
100+
"TranslatedText"
99101
]

pyrogram/types/messages_and_media/message.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5118,3 +5118,42 @@ async def view(self, force_read: bool = True) -> bool:
51185118
message_ids=self.id,
51195119
force_read=force_read
51205120
)
5121+
5122+
async def translate(
5123+
self,
5124+
to_language_code: str
5125+
) -> "types.TranslatedText":
5126+
"""Bound method *translate* of :obj:`~pyrogram.types.Message`.
5127+
5128+
Use as a shortcut for:
5129+
5130+
.. code-block:: python
5131+
5132+
await client.translate_message_text(
5133+
chat_id=message.chat.id,
5134+
message_ids=message_id,
5135+
to_language_code="en"
5136+
)
5137+
5138+
Example:
5139+
.. code-block:: python
5140+
5141+
await message.translate("en")
5142+
5143+
Parameters:
5144+
to_language_code (``str``):
5145+
Language code of the language to which the message is translated.
5146+
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".
5147+
5148+
Returns:
5149+
:obj:`~pyrogram.types.TranslatedText`: The translated result is returned.
5150+
5151+
Raises:
5152+
RPCError: In case of a Telegram RPC error.
5153+
5154+
"""
5155+
return await self._client.translate_message_text(
5156+
chat_id=self.chat.id,
5157+
message_ids=self.id,
5158+
to_language_code=to_language_code
5159+
)
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
# Pyrogram - Telegram MTProto API Client Library for Python
2+
# Copyright (C) 2017-present Dan <https://github.com/delivrance>
3+
#
4+
# This file is part of Pyrogram.
5+
#
6+
# Pyrogram is free software: you can redistribute it and/or modify
7+
# it under the terms of the GNU Lesser General Public License as published
8+
# by the Free Software Foundation, either version 3 of the License, or
9+
# (at your option) any later version.
10+
#
11+
# Pyrogram is distributed in the hope that it will be useful,
12+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
13+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14+
# GNU Lesser General Public License for more details.
15+
#
16+
# You should have received a copy of the GNU Lesser General Public License
17+
# along with Pyrogram. If not, see <http://www.gnu.org/licenses/>.
18+
19+
from typing import List
20+
21+
import pyrogram
22+
from pyrogram import raw, types
23+
24+
from ..object import Object
25+
from .message import Str
26+
27+
28+
class TranslatedText(Object):
29+
"""A translated text with entities.
30+
31+
Parameters:
32+
text (``str``):
33+
Translated text.
34+
35+
entities (``str``, *optional*):
36+
Entities of the text.
37+
"""
38+
39+
def __init__(
40+
self,
41+
*,
42+
text: str,
43+
entities: List["types.MessageEntity"] = None
44+
):
45+
self.text = text
46+
self.entities = entities
47+
48+
@staticmethod
49+
def _parse(
50+
client,
51+
translate_result: "raw.types.TextWithEntities"
52+
) -> "TranslatedText":
53+
entities = [
54+
types.MessageEntity._parse(client, entity, {})
55+
for entity in translate_result.entities
56+
]
57+
entities = types.List(filter(lambda x: x is not None, entities))
58+
59+
return TranslatedText(
60+
text=Str(translate_result.text).init(entities) or None, entities=entities or None
61+
)

0 commit comments

Comments
 (0)