ویکی‌پدیا:درخواست‌های ربات/روی نقشه همسنگ

از ویکی‌پدیا، دانشنامهٔ آزاد

این ربات برای افزودن الگوی روی نقشه به مقالات کاربرد دارد و از همه آرگومان‌های استاندارد برای آن می‌توان استفاده کرد. مانند -ref:الگو:زمین‌لرزه-خرد

<syntaxhighlight lang="python" line start=1>

#!/usr/bin/python

  1. -*- coding: utf-8 -*-
  2. BY: رضا (User:reza1615 on fa.wikipedia)
  3. Distributed under the terms of the CC-BY-SA 3.0.

import wikipedia import pagegenerators,query,sys import re, os, codecs, catlib wikipedia.config.put_throttle = 0 wikipedia.put_throttle.setDelay() secondwiki='en' faSite = wikipedia.getSite('fa') enSite = wikipedia.getSite(secondwiki) txtTmp= msg = u'ربات:افزودن روی نقشه همسنگ)'


def BotRun(page,text_fa,text_en):

   try:
       pagename=page.replace(u'Fa:',u).replace(u'fa:',u).replace(u'',u'').replace(u'',u).strip()
   except:    
       pagename=unicode(str(page),'UTF-8').replace(u'Fa:',u).replace(u'fa:',u).replace(u'',u'').replace(u'',u).strip()
   page=wikipedia.Page(faSite,pagename)
  1. --------------------------------------------------------------action that you want to do on pages-----------------
   if text_fa.find(u'{{Location map')!=-1 or text_fa.find(u'{{location map')!=-1:
       return False
   if text_fa.find(u'|نقشه')==-1:
       text_fa=text_fa.replace(u'|روی‌نقشه',u'|نقشه    =\n|روی‌نقشه')
       text_fa=text_fa.replace(u'| روی‌نقشه',u'|نقشه    =\n|روی‌نقشه')
   text_fa2=text_fa.replace(u'\n',u).replace(u'\r',u)
   text_en=text_en.replace(u'\n',u).replace(u'\r',u)
   imagename=u
   if text_fa.find(u'|نقشه')==-1:
       return False
   if text_en.find(u'{{location map')!=-1 :
           templateimage=u'{{location map'+text_en.split(u'{{location map')[1].split(u'}}')[0]+u'}}'
           spacefa=text_fa.split(u'|نقشه')[1].split(u'=')[0]
           text_fa=text_fa.replace(u'|نقشه'+spacefa+u'=',u'|نقشه'+spacefa+u'='+templateimage)
           return text_fa
   if text_en.find(u'{{Location map')!=-1 :
       templateimage=u'{{Location map'+text_en.split(u'{{Location map')[1].split(u'}}')[0]+u'}}'
       spacefa=text_fa.split(u'|نقشه')[1].split(u'=')[0]
       text_fa=text_fa.replace(u'|نقشه'+spacefa+u'=',u'|نقشه'+spacefa+u'='+templateimage)
       return text_fa
   return False
  1. ----------------------------------------------------------end of action that you want to do on pages---------------

def enpageget(interwiki):

           text_en=u' '
           for inter in interwiki:
               inters=str(inter)
               if inters.find(secondwiki+':')!=-1:
                   enSite = wikipedia.getSite(secondwiki)
                   page=wikipedia.Page(enSite,inter.title())
                   try:
                       text_en = page.get()#------------------------------geting pages content
                       return text_en
                   except wikipedia.NoPage:
                       wikipedia.output( u'Page %s not found' % page.title() )
                       continue
                   except wikipedia.IsRedirectPage:#----------------------geting pages redirects contents
                        pageRedirect = page.getRedirectTarget()
                        text_en = pageRedirect.get()
                        wikipedia.output( u'Page %s was Redirect but edited!' %  pageRedirect )
                        return text_en
                   except:
                        continue
                   return u' '

def run(generator):

       for pages in generator:
           try:
               pagename=unicode(str(pages),'UTF-8').replace(u'Fa:',u).replace(u'fa:',u).replace(u'',u'').replace(u'',u).strip()
           except:
              pagename=str(pages).replace(u'Fa:',u).replace(u'fa:',u).replace(u'',u'').replace(u'',u).strip()
           if pagename.find(u':')!=-1:
               continue
           pagefa=wikipedia.Page(faSite,pagename)
           try:
               if not pagefa.canBeEdited():    
                           wikipedia.output( u'Skipping locked page %s' % pagefa.title() )
                           continue
               text_fa = pagefa.get()#------------------------------geting pages content
               interwikis= pagefa.interwiki()
           except wikipedia.NoPage:
               wikipedia.output( u'Page %s not found' % pagefa.title() )
               continue
           except wikipedia.IsRedirectPage:#----------------------geting pages redirects contents
                pageRedirect = pagefa.getRedirectTarget()
                text_fa = pageRedirect.get()
                interwikis= pagefa.interwiki()
                wikipedia.output( u'Page %s was Redirect but edited!' %  pageRedirect )
           except:
                continue
           if interwikis==[]:
               wikipedia.output( u'---------------------------')
               wikipedia.output( pagename)
               wikipedia.output( u"dosen't have english page!")
               continue
           text_en=enpageget(interwikis)
           try:
              test=text_en.replace(u'\n',u)
           except:
               wikipedia.output( u'---------------------------')
               wikipedia.output( pagename)
               wikipedia.output( u"dosen't have english page!")
               continue    
           if text_en==u' ' or text_en==u:
               wikipedia.output( u'---------------------------')
               wikipedia.output( pagename)
               wikipedia.output( u"dosen't have english page!")
               continue
           wikipedia.output( u'---------------------------')
           wikipedia.output( pagename)
           new_text=BotRun(pagename,text_fa,text_en)
           
           if new_text:
               savepart(pagename,new_text )#---------------saving changes in page with new_text content-----------------------------------
           else:
               wikipedia.output( u'Skipping %s ' %  pagename )

