2016-08-05 127 views
1

我使用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行)的第一個聲明立即翻譯所有消息,並且即使裝飾器中的函數發生更改,消息也不會再被翻譯。

如何強制消息在裝飾器中再次翻譯?

回答

0

解決!

我只是忘記宣佈_()爲全球性的。這裏是正確的代碼:

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 
+0

謝謝你從電報.Bot()組(@pythontelegrambotgroup)在電報! –