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

如何在discord.py中基于用户/服务器区域设置本地化按钮标签?

Discord.py 按钮本地化:动态适配用户/服务器区域设置

1. 基于用户区域设置动态设置按钮标签

你可以在初始化视图时传入用户的区域设置,遍历视图内的按钮,将原始本地化键替换为对应用户语言的文本,让用户直接看到偏好语言的按钮标签。

实现代码:

class EmbedCreatorView(discord.ui.View):
    def __init__(self, locale: str):
        super().__init__(timeout=180)
        # 遍历按钮,用本地化工具替换标签
        for item in self.children:
            if isinstance(item, discord.ui.Button) and item.label.startswith("commands."):
                item.label = tanjunLocalizer.localize(locale, item.label)

    @discord.ui.button(label="commands.admin.embed.buttons.setTitle", style=discord.ButtonStyle.primary)
    async def set_title(self, interaction: discord.Interaction, button: discord.ui.Button):
        # 模态框交互逻辑...
        pass

    # 其他按钮定义...

在命令中调用视图:

发送带视图的消息时,传入用户的区域设置即可:

async def embed_command(interaction: discord.Interaction):
    # 获取用户区域设置,转为字符串适配本地化工具
    user_locale = str(interaction.user.locale)
    view = EmbedCreatorView(locale=user_locale)
    await interaction.response.send_message("请使用按钮编辑嵌入内容", view=view)

如果是持久化视图(通过bot.add_view注册的长期视图),可以在交互触发时更新按钮标签并编辑消息:

@discord.ui.button(label="commands.admin.embed.buttons.setTitle", style=discord.ButtonStyle.primary)
async def set_title(self, interaction: discord.Interaction, button: discord.ui.Button):
    # 获取用户区域设置并本地化按钮标签
    user_locale = str(interaction.user.locale)
    button.label = tanjunLocalizer.localize(user_locale, "commands.admin.embed.buttons.setTitle")
    # 更新消息视图使修改生效
    await interaction.message.edit(view=self)
    
    # 后续模态框逻辑...

2. 基于服务器默认区域设置设置标签

如果无法实现用户级本地化,可改用服务器的首选区域设置,逻辑和用户级一致,仅替换locale的获取来源:

实现代码:

class EmbedCreatorView(discord.ui.View):
    def __init__(self, locale: str):
        super().__init__(timeout=180)
        for item in self.children:
            if isinstance(item, discord.ui.Button) and item.label.startswith("commands."):
                item.label = tanjunLocalizer.localize(locale, item.label)

    # 按钮定义...

在命令中调用视图:

async def embed_command(interaction: discord.Interaction):
    # 获取服务器首选区域设置,私信用默认语言(示例为"en-US")
    guild_locale = str(interaction.guild.preferred_locale) if interaction.guild else "en-US"
    view = EmbedCreatorView(locale=guild_locale)
    await interaction.response.send_message("请使用按钮编辑嵌入内容", view=view)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 21:20:58