def savepart( page,new_text):

           pagename=page.replace(u'Fa:',u).replace(u'fa:',u).replace(u'',u'').replace(u'',u).strip()
           page=wikipedia.Page(faSite,pagename)
           try:
               page.put( new_text,msg % page ,watchArticle = None,minorEdit = True)
           except wikipedia.EditConflict:
               wikipedia.output( u'Skipping %s because of edit conflict' % ( page.title() ) )
           except wikipedia.SpamfilterError,url:
               wikipedia.output( u'Cannot change %s because of blacklist entry %s' % ( page.title(),url ) )

def categorydown(listacategory):

   wikipedia.config.put_throttle = 0
   wikipedia.put_throttle.setDelay()
   count=1
   for catname in listacategory:
       count+=1
       if count==200:
           break
       gencat = pagegenerators.SubCategoriesPageGenerator(catname, recurse=False)
       for subcat in gencat:
           try:
               wikipedia.output(subcat)
           except:
               wikipedia.output(str(subcat))
           if subcat in listacategory:
               continue
           else:
               listacategory.append(subcat)
   return listacategory

def facatlist(facat):

   wikipedia.config.put_throttle = 0
   wikipedia.put_throttle.setDelay()
   count=0
   listenpageTitle=[]
   PageTitle=facat.replace(u'',u'').replace(u'',u).strip()
   language='fa'
   PageTitles =[PageTitle]  
   for PageTitle in PageTitles:
       cat = catlib.Category( wikipedia.getSite(language),PageTitle )
       listacategory=[cat]
       listacategory=categorydown(listacategory)
       for enpageTitle in listacategory:
                  enpageTitle=str(enpageTitle).split(u'|')[0].split(u']]')[0].replace(u'[[',u).strip()
                  cat = catlib.Category( wikipedia.getSite(language),enpageTitle )
                  gent = pagegenerators.CategorizedPageGenerator( cat )
                  for pagework in gent:
                     count+=1
                     try:
                         link=str(pagework).split(u'|')[0].split(u']]')[0].replace(u'[[',u).strip()
                     except:
                         pagework=unicode(str(pagework),'UTF-8')
                         link=pagework.split(u'|')[0].split(u']]')[0].replace(u'[[',u).strip()
                     wikipedia.output(link)
                     fapagetitle=link
                     wikipedia.output(u'adding '+fapagetitle+u' to fapage lists')
                     listenpageTitle.append(fapagetitle)
   if listenpageTitle==[]:
       return False
   return listenpageTitle

def main():

   summary_commandline,template,gen = None,None,None
   exceptions,PageTitles,namespaces = [],[],[]
   cat=
   autoText,autoTitle = False,False
   genFactory = pagegenerators.GeneratorFactory()
   wikipedia.setAction( msg )
   arg=False#------if you dont want to work with arguments leave it False if you want change it to True---
   if arg==False:
       for arg in wikipedia.handleArgs():
           if arg == '-autotitle':
               autoTitle = True
           elif arg == '-autotext':
               autoText = True
           elif arg.startswith( '-page:' ):
               if len(arg) == 6:
                   PageTitles.append(wikipedia.input( u'Which page do you want to chage?' ))
               else:
                   PageTitles.append(arg[6:])
           elif arg.startswith( '-cat:' ):
               if len(arg) == 5:
                   cat=wikipedia.input( u'Which Category do you want to chage?' )
               else:
                   cat='Category:'+arg[5:]
           elif arg.startswith( '-template:' ):
               if len(arg) == 10:
                   template.append(wikipedia.input( u'Which Template do you want to chage?' ))
               else:
                   template.append('Template:'+arg[10:])
           elif arg.startswith('-except:'):
               exceptions.append(arg[8:])
           elif arg.startswith( '-namespace:' ):
               namespaces.append( int( arg[11:] ) )
           elif arg.startswith( '-ns:' ):
               namespaces.append( int( arg[4:] ) )
           elif arg.startswith( '-summary:' ):
               wikipedia.setAction( arg[9:] )
               summary_commandline = True
           else:
               generator = genFactory.handleArg(arg)
               if generator:
                   gen = generator
   else:
       PageTitles = [raw_input(u'Page:> ').decode('utf-8')]
   if cat!=:
       facatfalist=facatlist(cat)
       if facatfalist!=False:
           run(facatfalist)    
   if PageTitles:
       pages = [wikipedia.Page(faSite,PageTitle) for PageTitle in PageTitles]
       gen = iter( pages )
   if not gen:
       wikipedia.stopme()
       sys.exit()
   if namespaces != []:
       gen = pagegenerators.NamespaceFilterPageGenerator( gen,namespaces )
   preloadingGen = pagegenerators.PreloadingGenerator( gen,pageNumber = 60 )#---number of pages that you want load at same time
   run(preloadingGen)

if __name__ == "__main__":

   try:
       main()
   finally:
       wikipedia.stopme()