如何在discord.py中为命令及其参数添加本地化支持
如何在discord.py中为命令及其参数添加本地化支持
你想给discord.py的命令和参数加上本地化支持,让它们能根据用户的Discord客户端语言自动切换描述内容,就像你提到的Juniper Bot那样对吧?这事儿其实discord.py的App Command功能已经支持了,我来给你捋清楚怎么实现。
先看看你现在的代码:
@bot.tree.command(name='addcolorrole', description='Creates or updates a color role') @app_commands.describe(color='헵헲혅 헰헼헱헲, "pfp" or "random"') async def addcolorrole(ctx, color: str):
目前你只写了英文的命令描述和韩文的参数说明,没有做多语言适配,所以没法根据用户语言自动切换。接下来咱们一步步改造:
第一步:准备各语言的翻译文本
首先你得把命令描述、参数描述翻译成需要支持的语言,比如咱们支持英文、韩文、中文的话,先整理好对应的内容:
- 英文:命令描述是
Creates or updates a color role,参数color描述是Hex color, "pfp" or "random" - 韩文:命令描述可以是
색상 역할을 생성하거나 업데이트합니다,参数color描述是헥스 색상, "pfp" 또는 "random" - 中文:命令描述是
创建或更新色彩角色,参数color描述是十六进制颜色、"pfp" 或 "random"
第二步:给命令绑定本地化内容
discord.py提供了两种方式来添加本地化:
方式一:用localize方法绑定
先定义好本地化字典,再绑定到命令上:
import discord from discord import app_commands # 命令描述的本地化字典,key是discord支持的语言枚举 command_descriptions = { discord.Locale.en_US: "Creates or updates a color role", discord.Locale.ko: "색상 역할을 생성하거나 업데이트합니다", discord.Locale.zh_CN: "创建或更新色彩角色" } # 参数color的描述本地化字典 color_param_descriptions = { discord.Locale.en_US: "Hex color, \"pfp\" or \"random\"", discord.Locale.ko: "헥스 색상, \"pfp\" 또는 \"random\"", discord.Locale.zh_CN: "十六进制颜色、\"pfp\" 或 \"random\"" } # 定义命令,默认用英文描述 @bot.tree.command(name='addcolorrole', description='Creates or updates a color role') @app_commands.describe(color='Hex color, "pfp" or "random"') async def addcolorrole(ctx, color: str): # 这里写你的命令逻辑 await ctx.response.send_message(f"处理色彩角色:{color}") # 给命令绑定描述的本地化 addcolorrole.localize(command_descriptions, attribute="description") # 给参数color绑定描述的本地化 addcolorrole.localize(color_param_descriptions, attribute="description", parameter="color")
方式二:用@app_commands.translate装饰器
这种方式更简洁,直接在命令装饰器上面加:
import discord from discord import app_commands command_descriptions = { discord.Locale.en_US: "Creates or updates a color role", discord.Locale.ko: "색상 역할을 생성하거나 업데이트합니다", discord.Locale.zh_CN: "创建或更新色彩角色" } color_param_descriptions = { discord.Locale.en_US: "Hex color, \"pfp\" or \"random\"", discord.Locale.ko: "헥스 색상, \"pfp\" 또는 \"random\"", discord.Locale.zh_CN: "十六进制颜色、\"pfp\" 或 \"random\"" } @app_commands.translate(description=command_descriptions) @app_commands.translate(parameter="color", description=color_param_descriptions) @bot.tree.command(name='addcolorrole', description='Creates or updates a color role') @app_commands.describe(color='Hex color, "pfp" or "random"') async def addcolorrole(ctx, color: str): await ctx.response.send_message(f"处理色彩角色:{color}")
几个要注意的点
- 一定要用
discord.Locale里的枚举值作为字典的key,这些都是Discord官方支持的语言代码,比如en_US(美式英语)、ko(韩语)、zh_CN(简体中文)等,别自己瞎写代码。 - 如果用户的Discord语言没有对应的翻译,bot会自动回退到你在命令装饰器里写的默认描述。
- 你还可以给命令名称做本地化,比如不同语言显示不同的命令名,只需要把
attribute改成name就行。
你提供的两张图应该分别展示了不同语言下命令的显示效果,用上面的方法改造后,你的bot就能像Juniper Bot一样,根据用户的Discord语言自动切换命令和参数的描述啦。
备注:内容来源于stack exchange,提问作者Olimpiia_ ART




