Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions compiler/docs/compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,8 @@ def get_title_list(s: str) -> list:
view_messages
vote_poll
get_chat_sponsored_messages
translate_text
translate_message_text
""",
password="""
Password
Expand Down Expand Up @@ -552,6 +554,7 @@ def get_title_list(s: str) -> list:
ReactionTypeEmoji
ReactionTypeCustomEmoji
Thumbnail
TranslatedText
StrippedThumbnail
Poll
PollOption
Expand Down
1 change: 1 addition & 0 deletions docs/source/releases/changes-in-this-fork.rst
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ If you found any issue or have any suggestions, feel free to make `an issue <htt
| Scheme layer used: 181 |
+------------------------+

- 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>`_).
- 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>`_).
- Added :meth:`~Client.on_story` to listen to story updates.
- 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`.
Expand Down
3 changes: 2 additions & 1 deletion pyrogram/methods/messages/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@
from .get_chat_sponsored_messages import GetChatSponsoredMessages
from .search_public_hashtag_messages import SearchPublicHashtagMessages
from .search_public_hashtag_messages_count import SearchPublicHashtagMessagesCount

from .translate_text import TranslateText

class Messages(
CopyMediaGroup,
Expand Down Expand Up @@ -125,5 +125,6 @@ class Messages(
ViewMessages,
VotePoll,
GetChatSponsoredMessages,
TranslateText,
):
pass
139 changes: 139 additions & 0 deletions pyrogram/methods/messages/translate_text.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
# Pyrogram - Telegram MTProto API Client Library for Python
# Copyright (C) 2017-present Dan <https://github.com/delivrance>
#
# This file is part of Pyrogram.
#
# Pyrogram 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.
#
# Pyrogram 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 Pyrogram. If not, see <http://www.gnu.org/licenses/>.

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: Union[int, str],
message_ids: Union[int, List[int]]
) -> Union["types.TranslatedText", List["types.TranslatedText"]]:
"""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.

.. include:: /_includes/usable-by/users.rst

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".

chat_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the target chat.

message_ids (``int`` | List of ``int``):
Identifier or list of message identifiers of the target message.

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.

Example:
.. code-block:: python

await app.translate_message_text("en", chat_id, message_id)
"""
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
)
)

return (
types.TranslatedText._parse(self, r.result[0])
if len(r.result) == 1
else [
types.TranslatedText._parse(self, i)
for i in r.result
]
)


async def translate_text(
self: "pyrogram.Client",
to_language_code: str,
text: str,
parse_mode: Optional["enums.ParseMode"] = None,
entities: List["types.MessageEntity"] = None
) -> Union["types.TranslatedText", List["types.TranslatedText"]]:
"""Translates a text to the given language. If the current user is a Telegram Premium user, then text formatting is preserved.

.. include:: /_includes/usable-by/users.rst

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".

text (``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.

Example:
.. code-block:: python

await app.translate_text("fa", "Pyrogram")
"""
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 []
)
]
)
)

return (
types.TranslatedText._parse(self, r.result[0])
if len(r.result) == 1
else [
types.TranslatedText._parse(self, i)
for i in r.result
]
)
2 changes: 2 additions & 0 deletions pyrogram/types/messages_and_media/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
from .gift_code import GiftCode
from .gifted_premium import GiftedPremium
from .message_effect import MessageEffect
from .translated_text import TranslatedText

__all__ = [
"Animation",
Expand Down Expand Up @@ -96,4 +97,5 @@
"Voice",
"WebAppData",
"WebPage",
"TranslatedText"
]
39 changes: 39 additions & 0 deletions pyrogram/types/messages_and_media/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -5118,3 +5118,42 @@ async def view(self, force_read: bool = True) -> bool:
message_ids=self.id,
force_read=force_read
)

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
)
61 changes: 61 additions & 0 deletions pyrogram/types/messages_and_media/translated_text.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# Pyrogram - Telegram MTProto API Client Library for Python
# Copyright (C) 2017-present Dan <https://github.com/delivrance>
#
# This file is part of Pyrogram.
#
# Pyrogram 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.
#
# Pyrogram 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 Pyrogram. If not, see <http://www.gnu.org/licenses/>.

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
)