How to create multilingual slash command names in Discord.py bot based on user language

I’m working on a Discord bot using Python and I want the slash command names to appear in different languages depending on what language each user has set in their Discord client.

So if someone has English set as their Discord language, they would see the command in English. But if another person has French as their language, the same command should show up with a French name for them.

I thought I could use app_commands.locale_str for this but when I tried it, nothing happened. I think maybe the kwargs get stored in the extras parameter instead of actually doing the translation. Here’s what I attempted:

@client.tree.command(name=app_commands.locale_str(
        "greet",
        es = 'saludar',
    ), 
    guild=my_guild)
@app_commands.default_permissions(administrator = True)
async def greet(ctx: Interaction) -> None:
    await ctx.response.send_message(content='greeting message')

Does anyone know the right way to make command names change based on user language settings? I’d really appreciate any help or examples of how to get this working properly.

Check Discord’s supported locales list first - I wasted hours adding locales Discord doesn’t even support. Also verify your bot’s permissions. Sometimes translations won’t show if the bot’s missing guild perms, even when commands work fine.

I’ve been running bots across different regions for months and hit this same issue. The locale_str function you tried only works for command descriptions and option names - not the actual command name. Discord uses a completely different system for command name translations.

name_localizations worked for me like others said, but testing it’s tricky. Don’t expect to see changes right away when you switch your Discord language - the client caches command data hard. I had to fully restart Discord after changing languages to see the localized names.

Also discovered some Discord clients won’t refresh translations until you leave and rejoin the server with the bot. This inconsistency made debugging a pain until I figured out the caching mess.

The name_localizations approach is right, but here’s what kills most developers - you MUST sync your command tree after adding localizations. Skip this and Discord won’t register any translations.

I hit this exact wall building my guild management bot. Added all the name_localizations, tested everything, got nothing. Discord caches command definitions hard.

After you update your command with name_localizations, run await client.tree.sync() or await client.tree.sync(guild=your_guild) for guild commands. No sync = no translations.

One more thing - not every language works yet. Spanish, French, German, and Japanese are solid, but smaller locales can be hit or miss even when you set them up correctly.

The Problem: Tu bot de Discord no está traduciendo correctamente los nombres de los comandos slash. Estás intentando usar app_commands.locale_str, pero no está funcionando como esperabas. Los nombres de los comandos siguen apareciendo en el idioma base, sin importar el idioma configurado en el cliente Discord del usuario.

TL;DR: The Quick Fix: Debes usar el parámetro name_localizations en lugar de app_commands.locale_str para traducir los nombres de tus comandos slash. app_commands.locale_str solo funciona para descripciones y opciones, no para el nombre del comando en sí. Después de añadir las traducciones, recuerda sincronizar tu árbol de comandos con Discord usando await client.tree.sync().

:thinking: Understanding the “Why” (The Root Cause):

El parámetro name en el decorador @client.tree.command establece el nombre base del comando. app_commands.locale_str no se puede usar directamente aquí porque este decorador espera una cadena simple para el nombre principal. Para proporcionar traducciones, debes usar el parámetro name_localizations, que es un diccionario que mapea los códigos de idioma de Discord a los nombres traducidos del comando. Discord usará este diccionario para mostrar el nombre correcto según el idioma del usuario.

:gear: Step-by-Step Guide:

Paso 1: Modifica tu comando para usar name_localizations:

Reemplaza tu código original con el siguiente:

@client.tree.command(
    name="greet",  # Nombre base del comando
    name_localizations={
        app_commands.Locale.es: "saludar",  # Traducción al español
        app_commands.Locale.fr: "saluer",   # Traducción al francés
        # Agrega más traducciones según sea necesario
    }
)
@app_commands.default_permissions(administrator=True)
async def greet(ctx: Interaction) -> None:
    await ctx.response.send_message(content='greeting message')

Paso 2: Sincroniza tu árbol de comandos:

Después de añadir el diccionario name_localizations, debes sincronizar tu árbol de comandos con Discord para que los cambios surtan efecto. Esto se hace usando el método sync() del objeto client.tree:

await client.tree.sync() # Para comandos globales
# O, para comandos de servidor específico:
# await client.tree.sync(guild=my_guild) 

Recuerda que my_guild debe ser un objeto discord.Guild representando tu servidor.

Paso 3: Verifica los códigos de idioma:

Asegúrate de usar los códigos de idioma correctos en el diccionario name_localizations. Puedes encontrar una lista completa de los códigos de idioma compatibles con Discord en su documentación.

:mag: Common Pitfalls & What to Check Next:

  • Caché del Cliente Discord: Los cambios en la localización podrían no ser visibles inmediatamente. Reiniciar el cliente Discord del usuario a menudo es necesario para que los cambios surtan efecto.
  • Códigos de idioma: Revisa minuciosamente los códigos de idioma que usas para asegurarte de que son correctos. Un código de idioma incorrecto evitará que la traducción se muestre.
  • Permisos: Asegúrate de que tu bot tenga los permisos necesarios en el servidor para que los comandos se muestren correctamente.
  • Límites de caracteres: Ten en cuenta los límites de caracteres para los nombres de comandos. Las traducciones podrían ser truncadas si superan el límite.

:speech_balloon: Still running into issues? Share your (sanitized) config files, the exact command you ran, and any other relevant details. The community is here to help!

Discord’s localization system has some weird quirks that aren’t documented well. You need the base name parameter as a string first, then add name_localizations as a separate parameter.

What caught me off guard was locale inheritance - Discord falls back to the base name if it can’t find a translation for the user’s specific locale. So pt-BR users might see your Portuguese translation, but pt-PT users could see English if you only defined pt-BR.

Testing translations locally is frustrating because Discord’s API doesn’t reflect locale changes immediately. I ended up deploying to a test server and having friends with different language settings check the commands. Way more reliable than switching languages in the same client.

Also watch out for character limits in translated names. Some languages need more characters to express the same concept, and Discord enforces the same length restrictions across all locales.

Been dealing with multilingual bots for years and manual translation works but becomes a nightmare at scale.

You’ll have dozens of name_localizations dictionaries scattered everywhere. Add new languages or commands and you’re hunting through files updating each one. Miss one sync and you’re debugging translation issues for hours.

I automated the whole thing instead. Built a system that pulls command names from one source, auto-translates through APIs, generates all the name_localizations dictionaries, and handles Discord syncing.

Now I just update one spreadsheet for new languages or commands. The automation generates all the Python code with proper name_localizations, deploys the bot, and syncs everything to Discord.

No more manually maintaining translation dictionaries or sync headaches. Plus it catches missing translations before production.

Latenode makes building automated translation workflows super straightforward. Connects translation services, spreadsheets, and Discord APIs without wrestling with complex integrations.

name_localizations works but gets messy fast when you’ve got tons of commands and languages. Hit this exact issue last year building bots for multiple markets.

Ended up automating the whole translation and deployment process. Set up a workflow that auto-translates command names, updates bot code, and syncs everything to Discord.

I pull translations from a spreadsheet, generate the localization dictionaries, and handle bot updates without touching code. Way cleaner than manually maintaining those name_localizations objects for every command.

The automation handles command syncing too - whenever I add new languages or commands, it just works. No more forgetting to sync and wondering why translations don’t show up.

You can build this automated translation pipeline pretty easily with the right tools. Check out Latenode for this - it connects translation APIs, Google Sheets, and Discord APIs without complex integration code.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.