Python - 电报机器人的国际化
问题描述:
我使用Python gettext将我的电报机器人消息转换为pt_BR或将它们留在en_US中。这是我的代码:Python - 电报机器人的国际化
# Config the translations
lang_pt = gettext.translation("pt_BR", localedir="locale", languages=["pt_BR"])
def _(msg): return msg
# Connecting to Redis db
db = redis.StrictRedis(host="localhost", port=6379, db=0)
def user_language(func):
@wraps(func)
def wrapped(bot, update, *args, **kwargs):
lang = db.get(str(update.message.chat_id))
if lang == b"pt_BR":
# If language is pt_BR, translates
_ = lang_pt.gettext
else:
# If not, leaves as en_US
def _(msg): return msg
result = func(bot, update, *args, **kwargs)
return result
return wrapped
@user_language
def unknown(bot, update):
"""
Placeholder command when the user sends an unknown command.
"""
msg = _("Sorry, I don't know what you're asking for.")
bot.send_message(chat_id=update.message.chat_id,
text=msg)
但是,即使语言是pt_BR,文本仍然是en_US。看起来函数_()
(第3行)的第一个声明立即翻译所有消息,并且即使装饰器中的函数发生更改,消息也不会再被翻译。
如何强制消息在装饰器中再次翻译?
答
解决!
我只是忘记宣布_()为全球性的。这里是正确的代码:
def user_language(func):
@wraps(func)
def wrapped(bot, update, *args, **kwargs):
lang = db.get(str(update.message.chat_id))
global _
if lang == b"pt_BR":
# If language is pt_BR, translates
_ = lang_pt.gettext
else:
# If not, leaves as en_US
def _(msg): return msg
result = func(bot, update, *args, **kwargs)
return result
return wrapped
谢谢你从电报.Bot()组(@pythontelegrambotgroup)在电报! –