i18n
/i18n
Buduje wielojęzyczność bota discord.py: preferencje języka użytkownika, tabele lokalizacji i łańcuch zapasowych tłumaczeń.
- Autor
- drewdestar ↗
- Repozytorium
- discord-py-skills ↗
- Licencja
- MIT
- Ostatnia zmiana repozytorium
- 06.11.2026
Ocena i bezpieczeństwo
- Pliki w paczce
- 1
- Skrypty
- 0
- Komentarze HTML
- 0
- Adresy URL w SKILL.md
- 0
Brak sygnałów. Repozytorium zmienione 06.11.2026, bez odwołań do wycofanych modeli i API.
MIT, otwarta: można używać i zmieniać, z zachowaniem informacji o autorze.
Co robi i kiedy
Buduje wielojęzyczność bota discord.py: preferencje języka użytkownika, tabele lokalizacji i łańcuch zapasowych tłumaczeń.
Wyzwalacze z opisu
Oryginalny opis (EN)
Ship a multi-language discord.py bot: per-user locale preference, locale tables, fallback chain, and the translation pitfalls that break other languages. Use when the user says 'make the bot speak Indonesian', 'the bot answers in the wrong language', or 'add a /language command'. Do NOT use for translating at runtime with a machine translator; ship reviewed tables instead.
Jak działa
- How Discord locales work
- Store one preference per user
- The fallback chain
- Rules that prevent wrong-language replies
- Validate translations at startup
- Translator for command names
- The /language command
- Verify live
- Quality bar (no slop)
- Checklist
Podgląd SKILL.md
---
name: i18n
description: "Ship a multi-language discord.py bot: per-user locale preference, locale tables, fallback chain, and the translation pitfalls that break other languages. Use when the user says 'make the bot speak Indonesian', 'the bot answers in the wrong language', or 'add a /language command'. Do NOT use for translating at runtime with a machine translator; ship reviewed tables instead."
license: MIT
compatibility: "discord.py 2.x, Python 3.10+, no paid services"
metadata:
version: "0.5.0"
author: "drewdestar"
---
# Multi-Language Bots (i18n)
A bot that answers in the wrong language is worse than a bot that answers in English only. This skill builds locale support that is correct for every user, not just for the developer testing it.
## How Discord locales work
- Every interaction carries `interaction.locale`, the user's Discord client language (for example `id`, `en-US`, `ja`).
- discord.py resolves command names and descriptions through an `app_commands.Translator`. Subclass it, implement `translate()`, and install it with `await bot.tree.set_translator(...)` before syncing. `bot.tree.translator` is a read-only property — assigning to it raises `AttributeError`.
- Command names and descriptions can have per-locale strings. The user sees the command in their own language; the bot still receives the same command object.
## Store one preference per user
```python
# users table: user_id INTEGER PRIMARY KEY, locale TEXT NOT NULL DEFAULT 'en'
async def get_locale(db, user_id: int) -> str:
row = await (await db.execute(
"SELECT locale FROM users WHERE user_id = ?", (user_id,)
)).fetchone()
return row[0] if row else "en"
```
- One row per user, keyed by Discord user id. A `/language` command updates it. The choice survives restarts because it lives in the database, not in memory.
- Default is English. Never default to the developer's own language; the developer is not the average user.
## The fallback chain
Every string lookup follows this order, and stops at the first hit:
1. The user's chosen locale, if a translation exists for that exact key.
2. English. English is the base language and must have every key.
3. The key itself, so a missing translation shows `shop.buy.success` instead of crashing or showing nothing.
```python
STRINGS = {
"en": {"shop.buy.success": "Bought {item} for {price} gold.",
"language.set": "Language set to English."},
"id": {"shop.buy.success": "Membeli {item} seharga {price} gold.",
"language.set": "Bahasa diatur ke Indonesia."},
}
def t(locale: str, key: str, **kwargs: object) -> str:
text = STRINGS.get(locale, {}).get(key) or STRINGS.get("en", {}).get(key) or key
return text.format(**kwargs)
```
- The chain is code, not a hope. A lookup that raises `KeyError` on a missing translation is a bug that only appears for users of the least-tested language.
- Placeholders (`{item}`, `{price}`) are part of the key contract. Every translation of a key must contain exactly the same placeholders, or `.format()` raises at runtime.
## Rules that prevent wrong-language replies
1. **Never translate at runtime with an unvalidated machine translator.** Crowdsourced translation APIs return wrong-language results for short strings, and a bad result cached once poisons every later reply. Translate offline, review the strings, and ship a fixed table.
2. **Never translate single words without context.** "Shop" as a noun and "shop" as a verb translate differently in most languages. Keys carry the full sentence or the full UI string, never isolated words.
3. **Never guess a locale from a display name or a message.** Only `interaction.locale` and the stored per-user preference decide the reply language.
4. **Never cache by key alone.** Cache entries are keyed by `(locale, key)`. A cache keyed by key only serves the first language that asked and the wrong language to everyone after.
5. **Test every locale, not just the new one.** Adding Indonesian must not break Japanese. A test that renders one command in every supported locale catches regressions before users do.
6. **Keep placeholders intact.** A translator (human or machine) that drops `{user}` or renames it breaks the format call. Validate every translation file at load time: same placeholders as the English source, or the bot refuses to start.
## Validate translations at startup
```python
import string
def validate_table(table: dict[str, dict[str, str]]) -> list[str]:
errors = []
for locale, strings in table.items():
for key, text in strings.items():
source = table.get("en", {}).get(key)
if source is None:
errors.append(f"{locale}:{key} has no English source")
continue
want = {f for _, f, _, _ in string.Formatter().parse(source) if f}
got = {f for _, f, _, _ in string.Formatter().parse(text) if f}
if want != got:
errors.append(f"{locale}:{key} placeholders differ: want {want}, got {got}")
return errors
```
- Run this before the bot logs in. A translation bug found at startup costs a restart; the same bug found by a user costs trust.
## Translator for command names
Command descriptions only reach `translate()` when they are defined with `locale_str` keys. A plain English string is never translated — the translator receives the key, not the text:
```python
from discord import app_commands
@app_commands.command(
name="shop",
description=app_commands.locale_str("shop.description"))
async def shop(interaction: discord.Interaction) -> None:
...
class AppTranslator(app_commands.Translator):
async def translate(self, string: app_commands.locale_str, locale: discord.Locale, context) -> str | None:
lang = locale.value.split("-")[0] # 'en-US' -> 'en'
return STRINGS.get(lang, {}).get(string.message)
```
Install it before syncing:
```python
await bot.tree.set_translator(AppTranslator())
await bot.tree.sync()
```
- Return `None` when no translation exists; discord.py falls back to the source string. Returning the key or an empty string is worse than falling back.
## The `/language` command
```python
@app_commands.command(name="language", description="Set your reply language.")
@app_commands.describe(locale="Language code, for example id or en")
async def language(interaction: discord.Interaction, locale: str) -> None:
if locale not in STRINGS:
await interaction.response.send_message(
"Unknown language: %s. Available: %s"
% (locale, ", ".join(sorted(STRINGS))), ephemeral=True)
return
await db.execute(
"INSERT INTO users (user_id, locale) VALUES (?, ?) "
"ON CONFLICT(user_id) DO UPDATE SET locale = excluded.locale",
(interaction.user.id, locale))
await db.commit()
await interaction.response.send_message(
t(locale, "language.set"), ephemeral=True)
```
- `db` is the bot's one `aiosqlite` connection (see economy-database). The preference lives in the same `users` table `get_locale` reads, so the next reply uses it immediately.
## Verify live
- Render one command in every supported locale in a test, then run
`/language` in Discord, switch locale, and run the same command
again. The reply changes language; the placeholders still fill.
- Break one translation on purpose (drop a `{item}` placeholder)
and start the bot. Startup validation must refuse to start.
A bot that starts with broken translations ships broken replies.
## Quality bar (no slop)
- Never ship a translation you have not verified. A fluent-looking
string in a language nobody on the team reads is a guess, and a
wrong-language reply is worse than an English one.
- No em dash in any message or embed the bot sends.
## Checklist
- [ ] Every user-facing string lives in the table, none hardcoded in commands
- [ ] Fallback chain is code: locale, then English, then the key
- [ ] Placeholders validated at startup for every locale
- [ ] Cache keyed by `(locale, key)`
- [ ] One command rendered in every locale in tests
- [ ] `/language` updates the stored preference and the next reply uses it
Wersje
| Repozytorium | Wynik | Licencja |
|---|---|---|
| Ta strona · drewdestar/discord-py-skills | 100 | MIT |
| project-n-e-k-o/n.e.k.o | 100 | Apache-2.0 |
| DnsQueen/orcinus-skills | 100 | MIT |
| filipe-campos/walph | 100 | MIT |
| helderberto/agent-skills | 100 | MIT |
| OpenClaudia/openclaudia-skills | 100 | MIT |
| iofficeai/aionui | 100 | Apache-2.0 |
| pa001024/dna-builder | 100 | MIT |
| claude-dev-suite/claude-dev-suite | 100 | MIT |
Migawka bazy z 13.11.2026 · wersja paczki 8a86ee27446e (skrót SHA-256 całej paczki)
Pobrania w ostatnich 30 dniach: 2 · ranking
Zgłoś problem z tym skillem: szkodliwa treść, błędny opis albo prośba autora o usunięcie.
Podobne skille
- 100create-discord-bot
Zakłada serwer i aplikację bota Discord przez automatyzację przeglądarki, zbiera token bota oraz identyfikatory serwera i użytkownika i zapisuje je do pliku .env. - 100build-discord-bot
Buduje produkcyjnego bota Discord w discord.py: intencje, moduły, konfigurację ze zmiennych i logowanie. - 100discord-expert
Wspiera tworzenie botów Discord w discord.js i discord.py: komendy slash, embedy, kanały głosowe, moderacja i wdrożenie bota. - 100slash-commands
Dodaje komendy ukośnikowe do bota discord.py, z grupami, sprawdzeniami, podpowiedziami i obsługą błędów. - 100discord-bot-generator
Prawdopodobnie pomaga generować boty Discord na potrzeby automatyzacji procesów biznesowych, na podstawie nazwy i kategorii skilla. - 100discord-channel
Obsługuje Discord dla bota Pots: łączy bota z serwerem, wysyła wiadomości i wątki, a także przyciski, menu i formularze.