-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtranslator.py
More file actions
41 lines (36 loc) · 1.63 KB
/
Copy pathtranslator.py
File metadata and controls
41 lines (36 loc) · 1.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
from __future__ import annotations
from locale_keys import locale
import re
from typing import Any
import discord
from discord import app_commands
from localizer import TRANSLATION_NOT_FOUND, LocalizerService, tanjunLocalizer
_DISCORD_NAME_LOCATION_NAMES = frozenset({'command_name', 'group_name', 'parameter_name'})
def _normalize_discord_command_name(name: str) -> str | None:
normalized = re.sub('\\s+', '_', name.strip().lower())
normalized = re.sub('[^\\w\\-]', '', normalized, flags=re.UNICODE)
if not normalized:
return None
return normalized[:32]
class TanjunTranslator(app_commands.Translator):
"""Discord app command translator backed by the bot's LocalizerService.
Parameters
----------
localizer:
The :class:`LocalizerService` instance to use for translations.
Defaults to the global ``tanjunLocalizer``.
"""
def __init__(self, localizer: LocalizerService | None=None) -> None:
self._localizer = localizer or tanjunLocalizer
async def translate(self, string: app_commands.locale_str, locale: discord.Locale, context: app_commands.TranslationContext[Any, Any]) -> str | None:
key_str: str = str(string).replace('_', '.')
current = self._localizer.localize(locale, key_str)
if current == TRANSLATION_NOT_FOUND:
return None
location_name = getattr(context.location, 'name', None)
if location_name in _DISCORD_NAME_LOCATION_NAMES:
normalized: str | None = _normalize_discord_command_name(current)
if normalized is None:
return None
current = normalized
return current