You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现Discord中bot.tree.command命令参数的多语言适配?

实现Discord机器人命令的多语言自动适配

要让你的Discord机器人命令(比如/play)的描述和选项自动适配用户的Discord语言设置,核心是利用Discord的命令本地化API,结合翻译文件和翻译回调来实现。以下是具体步骤:

1. 准备多语言翻译文件

创建对应不同语言的JSON配置文件,存储命令、选项的本地化文本。比如:

zh-CN.json:

{
  "play.description": "播放音乐曲目",
  "play.options.query": "歌曲搜索关键词"
}

en-US.json:

{
  "play.description": "Play a music track",
  "play.options.query": "Search query for the song"
}

文件名需对应Discord标准语言代码(如zh-CN、en-US、ja等),确保和用户的Discord语言设置匹配。

2. 实现翻译器类

以Python的discord.py库为例,创建一个翻译器类,负责加载翻译文件并根据用户的语言环境返回对应文本:

import json
from discord import app_command

class CommandTranslator(app_command.Translator):
    def __init__(self):
        self.translations = {}
        # 加载所有语言的翻译文件
        lang_files = ["zh-CN.json", "en-US.json"]
        for file in lang_files:
            lang_code = file.split(".")[0]
            with open(file, "r", encoding="utf-8") as f:
                self.translations[lang_code] = json.load(f)
    
    async def translate(self, string: app_command.LocalizedString, locale: str, context: app_command.TranslationContext) -> str | None:
        # 优先使用用户的语言,没有则回退到英文
        target_lang = self.translations.get(locale) or self.translations.get("en-US")
        return target_lang.get(string.key)

3. 注册翻译器到机器人

将翻译器绑定到机器人的命令树,让Discord在处理命令时自动调用翻译逻辑:

bot.tree.set_translator(CommandTranslator())

4. 用本地化字符串注册命令

定义命令时,不再直接写固定文本,而是使用LocalizedString指定翻译文件中的key:

import discord
from discord import app_command

@bot.tree.command(
    name="play",
    description=app_command.LocalizedString(key="play.description")
)
@app_command.describe(
    query=app_command.LocalizedString(key="play.options.query")
)
async def play(interaction: discord.Interaction, query: str):
    # 这里写你的命令逻辑
    await interaction.response.send_message(f"正在播放: {query}")

5. 开发者平台配置支持的语言

登录Discord开发者门户,找到你的机器人应用:

  • 进入OAuth2 -> General页面
  • 在Supported Locales中添加你要支持的语言(如中文简体、英文等)
  • 保存配置,确保Discord能正确传递用户的语言信息给机器人

注意事项

  • 语言代码必须严格遵循Discord的标准,可直接搜索Discord locale codes获取完整列表
  • 若翻译文件中找不到对应key,机器人会回退到默认行为(通常显示key或无文本),所以要确保key的一致性
  • 其他Discord机器人库(如nextcord、py-cord)的实现逻辑基本一致,核心都是利用官方的本地化API和翻译回调机制

内容的提问来源于stack exchange,提问作者user28857236

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 15:17:06