How to use the pywikibot.i18n.translate function in pywikibot

To help you get started, we’ve selected a few pywikibot examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ricordisamoa / wiki / poem.py View on Github external
def process_lines(self, lines):
        """
        Remove old templates from lines and obtain line numbers.

        @param lines: the lines to clean up
        @type lines: unicode
        @return: cleaned-up lines and line numbers
        @rtype: tuple containing a unicode and a list of ints
        """
        ln = 0
        numbering = []
        lines = lines.split('\n')
        tmps = i18n.translate(self.current_page.site, self.line_tmps, fallback=False)
        for i, line in enumerate(lines):
            if line.strip() != '':
                ln += 1
                code = mwparserfromhell.parse(line)
                for tmp in code.ifilter_templates():
                    if tmp.name.strip() not in tmps:
                        pywikibot.warning(u'unexpected template: "{}"'.format(tmp.name))
                        continue
                    if ln in numbering:
                        raise PoemError(u'exceeding template: "{}"', tmp.name)
                    params = [param for param in tmp.params if tmp.has(param.name, True)]
                    if len(params) == 0:
                        raise PoemError(u'no parameters found in "{}"', tmp.name)
                    if len(params) > 1:
                        raise PoemError(u'multiple parameters found in "{}"', tmp.name)
                    if params[0].name.strip() != '1':
github JackPotte / JackBot / core / scripts / blockpageschecker.py View on Github external
namespace = int(value)
        else:
            genFactory.handleArg(arg)

    if config.mylang not in project_inserted:
        pywikibot.output(u"Your project is not supported by this script.\n"
                         u"You have to edit the script and add it!")
        return

    site = pywikibot.Site()

    if protectedpages:
        generator = site.protectedpages(namespace=namespace, type=protectType)
    # Take the right templates to use, the category and the comment
    TSP = i18n.translate(site, templateSemiProtection)
    TTP = i18n.translate(site, templateTotalProtection)
    TSMP = i18n.translate(site, templateSemiMoveProtection)
    TTMP = i18n.translate(site, templateTotalMoveProtection)
    TNR = i18n.translate(site, templateNoRegex)
    TU = i18n.translate(site, templateUnique)

    categories = i18n.translate(site, categoryToCheck)
    commentUsed = i18n.twtranslate(site, 'blockpageschecker-summary')
    if not generator:
        generator = genFactory.getCombinedGenerator()
    if not generator:
        generator = []
        pywikibot.output(u'Loading categories...')
        # Define the category if no other generator has been setted
        for CAT in categories:
            cat = pywikibot.Category(site, CAT)
            # Define the generator
github wikimedia / pywikibot / scripts / welcome.py View on Github external
def check_managed_sites(self):
        """Check that site is managed by welcome.py."""
        # Raises KeyError if site is not in netext dict.
        site_netext = i18n.translate(self.site, netext)
        if site_netext is None:
            raise KeyError(
                'welcome.py is not localized for site {0} in netext dict.'
                .format(self.site))
        self.welcome_text = site_netext
