changeset 2413:61380308535d

Added a dummy _ function so that string for translations can be gathered.
author Karol 'grzywacz' Nowak <grzywacz@sul.uni.lodz.pl>
date Tue, 17 Jul 2007 03:24:28 +0200
parents 46fd1b987437
children 58ae57239761
files jabberbot/i18n.py jabberbot/xmlrpcbot.py jabberbot/xmppbot.py
diffstat 3 files changed, 81 insertions(+), 36 deletions(-) [+]
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jabberbot/i18n.py	Tue Jul 17 03:24:28 2007 +0200
@@ -0,0 +1,24 @@
+# -*- coding: iso-8859-1 -*-
+"""
+    MoinMoin - jabber bot i18n routines
+
+    @copyright: 2007 by Karol Nowak <grywacz@gmail.com>
+    @license: GNU GPL, see COPYING for details.
+"""
+
+translations = None
+
+def getText(original, lang="en"):
+    global translations
+    
+    if not translations:
+        init_i18n()
+
+    try:
+        return translations[lang][original]
+    except KeyError:
+        return original
+
+def init_i18n():
+    global translations
+    translations = {'en': { } }
--- a/jabberbot/xmlrpcbot.py	Tue Jul 17 03:22:13 2007 +0200
+++ b/jabberbot/xmlrpcbot.py	Tue Jul 17 03:24:28 2007 +0200
@@ -6,13 +6,15 @@
     @license: GNU GPL, see COPYING for details.
 """
 
-import Queue
+import datetime, logging, time, xmlrpclib, Queue
+from SimpleXMLRPCServer import SimpleXMLRPCServer
 from threading import Thread
-import datetime, logging, time, xmlrpclib
-from SimpleXMLRPCServer import SimpleXMLRPCServer
 
 import jabberbot.commands as cmd
 from jabberbot.multicall import MultiCall
+from jabberbot.i18n import getText
+
+_ = getText
 
 class ConfigurationError(Exception):
     def __init__(self, message):
@@ -36,7 +38,7 @@
         self.log = logging.getLogger("log")
 
         if not config.secret:
-            error = "You must set a (long) secret string!"
+            error = _("You must set a (long) secret string!")
             self.log.critical(error)
             raise ConfigurationError(error)
 
@@ -74,7 +76,7 @@
             self.get_page_info(command)
 
     def report_error(self, jid, text):
-        report = cmd.NotificationCommand(jid, text, u"Error", async=False)
+        report = cmd.NotificationCommand(jid, text, _("Error"), async=False)
         self.commands_out.put_nowait(report)
 
     def get_auth_token(self, jid):
@@ -105,15 +107,15 @@
                     function(self, command)
                     self.commands_out.put_nowait(command)
                 except xmlrpclib.Fault, fault:
-                    msg = u"""Your request has failed. The reason is:\n%s"""
+                    msg = _("Your request has failed. The reason is:\n%s")
                     self.log.error(str(fault))
                     self.report_error(jid, msg % (fault.faultString, ))
                 except xmlrpclib.Error, err:
-                    msg = u"""A serious error occured while processing your request:\n%s"""
+                    msg = _("A serious error occured while processing your request:\n%s")
                     self.log.error(str(err))
                     self.report_error(jid, msg % (str(err), ))
                 except Exception, exc:
-                    msg = u"An internal error has occured, please contact the administrator."
+                    msg = _("An internal error has occured, please contact the administrator.")
                     self.log.critical(str(exc))
                     self.report_error(jid, msg)
 
@@ -124,7 +126,7 @@
         return wrapped_func
 
     def warn_no_credentials(self, jid):
-        msg = u"""Credentials check failed, you may be unable to see all information."""
+        msg = _("Credentials check failed, you may be unable to see all information.")
         warning = cmd.NotificationCommand([jid], msg, async=False)
         self.commands_out.put_nowait(warning)
 
@@ -165,7 +167,7 @@
     def get_page_list(self, command):
         """Returns a list of all accesible pages"""
 
-        txt = u"""This command may take a while to complete, please be patient..."""
+        txt = _("This command may take a while to complete, please be patient...")
         info = cmd.NotificationCommand([command.jid], txt, async=False)
         self.commands_out.put_nowait(info)
 
@@ -208,9 +210,9 @@
                     'time': datestr[9:17],
                 }
 
-        msg = u"""Last author: %(author)s
+        msg = _("""Last author: %(author)s
 Last modification: %(modification)s
-Current version: %(version)s""" % {
+Current version: %(version)s""") % {
              'author': author,
              'modification': date,
              'version': getpageinfo_result[0]['version'],
@@ -240,7 +242,7 @@
         if config.secret:
             self.secret = config.secret
         else:
-            error = "You must set a (long) secret string"
+            error = _("You must set a (long) secret string")
             self.log.critical(error)
             raise ConfigurationError(error)
 
@@ -268,7 +270,7 @@
         """
         def protected_func(secret, *args):
             if secret != self.secret:
-                raise xmlrpclib.Fault(1, "You are not allowed to use this bot!")
+                raise xmlrpclib.Fault(1, _("You are not allowed to use this bot!"))
             else:
                 return function(self, *args)
 
--- a/jabberbot/xmppbot.py	Tue Jul 17 03:22:13 2007 +0200
+++ b/jabberbot/xmppbot.py	Tue Jul 17 03:24:28 2007 +0200
@@ -18,6 +18,9 @@
 import pyxmpp.jabber.dataforms as forms
 
 import jabberbot.commands as cmd
+from jabberbot.i18n import getText
+
+_ = getText
 
 class Contact:
     """Abstraction of a roster item / contact
@@ -212,17 +215,25 @@
             self.remove_subscription(jid)
 
         elif isinstance(command, cmd.GetPage) or isinstance(command, cmd.GetPageHTML):
-            msg = u"""Here's the page "%s" that you've requested:\n\n%s"""
-            self.send_message(command.jid, msg % (command.pagename, command.data))
+            msg = _("""Here's the page "%(pagename)s" that you've requested:\n\n%(data)s""")
+            self.send_message(command.jid, msg % {
+                      'pagename': command.pagename, 
+                      'data': command.data,
+            })
 
         elif isinstance(command, cmd.GetPageList):
-            msg = u"""That's the list of pages accesible to you:\n\n%s"""
+            msg = _("That's the list of pages accesible to you:\n\n%s")
             pagelist = "\n".join(command.data)
             self.send_message(command.jid, msg % (pagelist, ))
 
         elif isinstance(command, cmd.GetPageInfo):
-            msg = u"""Following detailed information on page "%s" is available::\n\n%s"""
-            self.send_message(command.jid, msg % (command.pagename, command.data))
+            msg = _("""Following detailed information on page "%(pagename)s" \
+is available::\n\n%(data)s""")
+            
+            self.send_message(command.jid, msg % { 
+                      'pagename': command.pagename, 
+                      'data': command.data,
+            })
 
     def ask_for_subscription(self, jid):
         """Sends a <presence/> stanza with type="subscribe"
@@ -263,16 +274,16 @@
         pass
 
     def send_search_form(self, jid):
-        help_form = u"Submit this form to perform a wiki search"
-
-        title_search = forms.Option("t", "Title search")
-        full_search = forms.Option("f", "Full-text search")
+        help_form = _("Submit this form to perform a wiki search")
 
-        form = forms.Form(xmlnode_or_type="form", title="Wiki search", instructions=help_form)
+        title_search = forms.Option("t", _("Title search"))
+        full_search = forms.Option("f", _("Full-text search"))
+
+        form = forms.Form(xmlnode_or_type="form", title=_("Wiki search"), instructions=help_form)
         form.add_field(name="search_type", options=[title_search, full_search], field_type="list-single", label="Search type")
-        form.add_field(name="search", field_type="text-single", label="Search text")
+        form.add_field(name="search", field_type="text-single", label=_("Search text"))
 
-        message = Message(to_jid=jid, body="Please specify the search criteria.", subject="Wiki search")
+        message = Message(to_jid=jid, body=_("Please specify the search criteria."), subject=_("Wiki search"))
         message.add_content(form)
         self.get_stream().send(message)
 
@@ -350,7 +361,7 @@
             if self.contacts[jid].supports_forms(resource):
                 self.send_search_form(sender)
             else:
-                msg = u"This command requires a client supporting Data Forms"
+                msg = _("This command requires a client supporting Data Forms")
                 self.send_message(sender, msg, u"Error")
         else:
             # For unknown command return a generic help message
@@ -379,22 +390,27 @@
 
         """
         if command == "help":
-            return u"""The "help" command prints a short, helpful message about a given topic or function.\n\nUsage: help [topic_or_function]"""
+            return _("""The "help" command prints a short, helpful message \
+about a given topic or function.\n\nUsage: help [topic_or_function]""")
 
         elif command == "ping":
-            return u"""The "ping" command returns a "pong" message as soon as it's received."""
+            return _("""The "ping" command returns a "pong" message as soon \
+as it's received.""")
 
         elif command == "searchform":
-            return u"""searchform - perform a wiki search using a form"""
+            return _("""searchform - perform a wiki search using a form""")
 
         # Here we have to deal with help messages of external (xmlrpc) commands
         else:
             if command in self.xmlrpc_commands:
                 classobj = self.xmlrpc_commands[command]
-                help_str = u"%s - %s\n\nUsage: %s %s"
-                return help_str % (command, classobj.description, command, classobj.parameter_list)
+                help_str = _("%(command)s - %(description)s\n\nUsage: %(command)s %(params)s")
+                return help_str % { 'command': command, 
+                                    'description': classobj.description, 
+                                    'params': classobj.parameter_list,
+                                  }
             else:
-                return u"""Unknown command "%s" """ % (command, )
+                return _("""Unknown command "%s" """) % (command, )
 
     def handle_xmlrpc_command(self, sender, command):
         """Creates a command object, and puts it the command queue
@@ -415,8 +431,10 @@
 
         # This happens when user specifies wrong parameters
         except TypeError:
-            msg = u"You've specified a wrong parameter list. The call should look like:\n\n%s %s"
-            return msg % (command[0], command_class.parameter_list)
+            msg = _("You've specified a wrong parameter list. \
+The call should look like:\n\n%(command)s %(params)s")
+            
+            return msg % {'command': command[0], 'params': command_class.parameter_list}
 
     def handle_unsubscribed_presence(self, stanza):
         """Handles unsubscribed presence stanzas"""
@@ -563,7 +581,8 @@
         It's sent in response to an uknown message or the "help" command.
 
         """
-        msg = u"""Hello there! I'm a MoinMoin Notification Bot. Available commands:\n\n%s\n%s"""
+        msg = _("Hello there! I'm a MoinMoin Notification Bot. Available commands:\
+\n\n%(internal)s\n%(xmlrpc)s")
         internal = ", ".join(self.internal_commands)
         xmlrpc = ", ".join(self.xmlrpc_commands.keys())