Skip to content

Commit

Permalink
Implement /translator set_channel_main_language
Browse files Browse the repository at this point in the history
  • Loading branch information
SeoulSKY committed Jun 10, 2024
1 parent 9f7296c commit ca94cf7
Show file tree
Hide file tree
Showing 14 changed files with 238 additions and 69 deletions.
6 changes: 4 additions & 2 deletions sorusora/commands/chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
from utils.translator import Language, Localization, DEFAULT_LANGUAGE, get_translator
from utils.ui import LanguageSelectView

_ = google.protobuf.empty_pb2 # create an instance to not be removed when optimizing imports
_ = google.protobuf.empty_pb2 # assign the value to not be removed when optimizing imports

resources = [os.path.join("commands", "chat.ftl"), Localization.get_resource()]
default_loc = Localization(DEFAULT_LANGUAGE, resources)
Expand Down Expand Up @@ -52,7 +52,9 @@ def __init__(self, interaction: Interaction):
super().__init__(loc.format_value_or_translate("set-language-select"), interaction.locale, max_values=1)

async def callback(self, interaction: Interaction):
await super().callback(interaction)
"""
Callback for the language selection
"""

send = await defer_response(interaction)

Expand Down
89 changes: 77 additions & 12 deletions sorusora/commands/translator.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
from mongo.user import get_user, set_user
from utils import defer_response, templates
from utils.constants import ErrorCode, Limit
from utils.templates import success
from utils.templates import success, error
from utils.translator import Localization, Language, DEFAULT_LANGUAGE, get_translator, BaseTranslator
from utils.ui import LanguageSelectView, ChannelSelect, SubmitButton

