def main(): oldImage = None newImage = None summary = '' always = False loose = False # read command line parameters for arg in pywikibot.handleArgs(): if arg == '-always': always = True elif arg == '-loose': loose = True elif arg.startswith('-summary'): if len(arg) == len('-summary'): summary = pywikibot.input(u'Choose an edit summary: ') else: summary = arg[len('-summary:'):] else: if oldImage: newImage = arg else: oldImage = arg if not oldImage: pywikibot.showHelp('image') else: mysite = pywikibot.getSite() ns = mysite.image_namespace() oldImagePage = pywikibot.ImagePage(mysite, ns + ':' + oldImage) gen = pagegenerators.FileLinksGenerator(oldImagePage) preloadingGen = pagegenerators.PreloadingGenerator(gen) bot = ImageRobot(preloadingGen, oldImage, newImage, summary, always, loose) bot.run()
def main(): oldImage = None newImage = None summary = '' always = False loose = False # read command line parameters for arg in pywikibot.handleArgs(): if arg == '-always': always = True elif arg == '-loose': loose = True elif arg.startswith('-summary'): if len(arg) == len('-summary'): summary = pywikibot.input(u'Choose an edit summary: ') else: summary = arg[len('-summary:'):] else: if oldImage: newImage = arg else: oldImage = arg if not oldImage: pywikibot.showHelp('image') else: mysite = pywikibot.Site() ns = mysite.image_namespace() oldImagePage = pywikibot.ImagePage(mysite, ns + ':' + oldImage) gen = pagegenerators.FileLinksGenerator(oldImagePage) preloadingGen = pagegenerators.PreloadingGenerator(gen) bot = ImageRobot(preloadingGen, oldImage, newImage, summary, always, loose) bot.run()
def main(): featured = False gen = None # Process global args and prepare generator args parser local_args = pywikibot.handleArgs() genFactory = pagegenerators.GeneratorFactory() for arg in local_args: if arg == '-featured': featured = True else: genFactory.handleArg(arg) mysite = pywikibot.Site() if mysite.sitename() == 'wikipedia:nl': pywikibot.output( u'\03{lightred}There is consensus on the Dutch Wikipedia that bots should not be used to fix redirects.\03{default}' ) sys.exit() if featured: featuredList = i18n.translate(mysite, featured_articles) ref = pywikibot.Page(pywikibot.Site(), featuredList) gen = pagegenerators.ReferringPageGenerator(ref) gen = pagegenerators.NamespaceFilterPageGenerator(gen, [0]) if not gen: gen = genFactory.getCombinedGenerator() if gen: for page in pagegenerators.PreloadingGenerator(gen): workon(page) else: pywikibot.showHelp('fixing_redirects')
def main(*args): gen = None notitle = False fmt = '1' outputlang = None page_get = False # Process global args and prepare generator args parser local_args = pywikibot.handleArgs(*args) genFactory = GeneratorFactory() for arg in local_args: if arg == '-notitle': notitle = True elif arg.startswith("-format:"): fmt = arg[len("-format:"):] fmt = fmt.replace(u'\\03{{', u'\03{{') elif arg.startswith("-outputlang:"): outputlang = arg[len("-outputlang:"):] elif arg == '-get': page_get = True else: genFactory.handleArg(arg) gen = genFactory.getCombinedGenerator() if gen: for i, page in enumerate(gen, start=1): if not notitle: page_fmt = Formatter(page, outputlang) pywikibot.stdout(page_fmt.output(num=i, fmt=fmt)) if page_get: # TODO: catch exceptions pywikibot.output(page.text, toStdout=True) else: pywikibot.showHelp()
def main(): # This temporary array is used to read the page title if one single # page that should be unlinked. pageTitle = [] # Which namespaces should be processed? # default to [] which means all namespaces will be processed namespaces = [] always = False for arg in pywikibot.handleArgs(): if arg.startswith('-namespace:'): try: namespaces.append(int(arg[11:])) except ValueError: namespaces.append(arg[11:]) elif arg == '-always': always = True else: pageTitle.append(arg) if pageTitle: page = pywikibot.Page(pywikibot.getSite(), ' '.join(pageTitle)) bot = UnlinkBot(page, namespaces, always) bot.run() else: pywikibot.showHelp('unlink')
def main(*args): global bot # Disable cosmetic changes because we don't want to modify any page # content, so that we don't flood the histories with minor changes. config.cosmetic_changes = False #page generator gen = None genFactory = pagegenerators.GeneratorFactory() redirs = False # If the user chooses to work on a single page, this temporary array is # used to read the words from the page title. The words will later be # joined with spaces to retrieve the full title. pageTitle = [] for arg in pywikibot.handleArgs(*args): if genFactory.handleArg(arg): continue if arg == '-redir': redirs = True else: pageTitle.append(arg) pywikibot.Site().login() gen = genFactory.getCombinedGenerator() if not gen: if pageTitle: # work on a single page page = pywikibot.Page(pywikibot.Link(' '.join(pageTitle))) gen = iter([page]) else: pywikibot.showHelp() return preloadingGen = pagegenerators.PreloadingGenerator(gen) bot = TouchBot(preloadingGen, redirs) bot.run()
def main(): #page generator gen = None # If the user chooses to work on a single page, this temporary array is # used to read the words from the page title. The words will later be # joined with spaces to retrieve the full title. pageTitle = [] # This factory is responsible for processing command line arguments # that are also used by other scripts and that determine on which pages # to work on. genFactory = pagegenerators.GeneratorFactory() for arg in pywikibot.handleArgs(): if not genFactory.handleArg(arg): pageTitle.append(arg) if pageTitle: # work on a single page page = pywikibot.Page(pywikibot.getSite(), ' '.join(pageTitle)) gen = iter([page]) if not gen: gen = genFactory.getCombinedGenerator() if not gen: pywikibot.showHelp('inline_images') else: preloadingGen = pagegenerators.PreloadingGenerator(gen) bot = InlineImagesRobot(preloadingGen) bot.run()
def main(*args): """ Process command line arguments and invoke bot. If args is an empty list, sys.argv is used. @param args: command line arguments @type args: list of unicode """ global __simulate, __sys_argv for arg in pywikibot.handle_args(args): pywikibot.showHelp('script_wui') return __simulate = pywikibot.config.simulate __sys_argv = sys.argv site = pywikibot.Site() site.login() chan = '#' + site.language() + '.' + site.family.name bot = ScriptWUIBot(site, chan, site.user() + "_WUI", "irc.wikimedia.org") try: bot.start() except: bot.t.cancel() raise
def main(*args): """ Process command line arguments and invoke bot. If args is an empty list, sys.argv is used. @param args: command line arguments @type args: list of unicode """ gen = None options = {} # Process global args and prepare generator args parser local_args = pywikibot.handle_args(args) genFactory = pagegenerators.GeneratorFactory() for arg in local_args: if genFactory.handleArg(arg): continue if arg.startswith("-"): options[arg[1:].lower()] = True gen = genFactory.getCombinedGenerator() if gen: preloadingGen = pagegenerators.PreloadingGenerator(gen) bot = TouchBot(preloadingGen, **options) pywikibot.Site().login() bot.run() else: pywikibot.showHelp()
def main(): # This temporary string is used to read the title # of the page that should be unlinked. page_title = None options = {} for arg in pywikibot.handleArgs(): if arg.startswith('-namespace:'): if 'namespaces' not in options: options['namespaces'] = [] try: options['namespaces'].append(int(arg[11:])) except ValueError: options['namespaces'].append(arg[11:]) elif arg == '-always': options['always'] = True else: page_title = arg if page_title: page = pywikibot.Page(pywikibot.Site(), page_title) bot = UnlinkBot(page, **options) bot.run() else: pywikibot.showHelp()
def main(*args): """ Process command line arguments and invoke bot. If args is an empty list, sys.argv is used. @param args: command line arguments @type args: list of unicode """ parent = None basename = None options = {} # Process global args and prepare generator args parser local_args = pywikibot.handle_args(args) genFactory = pagegenerators.GeneratorFactory() for arg in local_args: if arg == '-always': options['always'] = True elif arg.startswith('-parent:'): parent = arg[len('-parent:'):].strip() elif arg.startswith('-basename'): basename = arg[len('-basename:'):].strip() else: genFactory.handleArg(arg) generator = genFactory.getCombinedGenerator() if generator and parent and basename: bot = CreateCategoriesBot(generator, parent, basename, **options) bot.run() pywikibot.output(u'All done') else: pywikibot.output(u'No pages to work on') pywikibot.showHelp()
def main(*args): """ Process command line arguments and invoke bot. If args is an empty list, sys.argv is used. @param args: command line arguments @type args: list of unicode """ local_args = pywikibot.handle_args(args) start = local_args[0] if local_args else '!' mysite = pywikibot.Site() try: mysite.disambcategory() except pywikibot.Error as e: pywikibot.output(e) pywikibot.showHelp() return generator = pagegenerators.CategorizedPageGenerator( mysite.disambcategory(), start=start, content=True, namespaces=[0]) bot = DisambiguationRedirectBot(generator=generator) bot.run()
def main(*args): """ Process command line arguments and invoke bot. If args is an empty list, sys.argv is used. @param args: command line arguments @type args: list of unicode """ # Page generator gen = None # Process global args and prepare generator args parser local_args = pywikibot.handle_args(args) genFactory = GeneratorFactory() botArgs = {} for arg in local_args: if arg == '-always': botArgs['always'] = True else: genFactory.handleArg(arg) gen = genFactory.getCombinedGenerator() if not gen: pywikibot.showHelp() return preloadingGen = PreloadingGenerator(gen) bot = SelflinkBot(preloadingGen, **botArgs) bot.run()
def main(*args): """ Process command line arguments and invoke bot. If args is an empty list, sys.argv is used. @param args: command line arguments @type args: list of unicode """ # Process global args and prepare generator args parser local_args = pywikibot.handle_args(args) gen = pagegenerators.GeneratorFactory() options = {} for arg in local_args: if (arg.startswith('-pageage:') or arg.startswith('-lastedit:')): key, val = arg.split(':', 1) options[key[1:]] = int(val) elif gen.handleArg(arg): pass else: options[arg[1:].lower()] = True generator = gen.getCombinedGenerator() if not generator: pywikibot.showHelp() return bot = NewItemRobot(generator, **options) bot.run()
def main(): """ Process command line arguments and invoke BasicBot. """ # Process global arguments to determine desired site local_args = pywikibot.handleArgs() # This factory is responsible for processing command line arguments # that are also used by other scripts and that determine on which pages # to work on. genFactory = pagegenerators.GeneratorFactory() # The generator gives the pages that should be worked upon. gen = None # If dry is True, doesn't do any real changes, but only show # what would have been changed. dry = False # Parse command line arguments for arg in local_args: if arg.startswith("-dry"): dry = True else: genFactory.handleArg(arg) if not gen: gen = genFactory.getCombinedGenerator() if gen: # The preloading generator is responsible for downloading multiple # pages from the wiki simultaneously. gen = pagegenerators.PreloadingGenerator(gen) bot = BasicBot(gen, dry) bot.run() else: pywikibot.showHelp()
def main(): opts = {} for arg in pywikibot.handleArgs(): if arg.startswith('-hours:'): opts['hours'] = float(arg[7:]) opts['no_repeat'] = False elif arg.startswith('-delay:'): opts['delay'] = int(arg[7:]) elif arg.startswith('-page'): if len(arg) == 5: opts['page'] = pywikibot.input( u'Which page do you want to change?') else: opts['page'] = arg[6:] elif arg.startswith('-text'): if len(arg) == 5: opts['text'] = pywikibot.input( u'What text do you want to substitute?') else: opts['text'] = arg[6:] elif arg == '-user': opts['user'] = True elif arg.startswith('-summary'): if len(arg) == len('-summary'): opts['summary'] = pywikibot.input(u'Enter the summary:') else: opts['summary'] = arg[9:] else: pywikibot.showHelp('clean_sandbox') return bot = SandboxBot(**opts) bot.run()
def main(*args): gen = None genFactory = pagegenerators.GeneratorFactory() options = {} # If the user chooses to work on a single page, this temporary array is # used to read the words from the page title. The words will later be # joined with spaces to retrieve the full title. pageTitle = [] for arg in pywikibot.handleArgs(*args): if genFactory.handleArg(arg): continue if arg.startswith("-"): options[arg[1:].lower()] = True else: pageTitle.append(arg) pywikibot.Site().login() gen = genFactory.getCombinedGenerator() if not gen: if pageTitle: # work on a single page page = pywikibot.Page(pywikibot.Link(' '.join(pageTitle))) gen = iter([page]) else: pywikibot.showHelp() return preloadingGen = pagegenerators.PreloadingGenerator(gen) bot = TouchBot(preloadingGen, **options) bot.run()
def main(*args): """ Process command line arguments and invoke bot. If args is an empty list, sys.argv is used. @param args: command line arguments @type args: list of unicode """ options = {} local_args = pywikibot.handle_args(args) genFactory = pagegenerators.GeneratorFactory() for arg in local_args: if arg in ('pages', 'categories'): options['action'] = arg elif arg == '-always': options['always'] = True else: genFactory.handleArg(arg) if 'action' in options: gen = genFactory.getCombinedGenerator() if gen: gen = pagegenerators.PreloadingGenerator(gen) bot = CommonsLinkBot(gen, **options) bot.run() return pywikibot.showHelp()
def main(*args): """ Process command line arguments and invoke bot. If args is an empty list, sys.argv is used. @param args: command line arguments @type args: list of unicode """ options = {} for arg in pywikibot.handle_args(args): if arg.startswith('-fromlang:'): options[arg[1:9]] = arg[10:].split(",") elif arg.startswith('-after:'): options['afterpage'] = arg[7:] elif arg.startswith('-nocache:'): options[arg[1:8]] = arg[9:].split(",") else: options[arg[1:].lower()] = True if options: bot = FeaturedBot(**options) bot.run() else: pywikibot.showHelp()
def main(*args): """ Process command line arguments and invoke bot. If args is an empty list, sys.argv is used. @param args: command line arguments @type args: list of unicode """ options = {} local_args = pywikibot.handle_args(args) genFactory = pagegenerators.GeneratorFactory() for arg in local_args: if arg == '-noimport': options['import_data'] = False elif arg.startswith('-import:'): options['import_data'] = list(set(arg[8:].split(','))) elif arg == '-remove': options['remove'] = True elif arg == '-remove-all-only': options['remove'] = True options['remove_all_only'] = True elif arg == '-always': options['always'] = True else: genFactory.handleArg(arg) generator = genFactory.getCombinedGenerator() if generator: bot = DataImportBot(generator, **options) bot.run() else: pywikibot.showHelp()
def main(*args): """ Process command line arguments and invoke bot. If args is an empty list, sys.argv is used. @param args: command line arguments @type args: list of unicode """ options = {} local_args = pywikibot.handle_args(args) genFactory = pagegenerators.GeneratorFactory() for arg in local_args: if arg == '-always': options['always'] = True elif arg == '-titlecase': options['titlecase'] = True else: genFactory.handleArg(arg) gen = genFactory.getCombinedGenerator() if gen: preloadingGen = pagegenerators.PreloadingGenerator(gen) bot = CapitalizeBot(preloadingGen, **options) bot.run() else: pywikibot.showHelp()
def main(*args): """ Process command line arguments and invoke bot. If args is an empty list, sys.argv is used. @param args: command line arguments @type args: list of unicode """ # Process global args and prepare generator args parser local_args = pywikibot.handle_args(args) gen = pagegenerators.GeneratorFactory() options = {} for arg in local_args: if ( arg.startswith('-pageage:') or arg.startswith('-lastedit:')): key, val = arg.split(':', 1) options[key[1:]] = int(val) elif gen.handleArg(arg): pass else: options[arg[1:].lower()] = True generator = gen.getCombinedGenerator() if not generator: pywikibot.showHelp() return bot = NewItemRobot(generator, **options) bot.run()
def main(*args): """ Process command line arguments and invoke bot. If args is an empty list, sys.argv is used. @param args: command line arguments @type args: list of unicode """ gen = None options = {} # Process global args and prepare generator args parser local_args = pywikibot.handle_args(args) genFactory = pagegenerators.GeneratorFactory() bot_class = TouchBot for arg in local_args: if arg == '-purge': bot_class = PurgeBot elif arg == '-redir': pywikibot.output(u'-redirect option is deprecated, ' 'do not use it anymore.') elif not genFactory.handleArg(arg) and arg.startswith("-"): options[arg[1:].lower()] = True gen = genFactory.getCombinedGenerator() if gen: preloadingGen = pagegenerators.PreloadingGenerator(gen) bot = bot_class(generator=preloadingGen, **options) pywikibot.Site().login() bot.run() else: pywikibot.showHelp()
def main(*args): """ Process command line arguments and invoke bot. If args is an empty list, sys.argv is used. @param args: command line arguments @type args: list of unicode """ options = {} local_args = pywikibot.handle_args(args) genFactory = pagegenerators.GeneratorFactory() for arg in local_args: if genFactory.handleArg(arg): continue if arg.startswith('-summary:'): options['summary'] = arg[9:] elif arg.startswith('-tmp:'): options['tmp'] = arg[5:] elif arg == '-force': options['force'] = True elif arg == '-always': options['always'] = True gen = genFactory.getCombinedGenerator() if gen: bot = BadgesBot(generator=gen, **options) bot.run() else: pywikibot.showHelp()
def main(): featured = False gen = None # Process global args and prepare generator args parser local_args = pywikibot.handleArgs() genFactory = pagegenerators.GeneratorFactory() for arg in local_args: if arg == '-featured': featured = True else: genFactory.handleArg(arg) mysite = pywikibot.Site() if mysite.sitename() == 'wikipedia:nl': pywikibot.output( u'\03{lightred}There is consensus on the Dutch Wikipedia that bots should not be used to fix redirects.\03{default}') sys.exit() if featured: featuredList = i18n.translate(mysite, featured_articles) ref = pywikibot.Page(pywikibot.Site(), featuredList) gen = pagegenerators.ReferringPageGenerator(ref) gen = pagegenerators.NamespaceFilterPageGenerator(gen, [0]) if not gen: gen = genFactory.getCombinedGenerator() if gen: for page in pagegenerators.PreloadingGenerator(gen): workon(page) else: pywikibot.showHelp('fixing_redirects')
def main(*args): """ Process command line arguments and invoke bot. If args is an empty list, sys.argv is used. @param args: command line arguments @type args: list of unicode """ options = {} # Process global args and prepare generator args parser local_args = pywikibot.handle_args(args) genFactory = pagegenerators.GeneratorFactory() for arg in local_args: if arg.startswith('-') and arg[1:] in ('always', 'to13', 'format'): options[arg[1:]] = True else: genFactory.handleArg(arg) gen = genFactory.getCombinedGenerator() if gen: preloadingGen = pagegenerators.PreloadingGenerator(gen) bot = IsbnBot(preloadingGen, **options) bot.run() else: pywikibot.showHelp()
def main(): genFactory = pagegenerators.GeneratorFactory() pageName = '' summary = None always = False undelete = False generator = None # read command line parameters local_args = pywikibot.handleArgs() mysite = pywikibot.Site() for arg in local_args: if arg == '-always': always = True elif arg.startswith('-summary'): if len(arg) == len('-summary'): summary = pywikibot.input(u'Enter a reason for the deletion:') else: summary = arg[len('-summary:'):] elif arg.startswith('-images'): pywikibot.output('\n\03{lightred}-image option is deprecated. ' 'Please use -imageused instead.\03{default}\n') local_args.append('-imageused' + arg[7:]) elif arg.startswith('-undelete'): undelete = True else: genFactory.handleArg(arg) found = arg.find(':') + 1 if found: pageName = arg[found:] if not summary: if pageName: if arg.startswith('-cat') or arg.startswith('-subcats'): summary = i18n.twtranslate(mysite, 'delete-from-category', {'page': pageName}) elif arg.startswith('-links'): summary = i18n.twtranslate(mysite, 'delete-linked-pages', {'page': pageName}) elif arg.startswith('-ref'): summary = i18n.twtranslate(mysite, 'delete-referring-pages', {'page': pageName}) elif arg.startswith('-imageused'): summary = i18n.twtranslate(mysite, 'delete-images', {'page': pageName}) elif arg.startswith('-file'): summary = i18n.twtranslate(mysite, 'delete-from-file') generator = genFactory.getCombinedGenerator() # We are just deleting pages, so we have no need of using a preloading # page generator to actually get the text of those pages. if generator: if summary is None: summary = pywikibot.input(u'Enter a reason for the %sdeletion:' % ['', 'un'][undelete]) bot = DeletionRobot(generator, summary, always, undelete) bot.run() else: # Show help text from the top of this file pywikibot.showHelp()
def main(*args): """ Process command line arguments and invoke bot. If args is an empty list, sys.argv is used. @param args: command line arguments @type args: list of unicode """ global __simulate, __sys_argv for arg in pywikibot.handle_args(args): pywikibot.showHelp("script_wui") return __simulate = pywikibot.config.simulate __sys_argv = sys.argv site = pywikibot.Site() site.login() chan = "#" + site.language() + "." + site.family.name bot = ScriptWUIBot(site, chan, site.user() + "_WUI", "irc.wikimedia.org") try: bot.start() except: bot.t.cancel() raise
def main(): """Main loop. Get a generator and options.""" parent = None basename = None options = {} # Process global args and prepare generator args parser local_args = pywikibot.handleArgs() genFactory = pagegenerators.GeneratorFactory() for arg in local_args: if arg == '-always': options['always'] = True elif arg.startswith('-parent:'): parent = arg[len('-parent:'):].strip() elif arg.startswith('-basename'): basename = arg[len('-basename:'):].strip() else: genFactory.handleArg(arg) generator = genFactory.getCombinedGenerator() if generator and parent and basename: bot = CreateCategoriesBot(generator, parent, basename, **options) bot.run() pywikibot.output(u'All done') else: pywikibot.output(u'No pages to work on') pywikibot.showHelp()
def main(*args): """ Process command line arguments and invoke bot. If args is an empty list, sys.argv is used. @param args: command line arguments @type args: list of unicode """ # Process global arguments to determine desired site local_args = pywikibot.handle_args(args) # This factory is responsible for processing command line arguments # that are also used by other scripts and that determine on which pages # to work on. genFactory = pagegenerators.GeneratorFactory() # Parse command line arguments for arg in local_args: if arg == '-dry': issue_deprecation_warning('-dry option', '-simulate', 1) pywikibot.config.simulate = True else: genFactory.handleArg(arg) gen = genFactory.getCombinedGenerator() if gen: # The preloading generator is responsible for downloading multiple # pages from the wiki simultaneously. gen = pagegenerators.PreloadingGenerator(gen) bot = BasicBot(gen) bot.run() else: pywikibot.showHelp()
def main(*args): """ Process command line arguments and invoke bot. If args is an empty list, sys.argv is used. @param args: command line arguments @type args: list of unicode """ options = {} local_args = pywikibot.handle_args(args) genFactory = pagegenerators.GeneratorFactory() for arg in local_args: if genFactory.handleArg(arg): continue if arg.startswith('-preferred:'): options['preferred'] = arg[11:] elif arg.startswith('-summary:'): options['summary'] = arg[9:] elif arg == '-always': options['always'] = True gen = genFactory.getCombinedGenerator() if gen: bot = PoemBot(gen, **options) bot.run() else: pywikibot.showHelp()
def main(*args): """ Process command line arguments and invoke bot. If args is an empty list, sys.argv is used. @param args: command line arguments @type args: list of unicode """ password = None sysop = False logall = False logout = False for arg in pywikibot.handle_args(args): if arg.startswith("-pass"): if len(arg) == 5: password = pywikibot.input(u'Password for all accounts (no characters will be shown):', password=True) else: password = arg[6:] elif arg == "-sysop": sysop = True elif arg == "-all": logall = True elif arg == "-force": pywikibot.output(u"To force a re-login, please delete the revelant " u"lines from '%s' (or the entire file) and try again." % join(config.base_dir, 'pywikibot.lwp')) elif arg == "-logout": logout = True else: pywikibot.showHelp('login') return if logall: if sysop: namedict = config.sysopnames else: namedict = config.usernames else: site = pywikibot.Site() namedict = {site.family.name: {site.code: None}} for familyName in namedict: for lang in namedict[familyName]: try: site = pywikibot.Site(code=lang, fam=familyName) if logout: site.logout() else: site.login(sysop) user = site.user() if user: pywikibot.output(u"Logged in on %(site)s as %(user)s." % locals()) else: if logout: pywikibot.output(u"Logged out of %(site)s." % locals()) else: pywikibot.output(u"Not logged in on %(site)s." % locals()) except SiteDefinitionError: pywikibot.output(u'%s.%s is not a valid site, please remove it' u' from your config' % (lang, familyName))
def main(*args): gen = None notitle = False page_get = False # Process global args and prepare generator args parser local_args = pywikibot.handleArgs(*args) genFactory = GeneratorFactory() for arg in local_args: if arg == '-notitle': notitle = True elif arg == '-get': page_get = True else: genFactory.handleArg(arg) gen = genFactory.getCombinedGenerator() if gen: for i, page in enumerate(gen, start=1): if not notitle: pywikibot.stdout("%4d: %s" % (i, page.title())) if page_get: # TODO: catch exceptions pywikibot.output(page.text, toStdout=True) else: pywikibot.showHelp()
def main(*args): """ Process command line arguments and invoke bot. If args is an empty list, sys.argv is used. @param args: command line arguments @type args: list of unicode """ # This temporary string is used to read the title # of the page that should be unlinked. page_title = None options = {} for arg in pywikibot.handle_args(args): if arg.startswith('-namespace:'): if 'namespaces' not in options: options['namespaces'] = [] try: options['namespaces'].append(int(arg[11:])) except ValueError: options['namespaces'].append(arg[11:]) elif arg == '-always': options['always'] = True else: page_title = arg if page_title: page = pywikibot.Page(pywikibot.Site(), page_title) bot = UnlinkBot(page, **options) bot.run() else: pywikibot.showHelp()
def __init__(self, generator, **kwargs): self.availableOptions.update({ 'enablePage': None, # Check if someone set an enablePage or not 'disambigPage': None, # If no disambigPage given, not use it. }) super(LonelyPagesBot, self).__init__(**kwargs) self.generator = generator # Take the configurations according to our project self.site = pywikibot.Site() if self.getOption('enablePage'): self.options['enablePage'] = pywikibot.Page( self.site, self.getOption('enablePage')) self.comment = i18n.twtranslate( self.site, 'lonelypages-comment-add-template') self.commentdisambig = i18n.twtranslate( self.site, 'lonelypages-comment-add-disambig-template') self.template = i18n.translate(self.site, template) self.exception = i18n.translate(self.site, exception_regex) if self.template is None or self.exception is None: pywikibot.showHelp() sys.exit(u'Missing configuration for site %s' % self.site) # DisambigPage part if self.getOption('disambigPage') is not None: self.disambigpage = pywikibot.Page(self.site, self.getOption('disambigPage')) try: self.disambigtext = self.disambigpage.get() except pywikibot.NoPage: pywikibot.output(u"%s doesn't esist, skip!" % self.disambigpage.title()) self.disambigtext = '' except pywikibot.IsRedirectPage: pywikibot.output(u"%s is a redirect, don't use it!" % self.disambigpage.title()) self.options['disambigPage'] = None
def main(): featured = False gen = None # This factory is responsible for processing command line arguments # that are also used by other scripts and that determine on which pages # to work on. genFactory = pagegenerators.GeneratorFactory() for arg in pywikibot.handleArgs(): if arg == '-featured': featured = True else: genFactory.handleArg(arg) mysite = pywikibot.getSite() if mysite.sitename() == 'wikipedia:nl': pywikibot.output( u'\03{lightred}There is consensus on the Dutch Wikipedia that bots should not be used to fix redirects.\03{default}') sys.exit() if featured: featuredList = i18n.translate(mysite, featured_articles) ref = pywikibot.Page(pywikibot.getSite(), featuredList) gen = pagegenerators.ReferringPageGenerator(ref) gen = pagegenerators.NamespaceFilterPageGenerator(gen, [0]) if not gen: gen = genFactory.getCombinedGenerator() if gen: for page in pagegenerators.PreloadingGenerator(gen): workon(page) else: pywikibot.showHelp('fixing_redirects')
def main(): #page generator gen = None # This temporary array is used to read the page title if one single # page to work on is specified by the arguments. pageTitle = [] # Which namespaces should be processed? # default to [] which means all namespaces will be processed namespaces = [] # Never ask before changing a page always = False # This factory is responsible for processing command line arguments # that are also used by other scripts and that determine on which pages # to work on. genFactory = pagegenerators.GeneratorFactory() for arg in pywikibot.handleArgs(): if arg.startswith('-xml'): if len(arg) == 4: xmlFilename = i18n.input('pywikibot-enter-xml-filename') else: xmlFilename = arg[5:] gen = XmlDumpNoReferencesPageGenerator(xmlFilename) elif arg.startswith('-namespace:'): try: namespaces.append(int(arg[11:])) except ValueError: namespaces.append(arg[11:]) elif arg == '-always': always = True else: if not genFactory.handleArg(arg): pageTitle.append(arg) if pageTitle: page = pywikibot.Page(pywikibot.getSite(), ' '.join(pageTitle)) gen = iter([page]) if not gen: gen = genFactory.getCombinedGenerator() if not gen: site = pywikibot.getSite() try: cat = maintenance_category[site.family.name][site.lang] except: pass else: if not namespaces: namespaces = [0] cat = catlib.Category(site, "%s:%s" % (site.category_namespace(), cat)) gen = pagegenerators.CategorizedPageGenerator(cat) if not gen: pywikibot.showHelp('noreferences') else: if namespaces: gen = pagegenerators.NamespaceFilterPageGenerator(gen, namespaces) preloadingGen = pagegenerators.PreloadingGenerator(gen) bot = NoReferencesBot(preloadingGen, always) bot.run()
def main(): index = None djvu = None pages = None # what would have been changed. ask = False overwrite = 'ask' # Parse command line arguments for arg in pywikibot.handleArgs(): if arg.startswith("-ask"): ask = True elif arg.startswith("-overwrite:"): overwrite = arg[11:12] if overwrite != 'y' and overwrite != 'n': pywikibot.output( u"Unknown argument %s; will ask before overwriting" % arg) overwrite = 'ask' elif arg.startswith("-djvu:"): djvu = arg[6:] elif arg.startswith("-index:"): index = arg[7:] elif arg.startswith("-pages:"): pages = arg[7:] else: pywikibot.output(u"Unknown argument %s" % arg) # Check the djvu file exists if djvu: os.stat(djvu) if not index: import os.path index = os.path.basename(djvu) if djvu and index: site = pywikibot.getSite() index_page = pywikibot.Page(site, index) if site.family.name != 'wikisource': raise pywikibot.PageNotFound( u"Found family '%s'; Wikisource required." % site.family.name) if not index_page.exists() and index_page.namespace() == 0: index_namespace = site.mediawiki_message( 'Proofreadpage index namespace') index_page = pywikibot.Page(pywikibot.getSite(), u"%s:%s" % (index_namespace, index)) if not index_page.exists(): raise pywikibot.NoPage(u"Page '%s' does not exist" % index) pywikibot.output(u"uploading text from %s to %s" % (djvu, index_page.title(asLink=True))) bot = DjVuTextBot(djvu, index, pages, ask, overwrite) if not bot.has_text(): raise ValueError("No text layer in djvu file") bot.run() else: pywikibot.showHelp()
def main(*args): global interactive, afterpage interactive = 0 afterpage = u"!" featuredcount = False fromlang = [] processType = 'featured' part = False options = {} for arg in pywikibot.handleArgs(): if arg == '-interactive': interactive = 1 elif arg.startswith('-fromlang:'): fromlang = arg[10:].split(",") part = True elif arg.startswith('-after:'): afterpage = arg[7:] elif arg.startswith('-nocache:'): options[arg[1:8]] = arg[9:].split(",") else: options[arg[1:].lower()] = True if part: try: # BUG: range with zh-min-nan (3 "-") if len(fromlang) == 1 and fromlang[0].index("-") >= 0: start, end = fromlang[0].split("--", 1) if not start: start = "" if not end: end = "zzzzzzz" if processType == 'good': fromlang = [lang for lang in good_name.keys() if lang >= start and lang <= end] elif processType == 'list': fromlang = [lang for lang in lists_name.keys() if lang >= start and lang <= end] elif processType == 'former': fromlang = [lang for lang in former_name.keys() if lang >= start and lang <= end] else: fromlang = [lang for lang in featured_name.keys() if lang >= start and lang <= end] except: pass ## for ll in fromlang: ## fromsite = pywikibot.getSite(ll) ## if featuredcount: ## try: ## featuredArticles(fromsite, processType).next() ## except StopIteration: ## continue if options: bot = FeaturedBot(**options) bot.run() else: pywikibot.showHelp()
def main(): #page generator gen = None # This temporary array is used to read the page title if one single # page to work on is specified by the arguments. pageTitle = [] # Which namespaces should be processed? # default to [] which means all namespaces will be processed namespaces = [] # This factory is responsible for processing command line arguments # that are also used by other scripts and that determine on which pages # to work on. genFactory = pagegenerators.GeneratorFactory() always = False for arg in pywikibot.handleArgs(): if arg.startswith('-xml'): if len(arg) == 4: xmlFilename = pywikibot.input( u'Please enter the XML dump\'s filename:') else: xmlFilename = arg[5:] gen = XmlDumpSelflinkPageGenerator(xmlFilename) elif arg == '-sql': # NOT WORKING YET query = """ SELECT page_namespace, page_title FROM page JOIN pagelinks JOIN text ON (page_id = pl_from AND page_id = old_id) WHERE pl_title = page_title AND pl_namespace = page_namespace AND page_namespace = 0 AND (old_text LIKE concat('%[[', page_title, ']]%') OR old_text LIKE concat('%[[', page_title, '|%')) LIMIT 100""" gen = pagegenerators.MySQLPageGenerator(query) elif arg.startswith('-namespace:'): try: namespaces.append(int(arg[11:])) except ValueError: namespaces.append(arg[11:]) elif arg == '-always': always = True else: if not genFactory.handleArg(arg): pageTitle.append(arg) if pageTitle: page = pywikibot.Page(pywikibot.getSite(), ' '.join(pageTitle)) gen = iter([page]) if not gen: gen = genFactory.getCombinedGenerator() if not gen: pywikibot.showHelp('selflink') else: if namespaces != []: gen = pagegenerators.NamespaceFilterPageGenerator(gen, namespaces) preloadingGen = pagegenerators.PreloadingGenerator(gen) bot = SelflinkBot(preloadingGen, always) bot.run()
def main(*args): """ Process command line arguments and invoke bot. If args is an empty list, sys.argv is used. @param args: command line arguments @type args: list of unicode """ # Process global args and prepare generator args parser local_args = pywikibot.handle_args(args) genFactory = pagegenerators.GeneratorFactory() csv_dir = None for arg in local_args: if arg.startswith('-csvdir:'): csv_dir = arg[8:] else: genFactory.handleArg(arg) config_generator = genFactory.getCombinedGenerator() if not config_generator or not csv_dir: pywikibot.showHelp() return for config_page in config_generator: try: config_page.get() except pywikibot.NoPage: pywikibot.error('%s does not exist' % config_page) continue configuration = DataIngestionBot.parseConfigurationPage(config_page) filename = os.path.join(csv_dir, configuration['csvFile']) try: f = codecs.open(filename, 'r', configuration['csvEncoding']) except (IOError, OSError) as e: pywikibot.error('%s could not be opened: %s' % (filename, e)) continue try: files = CSVReader(f, urlcolumn='url', site=config_page.site, dialect=configuration['csvDialect'], delimiter=str(configuration['csvDelimiter'])) bot = DataIngestionBot(files, configuration['titleFormat'], configuration['formattingTemplate'], site=None) bot.run() finally: f.close()
def main(): xmlFilename = None always = False ignorepdf = False limit = None namespaces = [] generator = None summary = None # Process global args and prepare generator args parser local_args = pywikibot.handleArgs() genFactory = pagegenerators.GeneratorFactory() for arg in local_args: if arg.startswith('-namespace:'): try: namespaces.append(int(arg[11:])) except ValueError: namespaces.append(arg[11:]) elif arg.startswith('-summary:'): summary = arg[9:] elif arg == '-always': always = True elif arg == '-ignorepdf': ignorepdf = True elif arg.startswith('-limit:'): limit = int(arg[7:]) elif arg.startswith('-xmlstart'): if len(arg) == 9: xmlStart = pywikibot.input( u'Please enter the dumped article to start with:') else: xmlStart = arg[10:] elif arg.startswith('-xml'): if len(arg) == 4: xmlFilename = pywikibot.input( u'Please enter the XML dump\'s filename:') else: xmlFilename = arg[5:] else: genFactory.handleArg(arg) if xmlFilename: try: xmlStart except NameError: xmlStart = None generator = XmlDumpPageGenerator(xmlFilename, xmlStart, namespaces) if not generator: generator = genFactory.getCombinedGenerator() if not generator: # syntax error, show help text from the top of this file pywikibot.showHelp() return generator = pagegenerators.PreloadingGenerator(generator, step=50) generator = pagegenerators.RedirectFilterPageGenerator(generator) bot = ReferencesRobot(generator, always, limit, ignorepdf, summary) bot.run()
def main(*args): password = None sysop = False logall = False logout = False for arg in pywikibot.handleArgs(*args): if arg.startswith("-pass"): if len(arg) == 5: password = pywikibot.input( u'Password for all accounts (no characters will be shown):', password=True) else: password = arg[6:] elif arg == "-sysop": sysop = True elif arg == "-all": logall = True elif arg == "-force": pywikibot.output( u"To force a re-login, please delete the revelant lines from '%s' (or the entire file) and try again." % join(config.base_dir, 'pywikibot.lwp')) elif arg == "-logout": logout = True else: pywikibot.showHelp('login') return if logall: if sysop: namedict = config.sysopnames else: namedict = config.usernames else: site = pywikibot.Site() namedict = {site.family.name: {site.code: None}} for familyName in namedict: for lang in namedict[familyName]: try: site = pywikibot.Site(code=lang, fam=familyName) if logout: site.logout() else: site.login(sysop) user = site.user() if user: pywikibot.output(u"Logged in on %(site)s as %(user)s." % locals()) else: if logout: pywikibot.output(u"Logged out of %(site)s." % locals()) else: pywikibot.output(u"Not logged in on %(site)s." % locals()) except NoSuchSite: pywikibot.output(u'%s.%s is not a valid site, please remove it' u' from your config' % (lang, familyName))
def main(*args): """ Process command line arguments and invoke bot. If args is an empty list, sys.argv is used. @param args: command line arguments @type args: list of unicode """ gen = None notitle = False fmt = '1' outputlang = None page_get = False # Process global args and prepare generator args parser local_args = pywikibot.handle_args(args) genFactory = GeneratorFactory() local_args.append("-titleregex .*?Dungeons & Dragons.*?") for arg in local_args: if arg == '-notitle': notitle = True elif arg.startswith("-format:"): fmt = arg[len("-format:"):] fmt = fmt.replace(u'\\03{{', u'\03{{') elif arg.startswith("-outputlang:"): outputlang = arg[len("-outputlang:"):] elif arg == '-get': page_get = True else: genFactory.handleArg(arg) gen = genFactory.getCombinedGenerator() this_site = pywikibot.Site() page_text = "#REDIRECT [[%s]]\n\n{{Redr|unprintworthy}}" if gen: for i, page in enumerate(gen, start=1): replace_title = page.title().replace('Dungeons & Dragons', 'Dungeons and Dragons') dest_page = pywikibot.Page(this_site, replace_title) if not dest_page.exists(): target_redirect = page.title() if page.isRedirectPage(): target_redirect = page.getRedirectTarget().title() dest_text = page_text % target_redirect dest_page.text = dest_text dest_page.save( comment=u'Hasteurbot task 13: Dungeons and Dragons', watch=False, botflag=True, force=True) else: pywikibot.showHelp()
def main(): exists_arg = '' commandline_claims = list() # Process global args and prepare generator args parser local_args = pywikibot.handleArgs() gen = pagegenerators.GeneratorFactory() for arg in local_args: # Handle args specifying how to handle duplicate claims if arg.startswith('-exists:'): exists_arg = arg.split(':')[1].strip('"') continue # Handle page generator args if gen.handleArg(arg): continue commandline_claims.append(arg) if len(commandline_claims) % 2: raise ValueError # or something. claims = list() repo = pywikibot.Site().data_repository() for i in range(0, len(commandline_claims), 2): claim = pywikibot.Claim(repo, commandline_claims[i]) if claim.type == 'wikibase-item': target = pywikibot.ItemPage(repo, commandline_claims[i + 1]) elif claim.type == 'string': target = commandline_claims[i + 1] elif claim.type == 'globe-coordinate': coord_args = [ float(c) for c in commandline_claims[i + 1].split(',') ] if len(coord_args) >= 3: precision = coord_args[2] else: precision = 0.0001 # Default value (~10 m at equator) target = pywikibot.Coordinate(coord_args[0], coord_args[1], precision=precision) else: raise NotImplementedError( "%s datatype is not yet supported by claimit.py" % claim.type) claim.setTarget(target) claims.append(claim) generator = gen.getCombinedGenerator() if not generator: # show help text from the top of this file pywikibot.showHelp() return bot = ClaimRobot(generator, claims, exists_arg) bot.run()
def main(): show = False # Parse command line arguments for arg in pywikibot.handleArgs(): show = True if not show: bot = BlockreviewBot() bot.run() else: pywikibot.showHelp()
def main(*args): """ Process command line arguments and invoke bot. If args is an empty list, sys.argv is used. @param args: command line arguments @type args: list of unicode """ options = {} # Process global args and prepare generator args parser local_args = pywikibot.handle_args(args) genFactory = pagegenerators.GeneratorFactory() for arg in local_args: if arg.startswith('-summary:'): options['comment'] = arg[len('-summary:'):] elif arg == '-always': options['always'] = True elif arg == '-async': options['async'] = True elif arg.startswith('-ignore:'): ignore_mode = arg[len('-ignore:'):].lower() if ignore_mode == 'method': options['ignore'] = CANCEL_METHOD elif ignore_mode == 'page': options['ignore'] = CANCEL_PAGE else: raise ValueError( 'Unknown ignore mode "{0}"!'.format(ignore_mode)) else: genFactory.handleArg(arg) site = pywikibot.Site() if 'comment' not in options or not options['comment']: # Load default summary message. options['comment'] = i18n.twtranslate(site, 'cosmetic_changes-standalone') gen = genFactory.getCombinedGenerator() if gen: if options.get('always') or pywikibot.input_yn( warning + '\nDo you really want to continue?', default=False, automatic_quit=False): site.login() preloadingGen = pagegenerators.PreloadingGenerator(gen) bot = CosmeticChangesBot(preloadingGen, **options) bot.run() else: pywikibot.showHelp()
def main(*args): """ Process command line arguments and invoke bot. If args is an empty list, sys.argv is used. @param args: command line arguments @type args: list of unicode """ options = {} generator = None checkcurrent = False ns = [] ns.append(14) # Process global args and prepare generator args parser local_args = pywikibot.handle_args(args) genFactory = pagegenerators.GeneratorFactory() for arg in local_args: if arg.startswith('-summary'): if len(arg) == 8: options['summary'] = pywikibot.input( u'What summary do you want to use?') else: options['summary'] = arg[9:] elif arg.startswith('-checkcurrent'): checkcurrent = True elif arg == '-always': options['always'] = True else: genFactory.handleArg(arg) if checkcurrent: primaryCommonscat, commonscatAlternatives = \ CommonscatBot.getCommonscatTemplate( pywikibot.Site().code) generator = pagegenerators.NamespaceFilterPageGenerator( pagegenerators.ReferringPageGenerator(pywikibot.Page( pywikibot.Site(), u'Template:' + primaryCommonscat), onlyTemplateInclusion=True), ns) if not generator: generator = genFactory.getCombinedGenerator() if generator: pregenerator = pagegenerators.PreloadingGenerator(generator) bot = CommonscatBot(pregenerator, **options) bot.run() else: pywikibot.showHelp()
def main(): options = {} for arg in pywikibot.handleArgs(): if arg == '-always': options['always'] = True bot = UnusedFilesBot(pywikibot.Site(), **options) try: bot.run() except pywikibot.Error as e: pywikibot.showHelp() pywikibot.warning(e)
def main(*args): """ Process command line arguments and invoke bot. If args is an empty list, sys.argv is used. @param args: command line arguments @type args: list of unicode """ pageTitle = None gen = None interwiki = False keep_name = False targetLang = None targetFamily = None local_args = pywikibot.handle_args(args) for arg in local_args: if arg == '-interwiki': interwiki = True elif arg.startswith('-keepname'): keep_name = True elif arg.startswith('-tolang:'): targetLang = arg[8:] elif arg.startswith('-tofamily:'): targetFamily = arg[10:] elif not pageTitle: pageTitle = arg if pageTitle: page = pywikibot.Page(pywikibot.Site(), pageTitle) gen = iter([page]) else: pywikibot.showHelp() return if not targetLang and not targetFamily: targetSite = pywikibot.Site('commons', 'commons') else: if not targetLang: targetLang = pywikibot.Site().language if not targetFamily: targetFamily = pywikibot.Site().family targetSite = pywikibot.Site(targetLang, targetFamily) bot = ImageTransferBot(gen, interwiki=interwiki, targetSite=targetSite, keep_name=keep_name) bot.run()