2024-03-18 18:21:56 +08:00
|
|
|
|
"""
|
|
|
|
|
语言模块,添加对多语言的支持
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
import json
|
2024-03-19 00:27:40 +08:00
|
|
|
|
import locale
|
2024-03-18 18:21:56 +08:00
|
|
|
|
import os
|
2024-03-23 19:55:12 +08:00
|
|
|
|
from typing import Any
|
2024-03-18 18:21:56 +08:00
|
|
|
|
|
|
|
|
|
import nonebot
|
|
|
|
|
|
2024-04-17 17:45:32 +08:00
|
|
|
|
from .config import config, get_config
|
2024-03-24 21:21:57 +08:00
|
|
|
|
from .data_manager import User, user_db
|
2024-03-18 18:21:56 +08:00
|
|
|
|
|
|
|
|
|
_language_data = {
|
|
|
|
|
"en": {
|
|
|
|
|
"name": "English",
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2024-04-17 17:45:32 +08:00
|
|
|
|
_user_lang = {
|
|
|
|
|
"user_id": "zh-CN"
|
|
|
|
|
}
|
|
|
|
|
|
2024-03-18 18:21:56 +08:00
|
|
|
|
|
|
|
|
|
def load_from_lang(file_path: str, lang_code: str = None):
|
|
|
|
|
"""
|
|
|
|
|
从lang文件中加载语言数据,用于简单的文本键值对
|
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
file_path: lang文件路径
|
|
|
|
|
lang_code: 语言代码,如果为None则从文件名中获取
|
|
|
|
|
"""
|
|
|
|
|
try:
|
|
|
|
|
if lang_code is None:
|
2024-03-26 17:14:41 +08:00
|
|
|
|
lang_code = os.path.basename(file_path).split(".")[0]
|
|
|
|
|
with open(file_path, "r", encoding="utf-8") as file:
|
2024-03-18 18:21:56 +08:00
|
|
|
|
data = {}
|
|
|
|
|
for line in file:
|
|
|
|
|
line = line.strip()
|
2024-03-26 17:14:41 +08:00
|
|
|
|
if not line or line.startswith("#"): # 空行或注释
|
2024-03-18 18:21:56 +08:00
|
|
|
|
continue
|
2024-03-26 17:14:41 +08:00
|
|
|
|
key, value = line.split("=", 1)
|
2024-03-18 18:21:56 +08:00
|
|
|
|
data[key.strip()] = value.strip()
|
|
|
|
|
if lang_code not in _language_data:
|
|
|
|
|
_language_data[lang_code] = {}
|
|
|
|
|
_language_data[lang_code].update(data)
|
2024-04-05 09:14:26 +08:00
|
|
|
|
nonebot.logger.debug(f"Loaded language data from {file_path}")
|
2024-03-18 18:21:56 +08:00
|
|
|
|
except Exception as e:
|
|
|
|
|
nonebot.logger.error(f"Failed to load language data from {file_path}: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def load_from_json(file_path: str, lang_code: str = None):
|
|
|
|
|
"""
|
|
|
|
|
从json文件中加载语言数据,可以定义一些变量
|
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
lang_code: 语言代码,如果为None则从文件名中获取
|
|
|
|
|
file_path: json文件路径
|
|
|
|
|
"""
|
|
|
|
|
try:
|
|
|
|
|
if lang_code is None:
|
2024-03-26 17:14:41 +08:00
|
|
|
|
lang_code = os.path.basename(file_path).split(".")[0]
|
|
|
|
|
with open(file_path, "r", encoding="utf-8") as file:
|
2024-03-18 18:21:56 +08:00
|
|
|
|
data = json.load(file)
|
|
|
|
|
if lang_code not in _language_data:
|
|
|
|
|
_language_data[lang_code] = {}
|
|
|
|
|
_language_data[lang_code].update(data)
|
2024-04-05 09:14:26 +08:00
|
|
|
|
nonebot.logger.debug(f"Loaded language data from {file_path}")
|
2024-03-18 18:21:56 +08:00
|
|
|
|
except Exception as e:
|
|
|
|
|
nonebot.logger.error(f"Failed to load language data from {file_path}: {e}")
|
|
|
|
|
|
|
|
|
|
|
2024-03-19 00:27:40 +08:00
|
|
|
|
def load_from_dir(dir_path: str):
|
|
|
|
|
"""
|
|
|
|
|
从目录中加载语言数据
|
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
dir_path: 目录路径
|
|
|
|
|
"""
|
|
|
|
|
for file in os.listdir(dir_path):
|
|
|
|
|
try:
|
|
|
|
|
file_path = os.path.join(dir_path, file)
|
|
|
|
|
if os.path.isfile(file_path):
|
2024-03-26 17:14:41 +08:00
|
|
|
|
if file.endswith(".lang"):
|
2024-03-19 00:27:40 +08:00
|
|
|
|
load_from_lang(file_path)
|
2024-03-26 17:14:41 +08:00
|
|
|
|
elif file.endswith(".json"):
|
2024-03-19 00:27:40 +08:00
|
|
|
|
load_from_json(file_path)
|
|
|
|
|
except Exception as e:
|
|
|
|
|
nonebot.logger.error(f"Failed to load language data from {file}: {e}")
|
|
|
|
|
continue
|
|
|
|
|
|
|
|
|
|
|
2024-03-18 18:21:56 +08:00
|
|
|
|
def load_from_dict(data: dict, lang_code: str):
|
|
|
|
|
"""
|
|
|
|
|
从字典中加载语言数据
|
|
|
|
|
|
|
|
|
|
Args:
|
|
|
|
|
lang_code: 语言代码
|
|
|
|
|
data: 字典数据
|
|
|
|
|
"""
|
|
|
|
|
if lang_code not in _language_data:
|
|
|
|
|
_language_data[lang_code] = {}
|
|
|
|
|
_language_data[lang_code].update(data)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class Language:
|
2024-04-17 17:45:32 +08:00
|
|
|
|
# 三重fallback
|
|
|
|
|
# 用户语言 > 默认语言/系统语言 > zh-CN
|
|
|
|
|
def __init__(self, lang_code: str = None, fallback_lang_code: str = None):
|
2024-03-18 18:21:56 +08:00
|
|
|
|
self.lang_code = lang_code
|
2024-04-17 17:45:32 +08:00
|
|
|
|
|
2024-04-15 20:21:50 +08:00
|
|
|
|
if self.lang_code is None:
|
|
|
|
|
self.lang_code = get_default_lang_code()
|
|
|
|
|
|
2024-03-18 18:21:56 +08:00
|
|
|
|
self.fallback_lang_code = fallback_lang_code
|
2024-04-03 01:03:25 +08:00
|
|
|
|
if self.fallback_lang_code is None:
|
|
|
|
|
self.fallback_lang_code = config.get("default_language", get_system_lang_code())
|
|
|
|
|
|
2024-03-19 00:27:40 +08:00
|
|
|
|
def get(self, item: str, *args, **kwargs) -> str | Any:
|
2024-03-18 18:21:56 +08:00
|
|
|
|
"""
|
2024-04-17 17:45:32 +08:00
|
|
|
|
获取当前语言文本,kwargs中的default参数为默认文本
|
2024-03-18 18:21:56 +08:00
|
|
|
|
Args:
|
|
|
|
|
item: 文本键
|
|
|
|
|
*args: 格式化参数
|
2024-03-24 21:21:57 +08:00
|
|
|
|
**kwargs: 格式化参数
|
2024-03-18 18:21:56 +08:00
|
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
|
str: 当前语言的文本
|
|
|
|
|
|
|
|
|
|
"""
|
2024-03-24 21:21:57 +08:00
|
|
|
|
default = kwargs.pop("default", None)
|
2024-04-17 17:45:32 +08:00
|
|
|
|
fallback = (self.lang_code, self.fallback_lang_code, "zh-CN")
|
2024-03-24 21:21:57 +08:00
|
|
|
|
|
2024-04-17 17:45:32 +08:00
|
|
|
|
for lang_code in fallback:
|
|
|
|
|
if lang_code in _language_data and item in _language_data[lang_code]:
|
|
|
|
|
trans: str = _language_data[lang_code][item]
|
|
|
|
|
try:
|
|
|
|
|
return trans.format(*args, **kwargs)
|
|
|
|
|
except Exception as e:
|
|
|
|
|
nonebot.logger.warning(f"Failed to format language data: {e}")
|
|
|
|
|
return trans
|
|
|
|
|
return default or item
|
2024-03-18 18:21:56 +08:00
|
|
|
|
|
2024-03-31 06:22:53 +08:00
|
|
|
|
|
2024-04-17 17:45:32 +08:00
|
|
|
|
def change_user_lang(user_id: str, lang_code: str):
|
|
|
|
|
"""
|
2024-04-17 20:45:44 +08:00
|
|
|
|
修改用户的语言,同时储存到数据库和内存中
|
2024-04-17 17:45:32 +08:00
|
|
|
|
"""
|
2024-05-12 00:18:53 +08:00
|
|
|
|
user = user_db.where_one(User(), "user_id = ?", user_id, default=User(user_id=user_id))
|
2024-04-17 17:45:32 +08:00
|
|
|
|
user.profile["lang"] = lang_code
|
2024-04-27 02:20:44 +08:00
|
|
|
|
user_db.save(user)
|
2024-04-17 20:45:44 +08:00
|
|
|
|
_user_lang[user_id] = lang_code
|
2024-03-31 06:22:53 +08:00
|
|
|
|
|
2024-03-18 18:21:56 +08:00
|
|
|
|
|
|
|
|
|
def get_user_lang(user_id: str) -> Language:
|
|
|
|
|
"""
|
2024-04-17 17:45:32 +08:00
|
|
|
|
获取用户的语言实例,优先从内存中获取
|
2024-03-18 18:21:56 +08:00
|
|
|
|
"""
|
2024-04-17 20:45:44 +08:00
|
|
|
|
user_id = str(user_id)
|
|
|
|
|
|
|
|
|
|
if user_id not in _user_lang:
|
2024-04-27 02:20:44 +08:00
|
|
|
|
nonebot.logger.debug(f"Loading user language for {user_id}")
|
2024-05-12 00:18:53 +08:00
|
|
|
|
user = user_db.where_one(
|
2024-04-17 17:45:32 +08:00
|
|
|
|
User(), "user_id = ?", user_id, default=User(
|
|
|
|
|
user_id=user_id,
|
|
|
|
|
username="Unknown"
|
|
|
|
|
)
|
|
|
|
|
)
|
|
|
|
|
lang_code = user.profile.get("lang", get_default_lang_code())
|
|
|
|
|
_user_lang[user_id] = lang_code
|
2024-04-17 20:45:44 +08:00
|
|
|
|
|
|
|
|
|
return Language(_user_lang[user_id])
|
2024-03-19 00:27:40 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def get_system_lang_code() -> str:
|
|
|
|
|
"""
|
|
|
|
|
获取系统语言代码
|
|
|
|
|
"""
|
|
|
|
|
return locale.getdefaultlocale()[0].replace('_', '-')
|
|
|
|
|
|
|
|
|
|
|
2024-04-15 20:21:50 +08:00
|
|
|
|
def get_default_lang_code() -> str:
|
2024-03-19 00:27:40 +08:00
|
|
|
|
"""
|
2024-04-17 17:45:32 +08:00
|
|
|
|
获取默认语言代码,若没有设置则使用系统语言
|
2024-04-15 20:21:50 +08:00
|
|
|
|
Returns:
|
|
|
|
|
|
2024-03-19 00:27:40 +08:00
|
|
|
|
"""
|
2024-04-17 17:45:32 +08:00
|
|
|
|
return get_config("default_language", default=get_system_lang_code())
|
2024-03-22 13:39:01 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def get_all_lang() -> dict[str, str]:
|
|
|
|
|
"""
|
|
|
|
|
获取所有语言
|
|
|
|
|
Returns
|
|
|
|
|
{'en': 'English'}
|
|
|
|
|
"""
|
|
|
|
|
d = {}
|
|
|
|
|
for key in _language_data:
|
|
|
|
|
d[key] = _language_data[key].get("language.name", key)
|
|
|
|
|
return d
|