Expand All @@ -29,14 +29,15 @@ class TranslatorLanguageSelectView(LanguageSelectView):
Select UI to select available languages for a translator
"""

def __init__(self, locale: Locale):
def __init__(self, interaction: Interaction, max_values: int = None):
"""
Create a view to select languages for a translator
:param locale: The locale of the user
:param interaction: The interaction of the command
:param max_values: Maximum number of values that can be selected
"""

loc = Localization(locale, resources)
super().__init__(loc.format_value_or_translate("select-languages"), locale)
loc = Localization(interaction.locale, resources)
super().__init__(interaction, loc.format_value_or_translate("select-languages"), max_values)


class TranslatorChannelSelect(ChannelSelect):
Expand Down Expand Up @@ -108,14 +109,17 @@ async def on_message(message: Message):
if self._translator.is_code_supported(code):
languages.append(Language(code))

await self._send_translation(message, languages)
await self._send_translation(message, languages, Language(chan.locale) if chan.locale else None)

self.bot.add_listener(on_message)

async def _send_translation(self, message: Message, dest_langs: Iterable[Language]) -> None:
async def _send_translation(self,
message: Message,
dest_langs: Iterable[Language],
src_lang: Language = None) -> None:
async with message.channel.typing():
text = message.content
source = Language((await asyncio.to_thread(langid.classify, text))[0])
source = src_lang if src_lang else Language((await asyncio.to_thread(langid.classify, text))[0])

if len(message.embeds) != 0:
text += "\n\n"
Expand Down Expand Up @@ -167,13 +171,13 @@ def _split(string: str, count: int):
)
async def set_languages(self, interaction: Interaction, all_channels: bool = ALL_CHANNELS_DEFAULT):
"""
Set languages to be translated for your messages
Set or remove the languages to be translated for your messages
"""

loc = Localization(interaction.locale, resources)
send = await defer_response(interaction)

language_view = await TranslatorLanguageSelectView(interaction.locale).init()
language_view = await TranslatorLanguageSelectView(interaction).init()
channel_select = await TranslatorChannelSelect(interaction.locale).init()

async def on_submit(interaction: Interaction):
Expand Down Expand Up @@ -206,13 +210,13 @@ async def on_submit(interaction: Interaction):
@app_commands.checks.has_permissions(administrator=True)
async def set_channel_languages(self, interaction: Interaction, this_channel: bool = THIS_CHANNEL_DEFAULT):
"""
Set languages to be translated for channels
Set or remove the languages to be translated for channels
"""

loc = Localization(interaction.locale, resources)
send = await defer_response(interaction)

language_view = await TranslatorLanguageSelectView(interaction.locale).init()
language_view = await TranslatorLanguageSelectView(interaction).init()
channel_select = await TranslatorChannelSelect(interaction.locale).init()

async def on_submit(interaction: Interaction):
Expand All @@ -237,5 +241,66 @@ async def on_submit(interaction: Interaction):

await send(view=language_view, ephemeral=True)

@app_commands.command(name=default_loc.format_value("set-channel-main-language-name"),
description=default_loc.format_value("set-channel-main-language-description"))
@app_commands.describe(this_channel=default_loc.format_value(
"set-channel-main-language-this-channel-description",
{"set-channel-main-language-this-channel-description-default": str(THIS_CHANNEL_DEFAULT)})
)
@app_commands.checks.has_permissions(administrator=True)
async def set_channel_main_language(self, interaction: Interaction, this_channel: bool = THIS_CHANNEL_DEFAULT):
"""
Set or remove the main language of the channels.
"""

loc = Localization(interaction.locale, resources)
send = await defer_response(interaction)

language_view = await TranslatorLanguageSelectView(interaction, 1).init()
channel_select = await TranslatorChannelSelect(interaction.locale).init()
channel_select_callback = channel_select.callback

async def on_submit(interaction: Interaction):
selected = list(language_view.selected)
channels = [interaction.channel_id] if this_channel else [channel.id for channel in channel_select.values]

if len(channels) == 0:
await interaction.response.send_message(
error(await loc.format_value_or_translate("no-channels-selected")),
ephemeral=True
)
return

for channel in channels:
config = await get_channel(channel)
config.locale = selected[0] if len(selected) != 0 else None
await set_channel(config)

await interaction.response.send_message(
success(await loc.format_value_or_translate("channel-main-language-updated")),
ephemeral=True
)

button = await SubmitButton(interaction.locale).init()
button.disabled = True
button.callback = on_submit

async def on_channel_select(select_interaction: Interaction):
await channel_select_callback(select_interaction)

button.disabled = len(channel_select.values) == 0
await interaction.edit_original_response(view=language_view)

channel_select.callback = on_channel_select

if not this_channel:
language_view.add_item(channel_select)

language_view.add_item(button)

await send(view=language_view, ephemeral=True)

set_languages.extras["set-languages-all-channels-description-default"] = str(ALL_CHANNELS_DEFAULT)
set_channel_languages.extras["set-channel-languages-this-channel-description-default"] = str(THIS_CHANNEL_DEFAULT)
set_channel_main_language.extras["set-channel-main-language-this-channel-description-default"] \
= str(THIS_CHANNEL_DEFAULT)
4 changes: 2 additions & 2 deletions sorusora/docs/help/translator/set_channel_languages/en.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# /translator set_channel_languages

Set languages to be translated for the selected channels.
Set or remove the languages to be translated for the selected channels.

For every message sent in the selected channels, SoruSora will translate the message into the selected languages and reply with the translations.

Expand All @@ -13,6 +13,6 @@ For every message sent in the selected channels, SoruSora will translate the mes

## Parameters

* `this_channel` (Optional): If set to `False`, it will send an dropdown menu to select multiple channels. Default value is `True`.
* `this_channel` (Optional): If set to `False`, it will send a dropdown menu to select multiple channels. Default value is `True`.

This command is only available for server admins.
2 changes: 1 addition & 1 deletion sorusora/docs/help/translator/set_channel_languages/ko.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

* 드롭다운 메뉴에서 메세지를 번역할 언어들을 선택합니다.
* 선택한 채널에 대한 번역을 비활성화하려면 아무 언어도 선택하지 마십시오.
* `this_channel``False`로 설정하여 여러 채널에 동일한 설정을 적용할 수 있습니다.
* `현재채널``False`로 설정하여 여러 채널에 동일한 설정을 적용할 수 있습니다.
* 설정을 저장하려면 `결정` 버튼을 누르십시오.

## 변수
Expand Down
12 changes: 6 additions & 6 deletions sorusora/docs/help/translator/set_channel_languages/zh-TW.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
# /翻譯訊息 設定頻道語言
# /翻譯訊息 頻道主語言設置

設置要翻譯頻道消息的語言
設置頻道的主語言。 翻譯器將選中的語言設置爲通道中所有消息的源語言

如果將信息發送到所選頻道,SoruSora就會用所選語言翻譯該信息,並將翻譯結果回覆給該信息
如果未建立通道的主語言,翻譯器檢測每條消息的語言並將其用作源語言

## 如何使用

* 從下拉菜單中選擇要翻譯消息的語言
* 不要選擇任何語言來禁用所選通道的翻譯
* 您可以通過將 `當前頻道` 設置爲 `False`, 對多個頻道應用相同的設置
* 從下拉菜單中選擇通道的主語言
* 如果不選擇語言,頻道的主語言將被刪除
* 您可以通過將 `當前頻道` 設置爲 `False`, 對多個頻道應用相同的設置。
* 點擊`結晶`按鈕保存設置。

## 參數
Expand Down
18 changes: 18 additions & 0 deletions sorusora/docs/help/translator/set_channel_main_language/en.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# /translator set_channel_main_language

Set or remove the main language of the channels. The translator will set the selected language as the source language for all messages in the channels.

If the main language of a channel is not set, the translator will detect the language of each message and use it as the source language.

## Usage

* Use the dropdown menu to select the main language for the channels.
* Select no languages to remove the main language from the channels.
* Set `this_channel` to `False` to apply the same settings to multiple channels.
* Press the `Submit` button to save the settings.

## Parameters

* `this_channel` (Optional): If set to `False`, it will send a dropdown menu to select multiple channels. Default value is `True`.

This command is only available for server admins.
18 changes: 18 additions & 0 deletions sorusora/docs/help/translator/set_channel_main_language/ko.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# /번역기 채널메인언어설정

선택한 채널의 메인 언어를 설정합니다. 번역기는 선택한 언어를 해당 채널의 모든 메세지의 소스 언어로 설정합니다.

채널의 메인 언어가 설정되지 않은 경우 번역기는 각 메세지의 언어를 감지하여 소스 언어로 사용합니다.

## 사용법

* 드롭다운 메뉴에서 채널의 메인 언어를 선택하십시오.
* 언어를 선택하지 않으면 채널의 메인 언어가 제거됩니다.
* `현재채널``False`로 설정하여 여러 채널에 동일한 설정을 적용할 수 있습니다.
* 설정을 저장하려면 `결정` 버튼을 누르십시오.

## 변수

* `현재채널` (옵션): `False`로 설정하면 여러 채널을 선택할 수 있는 드롭다운 메뉴가 전송됩니다. 기본값은 `True`입니다.

이 명령어는 서버 관리자만 사용할 수 있습니다.
18 changes: 18 additions & 0 deletions sorusora/docs/help/translator/set_channel_main_language/zh-TW.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# /翻譯訊息 設定頻道語言

設置要翻譯頻道消息的語言。

如果將信息發送到所選頻道,SoruSora就會用所選語言翻譯該信息,並將翻譯結果回覆給該信息。

## 如何使用

* 從下拉菜單中選擇要翻譯消息的語言。
* 不要選擇任何語言來禁用所選通道的翻譯。
* 您可以通過將 `當前頻道` 設置爲 `False`, 對多個頻道應用相同的設置。
* 點擊`結晶`按鈕保存設置。

## 參數

* `當前頻道` (可選): 設置成`False`會發送下拉菜單,可以選擇多個頻道。 默認值爲 `True`

這個指令只有服務器管理員才能使用。
2 changes: 1 addition & 1 deletion sorusora/docs/help/translator/set_languages/en.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# /translator set_languages

Set languages to be translated for your messages.
Set or remove the languages to be translated for your messages.

When this command is used, it will send dropdown menus to this channel. You can select the languages you want to translate your messages into. You can select multiple languages.

Expand Down
20 changes: 13 additions & 7 deletions sorusora/locales/en/commands/translator.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,30 @@ translator-name = translator
translator-description = Commands related to translation
set-languages-name = set_languages
set-languages-description = Set languages to be translated for your messages
set-languages-description = Set or remove the languages to be translated for your messages
set-languages-all-channels-name = all_channels
set-languages-all-channels-description = Set languages to be translated for your messages in all channels. Default is { $set-languages-all-channels-description-default }
set-languages-all-channels-description = Set or remove the languages to be translated for your messages in all channels. Default is { $set-languages-all-channels-description-default }
set-channel-languages-name = set_channel_languages
set-channel-languages-description = [Admins only] Set languages to be translated for channels
set-channel-languages-description = [Admins only] Set or remove the languages to be translated for channels
set-channel-languages-this-channel-name = this_channel
set-channel-languages-this-channel-description = Set languages to be translated for messages in this channel. Default is { $set-channel-languages-this-channel-description-default }
set-channel-languages-this-channel-description = Set or remove the languages to be translated for messages in this channel. Default is { $set-channel-languages-this-channel-description-default }
set-channel-main-language-name = set_channel_main_language
set-channel-main-language-description = [Admins only] Set or remove the main language of the channels
set-channel-main-language-this-channel-name = this_channel
set-channel-main-language-this-channel-description = Set or remove the main language of this channel. Default is { $set-channel-main-language-this-channel-description-default }
# Select UI
select-languages = Select the languages you want to translate your messages to
select-channels = Select the channels you want to translate messages in
select-channel-languages = Select the languages you want to translate messages in the channels to
select-languages = Select the languages you want to translate
select-channels = Select the channels you want to translate messages
# Successes
languages-updated = Your languages to be translated have been updated
channel-languages-updated = The languages of the channels to be translated have been updated
channel-main-language-updated = The main language of the channels has been updated
# Errors
invalid-user-settings = Your languages settings are invalid. Please set them again
invalid-channel-settings = This channel's languages settings are invalid. Please set them again
no-channels-selected = Select at least one channel
12 changes: 9 additions & 3 deletions sorusora/locales/ko/commands/translator.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,21 @@ set-channel-languages-description = [관리자 전용] 채널 메세지를 번
set-channel-languages-this-channel-name = 현재채널
set-channel-languages-this-channel-description = 채널 메세지를 번역할 언어들을 이 채널에 설정합니다. 기본값은 { $set-channel-languages-this-channel-description-default } 입니다
set-channel-main-language-name = 채널메인언어설정
set-channel-main-language-description = [관리자 전용] 채널의 메인 언어를 설정합니다
set-channel-main-language-this-channel-name = 현재채널
set-channel-main-language-this-channel-description = 채널의 메인 언어를 설정합니다. 기본값은 { $set-channel-main-language-this-channel-description-default } 입니다
# Select UI
select-languages = 당신의 메세지를 번역할 언어들을 선택하세요
select-channels = 당신의 메세지를 번역할 채널들을 선택하세요
select-channel-languages = 채널 메세지를 번역할 언어들을 선택하세요
select-languages = 번역할 언어를 선택하세요
select-channels = 번역할 채널을 선택하세요
# Successes
languages-updated = 당신의 메세지를 번역할 언어들이 변경되었습니다
channel-languages-updated = 채널 메세지를 번역할 언어들이 변경되었습니다
channel-main-language-updated = 채널의 메인 언어가 변경되었습니다
# Errors
invalid-user-settings = 당신의 언어 세팅이 잘못됐습니다. 다시 설정해주세요
invalid-channel-settings = 이 채널의 언어 세팅이 잘못됐습니다. 다시 설정해주세요
no-channels-selected = 적어도 하나의 채널을 선택해주세요
11 changes: 9 additions & 2 deletions sorusora/locales/zh-TW/commands/translator.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,12 @@ set-languages-all-channels-description = 應用至所有頻道,預設為 { $se
set-channel-languages-name = 設定頻道語言
set-channel-languages-description = [管理員專用] 設定要翻譯此頻道訊息的語言
set-channel-languages-this-channel-name = 當前頻道
set-channel-languages-this-channel-description = 在此頻道中設置要翻譯頻道消息的語言 。 默認值爲 { $set-channel-languages-this-channel-description-default }
set-channel-languages-this-channel-description = 在此頻道中設置要翻譯頻道消息的語言。 默認值爲 { $set-channel-languages-this-channel-description-default }
set-channel-main-language-name = 頻道主語言設置
set-channel-main-language-description = [管理員專用] 設置頻道的主語言。
set-channel-main-language-this-channel-name = 當前頻道
set-channel-main-language-this-channel-description = 設置頻道的主語言。 默認值爲 { $set-channel-main-language-this-channel-description-default }
# Select UI
select-languages = 選擇要翻譯的語言
Expand All @@ -19,8 +24,10 @@ select-channel-languages = 選擇要翻譯頻道消息的語言
# Successes
languages-updated = 成功更新翻譯
channel-languages-updated = 要翻譯頻道消息的語言已更改
channel-languages-updated = 選擇要翻譯的語言
channel-main-language-updated = 選擇要翻譯的頻道
# Errors
invalid-user-settings = 語言設定無效。請重新設定
invalid-channel-settings = 此頻道的語言設定無效。請重新設定
no-channels-selected = 請至少選擇一個頻道
4 changes: 2 additions & 2 deletions sorusora/mongo/channel.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
get_channel
set_channel
"""

from motor.motor_asyncio import AsyncIOMotorCollection

from mongo import db, Document, has_document, get_document, set_document
Expand All @@ -22,11 +21,12 @@ class Channel(Document):
A wrapper class to represent channel configs in the database
"""

def __init__(self, channel_id: int = -1, translate_to: list[str] = None):
def __init__(self, channel_id: int = -1, translate_to: list[str] = None, locale: str = None):
self.channel_id = channel_id
if translate_to is None:
translate_to = []
self.translate_to: list[str] = translate_to
self.locale = locale

@staticmethod
def from_dict(source: dict) -> "Channel":
Expand Down
Loading

0 comments on commit ca94cf7

Please sign in to comment.