github wikimedia / pywikibot / scripts / solve_disambiguation.py View on Github external
"""Setup i18n summary message."""
        # make list of new targets
        comma = self.mysite.mediawiki_message('comma-separator')
        targets = comma.join('[[{0}]]'.format(page_title)
                             for page_title in new_targets)

        if not targets:
            targets = i18n.twtranslate(self.mysite,
                                       'solve_disambiguation-unknown-page')

        # first check whether user has customized the edit comment
        if (self.mysite.family.name in config.disambiguation_comment and
                self.mylang in config.disambiguation_comment[
                    self.mysite.family.name]):
            try:
                self.comment = i18n.translate(
                    self.mysite,
                    config.disambiguation_comment[self.mysite.family.name],
                    fallback=True) % (disambPage.title(), targets)

            # Backwards compatibility, type error probably caused by too
            # many arguments for format string
            except TypeError:
                self.comment = i18n.translate(
                    self.mysite,
                    config.disambiguation_comment[self.mysite.family.name],
                    fallback=True) % disambPage.title()
        elif disambPage.isRedirectPage():
            # when working on redirects, there's another summary message
            if unlink_counter and not new_targets:
                self.comment = i18n.twtranslate(
                    self.mysite,
github wikimedia / pywikibot / scripts / archivebot.py View on Github external
def str2localized_duration(site, string):
    """
    Localise a shorthand duration.

    Translates a duration written in the shorthand notation (ex. "24h", "7d")
    into an expression in the local wiki language ("24 hours", "7 days").
    """
    key, duration = checkstr(string)
    template = site.mediawiki_message(MW_KEYS[key])
    if template:
        # replace plural variants
        exp = i18n.translate(site.code, template, {'$1': int(duration)})
        return exp.replace('$1', to_local_digits(duration, site.code))
    else:
        return to_local_digits(string, site.code)
github ricordisamoa / wiki / summary_notice.py View on Github external
def log(user, pages):
    talk = user.getUserTalkPage()
    titles = [page.title() for page in pages]
    notice = translate(talk.site, msg['notice']).format(titles=titles)
    text = talk.get(force=True)
    if notice in talk.text:
        pywikibot.output(u'\03{lightgreen}already logged')
        return
    header = translate()
    talk.text += u'\n\n== {} ==\n\n{} --~~~~'.format(header, notice)
    pywikibot.showDiff(text, talk.text)
    comment = translate(talk.site, msg['comment'], [bot_link(user.site)])
    talk.save(comment=comment, minor=False, botflag=True)
github JackPotte / JackBot / core / scripts / blockpageschecker.py View on Github external
if value:
                namespace = int(value)
        else:
            genFactory.handleArg(arg)

    if config.mylang not in project_inserted:
        pywikibot.output(u"Your project is not supported by this script.\n"
                         u"You have to edit the script and add it!")
        return

    site = pywikibot.Site()

    if protectedpages:
        generator = site.protectedpages(namespace=namespace, type=protectType)
    # Take the right templates to use, the category and the comment
    TSP = i18n.translate(site, templateSemiProtection)
    TTP = i18n.translate(site, templateTotalProtection)
    TSMP = i18n.translate(site, templateSemiMoveProtection)
    TTMP = i18n.translate(site, templateTotalMoveProtection)
    TNR = i18n.translate(site, templateNoRegex)
    TU = i18n.translate(site, templateUnique)

    categories = i18n.translate(site, categoryToCheck)
    commentUsed = i18n.twtranslate(site, 'blockpageschecker-summary')
    if not generator:
        generator = genFactory.getCombinedGenerator()
    if not generator:
        generator = []
        pywikibot.output(u'Loading categories...')
        # Define the category if no other generator has been setted
        for CAT in categories:
            cat = pywikibot.Category(site, CAT)
github wikimedia / pywikibot / scripts / replace.py View on Github external
except KeyError:
            pywikibot.output('Available predefined fixes are: {0}'
                             .format(', '.join(fixes.fixes.keys())))
            if not fixes.user_fixes_loaded:
                pywikibot.output('The user fixes file could not be found: '
                                 '{0}'.format(fixes.filename))
            return
        if not fix['replacements']:
            pywikibot.warning('No replacements defined for fix '
                              '"{0}"'.format(fix_name))
            continue
        if 'msg' in fix:
            if isinstance(fix['msg'], basestring):
                set_summary = i18n.twtranslate(site, str(fix['msg']))
            else:
                set_summary = i18n.translate(site, fix['msg'], fallback=True)
        else:
            set_summary = None
        if not generators_given and 'generator' in fix:
            gen_args = fix['generator']
            if isinstance(gen_args, basestring):
                gen_args = [gen_args]
            for gen_arg in gen_args:
                genFactory.handleArg(gen_arg)
        replacement_set = ReplacementList(fix.get('regex'),
                                          fix.get('exceptions'),
                                          fix.get('nocase'),
                                          set_summary,
                                          name=fix_name)
        # Whether some replacements have a summary, if so only show which
        # have none, otherwise just mention the complete fix
        missing_fix_summaries = []
github wikimedia / pywikibot / scripts / welcome.py View on Github external
else:
                text_get = ('This is a report page for the Bad-username, '
                            'please translate me. --~~~')
            pos = 0
            # The talk page includes "_" between the two names, in this way
            # replace them to " ".
            for usrna in self._BAQueue:
                username = pywikibot.url2link(usrna, self.site, self.site)
                n = re.compile(re.escape(username), re.UNICODE)
                y = n.search(text_get, pos)
                if y:
                    pywikibot.output('{} is already in the report page.'
                                     .format(username))
                else:
                    # Adding the log.
                    rep_text += i18n.translate(self.site,
                                               report_text) % username
                    if self.site.code == 'it':
                        rep_text = '%s%s}}' % (rep_text, self.bname[username])

            com = i18n.twtranslate(self.site, 'welcome-bad_username')
            if rep_text != '':
                rep_page.put(text_get + rep_text, summary=com, force=True,
                             minor=True)
                showStatus(5)
                pywikibot.output('Reported')
            self.BAQueue = []
        else:
            return True
github wikimedia / pywikibot / scripts / welcome.py View on Github external
if answer.lower() in ['yes', 'y'] or not globalvar.confirm:
                showStatus()
                pywikibot.output(
                    '{} is possibly an unwanted username. It will be reported.'
                    .format(name))
                if hasattr(self, '_BAQueue'):
                    self._BAQueue.append(name)
                else:
                    self._BAQueue = [name]

        if len(self._BAQueue) >= globalvar.dumpToLog or final:
            rep_text = ''
            # name in queue is max, put detail to report page
            pywikibot.output('Updating badname accounts to report page...')
            rep_page = pywikibot.Page(self.site,
                                      i18n.translate(self.site,
                                                     report_page))
            if rep_page.exists():
                text_get = rep_page.get()
            else:
                text_get = ('This is a report page for the Bad-username, '
                            'please translate me. --~~~')
            pos = 0
            # The talk page includes "_" between the two names, in this way
            # replace them to " ".
            for usrna in self._BAQueue:
                username = pywikibot.url2link(usrna, self.site, self.site)
                n = re.compile(re.escape(username), re.UNICODE)
                y = n.search(text_get, pos)
                if y:
                    pywikibot.output('{} is already in the report page.'
                                     .format(username))