国际化
国际化
Lingchu Bot 使用 Python gettext 和 Babel 管理运行时反馈文本。当前 catalog 覆盖简体中文 zh_CN 和英文 en_US,主要用于群管理命令的成功和失败反馈。
运行时 locale
i18n 辅助函数位于 src/plugins/nonebot_plugin_lingchu_bot/i18n。运行时会按顺序读取 NoneBot 配置:
lingchu_localelc_localelocale
如果没有可用配置,默认使用 zh_CN。locale 会在读取后规范化:
en-US会转换为en_US。en_US.UTF-8会转换为en_US。- 空值会回退到
zh_CN。
gettext 使用 fallback=True,因此未翻译文本会返回原文,而不是中断命令处理。
Catalog 结构
翻译文件位于:
src/plugins/nonebot_plugin_lingchu_bot/i18n/
├── babel.cfg
├── messages.pot
└── locales/
├── en_US/LC_MESSAGES/messages.po
├── en_US/LC_MESSAGES/messages.mo
├── zh_CN/LC_MESSAGES/messages.po
└── zh_CN/LC_MESSAGES/messages.momessages.pot 是提取模板,messages.po 是可编辑翻译源,messages.mo 是运行时读取的编译结果。
更新流程
修改可翻译字符串后,按顺序运行:
task i18ntask i18n 会按顺序执行提取、更新和编译。等价底层命令在 Taskfile.yml 中维护:
uv run pybabel extract -F src/plugins/nonebot_plugin_lingchu_bot/i18n/babel.cfg -o src/plugins/nonebot_plugin_lingchu_bot/i18n/messages.pot src/plugins/nonebot_plugin_lingchu_bot
uv run pybabel update -i src/plugins/nonebot_plugin_lingchu_bot/i18n/messages.pot -d src/plugins/nonebot_plugin_lingchu_bot/i18n/locales -D messages
uv run pybabel compile -d src/plugins/nonebot_plugin_lingchu_bot/i18n/locales -D messages编译前检查 .po 文件中是否残留 #, fuzzy,避免运行时加载未确认翻译。
异步路径
异步处理器应使用 _async、gettext_async 或 ngettext_async。这些辅助函数会把 catalog 加载放到 worker thread,避免在事件循环中执行同步文件读取。启动阶段会调用 warm_translation_cache 预热默认 locale。
同步 _ / gettext 只适合模块外的同步路径。不要在模块导入时翻译可随 locale 改变的默认参数;应在 handler 执行时读取和翻译。
最后更新于