【问题标题】:Python - Internationalization for Telegram botsPython - Telegram 机器人的国际化
【发布时间】:2016-08-05 16:51:20
【问题描述】:

我正在使用 Python gettext 将我的 Telegram 机器人消息翻译成 pt_BR 或将它们留在 en_US 中。这是我的代码:

# 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 行)一次翻译了所有消息,即使 _() 函数在装饰器中发生更改,消息也不会再次翻译。

如何强制在装饰器中重新翻译消息?

【问题讨论】:

  • 这似乎是线程不安全的,不是吗?

标签: python internationalization telegram


【解决方案1】:

解决了!

我只是忘了声明 _() 是全局的。这是正确的代码:

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

【讨论】:

  • 感谢 Telegram 中 telegram.Bot() 组 (@pythontelegrambotgroup) 的 Jannes Hoke!
猜你喜欢
  • 1970-01-01
  • 2019-01-25
  • 1970-01-01
  • 2011-10-07
  • 1970-01-01
  • 2016-01-20
  • 2022-11-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多