如何为Python Discord Bot实现多语言应用命令别名?
解决Discord应用命令本地化显示问题
问题原因
你的代码中app_commands.locale_str的语法本身是正确的,但未生效大概率是因为命令未同步到Discord服务器,本地化信息没有被提交,或者使用的discord.py版本过低(需v2.0+版本才支持本地化功能)。
解决方案
方案1:直接使用locale_str并确保命令同步
- 先安装/更新到最新版discord.py:
pip install -U discord.py
- 修改代码,添加命令同步逻辑,确保本地化信息提交到Discord:
import discord from discord import app_commands GUILD_ID = 你的服务器ID guild = discord.Object(id=GUILD_ID) class MyBot(discord.Client): def __init__(self): super().__init__(intents=discord.Intents.default()) self.tree = app_commands.CommandTree(self) async def setup_hook(self): # 同步指定服务器的命令,携带本地化信息 await self.tree.sync(guild=guild) bot = MyBot() @bot.tree.command( name=app_commands.locale_str("hello", fr="bonjour"), # 可选:给命令描述也添加本地化 description=app_commands.locale_str("Send a hello message", fr="Envoyer un message de salutation"), guild=guild ) @app_commands.default_permissions(manage_channels=True) async def hello(interaction: discord.Interaction) -> None: # 可选:根据用户的语言设置返回对应内容 if interaction.locale == discord.Locale.french: await interaction.response.send_message(content="Bonjour !") else: await interaction.response.send_message(content="Hello!") bot.run("你的Bot令牌")
方案2:使用翻译器(适合多命令多语言场景)
如果需要给大量命令做本地化,推荐用app_commands.Translator统一管理翻译内容:
import discord from discord import app_commands GUILD_ID = 你的服务器ID guild = discord.Object(id=GUILD_ID) class CommandTranslator(app_commands.Translator): async def translate(self, string: app_commands.locale_str, locale: discord.Locale, context: app_commands.TranslationContext) -> str | None: # 集中存储所有翻译映射 translation_map = { "hello": { discord.Locale.french: "bonjour", discord.Locale.english_us: "hello" }, "Send a hello message": { discord.Locale.french: "Envoyer un message de salutation" }, "hello_response": { discord.Locale.french: "Bonjour !", discord.Locale.english_us: "Hello!" } } return translation_map.get(string.message, {}).get(locale) class MyBot(discord.Client): def __init__(self): super().__init__(intents=discord.Intents.default()) self.tree = app_commands.CommandTree(self) # 注册翻译器 self.tree.translator = CommandTranslator() async def setup_hook(self): await self.tree.sync(guild=guild) bot = MyBot() @bot.tree.command( name="hello", description="Send a hello message", guild=guild ) @app_commands.default_permissions(manage_channels=True) async def hello(interaction: discord.Interaction) -> None: # 自动根据用户语言获取翻译内容 response = app_commands.locale_str("hello_response").resolve(interaction.locale) await interaction.response.send_message(content=response) bot.run("你的Bot令牌")
关键注意事项
- 必须调用
tree.sync()同步命令,否则Discord服务器无法接收本地化信息 - 测试时需切换Discord客户端的语言设置,之后重新打开命令菜单(可能需要重启客户端刷新缓存)
- 支持的语言列表可参考
discord.Locale枚举类,包含英语、法语、德语等主流语言
内容的提问来源于stack exchange,提问作者JIN
相关产品推荐
相关产品推荐

